diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ba9c85c..d49037a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -53,13 +53,17 @@ jobs: - uses: Swatinem/rust-cache@v2 with: key: test + # Rune links xkbcommon on Linux for keyboard input. + - if: runner.os == 'Linux' + run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libxkbcommon-dev - run: cargo test --all --all-features deny: - name: cargo-deny (license + advisories) + name: cargo-deny (advisories, bans, sources) runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: EmbarkStudios/cargo-deny-action@v2 with: - command: check licenses advisories bans sources + # Licenses are deliberately not checked; see docs/ARCHITECTURE.md §11. + command: check advisories bans sources diff --git a/CLAUDE.md b/CLAUDE.md index 75a1bd6..c89f369 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -21,8 +21,9 @@ cargo test -p modrix-core # one crate cargo test -p modrix-core deploy::apply_tests # one module's tests cargo clippy --all-targets --all-features -- -D warnings # zero warnings required cargo fmt --all -- --check -cargo deny check # license + advisory gate -cargo run -p modrix-gui # run the GUI +cargo deny check advisories bans sources # advisories gate (licenses are not checked) +cargo run -p modrix-gui # run the GUI (Rune, native GPU UI) +cargo run -p modrix-gui -- --snap out.png --scene mods # render one demo scene headless cargo run -p modrix-cli -- # binary is `modrix` cargo run -p modrix-cli -- --json # machine envelope for agents cargo run -p modrix-cli -- mcp # MCP server over stdio @@ -35,7 +36,7 @@ Releases are cut by pushing a `v*` tag (or running the **Release** workflow with version): `.github/workflows/release.yml` stamps the version, builds each OS, packages the NSIS installer, and publishes a GitHub Release - which the in-app updater checks. -Toolchain is pinned in `rust-toolchain.toml` (rustup installs it automatically). CI (`.github/workflows/ci.yml`) runs fmt + clippy `-D warnings` + tests on all three OSes, plus `cargo deny check licenses advisories bans sources`. +Toolchain is pinned in `rust-toolchain.toml` (rustup installs it automatically). CI (`.github/workflows/ci.yml`) runs fmt + clippy `-D warnings` + tests on all three OSes, plus `cargo deny check advisories bans sources`. ## Hard rules @@ -46,7 +47,7 @@ Toolchain is pinned in `rust-toolchain.toml` (rustup installs it automatically). - Tests are exempt from unwrap/panic/indexing (see `clippy.toml`), but not from arithmetic discipline. - The `power-of-ten-rust` skill covers this discipline in depth. -**GPL-2.0-only licensing** - mechanically gated by `deny.toml`. Apache-2.0-only dependencies are rejected (incompatible with GPLv2); dual `MIT OR Apache-2.0` crates pass via the MIT arm. This is why the HTTP stack is hyper + rustls + `rustls-rustcrypto` + `rustls-native-certs` and **never reqwest** (pulls `ring`/`sync_wrapper`). Every source file starts with `// SPDX-License-Identifier: GPL-2.0-only` (or the comment style of its format). +**Licensing** - the project is GPL-2.0-only and every source file starts with `// SPDX-License-Identifier: GPL-2.0-only` (or the comment style of its format). Dependency licenses are **not** gated: `deny.toml` checks advisories, bans and sources only. There is no rule against Apache-2.0 crates or against `reqwest`; the current hyper + rustls HTTP stack is kept because it works, not because anything forbids the alternative (see `docs/ARCHITECTURE.md §11`). **Dependency direction:** `modrix-core` depends on no UI, site-specific, or protocol crate. Frontends are thin - all business logic lives in core; a frontend only presents core's action layer. @@ -62,11 +63,16 @@ Cargo workspace, `crates/*`: - **`modrix-protocol`**: dormant `nxm://` OS handler; identity extraction only, not a download path. - **`modrix-plugin`**: Lua (mlua, vendored 5.4) plugin host + FOMOD installer. Lua is sandboxed: no raw `io`/`os`/`require`; plugins return stage plans (validated in `core::logic`), never write files directly; per-call instruction/time/memory budgets. - **`modrix-registry`**: community plugin registry client (curated `ParkerrDev/modrix-plugins` repo): index fetch, sha256-verified atomic install into `/plugins/` (where `core::defcat` looks), uninstall/gc. `MODRIX_REGISTRY` env overrides the source (local clone while the repo is private). +- **`modrix-il2cpp`**: reader for Unity's IL2CPP `global-metadata.dat` (types, methods, fields, assemblies). Pure safe Rust, no FFI - it only reads a file - which is why it sits in this workspace under the same lints as the engine. It is the first stage of generating managed interop assemblies so an IL2CPP game (Sons of the Forest) can be modded at all; see `docs/SONS-LOADER.md` for the full design and what remains. +- **`modrix-ecma335`**: a from-scratch ECMA-335 / PE32+ writer that emits .NET *reference* assemblies (types, fields, method signatures, no bodies). Pure safe Rust, no dependencies beyond `thiserror`. Validated by re-parsing its own output, by synthetic assemblies that straddle the coded-index width threshold, and by compiling real C# against it with the actual Roslyn `csc`. +- **`modrix-interop-gen`**: turns an IL2CPP game into compilable reference assemblies - partitions the flat type world into per-assembly models and encodes them via `modrix-ecma335`. This is what makes Sons of the Forest buildable with **no third-party loader**: `modrix interop generate` reads `GameAssembly.dll` + `global-metadata.dat` from the install and writes `_Modrix/interop/`. The game's embedded corlib is redirected onto the real `System.Runtime` rather than emitted, so `System.Object` does not exist twice. - **`modrix-mcp`**: MCP server (hand-rolled stdio JSON-RPC, serde_json only) exposing the full engine surface as tools + installed skill files as resources; run via `modrix mcp`. -- **`modrix-update`**: in-app updater over GitHub Releases, reusing `modrix-download`'s hyper+rustls client (never reqwest/ring). `check` compares the latest release tag (semver) to `CARGO_PKG_VERSION`; on Windows `download`+`apply` fetch and silently run the NSIS installer, then the GUI quits so it can self-replace. Best-effort: offline / private-repo / up-to-date all resolve to "no update". Non-Windows platforms get a manual-download link. -- **`modrix-cli`** (`modrix`), **`modrix-tui`** (ratatui), **`modrix-gui`** (Iced 0.13; screens in `src/view/*.rs`) - thin frontends. `modrix-gui` is the only crate allowed to link a GUI toolkit. +- **`modrix-update`**: in-app updater over GitHub Releases, reusing `modrix-download`'s hyper+rustls client. `check` compares the latest release tag (semver) to `CARGO_PKG_VERSION`; on Windows `download`+`apply` fetch and silently run the NSIS installer, then the GUI quits so it can self-replace. Best-effort: offline / private-repo / up-to-date all resolve to "no update". Non-Windows platforms get a manual-download link. +- **`modrix-cli`** (`modrix`), **`modrix-tui`** (ratatui), **`modrix-gui`** (Rune, a native GPU UI with no web view; screens in `src/ui/*.rs`, engine I/O on its own thread in `src/bus.rs`, demo scenes in `src/demo.rs` for `--snap out.png --scene ` renders) - thin frontends. `modrix-gui` is the only crate allowed to link a GUI toolkit. -Game definitions are two-tier: declarative `games//game.toml` (parsed in core; `api_version = 2` carries capabilities - load-order strategy, content dirs, base files, external scans, health checks, store-detection ids/`registry_keys`, `required_files`, `mod_base` (deploy into the install dir or the user profile) - so core has NO game-specific logic) covers most games; `game.lua` only when logic is required. Frontends gate features on `Engine::capabilities(game)`. **86 games, ported from Vortex, ship built-in** - embedded from `games//` by `crates/modrix-core/build.rs` (drop in a `game.toml` and it ships, no code change), spanning Bethesda/Gamebryo (Data/ + Plugins.txt + script-extender health), Unity (BepInEx/UMM), and many drop-into-a-folder titles; Skyrim SE and Subnautica are the reference defs. Install detection is Steam (cross-platform, VDF parsing) plus GOG/Epic/Xbox/Origin/Uplay and generic vendor `registry_keys` (Windows-only, via the `winreg` crate - target-gated since `unsafe` is forbidden). Reaching Vortex's 250+ is via the community registry as more defs are authored; the other Vortex games' logic lives on Nexus servers, not in-repo. + **GUI rules (Parker's, kept from the web build and binding on any toolkit):** the window is frameless with **no window controls at all** (Hyprland manages windows by keybind); the top bar and sidebar header are drag regions, nothing more. **No live blur on an always-visible layer**: no `backdrop_blur` on panels, sidebar or top bar - each one copies and blurs the whole 2560x1600 target per frame, which made the iGPU lag. Soft art is baked once on the CPU (`art.rs`), and the whole backdrop (wash, glow, hero, fade) is flattened into one image by `bake.rs`: every full-window layer costs the iGPU several ms a frame. No image or component is ever squished or letterboxed (cover-fit, anchored top), the sidebar cover always fills the full sidebar width, and images are never hidden during a resize. The layout is fluid: no fixed widths that squash when Hyprland tiles the window small. The MODRIX wordmark stays on one line; the notification bell has exactly one indicator (a count badge). All dropdowns and right-click menus are the app's own. The view only rebuilds when state it shows changed (`poll` returns `true` only then), so an idle window draws nothing. + +Game definitions are two-tier: declarative `games//game.toml` (parsed in core; `api_version = 2` carries capabilities - load-order strategy, content dirs, base files, external scans, health checks, store-detection ids/`registry_keys`, `required_files`, `mod_base` (deploy into the install dir or the user profile) - so core has NO game-specific logic) covers most games; `game.lua` only when logic is required. Frontends gate features on `Engine::capabilities(game)`. `api_version = 3` adds three more, all `#[serde(default)]` so every existing definition still parses: `[launch]` (how to start the game, its log path, and the environment it needs - `env` is a `BTreeMap` so rendered launch options are byte-stable), `[mod_loader]` (an injected mod loader Modrix can detect, version and conflict-check; named `mod_loader` rather than `loader` because `loader` is already a nested key under `[health]` and the misplaced-key guard requires top-level names never be valid inside a table), and `park_root_binaries` (an explicit override for the "is a top-level DLL a loader or the mod payload?" heuristic - Sons of the Forest must set it `false` or every mod deploys to the install root and silently does nothing). **86 games, ported from Vortex, ship built-in** - embedded from `games//` by `crates/modrix-core/build.rs` (drop in a `game.toml` and it ships, no code change), spanning Bethesda/Gamebryo (Data/ + Plugins.txt + script-extender health), Unity (BepInEx/UMM), and many drop-into-a-folder titles; Skyrim SE and Subnautica are the reference defs. Install detection is Steam (cross-platform, VDF parsing) plus GOG/Epic/Xbox/Origin/Uplay and generic vendor `registry_keys` (Windows-only, via the `winreg` crate - target-gated since `unsafe` is forbidden). Reaching Vortex's 250+ is via the community registry as more defs are authored; the other Vortex games' logic lives on Nexus servers, not in-repo. ## Conventions diff --git a/Cargo.lock b/Cargo.lock index f6a4c13..2ce9b9f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3,91 +3,106 @@ version = 4 [[package]] -name = "ab_glyph" -version = "0.2.32" +name = "accesskit" +version = "0.25.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2" +checksum = "4e883d1d28c5fd5568c79ed2d2bd48d9f2fd3945c8974ed0f53690ceddb051be" dependencies = [ - "ab_glyph_rasterizer", - "owned_ttf_parser", + "uuid", ] [[package]] -name = "ab_glyph_rasterizer" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" +name = "accesskit_atspi_common" +version = "0.21.1" +source = "git+https://github.com/anomalyco/rune?rev=e6f70eb09762180b86dcef912fe169a315bc31b7#e6f70eb09762180b86dcef912fe169a315bc31b7" +dependencies = [ + "accesskit", + "accesskit_consumer", + "atspi-common", + "phf", + "serde", + "zvariant", +] [[package]] -name = "adler2" -version = "2.0.1" +name = "accesskit_consumer" +version = "0.39.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +checksum = "f3da8f27636015191b2264ee1df681503170a632cafd832fdc1edfdd4e3a2fd3" +dependencies = [ + "accesskit", + "hashbrown 0.17.2", +] [[package]] -name = "aead" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +name = "accesskit_macos" +version = "0.27.2" +source = "git+https://github.com/anomalyco/rune?rev=e6f70eb09762180b86dcef912fe169a315bc31b7#e6f70eb09762180b86dcef912fe169a315bc31b7" dependencies = [ - "crypto-common", - "generic-array", + "accesskit", + "accesskit_consumer", + "hashbrown 0.17.2", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", ] [[package]] -name = "aes" -version = "0.8.4" +name = "accesskit_unix" +version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +checksum = "30d5192871228c54f1b0fb4a85cef000e11a3804f25d2165f14afa0daa67f3f6" dependencies = [ - "cfg-if", - "cipher", - "cpufeatures", + "accesskit", + "accesskit_atspi_common", + "async-channel", + "async-executor", + "async-task", + "atspi", + "futures-lite", + "futures-util", + "serde", + "zbus", ] [[package]] -name = "aes-gcm" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +name = "accesskit_windows" +version = "0.35.2" +source = "git+https://github.com/anomalyco/rune?rev=e6f70eb09762180b86dcef912fe169a315bc31b7#e6f70eb09762180b86dcef912fe169a315bc31b7" dependencies = [ - "aead", - "aes", - "cipher", - "ctr", - "ghash", - "subtle", + "accesskit", + "accesskit_consumer", + "hashbrown 0.17.2", + "static_assertions", + "windows", + "windows-core", ] [[package]] -name = "ahash" -version = "0.7.8" +name = "adler2" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891477e0c6a8957309ee5c45a6368af3ae14bb510732d2684ffa19af310920f9" -dependencies = [ - "getrandom 0.2.17", - "once_cell", - "version_check", -] +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "ahash" -version = "0.8.12" +version = "0.8.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +checksum = "54dae3d1d7b8956f3506c4e999a74e77f932a59153ccf38ab8cf96db74bb9dc0" dependencies = [ "cfg-if", - "getrandom 0.3.4", + "getrandom 0.4.3", "once_cell", + "serde", "version_check", "zerocopy", ] [[package]] name = "aho-corasick" -version = "1.1.4" +version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" dependencies = [ "memchr", ] @@ -105,16 +120,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0f2a1bb052857d5dd49572219344a7332b31b76405648eabac5bc68978251bcd" dependencies = [ "android-properties", - "bitflags 2.13.0", + "bitflags 2.13.2", "cc", "jni", "libc", "log", "ndk", "ndk-context", - "ndk-sys 0.6.0+11769913", + "ndk-sys", "num_enum", - "thiserror 2.0.18", + "thiserror 2.0.21", ] [[package]] @@ -125,9 +140,9 @@ checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04" [[package]] name = "android_system_properties" -version = "0.1.5" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" dependencies = [ "libc", ] @@ -184,26 +199,38 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.103" +version = "1.0.105" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3" +checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902" [[package]] -name = "approx" -version = "0.5.1" +name = "ar_archive_writer" +version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6" +checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec" dependencies = [ - "num-traits", + "object", ] [[package]] -name = "arbitrary" -version = "1.4.2" +name = "arboard" +version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" +checksum = "aeb9553e62312c8756a5979254fc6d7da8bbeb5986a1e17037fab932f7037917" dependencies = [ - "derive_arbitrary", + "clipboard-win", + "image 0.25.10", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "parking_lot", + "percent-encoding", + "windows-sys 0.61.2", + "wl-clipboard-rs", + "x11rb", ] [[package]] @@ -226,32 +253,11 @@ checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b" [[package]] name = "ash" -version = "0.37.3+1.3.251" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39e9c3835d686b0a6084ab4234fcd1b07dbf6e4767dce60874b12356a25ecd4a" -dependencies = [ - "libloading 0.7.4", -] - -[[package]] -name = "ashpd" -version = "0.11.1" +version = "0.38.0+1.3.281" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2f3f79755c74fd155000314eb349864caa787c6592eace6c6882dad873d9c39" +checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f" dependencies = [ - "enumflags2", - "futures-channel", - "futures-util", - "rand 0.9.4", - "raw-window-handle", - "serde", - "serde_repr", - "tokio", - "url", - "wayland-backend", - "wayland-client", - "wayland-protocols", - "zbus 5.17.0", + "libloading", ] [[package]] @@ -290,9 +296,9 @@ dependencies = [ [[package]] name = "async-executor" -version = "1.14.0" +version = "1.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" +checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37" dependencies = [ "async-task", "concurrent-queue", @@ -302,17 +308,6 @@ dependencies = [ "slab", ] -[[package]] -name = "async-fs" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8034a681df4aed8b8edbd7fbe472401ecf009251c8b40556b304567052e294c5" -dependencies = [ - "async-lock", - "blocking", - "futures-lite", -] - [[package]] name = "async-io" version = "2.6.0" @@ -326,16 +321,16 @@ dependencies = [ "futures-lite", "parking", "polling", - "rustix 1.1.4", + "rustix 1.1.6", "slab", "windows-sys 0.61.2", ] [[package]] name = "async-lock" -version = "3.4.2" +version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311" +checksum = "0876700b0d007ad25d5508865a4259c3af9af6d296bf663a0d586d0bc3369f6f" dependencies = [ "event-listener", "event-listener-strategy", @@ -357,18 +352,18 @@ dependencies = [ "cfg-if", "event-listener", "futures-lite", - "rustix 1.1.4", + "rustix 1.1.6", ] [[package]] name = "async-recursion" -version = "1.1.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11" +checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 3.0.10", ] [[package]] @@ -383,7 +378,7 @@ dependencies = [ "cfg-if", "futures-core", "futures-io", - "rustix 1.1.4", + "rustix 1.1.6", "signal-hook-registry", "slab", "windows-sys 0.61.2", @@ -397,13 +392,13 @@ checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" [[package]] name = "async-trait" -version = "0.1.89" +version = "0.1.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 3.0.10", ] [[package]] @@ -413,64 +408,87 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" [[package]] -name = "autocfg" -version = "1.5.1" +name = "atspi" +version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +checksum = "c77886257be21c9cd89a4ae7e64860c6f0eefca799bb79127913052bd0eefb3d" +dependencies = [ + "atspi-common", + "atspi-proxies", +] [[package]] -name = "base16ct" -version = "0.2.0" +name = "atspi-common" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" +checksum = "20c5617155740c98003016429ad13fe43ce7a77b007479350a9f8bf95a29f63d" +dependencies = [ + "enumflags2", + "serde", + "static_assertions", + "zbus", + "zbus-lockstep", + "zbus-lockstep-macros", + "zbus_names", + "zvariant", +] [[package]] -name = "base64" -version = "0.22.1" +name = "atspi-proxies" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +checksum = "2230e48787ed3eb4088996eab66a32ca20c0b67bbd4fd6cdfe79f04f1f04c9fc" +dependencies = [ + "atspi-common", + "serde", + "zbus", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] -name = "base64ct" -version = "1.8.3" +name = "base64" +version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" [[package]] name = "bit-set" -version = "0.5.3" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1" +checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d" dependencies = [ - "bit-vec 0.6.3", + "bit-vec 0.9.1", ] [[package]] name = "bit-set" -version = "0.8.0" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c" dependencies = [ - "bit-vec 0.8.0", + "bit-vec 0.10.2", ] [[package]] name = "bit-vec" -version = "0.6.3" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" +checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" [[package]] name = "bit-vec" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" - -[[package]] -name = "bit_field" -version = "0.10.3" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e4b40c7323adcfc0a41c4b88143ed58346ff65a288fc144329c5c45e05d70c6" +checksum = "72503af1e72be411d74ca45cd6b309878fcb35354e252fc2a3a8bda3a97082a0" +dependencies = [ + "borsh", + "serde", +] [[package]] name = "bitflags" @@ -480,15 +498,22 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.13.0" +version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" [[package]] -name = "block" -version = "0.1.6" +name = "blake3" +version = "1.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" +checksum = "6d9e454fc11f76977dc803893aff6304ed33d6a26efae8696573bea74baa27ae" +dependencies = [ + "arrayvec", + "cc", + "cfg-if", + "constant_time_eq 0.4.2", + "cpufeatures 0.3.1", +] [[package]] name = "block-buffer" @@ -505,7 +530,7 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f" dependencies = [ - "objc2 0.5.2", + "objc2 0.5.3", ] [[package]] @@ -514,14 +539,14 @@ version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" dependencies = [ - "objc2 0.6.4", + "objc2 0.6.5", ] [[package]] name = "blocking" -version = "1.6.2" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e83f8d02be6967315521be875afa792a316e28d57b5a2d401897e2a7921b7f21" +checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" dependencies = [ "async-channel", "async-task", @@ -530,11 +555,35 @@ dependencies = [ "piper", ] +[[package]] +name = "borsh" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" +dependencies = [ + "borsh-derive", + "bytes", + "cfg_aliases", +] + +[[package]] +name = "borsh-derive" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12cdfe656708a01f89b451a7d36466e6fe6c414de0aa18fc54f864f6f9ca9f56" +dependencies = [ + "once_cell", + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "bstr" -version = "1.13.0" +version = "1.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f7dc094d718f2e1c1559ad110e27eeaae14a5465d3d56dd6dbd793079fbd530" +checksum = "a680398c10c7bc0488067c4612226ea905a85f607134b69f3068d505d58c4214" dependencies = [ "memchr", "serde_core", @@ -542,34 +591,28 @@ dependencies = [ [[package]] name = "bumpalo" -version = "3.20.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" - -[[package]] -name = "by_address" -version = "1.2.1" +version = "3.20.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" [[package]] name = "bytemuck" -version = "1.25.0" +version = "1.25.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" dependencies = [ "bytemuck_derive", ] [[package]] name = "bytemuck_derive" -version = "1.10.2" +version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9abbd1bc6865053c427f7198e6af43bfdedc55ab791faed4fbd361d789575ff" +checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 3.0.10", ] [[package]] @@ -578,11 +621,17 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + [[package]] name = "bytes" -version = "1.12.0" +version = "1.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ae3f5d315924270530207e2a68396c3cc547f6dca3fbdca317cfb1a51edb593" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" [[package]] name = "calloop" @@ -590,7 +639,7 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", "log", "polling", "rustix 0.38.44", @@ -598,48 +647,23 @@ dependencies = [ "thiserror 1.0.69", ] -[[package]] -name = "calloop" -version = "0.14.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4dbf9978365bac10f54d1d4b04f7ce4427e51f71d61f2fe15e3fed5166474df7" -dependencies = [ - "bitflags 2.13.0", - "polling", - "rustix 1.1.4", - "slab", - "tracing", -] - [[package]] name = "calloop-wayland-source" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20" dependencies = [ - "calloop 0.13.0", + "calloop", "rustix 0.38.44", "wayland-backend", "wayland-client", ] -[[package]] -name = "calloop-wayland-source" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "138efcf0940a02ebf0cc8d1eff41a1682a46b431630f4c52450d6265876021fa" -dependencies = [ - "calloop 0.14.4", - "rustix 1.1.4", - "wayland-backend", - "wayland-client", -] - [[package]] name = "cc" -version = "1.2.66" +version = "1.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5d6cac793997bd970000024b2934968efe83b382de4fdcf4fcb46b6ee4ad996" +checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" dependencies = [ "find-msvc-tools", "jobserver", @@ -649,62 +673,32 @@ dependencies = [ [[package]] name = "cfg-if" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" - -[[package]] -name = "cfg_aliases" -version = "0.1.1" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" [[package]] name = "cfg_aliases" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" [[package]] name = "chacha20" -version = "0.9.1" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" dependencies = [ "cfg-if", - "cipher", - "cpufeatures", -] - -[[package]] -name = "chacha20poly1305" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" -dependencies = [ - "aead", - "chacha20", - "cipher", - "poly1305", - "zeroize", -] - -[[package]] -name = "cipher" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" -dependencies = [ - "crypto-common", - "inout", - "zeroize", + "cpufeatures 0.3.1", + "rand_core", ] [[package]] name = "clap" -version = "4.6.1" +version = "4.6.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" +checksum = "50066ca966813ca8957ee15361752f19424a8ff620dbe9c8993d9f99d99b04b3" dependencies = [ "clap_builder", "clap_derive", @@ -712,9 +706,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.6.0" +version = "4.6.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" +checksum = "a0ed97c96ef4efb3cc84e09fa388df4463e7cc3224ec38d7b1d9e45749333590" dependencies = [ "anstream", "anstyle", @@ -724,67 +718,38 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.6.1" +version = "4.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" +checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7" dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.118", + "syn 3.0.10", ] [[package]] name = "clap_lex" -version = "1.1.0" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" [[package]] name = "clipboard-win" -version = "5.4.1" +version = "5.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4" +checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a" dependencies = [ "error-code", ] -[[package]] -name = "clipboard_macos" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b7f4aaa047ba3c3630b080bb9860894732ff23e2aee290a418909aa6d5df38f" -dependencies = [ - "objc2 0.5.2", - "objc2-app-kit 0.2.2", - "objc2-foundation 0.2.2", -] - -[[package]] -name = "clipboard_wayland" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "003f886bc4e2987729d10c1db3424e7f80809f3fc22dbc16c685738887cb37b8" -dependencies = [ - "smithay-clipboard", -] - -[[package]] -name = "clipboard_x11" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd63e33452ffdafd39924c4f05a5dd1e94db646c779c6bd59148a3d95fff5ad4" -dependencies = [ - "thiserror 2.0.18", - "x11rb", -] - [[package]] name = "codespan-reporting" -version = "0.11.1" +version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3538270d33cc669650c4b093848450d380def10c331d38c768e34cac80576e6e" +checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681" dependencies = [ + "serde", "termcolor", "unicode-width", ] @@ -801,42 +766,11 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" -[[package]] -name = "com" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e17887fd17353b65b1b2ef1c526c83e26cd72e74f598a8dc1bee13a48f3d9f6" -dependencies = [ - "com_macros", -] - -[[package]] -name = "com_macros" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d375883580a668c7481ea6631fc1a8863e33cc335bf56bfad8d7e6d4b04b13a5" -dependencies = [ - "com_macros_support", - "proc-macro2", - "syn 1.0.109", -] - -[[package]] -name = "com_macros_support" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad899a1087a9296d5644792d7cb72b8e34c1bec8e7d4fbc002230169a6e8710c" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", -] - [[package]] name = "combine" -version = "4.6.7" +version = "4.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" dependencies = [ "bytes", "memchr", @@ -852,13 +786,32 @@ dependencies = [ ] [[package]] -name = "const-oid" -version = "0.9.6" +name = "console_error_panic_hook" +version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" +checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc" +dependencies = [ + "cfg-if", + "wasm-bindgen", +] [[package]] -name = "core-foundation" +name = "constant_time_eq" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" + +[[package]] +name = "constant_time_eq" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "144e7f1de087984240b7816d47f698b414979faa6f40839c5b86d6bd47db57b7" +dependencies = [ + "rustversion", +] + +[[package]] +name = "core-foundation" version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" @@ -908,27 +861,10 @@ dependencies = [ ] [[package]] -name = "cosmic-text" -version = "0.12.1" +name = "core_detect" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59fd57d82eb4bfe7ffa9b1cec0c05e2fd378155b47f255a67983cb4afe0e80c2" -dependencies = [ - "bitflags 2.13.0", - "fontdb", - "log", - "rangemap", - "rayon", - "rustc-hash 1.1.0", - "rustybuzz", - "self_cell", - "swash", - "sys-locale", - "ttf-parser 0.21.1", - "unicode-bidi", - "unicode-linebreak", - "unicode-script", - "unicode-segmentation", -] +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" [[package]] name = "cpufeatures" @@ -940,38 +876,28 @@ dependencies = [ ] [[package]] -name = "crc32fast" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" -dependencies = [ - "cfg-if", -] - -[[package]] -name = "crossbeam-deque" -version = "0.8.6" +name = "cpufeatures" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" dependencies = [ - "crossbeam-epoch", - "crossbeam-utils", + "libc", ] [[package]] -name = "crossbeam-epoch" -version = "0.9.20" +name = "crc32fast" +version = "1.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f" +checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945" dependencies = [ - "crossbeam-utils", + "cfg-if", ] [[package]] name = "crossbeam-utils" -version = "0.8.21" +version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" [[package]] name = "crunchy" @@ -979,18 +905,6 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" -[[package]] -name = "crypto-bigint" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" -dependencies = [ - "generic-array", - "rand_core 0.6.4", - "subtle", - "zeroize", -] - [[package]] name = "crypto-common" version = "0.1.7" @@ -1001,24 +915,6 @@ dependencies = [ "typenum", ] -[[package]] -name = "ctor" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83cf0d42651b16c6dfe68685716d18480d18a9c39c62d76e8cf3eb6ed5d8bcbf" -dependencies = [ - "dtor", -] - -[[package]] -name = "ctr" -version = "0.9.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" -dependencies = [ - "cipher", -] - [[package]] name = "cursor-icon" version = "1.2.0" @@ -1026,64 +922,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" [[package]] -name = "curve25519-dalek" -version = "4.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" -dependencies = [ - "cfg-if", - "cpufeatures", - "curve25519-dalek-derive", - "digest", - "fiat-crypto", - "rustc_version", - "subtle", - "zeroize", -] - -[[package]] -name = "curve25519-dalek-derive" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.118", -] - -[[package]] -name = "d3d12" -version = "0.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e3d747f100290a1ca24b752186f61f6637e1deffe3bf6320de6fcb29510a307" -dependencies = [ - "bitflags 2.13.0", - "libloading 0.8.9", - "winapi", -] - -[[package]] -name = "dark-light" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a76fa97167fa740dcdbfe18e8895601e1bc36525f09b044e00916e717c03a3c" -dependencies = [ - "dconf_rs", - "detect-desktop-environment", - "dirs", - "objc", - "rust-ini", - "web-sys", - "winreg 0.10.1", - "zbus 4.4.0", -] - -[[package]] -name = "dconf_rs" -version = "0.3.0" +name = "data-url" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7046468a81e6a002061c01e6a7c83139daf91b11c30e66795b13217c2d885c8b" +checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" [[package]] name = "deadpool" @@ -1103,34 +945,6 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b" -[[package]] -name = "der" -version = "0.7.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" -dependencies = [ - "const-oid", - "pem-rfc7468", - "zeroize", -] - -[[package]] -name = "derive_arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.118", -] - -[[package]] -name = "detect-desktop-environment" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21d8ad60dd5b13a4ee6bd8fa2d5d88965c597c67bce32b5fc49c94f55cb50810" - [[package]] name = "digest" version = "0.10.7" @@ -1138,9 +952,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", - "const-oid", "crypto-common", - "subtle", ] [[package]] @@ -1149,27 +961,7 @@ version = "5.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a49173b84e034382284f27f1af4dcbbd231ffa358c0fe316541a7337f376a35" dependencies = [ - "dirs-sys 0.4.1", -] - -[[package]] -name = "dirs" -version = "4.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca3aa72a6f96ea37bbc5aa912f6788242832f75369bdfdadcb0e38423f100059" -dependencies = [ - "dirs-sys 0.3.7", -] - -[[package]] -name = "dirs-sys" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b1d1d91c932ef41c0f2663aa8b0ca0342d444d842c06914aa0a7e352d0bada6" -dependencies = [ - "libc", - "redox_users", - "winapi", + "dirs-sys", ] [[package]] @@ -1196,21 +988,21 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", "block2 0.6.2", "libc", - "objc2 0.6.4", + "objc2 0.6.5", ] [[package]] name = "displaydoc" -version = "0.2.6" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 3.0.10", ] [[package]] @@ -1219,14 +1011,17 @@ version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a" dependencies = [ - "libloading 0.8.9", + "libloading", ] [[package]] -name = "dlv-list" -version = "0.3.0" +name = "document-features" +version = "0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0688c2a7f92e427f44895cd63841bff7b29f8d7a1648b9e7e07a4a365b2e1257" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] [[package]] name = "downcast-rs" @@ -1240,115 +1035,24 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" -[[package]] -name = "drm" -version = "0.14.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80bc8c5c6c2941f70a55c15f8d9f00f9710ebda3ffda98075f996a0e6c92756f" -dependencies = [ - "bitflags 2.13.0", - "bytemuck", - "drm-ffi", - "drm-fourcc", - "libc", - "rustix 0.38.44", -] - -[[package]] -name = "drm-ffi" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51a91c9b32ac4e8105dec255e849e0d66e27d7c34d184364fb93e469db08f690" -dependencies = [ - "drm-sys", - "rustix 1.1.4", -] - -[[package]] -name = "drm-fourcc" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0aafbcdb8afc29c1a7ee5fbe53b5d62f4565b35a042a662ca9fecd0b54dae6f4" - -[[package]] -name = "drm-sys" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecc8e1361066d91f5ffccff060a3c3be9c3ecde15be2959c1937595f7a82a9f8" -dependencies = [ - "libc", - "linux-raw-sys 0.9.4", -] - -[[package]] -name = "dtor" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edf234dd1594d6dd434a8fb8cada51ddbbc593e40e4a01556a0b31c62da2775b" - -[[package]] -name = "ecdsa" -version = "0.16.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" -dependencies = [ - "der", - "digest", - "elliptic-curve", - "rfc6979", - "signature", - "spki", -] - -[[package]] -name = "ed25519" -version = "2.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" -dependencies = [ - "pkcs8", - "signature", -] - -[[package]] -name = "ed25519-dalek" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" -dependencies = [ - "curve25519-dalek", - "ed25519", - "serde", - "sha2", - "subtle", - "zeroize", -] - [[package]] name = "either" -version = "1.16.0" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] -name = "elliptic-curve" -version = "0.13.8" +name = "encoding_rs" +version = "0.8.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" dependencies = [ - "base16ct", - "crypto-bigint", - "digest", - "ff", - "generic-array", - "group", - "hkdf", - "pem-rfc7468", - "pkcs8", - "rand_core 0.6.4", - "sec1", - "subtle", - "zeroize", + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", ] [[package]] @@ -1375,7 +1079,7 @@ checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 2.0.119", ] [[package]] @@ -1386,15 +1090,15 @@ checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe" [[package]] name = "equivalent" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" [[package]] name = "errno" -version = "0.3.14" +version = "0.3.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" dependencies = [ "libc", "windows-sys 0.61.2", @@ -1402,19 +1106,9 @@ dependencies = [ [[package]] name = "error-code" -version = "3.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dea2df4cf52843e0452895c455a1a2cfbb842a1e7329671acf418fdc53ed4c59" - -[[package]] -name = "etagere" -version = "0.2.15" +version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc89bf99e5dc15954a60f707c1e09d7540e5cd9af85fa75caa0b510bc08c5342" -dependencies = [ - "euclid", - "svg_fmt", -] +checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7" [[package]] name = "euclid" @@ -1427,11 +1121,10 @@ dependencies = [ [[package]] name = "event-listener" -version = "5.4.1" +version = "5.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" dependencies = [ - "concurrent-queue", "parking", "pin-project-lite", ] @@ -1446,21 +1139,6 @@ dependencies = [ "pin-project-lite", ] -[[package]] -name = "exr" -version = "1.74.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4300e043a56aa2cb633c01af81ca8f699a321879a7854d3896a0ba89056363be" -dependencies = [ - "bit_field", - "half", - "lebe", - "miniz_oxide", - "rayon-core", - "smallvec", - "zune-inflate", -] - [[package]] name = "fallible-iterator" version = "0.3.0" @@ -1474,16 +1152,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" [[package]] -name = "fast-srgb8" -version = "1.0.0" +name = "fastrand" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd2e7510819d6fbf51a5545c8f922716ecfb14df168a3242f7d33e0239efe6a1" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" [[package]] -name = "fastrand" -version = "2.4.1" +name = "fax" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" [[package]] name = "fdeflate" @@ -1495,42 +1173,33 @@ dependencies = [ ] [[package]] -name = "ff" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" -dependencies = [ - "rand_core 0.6.4", - "subtle", -] - -[[package]] -name = "fiat-crypto" -version = "0.2.9" +name = "find-msvc-tools" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" [[package]] -name = "find-msvc-tools" -version = "0.1.9" +name = "fixedbitset" +version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" +checksum = "5905ec755cc8386d7928353e4d356d2be3e89e81e5ca01fe630a1ca4d08dc175" [[package]] name = "flate2" -version = "1.1.9" +version = "1.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" dependencies = [ "crc32fast", - "miniz_oxide", + "miniz_oxide 0.9.1", + "zlib-rs", ] [[package]] -name = "float_next_after" -version = "1.0.0" +name = "float-cmp" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8bf7cc16383c4b8d58b9905a8509f02926ce3058053c056376248d958c9df1e8" +checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" [[package]] name = "fnv" @@ -1539,35 +1208,46 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" [[package]] -name = "font-types" -version = "0.7.3" +name = "foldhash" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3971f9a5ca983419cdc386941ba3b9e1feba01a0ab888adf78739feb2798492" -dependencies = [ - "bytemuck", -] +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" [[package]] -name = "fontconfig-parser" -version = "0.5.8" +name = "font-types" +version = "0.12.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646" +checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d" dependencies = [ - "roxmltree", + "bytemuck", ] [[package]] -name = "fontdb" -version = "0.16.2" +name = "fontique" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0299020c3ef3f60f526a4f64ab4a3d4ce116b1acbf24cdd22da0068e5d81dc3" +checksum = "bbf1df16263783918b7da396077521f92b729ef7c429444dfcf03581f1448b77" dependencies = [ - "fontconfig-parser", - "log", + "hashbrown 0.17.2", + "linebender_resource_handle", "memmap2", - "slotmap", - "tinyvec", - "ttf-parser 0.20.0", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-text", + "objc2-foundation 0.3.2", + "parlance", + "read-fonts", + "roxmltree 0.21.2", + "smallvec", + "windows", + "windows-core", + "yeslogic-fontconfig-sys", ] [[package]] @@ -1582,13 +1262,13 @@ dependencies = [ [[package]] name = "foreign-types-macros" -version = "0.2.3" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a5c6c585bc94aaf2c7b51dd4c2ba22680844aba4c687be581871a6f518c5742" +checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 3.0.10", ] [[package]] @@ -1599,18 +1279,18 @@ checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] [[package]] name = "futures" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" dependencies = [ "futures-channel", "futures-core", @@ -1623,9 +1303,9 @@ dependencies = [ [[package]] name = "futures-channel" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" dependencies = [ "futures-core", "futures-sink", @@ -1633,15 +1313,15 @@ dependencies = [ [[package]] name = "futures-core" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" [[package]] name = "futures-executor" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" dependencies = [ "futures-core", "futures-task", @@ -1650,9 +1330,9 @@ dependencies = [ [[package]] name = "futures-io" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" [[package]] name = "futures-lite" @@ -1669,32 +1349,32 @@ dependencies = [ [[package]] name = "futures-macro" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 3.0.10", ] [[package]] name = "futures-sink" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" [[package]] name = "futures-task" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" [[package]] name = "futures-util" -version = "0.3.32" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-channel", "futures-core", @@ -1715,7 +1395,6 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" dependencies = [ "typenum", "version_check", - "zeroize", ] [[package]] @@ -1724,7 +1403,7 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" dependencies = [ - "rustix 1.1.4", + "rustix 1.1.6", "windows-link", ] @@ -1758,146 +1437,42 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi 6.0.0", -] - -[[package]] -name = "ghash" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" -dependencies = [ - "opaque-debug", - "polyval", + "rand_core", + "wasm-bindgen", ] [[package]] name = "gif" -version = "0.13.3" +version = "0.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ae047235e33e2829703574b54fdec96bfbad892062d97fed2f76022287de61b" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" dependencies = [ "color_quant", "weezl", ] [[package]] -name = "gl_generator" -version = "0.14.0" +name = "gpu-allocator" +version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d" +checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795" dependencies = [ - "khronos_api", + "ash", + "hashbrown 0.16.1", "log", - "xml-rs", + "presser", + "thiserror 2.0.21", + "windows", ] [[package]] -name = "glam" -version = "0.25.0" +name = "h2" +version = "0.4.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "151665d9be52f9bb40fc7966565d39666f2d1e69233571b71b87791c7e0528b3" - -[[package]] -name = "glow" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd348e04c43b32574f2de31c8bb397d96c9fcfa1371bd4ca6d8bdc464ab121b1" -dependencies = [ - "js-sys", - "slotmap", - "wasm-bindgen", - "web-sys", -] - -[[package]] -name = "glutin_wgl_sys" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c8098adac955faa2d31079b65dc48841251f69efd3ac25477903fc424362ead" -dependencies = [ - "gl_generator", -] - -[[package]] -name = "gpu-alloc" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45cf04b2726f02df5508c6de726acdc90cdf97ac771a9a0ffd8ba10a6e696bf9" -dependencies = [ - "bitflags 2.13.0", - "gpu-alloc-types", -] - -[[package]] -name = "gpu-alloc-types" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2bbed164dd10ed526c2e4fe3e721ca4a71c61730e5aafac6844b417b3227058" -dependencies = [ - "bitflags 2.13.0", -] - -[[package]] -name = "gpu-allocator" -version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f56f6318968d03c18e1bcf4857ff88c61157e9da8e47c5f29055d60e1228884" -dependencies = [ - "log", - "presser", - "thiserror 1.0.69", - "winapi", - "windows", -] - -[[package]] -name = "gpu-descriptor" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc11df1ace8e7e564511f53af41f3e42ddc95b56fd07b3f4445d2a6048bc682c" -dependencies = [ - "bitflags 2.13.0", - "gpu-descriptor-types", - "hashbrown 0.14.5", -] - -[[package]] -name = "gpu-descriptor-types" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6bf0b36e6f090b7e1d8a4b49c0cb81c1f8376f72198c65dd3ad9ff3556b8b78c" -dependencies = [ - "bitflags 2.13.0", -] - -[[package]] -name = "group" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" -dependencies = [ - "ff", - "rand_core 0.6.4", - "subtle", -] - -[[package]] -name = "guillotiere" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b62d5865c036cb1393e23c50693df631d3f5d7bcca4c04fe4cc0fd592e74a782" -dependencies = [ - "euclid", - "svg_fmt", -] - -[[package]] -name = "h2" -version = "0.4.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6cb093c84e8bd9b188d4c4a8cb6579fc016968d14c99882163cd3ff402a4f155" +checksum = "b634322c4924093fe6a6e05ecbe5717cd3c6014934455f4ae8e5cf14ba3264a8" dependencies = [ "atomic-waker", "bytes", @@ -1920,56 +1495,58 @@ checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" dependencies = [ "cfg-if", "crunchy", + "num-traits", "zerocopy", ] [[package]] -name = "hashbrown" -version = "0.12.3" +name = "harfrust" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" +checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9" dependencies = [ - "ahash 0.7.8", + "bitflags 2.13.2", + "bytemuck", + "read-fonts", + "smallvec", ] [[package]] name = "hashbrown" -version = "0.14.5" +version = "0.15.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" dependencies = [ - "ahash 0.8.12", - "allocator-api2", + "foldhash 0.1.5", ] [[package]] name = "hashbrown" -version = "0.17.1" +version = "0.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash 0.2.0", +] [[package]] -name = "hashlink" -version = "0.9.1" +name = "hashbrown" +version = "0.17.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" dependencies = [ - "hashbrown 0.14.5", + "foldhash 0.2.0", ] [[package]] -name = "hassle-rs" -version = "0.11.0" +name = "hashlink" +version = "0.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af2a7e73e1f34c48da31fb668a907f250794837e08faa144fd24f0b8b741e890" +checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb" dependencies = [ - "bitflags 2.13.0", - "com", - "libc", - "libloading 0.8.9", - "thiserror 1.0.69", - "widestring", - "winapi", + "hashbrown 0.17.2", ] [[package]] @@ -1980,9 +1557,9 @@ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" [[package]] name = "hermit-abi" -version = "0.5.2" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" [[package]] name = "hex" @@ -1990,35 +1567,11 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" -[[package]] -name = "hexf-parse" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfa686283ad6dd069f105e5ab091b04c62850d3e4cf5d67debad1933f55023df" - -[[package]] -name = "hkdf" -version = "0.12.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" -dependencies = [ - "hmac", -] - -[[package]] -name = "hmac" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" -dependencies = [ - "digest", -] - [[package]] name = "http" -version = "1.4.2" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6970f50e31d6fc17d3fa27329444bfa74e196cf62e95052a3f6fee181dba6425" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" dependencies = [ "bytes", "itoa", @@ -2026,9 +1579,9 @@ dependencies = [ [[package]] name = "http-body" -version = "1.0.1" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" dependencies = [ "bytes", "http", @@ -2036,9 +1589,9 @@ dependencies = [ [[package]] name = "http-body-util" -version = "0.1.3" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" dependencies = [ "bytes", "futures-core", @@ -2061,9 +1614,9 @@ checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" [[package]] name = "hyper" -version = "1.10.1" +version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55281c53a1894c864990125767da440a4e630446785086f52523b20033b74498" +checksum = "229c6ff5584df4c6becbfe00567128bac768c8cd32ebc8a8366bd81ed072e8f3" dependencies = [ "atomic-waker", "bytes", @@ -2083,9 +1636,9 @@ dependencies = [ [[package]] name = "hyper-util" -version = "0.1.20" +version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" dependencies = [ "bytes", "http", @@ -2095,195 +1648,11 @@ dependencies = [ "tokio", ] -[[package]] -name = "iced" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88acfabc84ec077eaf9ede3457ffa3a104626d79022a9bf7f296093b1d60c73f" -dependencies = [ - "iced_core", - "iced_futures", - "iced_renderer", - "iced_widget", - "iced_winit", - "image", - "thiserror 1.0.69", -] - -[[package]] -name = "iced_core" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0013a238275494641bf8f1732a23a808196540dc67b22ff97099c044ae4c8a1c" -dependencies = [ - "bitflags 2.13.0", - "bytes", - "dark-light", - "glam", - "log", - "num-traits", - "once_cell", - "palette", - "rustc-hash 2.1.3", - "smol_str", - "thiserror 1.0.69", - "web-time", -] - -[[package]] -name = "iced_futures" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c04a6745ba2e80f32cf01e034fd00d853aa4f4cd8b91888099cb7aaee0d5d7c" -dependencies = [ - "futures", - "iced_core", - "log", - "rustc-hash 2.1.3", - "tokio", - "wasm-bindgen-futures", - "wasm-timer", -] - -[[package]] -name = "iced_glyphon" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41c3bb56f1820ca252bc1d0994ece33d233a55657c0c263ea7cb16895adbde82" -dependencies = [ - "cosmic-text", - "etagere", - "lru", - "rustc-hash 2.1.3", - "wgpu", -] - -[[package]] -name = "iced_graphics" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba25a18cfa6d5cc160aca7e1b34f73ccdff21680fa8702168c09739767b6c66f" -dependencies = [ - "bitflags 2.13.0", - "bytemuck", - "cosmic-text", - "half", - "iced_core", - "iced_futures", - "image", - "kamadak-exif", - "log", - "lyon_path", - "once_cell", - "raw-window-handle", - "rustc-hash 2.1.3", - "thiserror 1.0.69", - "unicode-segmentation", -] - -[[package]] -name = "iced_renderer" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73558208059f9e622df2bf434e044ee2f838ce75201a023cf0ca3e1244f46c2a" -dependencies = [ - "iced_graphics", - "iced_tiny_skia", - "iced_wgpu", - "log", - "thiserror 1.0.69", -] - -[[package]] -name = "iced_runtime" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "348b5b2c61c934d88ca3b0ed1ed913291e923d086a66fa288ce9669da9ef62b5" -dependencies = [ - "bytes", - "iced_core", - "iced_futures", - "raw-window-handle", - "thiserror 1.0.69", -] - -[[package]] -name = "iced_tiny_skia" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c625d368284fcc43b0b36b176f76eff1abebe7959dd58bd8ce6897d641962a50" -dependencies = [ - "bytemuck", - "cosmic-text", - "iced_graphics", - "kurbo", - "log", - "rustc-hash 2.1.3", - "softbuffer", - "tiny-skia", -] - -[[package]] -name = "iced_wgpu" -version = "0.13.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15708887133671d2bcc6c1d01d1f176f43a64d6cdc3b2bf893396c3ee498295f" -dependencies = [ - "bitflags 2.13.0", - "bytemuck", - "futures", - "glam", - "guillotiere", - "iced_glyphon", - "iced_graphics", - "log", - "lyon", - "once_cell", - "rustc-hash 2.1.3", - "thiserror 1.0.69", - "wgpu", -] - -[[package]] -name = "iced_widget" -version = "0.13.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81429e1b950b0e4bca65be4c4278fea6678ea782030a411778f26fa9f8983e1d" -dependencies = [ - "iced_renderer", - "iced_runtime", - "num-traits", - "once_cell", - "rustc-hash 2.1.3", - "thiserror 1.0.69", - "unicode-segmentation", -] - -[[package]] -name = "iced_winit" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f44cd4e1c594b6334f409282937bf972ba14d31fedf03c23aa595d982a2fda28" -dependencies = [ - "iced_futures", - "iced_graphics", - "iced_runtime", - "log", - "rustc-hash 2.1.3", - "thiserror 1.0.69", - "tracing", - "wasm-bindgen-futures", - "web-sys", - "winapi", - "window_clipboard", - "winit", -] - [[package]] name = "icu_collections" -version = "2.2.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" dependencies = [ "displaydoc", "potential_utf", @@ -2295,22 +1664,43 @@ dependencies = [ [[package]] name = "icu_locale_core" -version = "2.2.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" dependencies = [ "displaydoc", "litemap", + "serde", "tinystr", "writeable", "zerovec", ] +[[package]] +name = "icu_locale_fallback" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "406e9ae5b95d8aa37db6293405931b766a6172d1848daee22d70eb44aa78a43c" +dependencies = [ + "icu_locale_core", + "icu_locale_fallback_data", + "icu_provider", + "potential_utf", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locale_fallback_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3632ebbd0c5c3637ba1a40bdf8288f2cb9d2268e73441a69d5fc73d7cfbaa87c" + [[package]] name = "icu_normalizer" -version = "2.2.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" dependencies = [ "icu_collections", "icu_normalizer_data", @@ -2322,16 +1712,17 @@ dependencies = [ [[package]] name = "icu_normalizer_data" -version = "2.2.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" [[package]] name = "icu_properties" -version = "2.2.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" dependencies = [ + "displaydoc", "icu_collections", "icu_locale_core", "icu_properties_data", @@ -2342,18 +1733,20 @@ dependencies = [ [[package]] name = "icu_properties_data" -version = "2.2.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" [[package]] name = "icu_provider" -version = "2.2.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" dependencies = [ "displaydoc", "icu_locale_core", + "serde", + "stable_deref_trait", "writeable", "yoke", "zerofrom", @@ -2361,6 +1754,29 @@ dependencies = [ "zerovec", ] +[[package]] +name = "icu_segmenter" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61b195dc605f81aa181bec9b3bd14e26cc71b903e4644f6af578ca9772c7a710" +dependencies = [ + "icu_collections", + "icu_locale_fallback", + "icu_provider", + "icu_segmenter_data", + "potential_utf", + "smallvec", + "utf8_iter", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_segmenter_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "913a7d294ad056474749152107309fdee3ec17d2482d1ab70fdc61a81c64b9a3" + [[package]] name = "idna" version = "1.1.0" @@ -2391,41 +1807,54 @@ dependencies = [ "bytemuck", "byteorder", "color_quant", - "exr", - "gif", "jpeg-decoder", "num-traits", - "png", - "qoi", - "tiff", + "png 0.17.16", ] [[package]] -name = "indexmap" -version = "2.14.0" +name = "image" +version = "0.25.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" dependencies = [ - "equivalent", - "hashbrown 0.17.1", + "bytemuck", + "byteorder-lite", + "color_quant", + "gif", + "image-webp", + "moxcms", + "num-traits", + "png 0.18.1", + "tiff", + "zune-core", + "zune-jpeg", ] [[package]] -name = "inout" -version = "0.1.4" +name = "image-webp" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" dependencies = [ - "generic-array", + "byteorder-lite", + "quick-error 2.0.1", ] [[package]] -name = "instant" -version = "0.1.13" +name = "imagesize" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edcd27d72f2f071c64249075f42e205ff93c9a4c5f6c6da53e79ed9f9832c285" + +[[package]] +name = "indexmap" +version = "2.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ - "cfg-if", + "equivalent", + "hashbrown 0.17.2", ] [[package]] @@ -2436,9 +1865,9 @@ checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" [[package]] name = "itoa" -version = "1.0.18" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" [[package]] name = "jni" @@ -2452,7 +1881,7 @@ dependencies = [ "jni-sys 0.4.1", "log", "simd_cesu8", - "thiserror 2.0.18", + "thiserror 2.0.21", "walkdir", "windows-link", ] @@ -2467,7 +1896,7 @@ dependencies = [ "quote", "rustc_version", "simd_cesu8", - "syn 2.0.118", + "syn 2.0.119", ] [[package]] @@ -2495,7 +1924,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" dependencies = [ "quote", - "syn 2.0.118", + "syn 2.0.119", ] [[package]] @@ -2513,87 +1942,40 @@ name = "jpeg-decoder" version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00810f1d8b74be64b13dbf3db89ac67740615d6c891f0e7b6179326533011a07" -dependencies = [ - "rayon", -] [[package]] name = "js-sys" -version = "0.3.103" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53b44bfcdb3f8d5837a46dae1ca9660a837176eee74a28b229bc626816589102" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ "cfg-if", "futures-util", "wasm-bindgen", ] -[[package]] -name = "kamadak-exif" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef4fc70d0ab7e5b6bafa30216a6b48705ea964cdfc29c050f2412295eba58077" -dependencies = [ - "mutate_once", -] - -[[package]] -name = "khronos-egl" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76" -dependencies = [ - "libc", - "libloading 0.8.9", - "pkg-config", -] - -[[package]] -name = "khronos_api" -version = "3.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" - [[package]] name = "kurbo" -version = "0.10.4" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1618d4ebd923e97d67e7cd363d80aef35fe961005cbbbb3d2dad8bdd1bc63440" +checksum = "c62026ae44756f8a599ba21140f350303d4f08dcdcc71b5ad9c9bb8128c13c62" dependencies = [ "arrayvec", + "euclid", "smallvec", ] [[package]] name = "lazy_static" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" -dependencies = [ - "spin", -] - -[[package]] -name = "lebe" -version = "0.5.3" +version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" [[package]] name = "libc" -version = "0.2.186" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" - -[[package]] -name = "libloading" -version = "0.7.4" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f" -dependencies = [ - "cfg-if", - "winapi", -] +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "libloading" @@ -2613,21 +1995,21 @@ checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" [[package]] name = "libredox" -version = "0.1.18" +version = "0.1.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c943259e342f1e06ff2da7a83eabdfe7f92ce10262688dbf1895ff0b3e6e4652" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", "libc", "plain", - "redox_syscall 0.9.0", + "redox_syscall 0.9.5", ] [[package]] name = "libsqlite3-sys" -version = "0.30.1" +version = "0.40.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" +checksum = "b06e69070b7e12262b0cd90832f0a7396f142a2b330181255562decf9f0c6215" dependencies = [ "cc", "pkg-config", @@ -2635,16 +2017,16 @@ dependencies = [ ] [[package]] -name = "linux-raw-sys" -version = "0.4.15" +name = "linebender_resource_handle" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" +checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linux-raw-sys" -version = "0.9.4" +version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" [[package]] name = "linux-raw-sys" @@ -2654,9 +2036,15 @@ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" [[package]] name = "litemap" -version = "0.8.2" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "litrs" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" +checksum = "02b614978e47ce529faee66579f2b2fe19c94aa96d910a6a9a8043b2b02d8175" [[package]] name = "lock_api" @@ -2669,15 +2057,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.33" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" - -[[package]] -name = "lru" -version = "0.12.5" +version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" [[package]] name = "lua-src" @@ -2698,67 +2080,6 @@ dependencies = [ "which", ] -[[package]] -name = "lyon" -version = "1.0.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd0578bdecb7d6d88987b8b2b1e3a4e2f81df9d0ece1078623324a567904e7b7" -dependencies = [ - "lyon_algorithms", - "lyon_tessellation", -] - -[[package]] -name = "lyon_algorithms" -version = "1.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8575c0d003ae459399623c4def180c63b77f343b1a7fee64f249b349e7699a31" -dependencies = [ - "lyon_path", - "num-traits", -] - -[[package]] -name = "lyon_geom" -version = "1.0.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4336502e29e32af93cf2dad2214ed6003c17ceb5bd499df77b1de663b9042b92" -dependencies = [ - "arrayvec", - "euclid", - "num-traits", -] - -[[package]] -name = "lyon_path" -version = "1.0.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c463f9c428b7fc5ec885dcd39ce4aa61e29111d0e33483f6f98c74e89d8621e" -dependencies = [ - "lyon_geom", - "num-traits", -] - -[[package]] -name = "lyon_tessellation" -version = "1.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e43b7e44161571868f5c931d12583592c223c5583eef86b08aa02b7048a3552" -dependencies = [ - "float_next_after", - "lyon_path", - "num-traits", -] - -[[package]] -name = "malloc_buf" -version = "0.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb" -dependencies = [ - "libc", -] - [[package]] name = "matchers" version = "0.2.0" @@ -2780,15 +2101,15 @@ dependencies = [ [[package]] name = "memchr" -version = "2.8.2" +version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88904434abc2901f197fe8cc55f0445e7ded921dba5911dad2e2b39b48e663c4" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] name = "memmap2" -version = "0.9.11" +version = "0.9.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" dependencies = [ "libc", ] @@ -2803,25 +2124,20 @@ dependencies = [ ] [[package]] -name = "metal" -version = "0.27.0" +name = "miniz_oxide" +version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c43f73953f8cbe511f021b58f18c3ce1c3d1ae13fe953293e13345bf83217f25" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" dependencies = [ - "bitflags 2.13.0", - "block", - "core-graphics-types", - "foreign-types", - "log", - "objc", - "paste", + "adler2", + "simd-adler32", ] [[package]] name = "miniz_oxide" -version = "0.8.9" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" dependencies = [ "adler2", "simd-adler32", @@ -2829,9 +2145,9 @@ dependencies = [ [[package]] name = "mio" -version = "1.2.1" +version = "1.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02bd0af71c67b473010cbbc60715ee815645a4dc942899111f494b4b737d6fda" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" dependencies = [ "libc", "wasi", @@ -2848,7 +2164,7 @@ dependencies = [ "either", "mlua-sys", "num-traits", - "parking_lot 0.12.5", + "parking_lot", "rustc-hash 2.1.3", "rustversion", ] @@ -2873,6 +2189,8 @@ dependencies = [ "anyhow", "clap", "modrix-core", + "modrix-il2cpp", + "modrix-interop-gen", "modrix-ipc", "modrix-mcp", "modrix-plugin", @@ -2898,10 +2216,10 @@ dependencies = [ "serde_json", "sha2", "tempfile", - "thiserror 2.0.18", + "thiserror 2.0.21", "toml", "tracing", - "winreg 0.52.0", + "winreg", "zip", ] @@ -2916,24 +2234,30 @@ dependencies = [ "modrix-core", "rustls", "rustls-native-certs", - "rustls-rustcrypto", "serde", "serde_json", "sha2", "tempfile", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "tokio-rustls", "tracing", "wiremock", ] +[[package]] +name = "modrix-ecma335" +version = "0.1.0-beta.3" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "modrix-gui" version = "0.1.0-beta.3" dependencies = [ - "iced", - "image", + "anyhow", + "image 0.24.9", "modrix-core", "modrix-download", "modrix-ipc", @@ -2941,13 +2265,32 @@ dependencies = [ "modrix-registry", "modrix-service", "modrix-update", - "rfd", + "rune", + "rune-kit", + "serde", + "serde_json", "tempfile", "tokio", "tracing", "tracing-subscriber", ] +[[package]] +name = "modrix-il2cpp" +version = "0.1.0-beta.3" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "modrix-interop-gen" +version = "0.1.0-beta.3" +dependencies = [ + "modrix-ecma335", + "modrix-il2cpp", + "thiserror 2.0.21", +] + [[package]] name = "modrix-ipc" version = "0.1.0-beta.3" @@ -2956,7 +2299,7 @@ dependencies = [ "serde", "serde_json", "tempfile", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", ] @@ -2982,9 +2325,9 @@ version = "0.1.0-beta.3" dependencies = [ "mlua", "modrix-core", - "roxmltree", + "roxmltree 0.20.0", "tempfile", - "thiserror 2.0.18", + "thiserror 2.0.21", "tracing", ] @@ -3008,7 +2351,7 @@ dependencies = [ "serde_json", "sha2", "tempfile", - "thiserror 2.0.18", + "thiserror 2.0.21", "tokio", "toml", "tracing", @@ -3023,6 +2366,8 @@ dependencies = [ "modrix-download", "modrix-ipc", "modrix-plugin", + "serde", + "serde_json", "tempfile", "tokio", "tracing", @@ -3040,34 +2385,61 @@ dependencies = [ "semver", "serde", "serde_json", - "thiserror 2.0.18", + "thiserror 2.0.21", "tracing", ] [[package]] -name = "mutate_once" -version = "0.1.2" +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13d2233c9842d08cfe13f9eac96e207ca6a2ea10b80259ebe8ad0268be27d2af" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" [[package]] name = "naga" -version = "0.19.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50e3524642f53d9af419ab5e8dd29d3ba155708267667c2f3f06c88c9e130843" +version = "30.0.1" +source = "git+https://github.com/anomalyco/rune?rev=e6f70eb09762180b86dcef912fe169a315bc31b7#e6f70eb09762180b86dcef912fe169a315bc31b7" dependencies = [ - "bit-set 0.5.3", - "bitflags 2.13.0", + "arrayvec", + "bit-set 0.10.0", + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", "codespan-reporting", - "hexf-parse", + "half", + "hashbrown 0.17.2", "indexmap", + "libm", "log", + "naga-types", "num-traits", + "once_cell", "rustc-hash 1.1.0", "spirv", - "termcolor", - "thiserror 1.0.69", - "unicode-xid", + "thiserror 2.0.21", + "unicode-ident", +] + +[[package]] +name = "naga-types" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14474170feb673cfb18b3565111a9869797cc1d290fb9ec969c53f5e1e231c6d" +dependencies = [ + "hashbrown 0.17.2", + "indexmap", + "rustc-hash 1.1.0", + "thiserror 2.0.21", ] [[package]] @@ -3076,10 +2448,10 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", "jni-sys 0.3.1", "log", - "ndk-sys 0.6.0+11769913", + "ndk-sys", "num_enum", "raw-window-handle", "thiserror 1.0.69", @@ -3091,15 +2463,6 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" -[[package]] -name = "ndk-sys" -version = "0.5.0+25.2.9519653" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c196769dd60fd4f363e11d948139556a344e79d451aeb2fa2fd040738ef7691" -dependencies = [ - "jni-sys 0.3.1", -] - [[package]] name = "ndk-sys" version = "0.6.0+11769913" @@ -3111,60 +2474,32 @@ dependencies = [ [[package]] name = "nix" -version = "0.29.0" +version = "0.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" +checksum = "77730ed34f01f4990cb2ea67fec715ecebc6fab9a6396cf83c5529b13f581bdc" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", "cfg-if", - "cfg_aliases 0.2.1", + "cfg_aliases", "libc", - "memoffset", -] - -[[package]] -name = "nu-ansi-term" -version = "0.50.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "num-bigint-dig" -version = "0.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" -dependencies = [ - "lazy_static", - "libm", - "num-integer", - "num-iter", - "num-traits", - "rand 0.8.6", - "smallvec", - "zeroize", ] [[package]] -name = "num-integer" -version = "0.1.46" +name = "nom" +version = "8.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" dependencies = [ - "num-traits", + "memchr", ] [[package]] -name = "num-iter" -version = "0.1.45" +name = "nu-ansi-term" +version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "autocfg", - "num-integer", - "num-traits", + "windows-sys 0.61.2", ] [[package]] @@ -3206,17 +2541,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.118", -] - -[[package]] -name = "objc" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1" -dependencies = [ - "malloc_buf", - "objc_exception", + "syn 2.0.119", ] [[package]] @@ -3227,9 +2552,9 @@ checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310" [[package]] name = "objc2" -version = "0.5.2" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804" +checksum = "19d5490aaf8f1d7cf7688dfa9b0ce07900e168852c45cd2c03f534dfd27cfd0b" dependencies = [ "objc-sys", "objc2-encode", @@ -3237,9 +2562,9 @@ dependencies = [ [[package]] name = "objc2" -version = "0.6.4" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" dependencies = [ "objc2-encode", ] @@ -3250,10 +2575,10 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", "block2 0.5.1", "libc", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-core-data", "objc2-core-image", "objc2-foundation 0.2.2", @@ -3266,9 +2591,26 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", "block2 0.6.2", - "objc2 0.6.4", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-av-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "478ae33fcac9df0a18db8302387c666b8ef08a3e2d62b510ca4fc278a384b6c0" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-media", + "objc2-core-video", "objc2-foundation 0.3.2", ] @@ -3278,9 +2620,9 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-core-location", "objc2-foundation 0.2.2", ] @@ -3292,19 +2634,41 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a5ff520e9c33812fd374d8deecef01d4a840e7b41862d849513de77e44aa4889" dependencies = [ "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-core-audio" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1eebcea8b0dbff5f7c8504f3107c68fc061a3eb44932051c8cf8a68d969c3b2" +dependencies = [ + "dispatch2", + "objc2 0.6.5", + "objc2-core-audio-types", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-core-audio-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a89f2ec274a0cf4a32642b2991e8b351a404d290da87bb6a9a9d8632490bd1c" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", +] + [[package]] name = "objc2-core-data" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-foundation 0.2.2", ] @@ -3314,9 +2678,9 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", "dispatch2", - "objc2 0.6.4", + "objc2 0.6.5", ] [[package]] @@ -3325,9 +2689,9 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", "dispatch2", - "objc2 0.6.4", + "objc2 0.6.5", "objc2-core-foundation", "objc2-io-surface", ] @@ -3339,9 +2703,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80" dependencies = [ "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-foundation 0.2.2", - "objc2-metal", + "objc2-metal 0.2.2", ] [[package]] @@ -3351,28 +2715,67 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "000cfee34e683244f284252ee206a27953279d370e309649dc3ee317b37e5781" dependencies = [ "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-contacts", "objc2-foundation 0.2.2", ] [[package]] -name = "objc2-encode" -version = "4.1.0" +name = "objc2-core-media" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" +checksum = "05ec576860167a15dd9fce7fbee7512beb4e31f532159d3482d1f9c6caedf31d" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2 0.6.5", + "objc2-core-audio", + "objc2-core-audio-types", + "objc2-core-foundation", + "objc2-core-video", +] [[package]] -name = "objc2-foundation" -version = "0.2.2" +name = "objc2-core-text" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d" +dependencies = [ + "bitflags 2.13.2", + "objc2-core-foundation", +] + +[[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.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-io-surface", + "objc2-metal 0.3.2", +] + +[[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.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", "block2 0.5.1", "dispatch", "libc", - "objc2 0.5.2", + "objc2 0.5.3", ] [[package]] @@ -3381,8 +2784,8 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" dependencies = [ - "bitflags 2.13.0", - "objc2 0.6.4", + "bitflags 2.13.2", + "objc2 0.6.5", "objc2-core-foundation", ] @@ -3392,8 +2795,8 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" dependencies = [ - "bitflags 2.13.0", - "objc2 0.6.4", + "bitflags 2.13.2", + "objc2 0.6.5", "objc2-core-foundation", ] @@ -3404,7 +2807,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398" dependencies = [ "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-app-kit 0.2.2", "objc2-foundation 0.2.2", ] @@ -3415,23 +2818,36 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-foundation 0.2.2", ] +[[package]] +name = "objc2-metal" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", +] + [[package]] name = "objc2-quartz-core" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-foundation 0.2.2", - "objc2-metal", + "objc2-metal 0.2.2", ] [[package]] @@ -3440,10 +2856,12 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" dependencies = [ - "bitflags 2.13.0", - "objc2 0.6.4", + "bitflags 2.13.2", + "objc2 0.6.5", "objc2-core-foundation", + "objc2-core-graphics", "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", ] [[package]] @@ -3452,7 +2870,7 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0a684efe3dec1b305badae1a28f6555f6ddd3bb2c2267896782858d5a78404dc" dependencies = [ - "objc2 0.5.2", + "objc2 0.5.3", "objc2-foundation 0.2.2", ] @@ -3462,9 +2880,9 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-cloud-kit", "objc2-core-data", "objc2-core-image", @@ -3484,7 +2902,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "44fa5f9748dbfe1ca6c0b79ad20725a11eca7c2218bceb4b005cb1be26273bfe" dependencies = [ "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-foundation 0.2.2", ] @@ -3494,20 +2912,20 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", "block2 0.5.1", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-core-location", "objc2-foundation 0.2.2", ] [[package]] -name = "objc_exception" -version = "0.1.2" +name = "object" +version = "0.39.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad970fb455818ad6cba4c122ad012fae53ae8b4795f86378bce65e4f6bab2ca4" +checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" dependencies = [ - "cc", + "memchr", ] [[package]] @@ -3522,17 +2940,11 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" -[[package]] -name = "opaque-debug" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" - [[package]] name = "openssl-probe" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" [[package]] name = "option-ext" @@ -3540,6 +2952,12 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" +[[package]] +name = "opuscule" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "418827b94acaa183462024021324b6e733086466375604eb60e584c7acd4462c" + [[package]] name = "orbclient" version = "0.3.55" @@ -3551,13 +2969,12 @@ dependencies = [ ] [[package]] -name = "ordered-multimap" -version = "0.4.3" +name = "ordered-float" +version = "5.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccd746e37177e1711c20dd619a1620f34f5c8b569c53590a72dedd5344d8924a" +checksum = "7f59006ce1e204c30956638535b74d317bca99477b9356dfaec54c37f6f600ab" dependencies = [ - "dlv-list", - "hashbrown 0.12.3", + "num-traits", ] [[package]] @@ -3571,60 +2988,13 @@ dependencies = [ ] [[package]] -name = "owned_ttf_parser" -version = "0.25.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b" -dependencies = [ - "ttf-parser 0.25.1", -] - -[[package]] -name = "p256" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" -dependencies = [ - "ecdsa", - "elliptic-curve", - "primeorder", - "sha2", -] - -[[package]] -name = "p384" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6" -dependencies = [ - "ecdsa", - "elliptic-curve", - "primeorder", - "sha2", -] - -[[package]] -name = "palette" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cbf71184cc5ecc2e4e1baccdb21026c20e5fc3dcf63028a086131b3ab00b6e6" -dependencies = [ - "approx", - "fast-srgb8", - "palette_derive", - "phf", -] - -[[package]] -name = "palette_derive" -version = "0.7.6" +name = "os_pipe" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5030daf005bface118c096f510ffb781fc28f9ab6a32ab224d8631be6851d30" +checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ - "by_address", - "proc-macro2", - "quote", - "syn 2.0.118", + "libc", + "windows-sys 0.61.2", ] [[package]] @@ -3633,17 +3003,6 @@ version = "2.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" -[[package]] -name = "parking_lot" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d17b78036a60663b797adeaee46f5c9dfebb86948d1255007a1d6be0271ff99" -dependencies = [ - "instant", - "lock_api", - "parking_lot_core 0.8.6", -] - [[package]] name = "parking_lot" version = "0.12.5" @@ -3651,49 +3010,75 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" dependencies = [ "lock_api", - "parking_lot_core 0.9.12", + "parking_lot_core", ] [[package]] name = "parking_lot_core" -version = "0.8.6" +version = "0.9.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60a2cfe6f0ad2bfc16aefa463b497d5c7a5ecd44a23efa72aa342d90177356dc" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" dependencies = [ "cfg-if", - "instant", "libc", - "redox_syscall 0.2.16", + "redox_syscall 0.5.18", "smallvec", - "winapi", + "windows-link", ] [[package]] -name = "parking_lot_core" -version = "0.9.12" +name = "parlance" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +checksum = "73072a9470554c8e794778acece2312661218aaabb635600957d952cf01c716e" + +[[package]] +name = "parley" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61bd0c0c1737f0b3d3726dc06b225083af213b61913e4fbae1670613a106c6ce" dependencies = [ - "cfg-if", - "libc", - "redox_syscall 0.5.18", + "fontique", + "hashbrown 0.17.2", + "linebender_resource_handle", + "parlance", + "parley_engine", "smallvec", - "windows-link", ] [[package]] -name = "paste" -version = "1.0.15" +name = "parley_data" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" +checksum = "c43b63f808f6cc8f4a3b07de0d62a977bddd2e0bb5c232bd9e93ba8ef92e5e4b" +dependencies = [ + "icu_collections", + "icu_properties", +] [[package]] -name = "pem-rfc7468" -version = "0.7.0" +name = "parley_emoji" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +checksum = "9c4482d912d7671a7cd2089794f90ef3bb5f5f8c738230fb0fcd50fa020f0ed3" + +[[package]] +name = "parley_engine" +version = "0.12.0" +source = "git+https://github.com/anomalyco/rune?rev=e6f70eb09762180b86dcef912fe169a315bc31b7#e6f70eb09762180b86dcef912fe169a315bc31b7" dependencies = [ - "base64ct", + "fontique", + "harfrust", + "hashbrown 0.17.2", + "icu_locale_core", + "icu_normalizer", + "icu_properties", + "icu_segmenter", + "linebender_resource_handle", + "parlance", + "parley_data", + "parley_emoji", + "skrifa", ] [[package]] @@ -3702,79 +3087,91 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "petgraph" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" +dependencies = [ + "fixedbitset", + "hashbrown 0.15.5", + "indexmap", +] + [[package]] name = "phf" -version = "0.11.3" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" dependencies = [ "phf_macros", "phf_shared", + "serde", ] [[package]] name = "phf_generator" -version = "0.11.3" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" +checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100" dependencies = [ + "fastrand", "phf_shared", - "rand 0.8.6", ] [[package]] name = "phf_macros" -version = "0.11.3" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216" +checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085" dependencies = [ "phf_generator", "phf_shared", "proc-macro2", "quote", - "syn 2.0.118", + "syn 2.0.119", ] [[package]] name = "phf_shared" -version = "0.11.3" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +checksum = "c6fd9027e2d9319be6349febd1db4e8d02aa544921200c9b777720ac34a3aa89" dependencies = [ "siphasher", ] +[[package]] +name = "pico-args" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315" + [[package]] name = "pin-project" -version = "1.1.13" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +checksum = "a6c2123f4708bbd422630a6dae7c03f678b1ce1f1c99e4c4b3beac69c8174cc9" dependencies = [ "pin-project-internal", ] [[package]] name = "pin-project-internal" -version = "1.1.13" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +checksum = "358938fd6df944c1e44bb328b60fb275f13c804aac47ba26a1165d45a3f87756" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 3.0.10", ] [[package]] name = "pin-project-lite" -version = "0.2.17" +version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" - -[[package]] -name = "pin-utils" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" [[package]] name = "piper" @@ -3787,43 +3184,11 @@ dependencies = [ "futures-io", ] -[[package]] -name = "pkcs1" -version = "0.7.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" -dependencies = [ - "der", - "pkcs8", - "spki", -] - -[[package]] -name = "pkcs5" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e847e2c91a18bfa887dd028ec33f2fe6f25db77db3619024764914affe8b69a6" -dependencies = [ - "der", - "spki", -] - -[[package]] -name = "pkcs8" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" -dependencies = [ - "der", - "pkcs5", - "spki", -] - [[package]] name = "pkg-config" -version = "0.3.33" +version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" [[package]] name = "plain" @@ -3841,7 +3206,20 @@ dependencies = [ "crc32fast", "fdeflate", "flate2", - "miniz_oxide", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.13.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", ] [[package]] @@ -3854,86 +3232,62 @@ dependencies = [ "concurrent-queue", "hermit-abi", "pin-project-lite", - "rustix 1.1.4", + "rustix 1.1.6", "windows-sys 0.61.2", ] [[package]] name = "pollster" -version = "0.4.0" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3" +checksum = "7e9b9cf600136f5b976fbc5727d58c26e1ecab8ee23088d44ef1c7af793550ab" [[package]] -name = "poly1305" -version = "0.8.0" +name = "portable-atomic" +version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" -dependencies = [ - "cpufeatures", - "opaque-debug", - "universal-hash", -] +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" [[package]] -name = "polyval" -version = "0.6.2" +name = "portable-atomic-util" +version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" dependencies = [ - "cfg-if", - "cpufeatures", - "opaque-debug", - "universal-hash", + "portable-atomic", ] [[package]] name = "potential_utf" -version = "0.1.5" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" dependencies = [ + "serde_core", + "writeable", "zerovec", ] -[[package]] -name = "ppv-lite86" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" -dependencies = [ - "zerocopy", -] - [[package]] name = "presser" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa" -[[package]] -name = "primeorder" -version = "0.13.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" -dependencies = [ - "elliptic-curve", -] - [[package]] name = "proc-macro-crate" version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" dependencies = [ - "toml_edit 0.25.12+spec-1.1.0", + "toml_edit 0.25.21+spec-1.1.0", ] [[package]] name = "proc-macro2" -version = "1.0.106" +version = "1.0.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" dependencies = [ "unicode-ident", ] @@ -3946,16 +3300,17 @@ checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" [[package]] name = "proptest" -version = "1.11.0" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744" +checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" dependencies = [ - "bit-set 0.8.0", - "bit-vec 0.8.0", - "bitflags 2.13.0", + "bit-set 0.11.1", + "bit-vec 0.10.2", + "bitflags 2.13.2", + "chacha20", + "core_detect", "num-traits", - "rand 0.9.4", - "rand_chacha 0.9.0", + "rand", "rand_xorshift", "regex-syntax", "rusty-fork", @@ -3964,34 +3319,47 @@ dependencies = [ ] [[package]] -name = "qoi" -version = "0.4.1" +name = "psm" +version = "0.1.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001" +checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622" dependencies = [ - "bytemuck", + "ar_archive_writer", + "cc", ] +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + [[package]] name = "quick-error" version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + [[package]] name = "quick-xml" -version = "0.39.4" +version = "0.41.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdcc8dd4e2f670d309a5f0e83fe36dfdc05af317008fea29144da1a2ac858e5e" +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" dependencies = [ "memchr", ] [[package]] name = "quote" -version = "1.0.46" +version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" dependencies = [ "proc-macro2", ] @@ -4010,300 +3378,512 @@ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" [[package]] name = "rand" -version = "0.8.6" +version = "0.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" dependencies = [ - "libc", - "rand_chacha 0.3.1", - "rand_core 0.6.4", + "getrandom 0.4.3", + "rand_core", ] [[package]] -name = "rand" -version = "0.9.4" +name = "rand_core" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_xorshift" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf" dependencies = [ - "rand_chacha 0.9.0", - "rand_core 0.9.5", + "rand_core", ] [[package]] -name = "rand_chacha" -version = "0.3.1" +name = "range-alloc" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08" + +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "raw-window-metal" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135" dependencies = [ - "ppv-lite86", - "rand_core 0.6.4", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", ] [[package]] -name = "rand_chacha" -version = "0.9.0" +name = "read-fonts" +version = "0.41.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709" dependencies = [ - "ppv-lite86", - "rand_core 0.9.5", + "bytemuck", + "font-types", + "once_cell", ] [[package]] -name = "rand_core" -version = "0.6.4" +name = "redox_syscall" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" dependencies = [ - "getrandom 0.2.17", + "bitflags 1.3.2", ] [[package]] -name = "rand_core" +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "redox_syscall" version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" dependencies = [ - "getrandom 0.3.4", + "bitflags 2.13.2", ] [[package]] -name = "rand_xorshift" -version = "0.4.0" +name = "redox_users" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a" +checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" dependencies = [ - "rand_core 0.9.5", + "getrandom 0.2.17", + "libredox", + "thiserror 1.0.69", ] [[package]] -name = "range-alloc" -version = "0.1.5" +name = "regex" +version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08" +checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] [[package]] -name = "rangemap" -version = "1.7.1" +name = "regex-syntax" +version = "0.8.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "973443cf09a9c8656b574a866ab68dfa19f0867d0340648c7d2f6a71b8a8ea68" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" [[package]] -name = "raw-window-handle" -version = "0.6.2" +name = "renderdoc-sys" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" +checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" [[package]] -name = "rayon" -version = "1.12.0" +name = "resvg" +version = "0.45.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +checksum = "a8928798c0a55e03c9ca6c4c6846f76377427d2c1e1f7e6de3c06ae57942df43" dependencies = [ - "either", - "rayon-core", + "log", + "pico-args", + "rgb", + "svgtypes", + "tiny-skia", + "usvg", ] [[package]] -name = "rayon-core" -version = "1.13.0" +name = "rfd" +version = "0.17.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +checksum = "20dafead71c16a34e1ff357ddefc8afc11e7d51d6d2b9fbd07eaa48e3e540220" dependencies = [ - "crossbeam-deque", - "crossbeam-utils", + "block2 0.6.2", + "dispatch2", + "js-sys", + "libc", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "percent-encoding", + "raw-window-handle", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "windows-sys 0.61.2", ] [[package]] -name = "read-fonts" -version = "0.22.7" +name = "rgb" +version = "0.8.53" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69aacb76b5c29acfb7f90155d39759a29496aebb49395830e928a9703d2eec2f" +checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" dependencies = [ "bytemuck", - "font-types", ] [[package]] -name = "redox_syscall" -version = "0.2.16" +name = "ring" +version = "0.17.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" dependencies = [ - "bitflags 1.3.2", + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", ] [[package]] -name = "redox_syscall" -version = "0.4.1" +name = "roxmltree" +version = "0.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" +checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" + +[[package]] +name = "roxmltree" +version = "0.21.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907" dependencies = [ - "bitflags 1.3.2", + "memchr", ] [[package]] -name = "redox_syscall" -version = "0.5.18" +name = "rsqlite-vfs" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +checksum = "353b74f9810d5b085b6c42c9d86a5f0fdb795553235cdd48753b32e3809d18a7" dependencies = [ - "bitflags 2.13.0", + "thiserror 2.0.21", ] [[package]] -name = "redox_syscall" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5102a6aaa05aa011a238e178e6bca86d2cb56fc9f586d37cb80f5bca6e07759" +name = "rune" +version = "0.0.1" +source = "git+https://github.com/anomalyco/rune?rev=e6f70eb09762180b86dcef912fe169a315bc31b7#e6f70eb09762180b86dcef912fe169a315bc31b7" dependencies = [ - "bitflags 2.13.0", + "accesskit", + "accesskit_macos", + "accesskit_unix", + "accesskit_windows", + "arboard", + "async-channel", + "async-executor", + "async-io", + "blake3", + "block2 0.6.2", + "bytemuck", + "console_error_panic_hook", + "futures-lite", + "half", + "image 0.25.10", + "js-sys", + "libc", + "libloading", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-video", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", + "parley", + "png 0.18.1", + "pollster", + "raw-window-handle", + "rfd", + "rune-core", + "rune-edit", + "rune-gpu", + "rune-image", + "rune-media", + "rune-motion", + "rune-spell", + "rune-staging", + "rune-taffy", + "rune-text", + "rustc-demangle", + "rustc-hash 2.1.3", + "serde", + "serde_json", + "taffy", + "unicode-segmentation", + "wasm-bindgen", + "wasm-bindgen-futures", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-plasma", + "wayland-protocols-wlr", + "web-sys", + "wgpu", + "windows", + "windows-core", + "windows-registry", + "windows-sys 0.61.2", + "winit", + "x11rb", + "xkbcommon", + "zbus", + "zeroize", ] [[package]] -name = "redox_users" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" +name = "rune-core" +version = "0.0.1" +source = "git+https://github.com/anomalyco/rune?rev=e6f70eb09762180b86dcef912fe169a315bc31b7#e6f70eb09762180b86dcef912fe169a315bc31b7" dependencies = [ - "getrandom 0.2.17", - "libredox", - "thiserror 1.0.69", + "js-sys", + "libc", + "portable-atomic", + "rune-motion", + "rustc-hash 2.1.3", + "serde", + "serde_json", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "web-time", + "windows-sys 0.61.2", +] + +[[package]] +name = "rune-edit" +version = "0.0.1" +source = "git+https://github.com/anomalyco/rune?rev=e6f70eb09762180b86dcef912fe169a315bc31b7#e6f70eb09762180b86dcef912fe169a315bc31b7" +dependencies = [ + "js-sys", + "parley", + "rune-core", + "rune-text", + "serde_json", + "unicode-segmentation", + "zeroize", ] [[package]] -name = "regex" -version = "1.12.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1292b7759ae1cb9ec195452d1390a074f0cd8541ab7a5a8c31cd6db45d4a6ba" +name = "rune-gpu" +version = "0.0.1" +source = "git+https://github.com/anomalyco/rune?rev=e6f70eb09762180b86dcef912fe169a315bc31b7#e6f70eb09762180b86dcef912fe169a315bc31b7" dependencies = [ - "aho-corasick", - "memchr", - "regex-automata", - "regex-syntax", + "blake3", + "bytemuck", + "libc", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", + "objc2-quartz-core 0.3.2", + "parking_lot", + "pollster", + "raw-window-metal", + "rune-core", + "rune-motion", + "rune-staging", + "wayland-client", + "wayland-protocols", + "wgpu", + "wgpu-naga-bridge", + "windows", + "windows-sys 0.61.2", ] [[package]] -name = "regex-automata" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" +name = "rune-image" +version = "0.0.1" +source = "git+https://github.com/anomalyco/rune?rev=e6f70eb09762180b86dcef912fe169a315bc31b7#e6f70eb09762180b86dcef912fe169a315bc31b7" dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", + "blake3", + "image 0.25.10", + "js-sys", + "moxcms", + "objc2 0.6.5", + "objc2-foundation 0.3.2", + "resvg", + "rune-core", + "wasm-bindgen", + "wasm-bindgen-futures", + "windows-sys 0.61.2", ] [[package]] -name = "regex-syntax" -version = "0.8.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" - -[[package]] -name = "renderdoc-sys" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" +name = "rune-kit" +version = "0.0.1" +source = "git+https://github.com/anomalyco/rune?rev=e6f70eb09762180b86dcef912fe169a315bc31b7#e6f70eb09762180b86dcef912fe169a315bc31b7" +dependencies = [ + "icu_normalizer", + "rune", + "rune-motion", + "unicode-segmentation", +] [[package]] -name = "rfc6979" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +name = "rune-media" +version = "0.0.1" +source = "git+https://github.com/anomalyco/rune?rev=e6f70eb09762180b86dcef912fe169a315bc31b7#e6f70eb09762180b86dcef912fe169a315bc31b7" dependencies = [ - "hmac", - "subtle", + "ash", + "blake3", + "block2 0.6.2", + "bytemuck", + "libc", + "objc2 0.6.5", + "objc2-av-foundation", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-media", + "objc2-core-video", + "objc2-foundation 0.3.2", + "objc2-io-surface", + "objc2-metal 0.3.2", + "opuscule", + "pollster", + "rune-core", + "rune-gpu", + "rune-image", + "rune-staging", + "symphonia", + "wgpu", + "windows", + "windows-sys 0.61.2", ] [[package]] -name = "rfd" -version = "0.15.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef2bee61e6cffa4635c72d7d81a84294e28f0930db0ddcb0f66d10244674ebed" +name = "rune-motion" +version = "0.1.0" +source = "git+https://github.com/anomalyco/rune?rev=e6f70eb09762180b86dcef912fe169a315bc31b7#e6f70eb09762180b86dcef912fe169a315bc31b7" + +[[package]] +name = "rune-spell" +version = "0.0.1" +source = "git+https://github.com/anomalyco/rune?rev=e6f70eb09762180b86dcef912fe169a315bc31b7#e6f70eb09762180b86dcef912fe169a315bc31b7" dependencies = [ - "ashpd", - "block2 0.6.2", - "dispatch2", "js-sys", - "log", - "objc2 0.6.4", "objc2-app-kit 0.3.2", - "objc2-core-foundation", "objc2-foundation 0.3.2", - "pollster", - "raw-window-handle", - "urlencoding", + "rune-core", + "rustc-hash 2.1.3", + "spellbook", + "unicode-segmentation", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", - "windows-sys 0.59.0", + "windows", + "windows-sys 0.61.2", ] [[package]] -name = "ring" -version = "0.17.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +name = "rune-staging" +version = "0.0.1" +source = "git+https://github.com/anomalyco/rune?rev=e6f70eb09762180b86dcef912fe169a315bc31b7#e6f70eb09762180b86dcef912fe169a315bc31b7" dependencies = [ - "cc", - "cfg-if", - "getrandom 0.2.17", - "libc", - "untrusted", - "windows-sys 0.52.0", + "wgpu", + "windows", ] [[package]] -name = "roxmltree" -version = "0.20.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" +name = "rune-taffy" +version = "0.0.1" +source = "git+https://github.com/anomalyco/rune?rev=e6f70eb09762180b86dcef912fe169a315bc31b7#e6f70eb09762180b86dcef912fe169a315bc31b7" +dependencies = [ + "stacker", + "taffy", +] [[package]] -name = "rsa" -version = "0.9.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +name = "rune-text" +version = "0.0.1" +source = "git+https://github.com/anomalyco/rune?rev=e6f70eb09762180b86dcef912fe169a315bc31b7#e6f70eb09762180b86dcef912fe169a315bc31b7" dependencies = [ - "const-oid", - "digest", - "num-bigint-dig", - "num-integer", - "num-traits", - "pkcs1", - "pkcs8", - "rand_core 0.6.4", - "sha2", - "signature", - "spki", - "subtle", + "bytemuck", + "fontique", + "icu_properties", + "icu_segmenter", + "objc2-core-foundation", + "objc2-core-text", + "parley", + "parley_engine", + "rune-core", + "rune-image", + "rune-motion", + "rune-tiny-skia-path", + "rustc-hash 2.1.3", + "skrifa", + "swash", + "unicode-segmentation", + "wasm-bindgen", + "windows", + "windows-core", + "windows-sys 0.61.2", "zeroize", ] +[[package]] +name = "rune-tiny-skia-path" +version = "0.11.4" +source = "git+https://github.com/anomalyco/rune?rev=e6f70eb09762180b86dcef912fe169a315bc31b7#e6f70eb09762180b86dcef912fe169a315bc31b7" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + [[package]] name = "rusqlite" -version = "0.32.1" +version = "0.43.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e" +checksum = "f172c4812a19b26d1c23cdb0070e69db335503dfa378b910eb857386e5b8beba" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", "fallible-iterator", "fallible-streaming-iterator", "hashlink", "libsqlite3-sys", "smallvec", + "sqlite-wasm-rs", ] [[package]] -name = "rust-ini" -version = "0.18.0" +name = "rustc-demangle" +version = "0.1.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6d5f2436026b4f6e79dc829837d467cc7e9a55ee40e750d716713540715a2df" -dependencies = [ - "cfg-if", - "ordered-multimap", -] +checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" [[package]] name = "rustc-hash" @@ -4332,7 +3912,7 @@ version = "0.38.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", "errno", "libc", "linux-raw-sys 0.4.15", @@ -4341,11 +3921,11 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.4" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", "errno", "libc", "linux-raw-sys 0.12.1", @@ -4354,23 +3934,24 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.41" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b92b125634d9b795e7beca796cc790df15a7fb38323bf3196fda83292d06b1f" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "log", "once_cell", + "ring", "rustls-pki-types", - "rustls-webpki 0.103.13", + "rustls-webpki", "subtle", "zeroize", ] [[package]] name = "rustls-native-certs" -version = "0.8.4" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" dependencies = [ "openssl-probe", "rustls-pki-types", @@ -4380,59 +3961,18 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.15.0" +version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "764899a24af3980067ee14bc143654f297b22eaebfe3c7b6b211920a5a59b046" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" dependencies = [ "zeroize", ] -[[package]] -name = "rustls-rustcrypto" -version = "0.0.2-alpha" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f12052947763ab8515f753315357599e9b0b4dab3b8ba15f30f725fe6d025557" -dependencies = [ - "aead", - "aes-gcm", - "chacha20poly1305", - "crypto-common", - "der", - "digest", - "ecdsa", - "ed25519-dalek", - "hmac", - "p256", - "p384", - "paste", - "pkcs8", - "rand_core 0.6.4", - "rsa", - "rustls", - "rustls-pki-types", - "rustls-webpki 0.102.8", - "sec1", - "sha2", - "signature", - "x25519-dalek", -] - -[[package]] -name = "rustls-webpki" -version = "0.102.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64ca1bc8749bd4cf37b5ce386cc146580777b4e8572c7b97baf22c83f444bee9" -dependencies = [ - "ring", - "rustls-pki-types", - "untrusted", -] - [[package]] name = "rustls-webpki" -version = "0.103.13" +version = "0.103.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" dependencies = [ "ring", "rustls-pki-types", @@ -4441,9 +3981,9 @@ dependencies = [ [[package]] name = "rustversion" -version = "1.0.22" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" [[package]] name = "rusty-fork" @@ -4452,28 +3992,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" dependencies = [ "fnv", - "quick-error", + "quick-error 1.2.3", "tempfile", "wait-timeout", ] -[[package]] -name = "rustybuzz" -version = "0.14.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfb9cf8877777222e4a3bc7eb247e398b56baba500c38c1c46842431adc8b55c" -dependencies = [ - "bitflags 2.13.0", - "bytemuck", - "libm", - "smallvec", - "ttf-parser 0.21.1", - "unicode-bidi-mirroring", - "unicode-ccc", - "unicode-properties", - "unicode-script", -] - [[package]] name = "same-file" version = "1.0.6" @@ -4485,9 +4008,9 @@ dependencies = [ [[package]] name = "schannel" -version = "0.1.29" +version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" dependencies = [ "windows-sys 0.61.2", ] @@ -4507,37 +4030,20 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] name = "sctk-adwaita" version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec" +source = "git+https://github.com/anomalyco/rune?rev=e6f70eb09762180b86dcef912fe169a315bc31b7#e6f70eb09762180b86dcef912fe169a315bc31b7" dependencies = [ - "ab_glyph", "log", - "memmap2", - "smithay-client-toolkit 0.19.2", + "smithay-client-toolkit", "tiny-skia", ] -[[package]] -name = "sec1" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" -dependencies = [ - "base16ct", - "der", - "generic-array", - "pkcs8", - "subtle", - "zeroize", -] - [[package]] name = "security-framework" version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", "core-foundation 0.10.1", "core-foundation-sys", "libc", @@ -4554,12 +4060,6 @@ dependencies = [ "libc", ] -[[package]] -name = "self_cell" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b12e76d157a900eb52e81bc6e9f3069344290341720e9178cde2407113ac8d89" - [[package]] name = "semver" version = "1.0.28" @@ -4568,9 +4068,9 @@ checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" [[package]] name = "serde" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ "serde_core", "serde_derive", @@ -4578,29 +4078,29 @@ dependencies = [ [[package]] name = "serde_core" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.228" +version = "1.0.229" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 3.0.10", ] [[package]] name = "serde_json" -version = "1.0.150" +version = "1.0.154" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ "itoa", "memchr", @@ -4611,13 +4111,13 @@ dependencies = [ [[package]] name = "serde_repr" -version = "0.1.20" +version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 3.0.10", ] [[package]] @@ -4629,17 +4129,6 @@ dependencies = [ "serde", ] -[[package]] -name = "sha1" -version = "0.10.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" -dependencies = [ - "cfg-if", - "cpufeatures", - "digest", -] - [[package]] name = "sha2" version = "0.10.9" @@ -4647,7 +4136,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", - "cpufeatures", + "cpufeatures 0.2.17", "digest", ] @@ -4676,27 +4165,17 @@ dependencies = [ "libc", ] -[[package]] -name = "signature" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" -dependencies = [ - "digest", - "rand_core 0.6.4", -] - [[package]] name = "simd-adler32" -version = "0.3.9" +version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" [[package]] name = "simd_cesu8" -version = "1.1.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94f90157bb87cddf702797c5dadfa0be7d266cdf49e22da2fcaa32eff75b2c33" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" dependencies = [ "rustc_version", "simdutf8", @@ -4708,17 +4187,26 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" +[[package]] +name = "simplecss" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c" +dependencies = [ + "log", +] + [[package]] name = "siphasher" -version = "1.0.3" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" [[package]] name = "skrifa" -version = "0.22.3" +version = "0.44.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e1c44ad1f6c5bdd4eefed8326711b7dbda9ea45dfd36068c427d332aa382cbe" +checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68" dependencies = [ "bytemuck", "read-fonts", @@ -4741,9 +4229,9 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.15.2" +version = "1.16.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" [[package]] name = "smithay-client-toolkit" @@ -4751,9 +4239,9 @@ version = "0.19.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016" dependencies = [ - "bitflags 2.13.0", - "calloop 0.13.0", - "calloop-wayland-source 0.3.0", + "bitflags 2.13.2", + "calloop", + "calloop-wayland-source", "cursor-icon", "libc", "log", @@ -4769,119 +4257,53 @@ dependencies = [ "wayland-scanner", "xkeysym", ] - -[[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.0", - "calloop 0.14.4", - "calloop-wayland-source 0.4.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]] -name = "smithay-clipboard" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71704c03f739f7745053bde45fa203a46c58d25bc5c4efba1d9a60e9dba81226" -dependencies = [ - "libc", - "smithay-client-toolkit 0.20.0", - "wayland-backend", -] - -[[package]] -name = "smol_str" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead" -dependencies = [ - "serde", -] - -[[package]] -name = "socket2" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51" -dependencies = [ - "libc", - "windows-sys 0.61.2", -] - -[[package]] -name = "softbuffer" -version = "0.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aac18da81ebbf05109ab275b157c22a653bb3c12cf884450179942f81bcbf6c3" -dependencies = [ - "as-raw-xcb-connection", - "bytemuck", - "drm", - "fastrand", - "js-sys", - "memmap2", - "ndk", - "objc2 0.6.4", - "objc2-core-foundation", - "objc2-core-graphics", - "objc2-foundation 0.3.2", - "objc2-quartz-core 0.3.2", - "raw-window-handle", - "redox_syscall 0.5.18", - "rustix 1.1.4", - "tiny-xlib", - "tracing", - "wasm-bindgen", - "wayland-backend", - "wayland-client", - "wayland-sys", - "web-sys", + +[[package]] +name = "smol_str" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead" +dependencies = [ + "serde", +] + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", "windows-sys 0.61.2", - "x11rb", ] [[package]] -name = "spin" -version = "0.9.9" +name = "spellbook" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" +checksum = "0d204abcbdf8e88729306a8d0ca01a79d8a49969fe1f84696909d6dbc4321c1a" +dependencies = [ + "foldhash 0.2.0", + "hashbrown 0.17.2", +] [[package]] name = "spirv" -version = "0.3.0+sdk-1.3.268.0" +version = "0.4.0+sdk-1.4.341.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eda41003dc44290527a59b13432d4a0379379fa074b70174882adfbdfd917844" +checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", ] [[package]] -name = "spki" -version = "0.7.3" +name = "sqlite-wasm-rs" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +checksum = "a6cd504cecbfe7eef649988840f9a6cb768d11085efec138f8e99f160632d867" dependencies = [ - "base64ct", - "der", + "cc", + "rsqlite-vfs", ] [[package]] @@ -4890,6 +4312,19 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "stacker" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" +dependencies = [ + "cc", + "cfg-if", + "libc", + "psm", + "windows-sys 0.61.2", +] + [[package]] name = "static_assertions" version = "1.1.0" @@ -4901,6 +4336,9 @@ name = "strict-num" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" +dependencies = [ + "float-cmp", +] [[package]] name = "strsim" @@ -4915,27 +4353,116 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] -name = "svg_fmt" -version = "0.4.5" +name = "svgtypes" +version = "0.15.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0193cc4331cfd2f3d2011ef287590868599a2f33c3e69bc22c1a3d3acf9e02fb" +checksum = "68c7541fff44b35860c1a7a47a7cadf3e4a304c457b58f9870d9706ece028afc" +dependencies = [ + "kurbo", + "siphasher", +] [[package]] name = "swash" -version = "0.1.19" +version = "0.2.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cbd59f3f359ddd2c95af4758c18270eddd9c730dde98598023cdabff472c2ca2" +checksum = "6c2499c2d826531388872b2268718aed907a39bd785ab0dcfe57fab26283f92e" dependencies = [ "skrifa", "yazi", "zeno", ] +[[package]] +name = "symphonia" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5773a4c030a19d9bfaa090f49746ff35c75dfddfa700df7a5939d5e076a57039" +dependencies = [ + "lazy_static", + "symphonia-codec-vorbis", + "symphonia-core", + "symphonia-format-mkv", + "symphonia-format-ogg", + "symphonia-metadata", +] + +[[package]] +name = "symphonia-codec-vorbis" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f025837c309cd69ffef572750b4a2257b59552c5399a5e49707cc5b1b85d1c73" +dependencies = [ + "log", + "symphonia-core", + "symphonia-utils-xiph", +] + +[[package]] +name = "symphonia-core" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea00cc4f79b7f6bb7ff87eddc065a1066f3a43fe1875979056672c9ef948c2af" +dependencies = [ + "arrayvec", + "bitflags 1.3.2", + "bytemuck", + "lazy_static", + "log", +] + +[[package]] +name = "symphonia-format-mkv" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "122d786d2c43a49beb6f397551b4a050d8229eaa54c7ddf9ee4b98899b8742d0" +dependencies = [ + "lazy_static", + "log", + "symphonia-core", + "symphonia-metadata", + "symphonia-utils-xiph", +] + +[[package]] +name = "symphonia-format-ogg" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b4955c67c1ed3aa8ae8428d04ca8397fbef6a19b2b051e73b5da8b1435639cb" +dependencies = [ + "log", + "symphonia-core", + "symphonia-metadata", + "symphonia-utils-xiph", +] + +[[package]] +name = "symphonia-metadata" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36306ff42b9ffe6e5afc99d49e121e0bd62fe79b9db7b9681d48e29fa19e6b16" +dependencies = [ + "encoding_rs", + "lazy_static", + "log", + "symphonia-core", +] + +[[package]] +name = "symphonia-utils-xiph" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27c85ab799a338446b68eec77abf42e1a6f1bb490656e121c6e27bfbab9f16" +dependencies = [ + "symphonia-core", + "symphonia-metadata", +] + [[package]] name = "syn" -version = "1.0.109" +version = "2.0.119" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" dependencies = [ "proc-macro2", "quote", @@ -4944,9 +4471,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.118" +version = "3.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" dependencies = [ "proc-macro2", "quote", @@ -4955,22 +4482,24 @@ dependencies = [ [[package]] name = "synstructure" -version = "0.13.2" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 3.0.10", ] [[package]] -name = "sys-locale" -version = "0.3.2" +name = "taffy" +version = "0.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4" +checksum = "31f7bd2d97198df05186f93a3a3c306845f40e8b3c22bf9279cdd7e5cf5fea7d" dependencies = [ - "libc", + "serde", + "slotmap", + "smallvec", ] [[package]] @@ -4982,7 +4511,7 @@ dependencies = [ "fastrand", "getrandom 0.4.3", "once_cell", - "rustix 1.1.4", + "rustix 1.1.6", "windows-sys 0.61.2", ] @@ -5006,11 +4535,11 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.18" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ - "thiserror-impl 2.0.18", + "thiserror-impl 2.0.21", ] [[package]] @@ -5021,38 +4550,41 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 2.0.119", ] [[package]] name = "thiserror-impl" -version = "2.0.18" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 3.0.10", ] [[package]] name = "thread_local" -version = "1.1.9" +version = "1.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" dependencies = [ "cfg-if", ] [[package]] name = "tiff" -version = "0.9.1" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba1310fcea54c6a9a4fd1aad794ecc02c31682f6bfbecdf460bf19533eed1e3e" +checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" dependencies = [ + "fax", "flate2", - "jpeg-decoder", + "half", + "quick-error 2.0.1", "weezl", + "zune-jpeg", ] [[package]] @@ -5066,7 +4598,7 @@ dependencies = [ "bytemuck", "cfg-if", "log", - "png", + "png 0.17.16", "tiny-skia-path", ] @@ -5081,77 +4613,48 @@ dependencies = [ "strict-num", ] -[[package]] -name = "tiny-xlib" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a90a0ca3ee6a69f2ad28fd11621a4c3f03b371f366be500b64df260c4ffbafb4" -dependencies = [ - "as-raw-xcb-connection", - "ctor", - "libloading 0.8.9", - "pkg-config", - "tracing", -] - [[package]] name = "tinystr" -version = "0.8.3" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" dependencies = [ "displaydoc", + "serde_core", "zerovec", ] -[[package]] -name = "tinyvec" -version = "1.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" - [[package]] name = "tokio" -version = "1.52.3" +version = "1.54.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" dependencies = [ "bytes", "libc", "mio", "pin-project-lite", - "signal-hook-registry", "socket2", "tokio-macros", - "tracing", "windows-sys 0.61.2", ] [[package]] name = "tokio-macros" -version = "2.7.0" +version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 3.0.10", ] [[package]] name = "tokio-rustls" -version = "0.26.4" +version = "0.26.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" dependencies = [ "rustls", "tokio", @@ -5159,13 +4662,14 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.7.18" +version = "0.7.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" dependencies = [ "bytes", "futures-core", "futures-sink", + "libc", "pin-project-lite", "tokio", ] @@ -5193,9 +4697,9 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "1.1.1+spec-1.1.0" +version = "1.1.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" dependencies = [ "serde_core", ] @@ -5216,23 +4720,23 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.25.12+spec-1.1.0" +version = "0.25.21+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2153edc6955a6c354fad8f5efd38b6a8769bdccf9fe50f8e1329f81b0baa5d7" +checksum = "88497dab46de5bf343ec66b05c251e48c6213f3e9170c70a70a823f7abe886a4" dependencies = [ "indexmap", - "toml_datetime 1.1.1+spec-1.1.0", + "toml_datetime 1.1.3+spec-1.1.0", "toml_parser", - "winnow 1.0.3", + "winnow 1.0.5", ] [[package]] name = "toml_parser" -version = "1.1.2+spec-1.1.0" +version = "1.1.7+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526" +checksum = "0bb28d6e049a9766c3bd91a8326e6179f5b132dec87906bb97018ef7a2f3431a" dependencies = [ - "winnow 1.0.3", + "winnow 1.0.5", ] [[package]] @@ -5247,7 +4751,6 @@ version = "0.1.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" dependencies = [ - "log", "pin-project-lite", "tracing-attributes", "tracing-core", @@ -5261,7 +4764,7 @@ checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 2.0.119", ] [[package]] @@ -5304,28 +4807,27 @@ dependencies = [ ] [[package]] -name = "try-lock" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" - -[[package]] -name = "ttf-parser" -version = "0.20.0" +name = "tree_magic_mini" +version = "3.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17f77d76d837a7830fe1d4f12b7b4ba4192c1888001c7164257e4bc6d21d96b4" +checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6" +dependencies = [ + "memchr", + "nom", + "petgraph", +] [[package]] -name = "ttf-parser" -version = "0.21.1" +name = "try-lock" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c591d83f69777866b9126b24c6dd9a18351f177e49d625920d19f989fd31cf8" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" [[package]] -name = "ttf-parser" -version = "0.25.1" +name = "typed-path" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" +checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" [[package]] name = "typenum" @@ -5350,47 +4852,11 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" -[[package]] -name = "unicode-bidi" -version = "0.3.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" - -[[package]] -name = "unicode-bidi-mirroring" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23cb788ffebc92c5948d0e997106233eeb1d8b9512f93f41651f52b6c5f5af86" - -[[package]] -name = "unicode-ccc" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1df77b101bcc4ea3d78dafc5ad7e4f58ceffe0b2b16bf446aeb50b6cb4157656" - [[package]] name = "unicode-ident" -version = "1.0.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" - -[[package]] -name = "unicode-linebreak" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f" - -[[package]] -name = "unicode-properties" -version = "0.1.4" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" - -[[package]] -name = "unicode-script" -version = "0.5.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "383ad40bb927465ec0ce7720e033cb4ca06912855fc35db31b5755d0de75b1ee" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" [[package]] name = "unicode-segmentation" @@ -5400,25 +4866,9 @@ checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" [[package]] name = "unicode-width" -version = "0.1.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" - -[[package]] -name = "unicode-xid" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" - -[[package]] -name = "universal-hash" -version = "0.5.1" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" -dependencies = [ - "crypto-common", - "subtle", -] +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" [[package]] name = "untrusted" @@ -5428,28 +4878,46 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", "percent-encoding", "serde", - "serde_derive", ] [[package]] -name = "urlencoding" -version = "2.1.3" +name = "usvg" +version = "0.45.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" +checksum = "80be9b06fbae3b8b303400ab20778c80bbaf338f563afe567cf3c9eea17b47ef" +dependencies = [ + "base64", + "data-url", + "flate2", + "imagesize", + "kurbo", + "log", + "pico-args", + "roxmltree 0.20.0", + "simplecss", + "siphasher", + "strict-num", + "svgtypes", + "tiny-skia-path", + "xmlwriter", +] [[package]] name = "utf8_iter" -version = "1.0.4" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] [[package]] name = "utf8parse" @@ -5457,11 +4925,17 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + [[package]] name = "uuid" -version = "1.23.4" +version = "1.29.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf80a72845275afea99e7f2b434723d3bc7e38470fcd1c7ed39a599c73319a53" +checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64" dependencies = [ "js-sys", "serde_core", @@ -5497,9 +4971,9 @@ dependencies = [ [[package]] name = "walkdir" -version = "2.5.0" +version = "2.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +checksum = "b42e295b7452c4604982280d8586001fcad9b8b201cac67bca9771e7a7475403" dependencies = [ "same-file", "winapi-util", @@ -5507,9 +4981,9 @@ dependencies = [ [[package]] name = "want" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" dependencies = [ "try-lock", ] @@ -5531,12 +5005,11 @@ dependencies = [ [[package]] name = "wasm-bindgen" -version = "0.2.126" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b067c0c11094aef6b7a801c1e34a26affafdf3d051dba08456b868789aaf9a4" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if", - "once_cell", "rustversion", "wasm-bindgen-macro", "wasm-bindgen-shared", @@ -5544,19 +5017,20 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.76" +version = "0.4.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c62df1340f32221cb9c54d6a27b030e3dba64361d4a95bed55f9aacb44da291d" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" dependencies = [ "js-sys", + "tokio", "wasm-bindgen", ] [[package]] name = "wasm-bindgen-macro" -version = "0.2.126" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "167ce5e579f6bcf889c4f7175a8a5a585de84e8ff93976ce393efa5f2837aab1" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -5564,50 +5038,35 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.126" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3997c7839262f4ef12cf90b818d6340c18e80f263f1a94bf157d0ec4420380e" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 2.0.118", + "syn 3.0.10", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.126" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc1b4cb0cc549fcf58d7dfc081778139b3d283a081644e833e84682ad71cea24" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" dependencies = [ "unicode-ident", ] -[[package]] -name = "wasm-timer" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be0ecb0db480561e9a7642b5d3e4187c128914e58aa84330b9493e3eb68c5e7f" -dependencies = [ - "futures", - "js-sys", - "parking_lot 0.11.2", - "pin-utils", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", -] - [[package]] name = "wayland-backend" -version = "0.3.15" +version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2857dd20b54e916ec7253b3d6b4d5c4d7d4ca2c33c2e11c6c76a99bd8744755d" +checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" dependencies = [ "cc", "downcast-rs", - "rustix 1.1.4", + "rustix 1.1.6", "scoped-tls", "smallvec", "wayland-sys", @@ -5615,12 +5074,12 @@ dependencies = [ [[package]] name = "wayland-client" -version = "0.31.14" +version = "0.31.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "645c7c96bb74690c3189b5c9cb4ca1627062bb23693a4fad9d8c3de958260144" +checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" dependencies = [ - "bitflags 2.13.0", - "rustix 1.1.4", + "bitflags 2.13.2", + "rustix 1.1.6", "wayland-backend", "wayland-scanner", ] @@ -5631,7 +5090,7 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", "cursor-icon", "wayland-backend", ] @@ -5642,7 +5101,7 @@ version = "0.31.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" dependencies = [ - "rustix 1.1.4", + "rustix 1.1.6", "wayland-client", "xcursor", ] @@ -5653,35 +5112,9 @@ version = "0.32.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6" dependencies = [ - "bitflags 2.13.0", - "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.0", - "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.0", + "bitflags 2.13.2", "wayland-backend", "wayland-client", - "wayland-protocols", "wayland-scanner", ] @@ -5691,7 +5124,7 @@ version = "0.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", "wayland-backend", "wayland-client", "wayland-protocols", @@ -5704,7 +5137,7 @@ version = "0.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", "wayland-backend", "wayland-client", "wayland-protocols", @@ -5713,9 +5146,9 @@ dependencies = [ [[package]] name = "wayland-scanner" -version = "0.31.10" +version = "0.31.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c324a910fd86ebdc364a3e61ec1f11737d3b1d6c273c0239ee8ff4bc0d24b4a" +checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" dependencies = [ "proc-macro2", "quick-xml", @@ -5736,9 +5169,9 @@ dependencies = [ [[package]] name = "web-sys" -version = "0.3.103" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8622dcb61c0bcc9fffa6938bed81210af2da9a7e4a1a834b2e37a59b6dfb6141" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" dependencies = [ "js-sys", "wasm-bindgen", @@ -5762,17 +5195,22 @@ checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" [[package]] name = "wgpu" -version = "0.19.4" +version = "30.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cbd7311dbd2abcfebaabf1841a2824ed7c8be443a0f29166e5d3c6a53a762c01" +checksum = "146fc3d654250e6207921a66c87534c621bc886c70df83dcf466c1d66813810e" dependencies = [ "arrayvec", + "bitflags 2.13.2", + "bytemuck", "cfg-if", - "cfg_aliases 0.1.1", + "cfg_aliases", + "document-features", + "hashbrown 0.17.2", "js-sys", "log", "naga", - "parking_lot 0.12.5", + "parking_lot", + "portable-atomic", "profiling", "raw-window-handle", "smallvec", @@ -5787,83 +5225,124 @@ dependencies = [ [[package]] name = "wgpu-core" -version = "0.19.4" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad661da2ee99f208c30090b585284b2ab5b8bf2358ddf2d2215592808ec62f1a" +dependencies = [ + "arrayvec", + "bit-set 0.10.0", + "bit-vec 0.9.1", + "bitflags 2.13.2", + "bytemuck", + "cfg_aliases", + "document-features", + "hashbrown 0.17.2", + "indexmap", + "log", + "naga", + "naga-types", + "once_cell", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "rustc-hash 1.1.0", + "smallvec", + "thiserror 2.0.21", + "wgpu-core-deps-apple", + "wgpu-core-deps-windows-linux-android", + "wgpu-hal", + "wgpu-naga-bridge", + "wgpu-types", +] + +[[package]] +name = "wgpu-core-deps-apple" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d3f2f24aee039ffe9ef527300daf6b7428c58edeefdaa1700f4fa0fd754df16" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-windows-linux-android" +version = "30.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28b94525fc99ba9e5c9a9e24764f2bc29bad0911a7446c12f446a8277369bf3a" +checksum = "1331b08fa2362c5d454eccc4448e6e4f01eccfea569a00e310adbfc4415f2bdc" dependencies = [ - "arrayvec", - "bit-vec 0.6.3", - "bitflags 2.13.0", - "cfg_aliases 0.1.1", - "codespan-reporting", - "indexmap", - "log", - "naga", - "once_cell", - "parking_lot 0.12.5", - "profiling", - "raw-window-handle", - "rustc-hash 1.1.0", - "smallvec", - "thiserror 1.0.69", - "web-sys", "wgpu-hal", - "wgpu-types", ] [[package]] name = "wgpu-hal" -version = "0.19.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfabcfc55fd86611a855816326b2d54c3b2fd7972c27ce414291562650552703" +version = "30.0.1" +source = "git+https://github.com/anomalyco/rune?rev=e6f70eb09762180b86dcef912fe169a315bc31b7#e6f70eb09762180b86dcef912fe169a315bc31b7" dependencies = [ "android_system_properties", "arrayvec", "ash", - "bit-set 0.5.3", - "bitflags 2.13.0", - "block", - "cfg_aliases 0.1.1", - "core-graphics-types", - "d3d12", - "glow", - "glutin_wgl_sys", - "gpu-alloc", + "bit-set 0.10.0", + "bitflags 2.13.2", + "block2 0.6.2", + "bytemuck", + "cfg-if", + "cfg_aliases", "gpu-allocator", - "gpu-descriptor", - "hassle-rs", - "js-sys", - "khronos-egl", + "hashbrown 0.17.2", "libc", - "libloading 0.8.9", + "libloading", "log", - "metal", "naga", - "ndk-sys 0.5.0+25.2.9519653", - "objc", + "naga-types", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", + "objc2-quartz-core 0.3.2", "once_cell", - "parking_lot 0.12.5", + "ordered-float", + "parking_lot", + "portable-atomic", + "portable-atomic-util", "profiling", "range-alloc", "raw-window-handle", + "raw-window-metal", "renderdoc-sys", - "rustc-hash 1.1.0", "smallvec", - "thiserror 1.0.69", - "wasm-bindgen", - "web-sys", + "static_assertions", + "thiserror 2.0.21", + "wgpu-naga-bridge", + "wgpu-types", + "windows", + "windows-core", +] + +[[package]] +name = "wgpu-naga-bridge" +version = "30.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44a62ead68aad7cd40ac9e2cd2b8ec64f32dfbad2765f429b9fb74b8b735869f" +dependencies = [ + "naga", "wgpu-types", - "winapi", ] [[package]] name = "wgpu-types" -version = "0.19.2" +version = "30.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b671ff9fb03f78b46ff176494ee1ebe7d603393f42664be55b64dc8d53969805" +checksum = "a9f6ee0bd50f5ab79fb8c25e3f33afb27126f034af4ba5909c7a0967058659e6" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", + "bytemuck", "js-sys", + "log", + "naga-types", + "raw-window-handle", + "static_assertions", "web-sys", ] @@ -5875,85 +5354,130 @@ checksum = "24d643ce3fd3e5b54854602a080f34fb10ab75e0b813ee32d00ca2b44fa74762" dependencies = [ "either", "env_home", - "rustix 1.1.4", + "rustix 1.1.6", "winsafe", ] [[package]] -name = "widestring" -version = "1.2.1" +name = "winapi-util" +version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] [[package]] -name = "winapi" -version = "0.3.9" +name = "windows" +version = "0.62.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", ] [[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" +name = "windows-collections" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] [[package]] -name = "winapi-util" -version = "0.1.11" +name = "windows-core" +version = "0.62.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" dependencies = [ - "windows-sys 0.61.2", + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", ] [[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" +name = "windows-implement" +version = "0.60.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] [[package]] -name = "window_clipboard" -version = "0.4.1" +name = "windows-interface" +version = "0.59.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6d692d46038c433f9daee7ad8757e002a4248c20b0a3fbc991d99521d3bcb6d" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" dependencies = [ - "clipboard-win", - "clipboard_macos", - "clipboard_wayland", - "clipboard_x11", - "raw-window-handle", - "thiserror 1.0.69", + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] -name = "windows" -version = "0.52.0" +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e48a53791691ab099e5e2ad123536d0fff50652600abaf43bbf952894110d0be" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" dependencies = [ "windows-core", - "windows-targets 0.52.6", + "windows-link", ] [[package]] -name = "windows-core" -version = "0.52.0" +name = "windows-registry" +version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" dependencies = [ - "windows-targets 0.52.6", + "windows-link", + "windows-result", + "windows-strings", ] [[package]] -name = "windows-link" -version = "0.2.1" +name = "windows-result" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] [[package]] name = "windows-sys" @@ -6022,6 +5546,15 @@ dependencies = [ "windows_x86_64_msvc 0.52.6", ] +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + [[package]] name = "windows_aarch64_gnullvm" version = "0.48.5" @@ -6115,17 +5648,16 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winit" version = "0.30.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d" +source = "git+https://github.com/anomalyco/rune?rev=e6f70eb09762180b86dcef912fe169a315bc31b7#e6f70eb09762180b86dcef912fe169a315bc31b7" dependencies = [ - "ahash 0.8.12", + "ahash", "android-activity", "atomic-waker", - "bitflags 2.13.0", + "bitflags 2.13.2", "block2 0.5.1", "bytemuck", - "calloop 0.13.0", - "cfg_aliases 0.2.1", + "calloop", + "cfg_aliases", "concurrent-queue", "core-foundation 0.9.4", "core-graphics", @@ -6135,7 +5667,7 @@ dependencies = [ "libc", "memmap2", "ndk", - "objc2 0.5.2", + "objc2 0.5.3", "objc2-app-kit 0.2.2", "objc2-foundation 0.2.2", "objc2-ui-kit", @@ -6146,7 +5678,7 @@ dependencies = [ "redox_syscall 0.4.1", "rustix 0.38.44", "sctk-adwaita", - "smithay-client-toolkit 0.19.2", + "smithay-client-toolkit", "smol_str", "tracing", "unicode-segmentation", @@ -6175,22 +5707,13 @@ dependencies = [ [[package]] name = "winnow" -version = "1.0.3" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0592e1c9d151f854e6fd382574c3a0855250e1d9b2f99d9281c6e6391af352f1" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" dependencies = [ "memchr", ] -[[package]] -name = "winreg" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d" -dependencies = [ - "winapi", -] - [[package]] name = "winreg" version = "0.52.0" @@ -6236,11 +5759,29 @@ version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +[[package]] +name = "wl-clipboard-rs" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "959c7ac3b8afde864f7a7448ac16f29b2b83350b7eccbf77fb781c3999aa6848" +dependencies = [ + "libc", + "log", + "os_pipe", + "rustix 1.1.6", + "thiserror 2.0.21", + "tree_magic_mini", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-wlr", +] + [[package]] name = "writeable" -version = "0.6.3" +version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" [[package]] name = "x11-dl" @@ -6262,9 +5803,9 @@ dependencies = [ "as-raw-xcb-connection", "gethostname", "libc", - "libloading 0.8.9", + "libloading", "once_cell", - "rustix 1.1.4", + "rustix 1.1.6", "x11rb-protocol", ] @@ -6274,31 +5815,21 @@ version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" -[[package]] -name = "x25519-dalek" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277" -dependencies = [ - "curve25519-dalek", - "rand_core 0.6.4", - "zeroize", -] - [[package]] name = "xcursor" -version = "0.3.10" +version = "0.3.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bec9e4a500ca8864c5b47b8b482a73d62e4237670e5b5f1d6b9e3cae50f28f2b" +checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23" [[package]] -name = "xdg-home" -version = "1.3.0" +name = "xkbcommon" +version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec1cdab258fb55c0da61328dc52c8764709b249011b2cad0454c72f0bf10a1f6" +checksum = "a7a974f48060a14e95705c01f24ad9c3345022f4d97441b8a36beb7ed5c4a02d" dependencies = [ "libc", - "windows-sys 0.59.0", + "memmap2", + "xkeysym", ] [[package]] @@ -6307,7 +5838,7 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d039de8032a9a8856a6be89cea3e5d12fdd82306ab7c94d74e6deab2460651c5" dependencies = [ - "bitflags 2.13.0", + "bitflags 2.13.2", "dlib", "log", "once_cell", @@ -6321,22 +5852,33 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" [[package]] -name = "xml-rs" -version = "0.8.28" +name = "xmlwriter" +version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ae8337f8a065cfc972643663ea4279e04e7256de865aa66fe25cec5fb912d3f" +checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" [[package]] name = "yazi" -version = "0.1.6" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c94451ac9513335b5e23d7a8a2b61a7102398b8cca5160829d313e84c9d98be1" +checksum = "ac366ea532fa8ee6a992cec9dea525b1dc284e69702f36c2ab5fbebadc81ec86" + +[[package]] +name = "yeslogic-fontconfig-sys" +version = "6.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d8b8abf912b9a29ff112e1671c97c33636903d13a69712037190e6805af4f76" +dependencies = [ + "dlib", + "once_cell", + "pkg-config", +] [[package]] name = "yoke" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" dependencies = [ "stable_deref_trait", "yoke-derive", @@ -6345,25 +5887,24 @@ dependencies = [ [[package]] name = "yoke-derive" -version = "0.8.2" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 3.0.10", "synstructure", ] [[package]] name = "zbus" -version = "4.4.0" +version = "5.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb97012beadd29e654708a0fdb4c84bc046f537aecfde2c3ee0a9e4b4d48c725" +checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" dependencies = [ "async-broadcast", "async-executor", - "async-fs", "async-io", "async-lock", "async-process", @@ -6374,129 +5915,118 @@ dependencies = [ "enumflags2", "event-listener", "futures-core", - "futures-sink", - "futures-util", + "futures-lite", "hex", - "nix", + "libc", "ordered-stream", - "rand 0.8.6", + "rustix 1.1.6", "serde", "serde_repr", - "sha1", - "static_assertions", "tracing", "uds_windows", - "windows-sys 0.52.0", - "xdg-home", - "zbus_macros 4.4.0", - "zbus_names 3.0.0", - "zvariant 4.2.0", + "uuid", + "windows-sys 0.61.2", + "winnow 1.0.5", + "zbus_macros", + "zbus_names", + "zvariant", ] [[package]] -name = "zbus" -version = "5.17.0" +name = "zbus-lockstep" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a28b97f866896a4be7aefd2b5a8e01bb6773d19a775d54ab28b4d094b9a4480e" +checksum = "6998de05217a084b7578728a9443d04ea4cd80f2a0839b8d78770b76ccd45863" dependencies = [ - "async-broadcast", - "async-recursion", - "async-trait", - "enumflags2", - "event-listener", - "futures-core", - "futures-lite", - "hex", - "libc", - "ordered-stream", - "rustix 1.1.4", - "serde", - "serde_repr", - "tokio", - "tracing", - "uds_windows", - "uuid", - "windows-sys 0.61.2", - "winnow 1.0.3", - "zbus_macros 5.17.0", - "zbus_names 4.3.3", - "zvariant 5.13.0", + "zbus_xml", + "zvariant", ] [[package]] -name = "zbus_macros" -version = "4.4.0" +name = "zbus-lockstep-macros" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "267db9407081e90bbfa46d841d3cbc60f59c0351838c4bc65199ecd79ab1983e" +checksum = "10da05367f3a7b7553c8cdf8fa91aee6b64afebe32b51c95177957efc47ca3a0" dependencies = [ - "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.118", - "zvariant_utils 2.1.0", + "syn 2.0.119", + "zbus-lockstep", + "zbus_xml", + "zvariant", ] [[package]] name = "zbus_macros" -version = "5.17.0" +version = "5.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e05ad887425eecf5e8384dc2406a4a9313eb73468712fc1cdea362eb4fe0469" +checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.118", - "zbus_names 4.3.3", - "zvariant 5.13.0", - "zvariant_utils 3.5.0", + "syn 3.0.10", + "zbus_names", + "zvariant", + "zvariant_utils", ] [[package]] name = "zbus_names" -version = "3.0.0" +version = "4.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b9b1fef7d021261cc16cba64c351d291b715febe0fa10dc3a443ac5a5022e6c" +checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" dependencies = [ "serde", - "static_assertions", - "zvariant 4.2.0", + "winnow 1.0.5", + "zvariant", ] [[package]] -name = "zbus_names" -version = "4.3.3" +name = "zbus_xml" +version = "5.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1039ca249fee9559680f3a9f05b55e0761fee51af4f6c1e7d8c1f31e549721d2" +checksum = "d1586c021a01ca0a9216dcd874e546382e156a5cbab5fab6cb5f10087e22682a" +dependencies = [ + "serde", + "winnow 1.0.5", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zcheapstr" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2da34e7164b75d803c3197b86e6cf61b874106fbd472c5082575a8bc5fbd0907" dependencies = [ "serde", - "winnow 1.0.3", - "zvariant 5.13.0", ] [[package]] name = "zeno" -version = "0.2.3" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd15f8e0dbb966fd9245e7498c7e9e5055d9e5c8b676b95bd67091cd11a1e697" +checksum = "6df3dc4292935e51816d896edcd52aa30bc297907c26167fec31e2b0c6a32524" [[package]] name = "zerocopy" -version = "0.8.52" +version = "0.8.66" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce1022995ff5ff5d841ad7d994facc23098cd40152f2c1d11cd607c6f530653f" +checksum = "cba8a86aee14fc8cc6c208af60854b3d4ab7185a9a369a12c648faa2716ff42a" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.52" +version = "0.8.66" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ae7f38b72ec2a254e2b87ef277cf2cd4fb97cbebf944faa6f33354da0867930" +checksum = "f89bca3b96ceb3cfcb4572790402f977442270d252b9a8504ebc258760c55f94" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 2.0.119", ] [[package]] @@ -6510,21 +6040,21 @@ dependencies = [ [[package]] name = "zerofrom-derive" -version = "0.1.7" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 3.0.10", "synstructure", ] [[package]] name = "zeroize" -version = "1.9.0" +version = "1.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" dependencies = [ "zeroize_derive", ] @@ -6537,26 +6067,28 @@ checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 2.0.119", ] [[package]] name = "zerotrie" -version = "0.2.4" +version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" dependencies = [ "displaydoc", "yoke", "zerofrom", + "zerovec", ] [[package]] name = "zerovec" -version = "0.11.6" +version = "0.11.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" dependencies = [ + "serde", "yoke", "zerofrom", "zerovec-derive", @@ -6564,120 +6096,98 @@ dependencies = [ [[package]] name = "zerovec-derive" -version = "0.11.3" +version = "0.11.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" dependencies = [ "proc-macro2", "quote", - "syn 2.0.118", + "syn 3.0.10", ] [[package]] name = "zip" -version = "2.4.2" +version = "9.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50" +checksum = "2d8dbe089cf6b0448b78f5fc50139ab5aaa40d08ac07cdc1baf2c13add35fcce" dependencies = [ - "arbitrary", + "constant_time_eq 0.6.2", "crc32fast", - "crossbeam-utils", - "displaydoc", "flate2", + "getrandom 0.4.3", "indexmap", + "libc", "memchr", - "thiserror 2.0.18", + "nix", + "typed-path", + "windows-sys 0.61.2", + "zeroize", ] +[[package]] +name = "zlib-rs" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac" + [[package]] name = "zmij" -version = "1.0.21" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" [[package]] -name = "zune-inflate" -version = "0.2.54" +name = "zune-core" +version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02" -dependencies = [ - "simd-adler32", -] +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" [[package]] -name = "zvariant" -version = "4.2.0" +name = "zune-jpeg" +version = "0.5.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2084290ab9a1c471c38fc524945837734fbf124487e105daec2bb57fd48c81fe" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" dependencies = [ - "endi", - "enumflags2", - "serde", - "static_assertions", - "zvariant_derive 4.2.0", + "zune-core", ] [[package]] name = "zvariant" -version = "5.13.0" +version = "5.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cf057bb00bf5c9ad77abb6147b0ca4818236a1858416e9d988e40d6322fefa7" +checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" dependencies = [ "endi", "enumflags2", "serde", - "url", - "winnow 1.0.3", - "zvariant_derive 5.13.0", - "zvariant_utils 3.5.0", -] - -[[package]] -name = "zvariant_derive" -version = "4.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73e2ba546bda683a90652bac4a279bc146adad1386f25379cf73200d2002c449" -dependencies = [ - "proc-macro-crate", - "proc-macro2", - "quote", - "syn 2.0.118", - "zvariant_utils 2.1.0", + "winnow 1.0.5", + "zcheapstr", + "zvariant_derive", + "zvariant_utils", ] [[package]] name = "zvariant_derive" -version = "5.13.0" +version = "5.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8118ca6bda77bfc0ab51d660db0c955f2505eef854c9a449435bccb616933b31" +checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.118", - "zvariant_utils 3.5.0", -] - -[[package]] -name = "zvariant_utils" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c51bcff7cc3dbb5055396bcf774748c3dab426b4b8659046963523cee4808340" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.118", + "syn 3.0.10", + "zvariant_utils", ] [[package]] name = "zvariant_utils" -version = "3.5.0" +version = "4.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90cb9383f9b45290407a1258b202d3f8f01db719eb60b4e4055c6375af4fc7c7" +checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" dependencies = [ "proc-macro2", "quote", "serde", - "syn 2.0.118", - "winnow 1.0.3", + "syn 3.0.10", + "winnow 1.0.5", ] diff --git a/Cargo.toml b/Cargo.toml index ad67c61..3a57e3f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,7 +10,7 @@ members = ["crates/*"] # `v*` tag, so a tag is always authoritative and code/About/release stay in sync. version = "0.1.0-beta.3" edition = "2024" -rust-version = "1.96" +rust-version = "1.99" license = "GPL-2.0-only" authors = ["Modrix contributors"] @@ -20,6 +20,8 @@ modrix-core = { path = "crates/modrix-core" } modrix-plugin = { path = "crates/modrix-plugin" } modrix-download = { path = "crates/modrix-download" } modrix-ipc = { path = "crates/modrix-ipc" } +modrix-il2cpp = { path = "crates/modrix-il2cpp" } +modrix-interop-gen = { path = "crates/modrix-interop-gen" } modrix-mcp = { path = "crates/modrix-mcp" } modrix-registry = { path = "crates/modrix-registry" } modrix-service = { path = "crates/modrix-service" } @@ -28,17 +30,15 @@ modrix-update = { path = "crates/modrix-update" } anyhow = "1" thiserror = "2" directories = "5" -rusqlite = { version = "0.32", features = ["bundled"] } +rusqlite = { version = "0.43", features = ["bundled"] } tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } clap = { version = "4", features = ["derive", "env"] } tempfile = "3" # --- async runtime (Phase 2) --- -# NOTE: the HTTP *client* stack does NOT use reqwest - it transitively pulls -# Apache-2.0-encumbered crates (`ring`, `sync_wrapper`), which are GPLv2- -# incompatible. The download pipeline (added next) assembles a pure-Rust, -# GPLv2-clean stack instead: hyper + rustls + a RustCrypto crypto provider + -# the OS trust store, all MIT/ISC. See docs/ARCHITECTURE.md §8/§11. +# The HTTP client is assembled from hyper + rustls (ring provider) + the OS +# trust store. It is small and already audited against our usage; it is a +# choice, not a rule (see docs/ARCHITECTURE.md §11). tokio = { version = "1", default-features = false, features = [ "rt-multi-thread", "macros", "net", "io-util", "fs", "sync", "time", ] } @@ -46,36 +46,39 @@ hyper = { version = "1", features = ["client", "http1"] } hyper-util = { version = "0.1", default-features = false, features = ["tokio"] } http-body-util = "0.1" tokio-rustls = { version = "0.26", default-features = false, features = ["tls12", "logging"] } -rustls = { version = "0.23", default-features = false, features = ["std", "tls12", "logging"] } -rustls-rustcrypto = "=0.0.2-alpha" # pure-Rust CryptoProvider (RustCrypto primitives) +rustls = { version = "0.23", default-features = false, features = ["std", "tls12", "logging", "ring"] } rustls-native-certs = "0.8" # OS trust store (avoids CDLA webpki-roots) getrandom = "0.3" -iced = { version = "0.13", default-features = false, features = ["wgpu", "tiny-skia", "tokio", "auto-detect-theme", "canvas", "image"] } -# FOMOD installer config parsing (read-only XML DOM; MIT arm of MIT/Apache dual). +# Native GPU UI: Rune's renderer, layout, text and springs, plus its +# component kit. Pinned to one `dev` rev; the [patch.crates-io] block at the +# bottom must use the same URL and rev (Rune ships patched winit/wgpu-hal/etc). +rune = { git = "https://github.com/anomalyco/rune", rev = "e6f70eb09762180b86dcef912fe169a315bc31b7", features = ["native-file-dialog"] } +rune-kit = { git = "https://github.com/anomalyco/rune", rev = "e6f70eb09762180b86dcef912fe169a315bc31b7", default-features = false } +# FOMOD installer config parsing (read-only XML DOM). roxmltree = "0.20" # Decode Steam artwork + bake the per-game backdrop / extract accent colors -# (GUI only; MIT arm of MIT/Apache dual; the same 0.24 iced already resolves). +# (GUI only). image = { version = "0.24", default-features = false, features = ["jpeg", "png"] } -# Sandboxed Lua host for Tier-2 game plugins (MIT; vendors Lua 5.4, also MIT). +# Sandboxed Lua host for Tier-2 game plugins (vendors Lua 5.4). mlua = { version = "0.10", default-features = false, features = ["lua54", "vendored"] } -# Native file-open dialogs via the XDG portal (MIT; no GTK linkage). +# Native file-open dialogs via the XDG portal (no GTK linkage). rfd = { version = "0.15", default-features = false, features = ["xdg-portal", "tokio"] } serde = { version = "1", features = ["derive"] } wiremock = "0.6" serde_json = "1" -# Semantic-version comparison for the in-app updater (MIT arm of MIT/Apache dual). +# Semantic-version comparison for the in-app updater. semver = "1" toml = "0.8" # Windows registry reads for non-Steam store detection (GOG / Xbox / Uplay / -# vendor keys like Bethesda Softworks). MIT; target-gated to cfg(windows). Its +# vendor keys like Bethesda Softworks). Target-gated to cfg(windows). Its # FFI `unsafe` lives inside the crate, not ours (workspace forbids unsafe). winreg = "0.52" sha2 = "0.10" -md-5 = "0.10" # Nexus publishes file MD5s; RustCrypto, MIT/Apache -# zip for reading mod archives. We DECOMPRESS only, so we take the pure-Rust -# flate2 (miniz_oxide) backend and never enable `deflate` (which would pull in -# zopfli, an Apache-2.0-only crate rejected by our GPLv2 license gate). -zip = { version = "2", default-features = false, features = ["deflate-flate2", "flate2"] } +md-5 = "0.10" # Nexus publishes file MD5s; RustCrypto +# zip for reading mod archives. We DECOMPRESS only, so the pure-Rust flate2 +# (miniz_oxide) backend is all that is needed; `deflate` (zopfli) would add a +# compressor we never use. +zip = { version = "9", default-features = false, features = ["deflate-flate2"] } flate2 = { version = "1", default-features = false, features = ["rust_backend"] } proptest = "1" @@ -105,3 +108,16 @@ print_stderr = "warn" [profile.release] overflow-checks = true # Power of Ten: no silent integer wraparound + +# Rune's patched windowing/text/GPU crates. Cargo does not inherit a +# dependency's patches, so they live here at the same rev as `rune` above. +# Re-check Rune's own Cargo.toml [patch.crates-io] list whenever the rev moves. +[patch.crates-io] +winit = { git = "https://github.com/anomalyco/rune", rev = "e6f70eb09762180b86dcef912fe169a315bc31b7" } +sctk-adwaita = { git = "https://github.com/anomalyco/rune", rev = "e6f70eb09762180b86dcef912fe169a315bc31b7" } +parley_engine = { git = "https://github.com/anomalyco/rune", rev = "e6f70eb09762180b86dcef912fe169a315bc31b7" } +wgpu-hal = { git = "https://github.com/anomalyco/rune", rev = "e6f70eb09762180b86dcef912fe169a315bc31b7" } +naga = { git = "https://github.com/anomalyco/rune", rev = "e6f70eb09762180b86dcef912fe169a315bc31b7" } +accesskit_windows = { git = "https://github.com/anomalyco/rune", rev = "e6f70eb09762180b86dcef912fe169a315bc31b7" } +accesskit_macos = { git = "https://github.com/anomalyco/rune", rev = "e6f70eb09762180b86dcef912fe169a315bc31b7" } +accesskit_atspi_common = { git = "https://github.com/anomalyco/rune", rev = "e6f70eb09762180b86dcef912fe169a315bc31b7" } diff --git a/README.md b/README.md index db57963..ccc3643 100644 --- a/README.md +++ b/README.md @@ -128,7 +128,7 @@ rm -rf ~/.cache/modrix # artwork + download staging |---|---| | Linux, Windows, or macOS | Steam plus Proton is first-class on Linux | | Rust (pinned toolchain) | Build-time only; `rustup` installs it from `rust-toolchain.toml` | -| A GPU or software renderer | The GUI uses `wgpu` (falls back to `tiny-skia`) | +| A GPU, or a software adapter | The GUI renders with `wgpu` (Vulkan, Metal or DirectX 12) and falls back to a software adapter such as WARP or llvmpipe | @@ -139,7 +139,7 @@ rm -rf ~/.cache/modrix # artwork + download staging
-1. Launch `modrix-gui`. On **Games**, register your game. If it is installed through Steam, Modrix usually detects it and offers a one-click "Add and switch"; otherwise point it at the install directory. +1. Launch `modrix-gui`. On **Games**, register your game. If it is installed through Steam, Modrix usually detects it and offers it under **Found on this computer** with a one-click **Add**; otherwise point it at the install directory. 2. Load the `extension/` folder unpacked in your browser (see Installation). No token needed. 3. Click **Download** on nexusmods.com. The file downloads segmented, stages itself into the library, and appears under **Mods**. 4. Enable the mod, resolve any conflicts under **Conflicts**, then hit **Deploy**. Use **Verify** to confirm the game folder matches the manifest, and **Undeploy** to reverse it. @@ -265,13 +265,13 @@ Modrix follows the platform's standard directories (via the `directories` crate) | Directory | Linux default | Holds | |---|---|---| | Data | `~/.local/share/modrix` | SQLite database, staged mod library, installed plugins | -| Config | `~/.config/modrix` | GUI theme (`gui.toml`), extra game definitions | +| Config | `~/.config/modrix` | GUI appearance (`gui.toml`), extra game definitions | | Cache | `~/.cache/modrix` | Steam artwork bakes, download staging, update downloads | On Windows these map to `%LOCALAPPDATA%` and `%APPDATA%`; on macOS to `~/Library`. - **Extra games:** drop a `game.toml` at `/games//game.toml`. -- **GUI theme:** the theme picker in **Settings** persists to `/gui.toml` (Aurora glass by default, Gold as an alternative). +- **GUI appearance:** **Settings** chooses System, Dark or Light and saves it to `/gui.toml`. The accent colour comes from the selected game's artwork. - **Registry source:** `MODRIX_REGISTRY` overrides where game-support plugins are fetched from. @@ -300,7 +300,7 @@ Modrix is a Cargo workspace. `modrix-core` depends on no UI, site-specific, or p | `modrix-update` | In-app updater over GitHub Releases (reuses the hyper plus rustls client). | | `modrix-cli` | The `clap` frontend (binary: `modrix`). | | `modrix-tui` | The `ratatui` frontend. | -| `modrix-gui` | The `iced` frontend (the only crate allowed to link a GUI toolkit). | +| `modrix-gui` | The native GPU frontend, built with [Rune](https://github.com/anomalyco/rune) (the only crate allowed to link a GUI toolkit). | ### Deploy data flow @@ -331,9 +331,9 @@ enabled mods (load order) 4. **Crash-safety.** The journal is written before any file moves, so an interrupted deploy is recovered on next launch. 5. **Determinism.** The planner is a pure function of the enabled set and load order. -### Licensing gate +### Licensing -The whole tree is GPL-2.0-only, enforced mechanically by `cargo-deny` in CI. Apache-2.0-only dependencies are rejected as GPLv2-incompatible, which is why the HTTP stack is `hyper` plus `rustls` plus `rustls-rustcrypto` plus `rustls-native-certs` and never `reqwest` (which pulls `ring`). The sole carve-out is a documented [GUI linking exception](docs/LICENSE-EXCEPTIONS.md) for the windowing and text crates the Iced GUI needs; the engine links zero Apache-2.0 code. +Modrix itself is GPL-2.0-only. Dependency licenses are not gated: `cargo-deny` runs for security advisories, duplicate-version policy and registry sources only. The HTTP stack is `hyper` plus `rustls` because it is small, pure Rust and already audited against how Modrix uses it - not because anything forbids the alternatives. ### Power of Ten for Rust @@ -360,7 +360,7 @@ Windows builds keep themselves current through GitHub Releases, with no telemetr - When a newer release exists, a notification appears and **Settings** grows an **Updates** card with the version, its notes, and a one-click **Download and install**. - Installing downloads the signed installer, launches it silently, and quits Modrix so the installer can replace the running executable and relaunch it. Because the install is per-user, no administrator prompt is involved. -The updater reuses the same GPLv2-clean `hyper` plus `rustls` HTTP client as the rest of Modrix (never `reqwest`). Pre-releases (betas) are skipped, so a beta never auto-updates a stable install. On Linux and macOS the same check links you to the release page for a manual download. +The updater reuses the same `hyper` plus `rustls` HTTP client as the rest of Modrix. Pre-releases (betas) are skipped, so a beta never auto-updates a stable install. On Linux and macOS the Updates card links to the release page instead of installing, since there is no installer to run. @@ -382,7 +382,7 @@ cargo build cargo test --all --all-features # what CI runs cargo clippy --all-targets --all-features -- -D warnings # zero warnings required cargo fmt --all -- --check -cargo deny check # license + advisory gate +cargo deny check advisories bans sources # advisories gate (licenses are not checked) ``` Run the GUI with `cargo run -p modrix-gui`, the CLI with `cargo run -p modrix-cli -- `. @@ -403,7 +403,7 @@ Most games need only a declarative definition. Drop a `game.toml` at `/g 1. Fork the repository and branch: `feat/short-description` or `fix/short-description`. 2. Keep commits focused, one logical change each. -3. Run the full gate before pushing: `cargo fmt --all -- --check`, `cargo clippy --all-targets --all-features -- -D warnings`, `cargo test --all --all-features`, `cargo deny check`. +3. Run the full gate before pushing: `cargo fmt --all -- --check`, `cargo clippy --all-targets --all-features -- -D warnings`, `cargo test --all --all-features`, `cargo deny check advisories bans sources`. 4. Open a PR against `main` describing what it changes, how you tested it, and any edge cases considered. For deploy-engine changes, note which invariant your test protects. @@ -417,7 +417,7 @@ Most games need only a declarative definition. Drop a `game.toml` at `/g Modrix is released under the **GNU General Public License v2.0 only** (`GPL-2.0-only`). -You are free to use, modify, and distribute it under the terms of the GPLv2. Every dependency is GPLv2-compatible, verified by `cargo-deny` in CI. The one documented carve-out is a [GUI linking exception](docs/LICENSE-EXCEPTIONS.md) for the Apache-2.0 windowing and text crates the Iced GUI links; the engine itself links zero Apache-2.0 code. +You are free to use, modify, and distribute it under the terms of the GPLv2. Dependency licenses are not policed by the build; consult `cargo tree` and each crate's own license if you redistribute binaries. See [`LICENSE`](LICENSE) for the full text. diff --git a/branding/README.md b/branding/README.md index 27bc90b..83a6fba 100644 --- a/branding/README.md +++ b/branding/README.md @@ -36,9 +36,9 @@ Two-tone: `MOD` in the accent blue, `RIX` in white, on black. | white | `#FFFFFF` | `RIX` | | black | `#000000` | background | -The blue is the same value as `theme::AURORA.accent` in -`crates/modrix-gui/src/theme.rs`. If one changes, change the other: the logo and -the running app are meant to share one accent. +The running app takes its accent from the selected game's artwork. With no +artwork it falls back to this blue's hue (`DEFAULT_HUE` in +`crates/modrix-gui/src/look.rs`); if the blue changes, change that too. Typeface is **Noto Sans Bold**. Its outlines are baked into `glyphs.json` as SVG path data, so the marks render identically everywhere with no font dependency and @@ -112,4 +112,4 @@ Noto Sans is licensed under the SIL Open Font License 1.1 by the Noto Project Authors. `glyphs.json` contains outlines for six characters converted to path data, used as artwork rather than redistributed as font software, which is the ordinary way a typeface is used to set a logo. The OFL is not in Modrix's -dependency graph and is not checked by `cargo deny`, which only sees Rust crates. +dependency graph and is outside anything `cargo deny` sees (it checks Rust crates, and no longer their licenses). diff --git a/crates/modrix-cli/Cargo.toml b/crates/modrix-cli/Cargo.toml index 42f9aa3..30b4467 100644 --- a/crates/modrix-cli/Cargo.toml +++ b/crates/modrix-cli/Cargo.toml @@ -14,6 +14,8 @@ path = "src/main.rs" [dependencies] modrix-core.workspace = true +modrix-il2cpp.workspace = true +modrix-interop-gen.workspace = true modrix-ipc.workspace = true modrix-mcp.workspace = true modrix-plugin.workspace = true diff --git a/crates/modrix-cli/src/interop.rs b/crates/modrix-cli/src/interop.rs new file mode 100644 index 0000000..903ba64 --- /dev/null +++ b/crates/modrix-cli/src/interop.rs @@ -0,0 +1,315 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! `modrix interop` - generate the managed reference assemblies an IL2CPP game +//! needs before a mod can be compiled against it. +//! +//! This is what makes an IL2CPP game buildable without any third-party loader. +//! Both inputs already sit in the game directory: `global-metadata.dat` names +//! every type, and `GameAssembly.dll` carries the type table those names index +//! into. Nothing is downloaded and nothing else has to be installed. + +use std::io::Write; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result, bail}; +use modrix_core::{Engine, Game}; +use modrix_il2cpp::{GameBinary, Metadata}; +use modrix_interop_gen::{GameModel, emit_all}; + +use crate::Cli; +use crate::output; + +/// Where the metadata lives, relative to the install directory, per game. +/// The data folder is named after the executable, so it cannot be derived +/// generically - but it is discoverable by looking for the one `*_Data` folder +/// that contains an `il2cpp_data` subdirectory. +const METADATA_TAIL: &str = "il2cpp_data/Metadata/global-metadata.dat"; + +/// Interop subcommands. +#[derive(clap::Subcommand, Debug)] +pub enum InteropCmd { + /// Generate reference assemblies into the loader's interop directory. + Generate { + /// Write here instead of the loader's own interop directory. + #[arg(long)] + out: Option, + }, + /// Look up types in the game's metadata: members, and enum values. + /// + /// Reads `global-metadata.dat` directly, so it answers from the shipped + /// game rather than from generated assemblies - which matters when the + /// question is "what integer does this enum member actually have", since + /// that is the kind of constant a mod otherwise has to hardcode and guess. + Inspect { + /// Case-insensitive substring matched against `Namespace.Name`. + pattern: String, + /// Also list each matching type's methods. + #[arg(long)] + methods: bool, + /// Stop after this many types. + #[arg(long, default_value_t = 20)] + limit: usize, + }, +} + +/// What a generation run produced. +#[derive(serde::Serialize)] +struct GenerateReport { + /// Where the assemblies were written. + output: PathBuf, + /// How many assemblies were emitted. + assemblies: usize, + /// Total bytes written. + bytes: u64, + /// The game's IL2CPP metadata version. + metadata_version: i32, +} + +/// Run an `interop` subcommand. +/// +/// # Errors +/// +/// Fails if the game is not IL2CPP, its files cannot be read, or the output +/// directory cannot be written. +pub fn interop_cmd( + cmd: &InteropCmd, + cli: &Cli, + engine: &Engine, + out: &mut dyn Write, +) -> Result<()> { + let game = crate::resolve_game(cli, engine)?; + match cmd { + InteropCmd::Generate { out: dest } => generate(&game, engine, dest.as_deref(), cli, out), + InteropCmd::Inspect { + pattern, + methods, + limit, + } => inspect(&game, pattern, *methods, *limit, out), + } +} + +fn generate( + game: &Game, + engine: &Engine, + dest: Option<&Path>, + cli: &Cli, + out: &mut dyn Write, +) -> Result<()> { + let install = Path::new(&game.install_path); + let metadata_path = find_metadata(install) + .with_context(|| format!("{} does not look like an IL2CPP game", game.name))?; + let binary_path = install.join("GameAssembly.dll"); + if !binary_path.exists() { + bail!("GameAssembly.dll is missing from {}", install.display()); + } + + let target = match dest { + Some(path) => path.to_path_buf(), + None => interop_dir(game, engine)?, + }; + + let metadata = Metadata::open(&metadata_path) + .with_context(|| format!("reading {}", metadata_path.display()))?; + let type_count = metadata.type_count()?; + let binary = GameBinary::open(&binary_path, type_count) + .with_context(|| format!("reading {}", binary_path.display()))?; + let model = GameModel::build(&metadata, &binary)?; + let emitted = emit_all(&model, &metadata)?; + + std::fs::create_dir_all(&target).with_context(|| format!("creating {}", target.display()))?; + let mut bytes = 0_u64; + for (name, body) in &emitted { + let path = target.join(format!("{name}.dll")); + std::fs::write(&path, body).with_context(|| format!("writing {}", path.display()))?; + bytes = bytes.saturating_add(u64::try_from(body.len()).unwrap_or(u64::MAX)); + } + // Stamp what the assemblies were generated from, so a game update can be + // detected as "these are stale" rather than surfacing as mystery compile + // errors against renamed types. + let stamp = target.join("generated-from.txt"); + let _ = std::fs::write( + &stamp, + format!( + "metadata_version={}\ntypes={}\nassemblies={}\n", + metadata.version(), + type_count, + emitted.len() + ), + ); + + let report = GenerateReport { + output: target, + assemblies: emitted.len(), + bytes, + metadata_version: metadata.version(), + }; + output::emit(out, cli.json, &report, |out, report| { + // Integer megabytes: the exact byte count is in the JSON envelope, and + // a float cast here trips the precision lint for no reader benefit. + let megabytes = report.bytes.saturating_div(1_048_576); + writeln!( + out, + "Generated {} reference assemblies ({megabytes} MB) from IL2CPP metadata v{}", + report.assemblies, report.metadata_version + )?; + writeln!(out, " -> {}", report.output.display())?; + writeln!( + out, + "\nMods can now be compiled against this game with no third-party loader." + )?; + Ok(()) + }) +} + +/// The loader's interop directory, from the game definition. +fn interop_dir(game: &Game, engine: &Engine) -> Result { + let def = engine.game_def(game.id)?; + let loader = def + .mod_loader + .as_ref() + .context("this game declares no mod loader, so there is nowhere to put interop")?; + let relative = loader + .interop_dir + .as_deref() + .context("this game's loader declares no interop directory")?; + Ok(Path::new(&game.install_path).join(relative)) +} + +/// Locate `global-metadata.dat` under whichever `*_Data` folder holds it. +fn find_metadata(install: &Path) -> Result { + let entries = + std::fs::read_dir(install).with_context(|| format!("reading {}", install.display()))?; + for entry in entries.flatten().take(4096) { + let path = entry.path(); + if !path.is_dir() { + continue; + } + let candidate = path.join(METADATA_TAIL); + if candidate.is_file() { + return Ok(candidate); + } + } + bail!("no {METADATA_TAIL} found under {}", install.display()) +} + +/// Print every type whose `Namespace.Name` contains `pattern`. +/// +/// # Errors +/// +/// Fails when the game is not IL2CPP or its metadata cannot be read. +fn inspect( + game: &Game, + pattern: &str, + with_methods: bool, + limit: usize, + out: &mut dyn Write, +) -> Result<()> { + let install = Path::new(&game.install_path); + let metadata_path = find_metadata(install) + .with_context(|| format!("{} does not look like an IL2CPP game", game.name))?; + let metadata = Metadata::open(&metadata_path) + .with_context(|| format!("reading {}", metadata_path.display()))?; + + // Constants are stored in one table keyed by field index, so it is read once + // rather than per field - the alternative is a linear scan per enum member. + let defaults = metadata.default_values()?; + let needle = pattern.to_lowercase(); + let total = metadata.type_count()?; + + let mut shown = 0_usize; + for index in 0..total { + if shown >= limit { + writeln!( + out, + "... stopping at {limit} types; narrow the pattern or raise --limit" + )?; + break; + } + let type_def = metadata.type_def(index)?; + let full = if type_def.namespace.is_empty() { + type_def.name.clone() + } else { + format!("{}.{}", type_def.namespace, type_def.name) + }; + if !full.to_lowercase().contains(&needle) { + continue; + } + shown = shown.saturating_add(1); + writeln!(out, "{full}")?; + write_fields(&metadata, &type_def, &defaults, out)?; + if with_methods { + write_methods(&metadata, &type_def, out)?; + } + } + + if shown == 0 { + writeln!(out, "no type matching '{pattern}' in {}", game.name)?; + } + Ok(()) +} + +/// Print a type's fields, with the constant value when it has one. +fn write_fields( + metadata: &Metadata, + type_def: &modrix_il2cpp::TypeDef, + defaults: &std::collections::HashMap, + out: &mut dyn Write, +) -> Result<()> { + let Some(start) = type_def.fields.start else { + return Ok(()); + }; + let count = type_def.fields.count; + for offset in 0..count { + let index = start.saturating_add(offset); + let field = metadata.field_def(index)?; + match defaults.get(&index) { + // An enum member or a const: the value is the whole point of asking. + Some(default) => writeln!(out, " {} = {}", field.name, default.value)?, + None => writeln!(out, " {}", field.name)?, + } + } + Ok(()) +} + +/// Print a type's methods with their parameter names. +fn write_methods( + metadata: &Metadata, + type_def: &modrix_il2cpp::TypeDef, + out: &mut dyn Write, +) -> Result<()> { + /// `MethodAttributes.Static`. + const STATIC: u16 = 0x0010; + + let Some(start) = type_def.methods.start else { + return Ok(()); + }; + let count = type_def.methods.count; + for offset in 0..count { + let index = start.saturating_add(offset); + let method = metadata.method_def(index)?; + let params = method_parameters(metadata, &method)?; + let modifier = if method.flags & STATIC != 0 { + "static " + } else { + "" + }; + writeln!(out, " {modifier}{}({})", method.name, params.join(", "))?; + } + Ok(()) +} + +/// Parameter names for one method, in declaration order. +fn method_parameters( + metadata: &Metadata, + method: &modrix_il2cpp::MethodDef, +) -> Result> { + let Some(start) = method.parameters.start else { + return Ok(Vec::new()); + }; + let count = method.parameters.count; + let mut names = Vec::with_capacity(count); + for offset in 0..count { + let param = metadata.param_def(start.saturating_add(offset))?; + names.push(param.name); + } + Ok(names) +} diff --git a/crates/modrix-cli/src/main.rs b/crates/modrix-cli/src/main.rs index f917d8e..9f5b283 100644 --- a/crates/modrix-cli/src/main.rs +++ b/crates/modrix-cli/src/main.rs @@ -6,6 +6,7 @@ //! do is reachable here. All business logic lives in the engine - this file only //! parses arguments, calls engine methods, and formats the result. +mod interop; mod output; mod parity; mod registry; @@ -71,6 +72,31 @@ enum Command { }, /// Remove everything the current deployment placed, restoring originals. Undeploy, + /// Start the game. Returns immediately; follow `modrix log` to watch it boot. + Launch { + /// Deploy the active profile first (the usual test-a-change one-shot). + #[arg(long)] + deploy: bool, + }, + /// Read the game's log. Pass the printed cursor as `--since` to follow it. + Log { + /// Byte offset to resume from; 0 reads the newest window. + #[arg(long, default_value_t = 0)] + since: u64, + /// Maximum lines to print (capped at 2000). + #[arg(long, default_value_t = 200)] + lines: usize, + }, + /// Generate the reference assemblies an IL2CPP game needs to build mods. + Interop { + #[command(subcommand)] + cmd: interop::InteropCmd, + }, + /// Inspect the game's mod loader. + Loader { + #[command(subcommand)] + cmd: LoaderCmd, + }, /// Verify the current deployment against the manifest. Verify, /// Run the headless background service that handles browser download @@ -261,6 +287,10 @@ fn dispatch(cli: &Cli, engine: &Engine, out: &mut dyn Write) -> Result<()> { Command::Deploy { dry_run } => deploy(cli, engine, *dry_run, out), Command::Undeploy => undeploy(cli, engine, out), Command::Verify => verify(cli, engine, out), + Command::Launch { deploy } => launch(cli, engine, *deploy, out), + Command::Log { since, lines } => log_tail(cli, engine, *since, *lines, out), + Command::Interop { cmd } => interop::interop_cmd(cmd, cli, engine, out), + Command::Loader { cmd } => loader_cmd(cmd, cli, engine, out), Command::Registry { cmd } => registry::registry_cmd(cmd, engine, out), Command::Plugin { cmd } => registry::plugin_cmd(cmd, out), Command::Plugins { cmd } => parity::plugins_cmd(cmd, cli, engine, out), @@ -512,10 +542,99 @@ fn verify(cli: &Cli, engine: &Engine, out: &mut dyn Write) -> Result<()> { output::emit(out, cli.json, &data, |out, _| output::verify(&report, out)) } +// --- launch, loader, and logs ---------------------------------------------- + +/// Loader subcommands. +#[derive(Subcommand, Debug)] +enum LoaderCmd { + /// Whether the mod loader is installed, and what is in its way. + Status, +} + +fn launch(cli: &Cli, engine: &Engine, deploy_first: bool, out: &mut dyn Write) -> Result<()> { + let game = resolve_game(cli, engine)?; + if deploy_first { + let profile = engine.active_profile(game.id)?; + engine.deploy(profile.id)?; + } + let outcome = engine.launch(game.id)?; + output::emit(out, cli.json, &outcome, |out, outcome| { + if outcome.stopped_existing { + writeln!(out, "Stopped the running instance.")?; + } + writeln!(out, "Launched {} via {}", game.name, outcome.command)?; + // A launch that cannot deliver the loader's environment starts a + // perfectly working *unmodded* game, which is the confusing case. + if let Some(warning) = &outcome.readiness.warning { + writeln!(out, "\nwarning: {warning}")?; + } + Ok(()) + }) +} + +fn log_tail( + cli: &Cli, + engine: &Engine, + since: u64, + lines: usize, + out: &mut dyn Write, +) -> Result<()> { + let game = resolve_game(cli, engine)?; + let tail = engine.tail_log(game.id, since, lines)?; + output::emit(out, cli.json, &tail, |out, tail| { + if tail.truncated { + writeln!(out, "-- log restarted (new session) --")?; + } + for line in &tail.lines { + writeln!(out, "{line}")?; + } + writeln!(out, "-- cursor {} --", tail.next_cursor)?; + Ok(()) + }) +} + +fn loader_cmd(cmd: &LoaderCmd, cli: &Cli, engine: &Engine, out: &mut dyn Write) -> Result<()> { + let game = resolve_game(cli, engine)?; + match cmd { + LoaderCmd::Status => { + let status = engine.loader_status(game.id)?; + output::emit(out, cli.json, &status, |out, status| { + let state = if status.installed { + "installed" + } else { + "not installed" + }; + writeln!(out, "{}: {state}", status.kind)?; + if let Some(version) = &status.version { + writeln!(out, " version: {version}")?; + } + writeln!(out, " root: {}", status.install_root.display())?; + writeln!( + out, + " interop: {}", + if status.interop_ready { + "generated" + } else { + "not generated - mods cannot be compiled yet" + } + )?; + if let Some(conflict) = &status.conflict { + writeln!( + out, + "\nwarning: `{conflict}` already occupies the loader slot. \ + Two loaders cannot share it - remove that one first." + )?; + } + Ok(()) + }) + } + } +} + // --- resolution helpers ---------------------------------------------------- /// Resolve the game to act on from `--game` (or the sole game if unambiguous). -fn resolve_game(cli: &Cli, engine: &Engine) -> Result { +pub(crate) fn resolve_game(cli: &Cli, engine: &Engine) -> Result { let games = engine.games()?; if games.is_empty() { bail!("no games registered - add one with `modrix game add`"); diff --git a/crates/modrix-core/src/defcat.rs b/crates/modrix-core/src/defcat.rs index 3d43845..88c1663 100644 --- a/crates/modrix-core/src/defcat.rs +++ b/crates/modrix-core/src/defcat.rs @@ -133,8 +133,8 @@ mod tests { let defs = builtin_defs(); assert!(!defs.is_empty(), "at least the shipped games must embed"); for entry in &defs { - assert!(!entry.def.id.trim().is_empty()); - assert!(!entry.def.name.trim().is_empty()); + assert_ne!(entry.def.id.trim(), ""); + assert_ne!(entry.def.name.trim(), ""); } } diff --git a/crates/modrix-core/src/deploy/fsops.rs b/crates/modrix-core/src/deploy/fsops.rs index 4932e1b..09084a8 100644 --- a/crates/modrix-core/src/deploy/fsops.rs +++ b/crates/modrix-core/src/deploy/fsops.rs @@ -464,7 +464,10 @@ mod tests { assert!(created[0].ends_with("a")); assert!(created[2].ends_with("a/b/c") || created[2].ends_with("a\\b\\c")); // Re-running creates nothing new. - assert!(ensure_parent_dirs(&target).unwrap().is_empty()); + { + let left = ensure_parent_dirs(&target).unwrap(); + assert!(left.is_empty(), "expected empty, got {left:?}"); + } } #[test] diff --git a/crates/modrix-core/src/deploy/plan.rs b/crates/modrix-core/src/deploy/plan.rs index 598738a..d8f51f9 100644 --- a/crates/modrix-core/src/deploy/plan.rs +++ b/crates/modrix-core/src/deploy/plan.rs @@ -347,7 +347,7 @@ mod tests { assert_eq!(p.to_add(), 2); assert_eq!(p.to_remove(), 0); assert_eq!(p.unchanged(), 0); - assert!(p.conflicts().is_empty()); + assert_eq!(p.conflicts(), []); } #[test] diff --git a/crates/modrix-core/src/detect.rs b/crates/modrix-core/src/detect.rs index cad9e4f..766525d 100644 --- a/crates/modrix-core/src/detect.rs +++ b/crates/modrix-core/src/detect.rs @@ -512,7 +512,10 @@ mod tests { let text = "\"libraryfolders\"\n{\n\t\"0\"\n\t{\n\t\t\"path\"\t\t\"/games/lib\"\n\t\t\"apps\"\n\t\t{\n\t\t\t\"264710\"\t\t\"7\"\n\t\t}\n\t}\n}\n"; assert_eq!(vdf_values(text, "path"), vec!["/games/lib".to_owned()]); // `apps` and `libraryfolders` are block headers: no scalar value. - assert!(vdf_values(text, "apps").is_empty()); + { + let left = vdf_values(text, "apps"); + assert!(left.is_empty(), "expected empty, got {left:?}"); + } } #[test] diff --git a/crates/modrix-core/src/engine.rs b/crates/modrix-core/src/engine.rs index fc0a591..8878729 100644 --- a/crates/modrix-core/src/engine.rs +++ b/crates/modrix-core/src/engine.rs @@ -251,12 +251,89 @@ impl Engine { load_order: crate::loadorder::LoadOrderStrategy::from_def(&def).is_some(), external_scan: !external_scans_of(&def).is_empty(), health_checks: def.health.is_some(), + launch: def.launch.is_some(), + mod_loader: def.mod_loader.is_some(), + store: def.store.is_some(), }) } + + // --- launch, loader, and logs ------------------------------------------ + // + // These are the only actions that touch anything outside the mod store, so + // they stay deliberately thin: `launch.rs` holds the logic, the engine just + // resolves the game's definition and install path and hands off. + + /// Whether the game's mod loader is installed, and what is in the way. + /// + /// # Errors + /// + /// Returns [`Error::NotFound`] for an unknown game, or [`Error::Loader`] + /// if the game declares no loader at all. + pub fn loader_status(&self, id: GameId) -> Result { + let (game, def) = (self.game(id)?, self.game_def(id)?); + let loader = def.mod_loader.as_ref().ok_or_else(|| Error::Loader { + message: format!("{} does not use a mod loader", game.name), + })?; + crate::launch::loader_status(Path::new(&game.install_path), loader) + } + + /// Start the game. + /// + /// Fire-and-forget: this returns once the launch is handed off, without + /// waiting for the game to appear. Poll [`Engine::tail_log`] if you need to + /// know it actually started. + /// + /// # Errors + /// + /// Returns [`Error::NotFound`] for an unknown game, or [`Error::Launch`] if + /// the game declares no launch method or the command could not be spawned. + pub fn launch(&self, id: GameId) -> Result { + let (game, def) = (self.game(id)?, self.game_def(id)?); + let launch = def.launch.as_ref().ok_or_else(|| Error::Launch { + message: format!("{} does not declare how to launch", game.name), + })?; + crate::launch::launch(Path::new(&game.install_path), launch, def.steam_appid) + } + + /// Read a bounded window of the game's log, starting at byte `since`. + /// + /// Pass the returned `next_cursor` as the next `since` to follow the log. + /// A `truncated` result means the log restarted (the loader truncates on + /// launch), so a caller following it should reset its own view. + /// + /// # Errors + /// + /// Returns [`Error::NotFound`] for an unknown game, or [`Error::Launch`] if + /// the game declares no log path. A log that does not exist yet is *not* an + /// error - it yields an empty tail. + pub fn tail_log( + &self, + id: GameId, + since: u64, + max_lines: usize, + ) -> Result { + let (game, def) = (self.game(id)?, self.game_def(id)?); + let rel = def + .launch + .as_ref() + .and_then(|l| l.log.as_deref()) + .ok_or_else(|| Error::Launch { + message: format!("{} does not declare a log path", game.name), + })?; + crate::launch::tail_log(&Path::new(&game.install_path).join(rel), since, max_lines) + } } /// What a game supports, derived from its definition. +/// +/// Frontends gate whole screens on these, so each really is an independent +/// yes/no about one feature - the usual "replace the bools with an enum" +/// advice does not apply, because a game can support any combination. #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] +#[expect( + clippy::struct_excessive_bools, + reason = "one independent capability flag per feature; not a state machine" +)] pub struct GameCapabilities { /// The game has a load-order strategy (a Load Order screen makes sense). pub load_order: bool, @@ -264,6 +341,13 @@ pub struct GameCapabilities { pub external_scan: bool, /// The game declares game-specific health checks. pub health_checks: bool, + /// The game declares how to launch it (a Play button makes sense). + pub launch: bool, + /// The game declares a mod loader Modrix can install and check. + pub mod_loader: bool, + /// The game declares a community mod store (a browse-and-install screen + /// makes sense). + pub store: bool, } /// A minimal definition for a legacy row whose definition file is gone: @@ -291,6 +375,14 @@ fn synthesize_def(game: &Game) -> GameDef { base_files: Vec::new(), external_scan: Vec::new(), health: None, + // A legacy row predates v3, so it declares none of these: keep the + // mod-root-shape inference, and offer neither launch nor loader + // management (frontends gate on `capabilities`, so the controls + // simply stay hidden rather than failing at the point of use). + park_root_binaries: None, + launch: None, + mod_loader: None, + store: None, } } @@ -431,16 +523,23 @@ impl Engine { let version = detected.and_then(|d| d.version.as_deref()); let nexus_mod_id = detected.and_then(|d| d.nexus_mod_id); let mod_root = self.game(game)?.mod_root; - // The definition's content-dir list steers archive normalization - // (which lone root directories are content vs packaging wrappers). - let content_dirs = self - .game_def(game) - .map(|d| d.content_dirs) + // The definition steers archive normalization: which lone root + // directories are content vs packaging wrappers, and whether a + // top-level binary is a loader to park or the mod payload itself. + let def = self.game_def(game).ok(); + let content_dirs = def + .as_ref() + .map(|d| d.content_dirs.clone()) .unwrap_or_default(); + let shape = ShapeOpts { + mod_root: &mod_root, + content_dirs: &content_dirs, + park_root: def.as_ref().and_then(|d| d.park_root_binaries), + }; let staged = self.paths.staging_root().join(game.to_string()).join(name); let logic = self.logic_of(game); self.progress.begin(&format!("Installing · {name}"), 0); - let extracted = extract_into(path, &staged, &mod_root, &content_dirs, logic.as_deref()); + let extracted = extract_into(path, &staged, &shape, logic.as_deref()); self.progress.finish(); if let Err(error) = extracted { // Never leave a half-staged tree behind a failed stage. @@ -1307,14 +1406,24 @@ fn is_system_archive(path: &Path) -> bool { EXTS.iter().any(|ext| name.ends_with(ext)) } +/// How the game definition says a staged tree should be shaped. Bundled into +/// one struct so `extract_into` stays inside the workspace argument limit. +struct ShapeOpts<'a> { + /// Where mods deploy, relative to the base (`Data`, `BepInEx/plugins`). + mod_root: &'a str, + /// Directory names that are content, not a packaging wrapper. + content_dirs: &'a [String], + /// Override for loader-binary parking; `None` = infer from `mod_root`. + park_root: Option, +} + /// Extract or copy `path` into `staged`, then shape the tree: a registered /// Tier-2 plugin may return a stage plan (validated and applied by core); /// otherwise the data-driven normalization runs. fn extract_into( path: &Path, staged: &Path, - mod_root: &str, - content_dirs: &[String], + shape: &ShapeOpts<'_>, logic: Option<&dyn crate::logic::GameLogic>, ) -> Result<()> { if path.is_dir() { @@ -1332,7 +1441,7 @@ fn extract_into( } match logic.map(|l| l.install(staged)).transpose()? { Some(Some(plan)) => crate::logic::apply_plan(staged, &plan)?, - _ => store::normalize_staged(staged, mod_root, content_dirs)?, + _ => store::normalize_staged(staged, shape.mod_root, shape.content_dirs, shape.park_root)?, } // Stamp AFTER structural shaping so the final tree is covered // (renames preserve mtimes, so order is for clarity, not correctness). diff --git a/crates/modrix-core/src/error.rs b/crates/modrix-core/src/error.rs index 19e3d7f..4f710d5 100644 --- a/crates/modrix-core/src/error.rs +++ b/crates/modrix-core/src/error.rs @@ -23,6 +23,20 @@ pub enum Error { #[error("could not determine platform directories for this user")] NoProjectDirs, + /// The game could not be started, or its definition does not say how. + #[error("could not launch the game: {message}")] + Launch { + /// What went wrong. + message: String, + }, + + /// A mod loader operation was refused or failed. + #[error("mod loader: {message}")] + Loader { + /// What went wrong. + message: String, + }, + /// A database operation failed. #[error("database error: {0}")] Database(#[from] rusqlite::Error), diff --git a/crates/modrix-core/src/gamedef.rs b/crates/modrix-core/src/gamedef.rs index cc3b0ec..e0f4c5a 100644 --- a/crates/modrix-core/src/gamedef.rs +++ b/crates/modrix-core/src/gamedef.rs @@ -15,10 +15,19 @@ use std::path::Path; use crate::error::{Error, Result}; +/// The `mod_loader.kind` that means "Modrix supplies this loader itself" - there +/// is nothing to download and no third-party project to track. +pub const NATIVE_LOADER_KIND: &str = "modrix-sons"; + /// The oldest `game.toml` schema version this build understands. pub const MIN_API_VERSION: u32 = 1; /// The newest `game.toml` schema version this build understands. -pub const MAX_API_VERSION: u32 = 2; +/// +/// v3 adds `[launch]`, `[mod_loader]` and `park_root_binaries`: a definition can +/// now declare how to start the game, which mod loader it needs, and that its +/// mod root must not have top-level binaries parked away from it. Every new +/// field is `#[serde(default)]`, so v1/v2 definitions parse unchanged. +pub const MAX_API_VERSION: u32 = 3; /// A parsed, validated game definition. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] @@ -121,6 +130,149 @@ pub struct GameDef { /// pairings). Absent = none run. #[serde(default)] pub health: Option, + /// Whether a top-level `.exe`/`.dll` in a staged archive is a *loader* + /// that belongs beside the game binary (parked into `.root/`) rather than + /// the mod payload itself. + /// + /// Absent = infer from the shape of `mod_root`, which is right for + /// Bethesda (`Data` sits beside the binary, so a loose DLL is SKSE) and + /// for nested roots (`BepInEx/plugins` IS the plugin container). It is + /// WRONG for a loader whose mod directory is a single component holding + /// bare payload DLLs - Sons of the Forest deploys `Mods/.dll`, and + /// inferring would park every mod to the install root where nothing loads + /// it. Such a game sets this to `false` explicitly. + #[serde(default)] + pub park_root_binaries: Option, + /// How to start the game (and where it writes its log). Absent = Modrix + /// cannot launch this game and frontends hide the control. + #[serde(default)] + pub launch: Option, + /// The mod loader this game needs before any mod will load. Absent = + /// mods drop straight into the game and no loader is managed. + /// + /// Named `mod_loader` rather than `loader` because `loader` is already a + /// nested key under `[health]`, and the misplaced-key guard below relies + /// on top-level names never being valid inside a table. + #[serde(default)] + pub mod_loader: Option, + /// The community mod store this game has, when one exists. Absent = mods + /// arrive only through the browser hand-off and frontends hide the + /// browse-and-install screen entirely. + #[serde(default)] + pub store: Option, +} + +/// A community mod store a game's mods can be browsed and installed from. +/// +/// Deliberately just an identity plus an origin: `kind` selects the client that +/// knows the site's JSON shape (each store's API differs, so there is no useful +/// generic schema to declare here), and `base_url` is the only thing that ever +/// varies per deployment. Core stores and validates this; it does not speak +/// HTTP - the client lives in `modrix-service`, keeping core free of any +/// site-specific code. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct StoreDef { + /// Which store client handles this API (e.g. `sotf-mods`). An unknown kind + /// is not an error here - a newer definition may name a client this build + /// does not have yet, and the frontend simply finds no handler. + pub kind: String, + /// The API origin, with no trailing slash (e.g. `https://api.sotf-mods.com`). + /// Must be `https://` - a store install runs unattended and ends in code + /// deployed into the game directory, so the transport is never optional. + pub base_url: String, +} + +/// How to start a game, and where to read its log afterwards. +/// +/// Deliberately fire-and-forget: Modrix starts the game and stops caring. +/// Supervising a game process (PID tracking, restart watchdogs) is a different +/// problem with its own failure modes, and nothing here needs it. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct LaunchDef { + /// `"steam"` (via `steam://rungameid/`) or `"exe"` (run + /// `exe` from the install directory). + pub mode: String, + /// For `mode = "exe"`: the executable, relative to the install directory. + #[serde(default)] + pub exe: Option, + /// Extra command-line arguments. + #[serde(default)] + pub args: Vec, + /// Environment variables the game needs. On Linux/macOS a Windows-only + /// title runs under Proton/Wine, where a loader's proxy DLL is inert + /// unless `WINEDLLOVERRIDES` names it - that is what this carries. + /// Ignored on Windows, where the proxy loads natively. + /// + /// A `BTreeMap` rather than a `HashMap` so the rendered launch options are + /// byte-stable across runs; Modrix compares them to decide whether a + /// Steam config actually needs rewriting. + #[serde(default)] + pub env: std::collections::BTreeMap, + /// The game/loader log, relative to the install directory. + #[serde(default)] + pub log: Option, + /// Process image name used to stop a running instance before relaunching + /// (e.g. `SonsOfTheForest.exe`). Absent = never kill anything. + #[serde(default)] + pub process: Option, +} + +/// A mod loader that must be installed into the game before mods will load. +/// +/// This is *not* a mod: it is infrastructure that lives beside the game binary +/// and is deliberately kept out of the deployment manifest, so `verify` and +/// `undeploy` never treat it as owned content. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct LoaderDef { + /// Loader identity. `modrix-sons` is Modrix's own native loader (built in, + /// nothing to download); anything else names a third-party loader that + /// `source` says how to fetch. + pub kind: String, + /// The loader's own directory, relative to the install dir (`_Modrix`). + pub install_root: String, + /// A file that exists if and only if the loader is installed, relative to + /// the install dir. This is the installed/not-installed test. + pub sentinel: String, + /// The proxy DLL the loader injects through, relative to the install dir + /// (`version.dll`). Games have exactly one such slot, which is why two + /// loaders can never coexist. + #[serde(default)] + pub proxy: Option, + /// Where generated interop assemblies land, relative to the install dir. + /// IL2CPP games only; mods compile against these. + #[serde(default)] + pub interop_dir: Option, + /// A file holding the installed version string, relative to the install + /// dir. Absent = version is unknown but installation is still detectable. + #[serde(default)] + pub version_file: Option, + /// Paths (relative to the install dir) whose presence means a *rival* + /// loader already owns the proxy slot. Installing over one of these + /// bricks both, so Modrix refuses rather than guessing. + #[serde(default)] + pub conflicts: Vec, + /// Where to fetch a third-party loader. Absent = `kind` is native and + /// Modrix supplies it. + #[serde(default)] + pub source: Option, +} + +/// Where a third-party loader's release archive comes from. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct LoaderSourceDef { + /// `owner/repo` whose latest GitHub release carries the loader. + #[serde(default)] + pub github_repo: Option, + /// Release asset name, matched case-insensitively (asset casing drifts + /// between releases, so this is never an exact match). + #[serde(default)] + pub asset: Option, + /// A direct download URL, used instead of `github_repo`. + #[serde(default)] + pub url: Option, + /// Expected SHA-256 of the archive, when it is pinned. + #[serde(default)] + pub sha256: Option, } /// A load-order strategy declaration. @@ -224,7 +376,7 @@ pub struct RecommendDef { /// unambiguously a misplaced key rather than a field from a newer schema /// (unknown nested keys stay tolerated, so definitions written for a later /// build still load). -const TOP_LEVEL_KEYS: [&str; 21] = [ +const TOP_LEVEL_KEYS: [&str; 25] = [ "api_version", "id", "name", @@ -246,6 +398,10 @@ const TOP_LEVEL_KEYS: [&str; 21] = [ "base_files", "external_scan", "health", + "park_root_binaries", + "launch", + "mod_loader", + "store", ]; /// Most nodes the misplaced-key walk will visit (bounded loop, no recursion). @@ -419,6 +575,83 @@ impl GameDef { return Some("a registry_keys entry needs a `key` and a `value`".to_owned()); } } + self.validate_launch() + .or_else(|| self.validate_loader()) + .or_else(|| self.validate_store()) + } + + /// Check the `[launch]` table. Split out of [`Self::validate_details`] to + /// keep each validator under the workspace's 60-line ceiling. + fn validate_launch(&self) -> Option { + let launch = self.launch.as_ref()?; + match launch.mode.as_str() { + "steam" => { + if self.steam_appid.is_none() { + return Some("launch.mode = \"steam\" needs a `steam_appid`".to_owned()); + } + } + "exe" => { + let named = launch.exe.as_ref().is_some_and(|e| !e.trim().is_empty()); + if !named { + return Some("launch.mode = \"exe\" needs an `exe`".to_owned()); + } + } + other => return Some(format!("unknown launch mode `{other}` (steam/exe)")), + } + if launch.log.as_ref().is_some_and(|l| l.trim().is_empty()) { + return Some("launch.log must not be empty when present".to_owned()); + } + None + } + + /// Check the `[loader]` table. + fn validate_loader(&self) -> Option { + let loader = self.mod_loader.as_ref()?; + if loader.kind.trim().is_empty() { + return Some("mod_loader.kind must not be empty".to_owned()); + } + if loader.install_root.trim().is_empty() { + return Some("mod_loader.install_root must not be empty".to_owned()); + } + if loader.sentinel.trim().is_empty() { + return Some("mod_loader.sentinel must not be empty".to_owned()); + } + // A non-native loader has to say where it comes from, or `install` + // would have nothing to do and would silently report success. + if loader.kind != NATIVE_LOADER_KIND { + let src = loader.source.as_ref(); + let fetchable = src.is_some_and(|s| s.github_repo.is_some() || s.url.is_some()); + if !fetchable { + return Some(format!( + "mod_loader.kind `{}` is not native, so [mod_loader.source] needs a `github_repo` or `url`", + loader.kind + )); + } + } + None + } + + /// Check the `[store]` table. Split out for the same reason as + /// [`Self::validate_launch`]: the 60-line ceiling is per function. + fn validate_store(&self) -> Option { + let store = self.store.as_ref()?; + if store.kind.trim().is_empty() { + return Some("store.kind must not be empty".to_owned()); + } + // Plain http would let anyone on the path choose which archive gets + // extracted into the game directory, so it is rejected outright rather + // than warned about. + if !store.base_url.starts_with("https://") { + return Some(format!( + "store.base_url `{}` must be an https:// origin", + store.base_url + )); + } + // A trailing slash would produce `…//api/mods` once a client joins a + // path onto it. Some servers 404 that, so normalize by refusing it. + if store.base_url.ends_with('/') { + return Some("store.base_url must not end with a slash".to_owned()); + } None } } @@ -655,13 +888,150 @@ mod tests { let def = GameDef::from_toml_str(text, &inline()).unwrap(); assert_eq!(def.mod_root, ""); assert!(def.steam_appid.is_none()); - assert!(def.install_probe.is_empty()); - assert!(def.content_dirs.is_empty()); + assert!( + def.install_probe.is_empty(), + "expected empty, got {:?}", + def.install_probe + ); + assert!( + def.content_dirs.is_empty(), + "expected empty, got {:?}", + def.content_dirs + ); assert!(def.external_scan.is_empty()); assert!(def.health.is_none()); assert!(def.gog_id.is_none()); assert!(def.epic_id.is_none()); assert!(def.registry_keys.is_empty()); - assert!(def.required_files.is_empty()); + assert!( + def.required_files.is_empty(), + "expected empty, got {:?}", + def.required_files + ); + // v3 fields default to absent, which is what keeps every v1/v2 + // definition parsing unchanged. + assert!(def.park_root_binaries.is_none()); + assert!(def.launch.is_none()); + assert!(def.mod_loader.is_none()); + assert!(def.store.is_none()); + } + + #[test] + fn parses_a_v3_definition_with_launch_and_loader() { + let text = "\ +api_version = 3 +id = \"g\" +name = \"G\" +steam_appid = 1 +park_root_binaries = false + +[launch] +mode = \"steam\" +log = \"_Modrix/Latest.log\" +process = \"G.exe\" + +[launch.env] +WINEDLLOVERRIDES = \"version=n,b\" + +[mod_loader] +kind = \"modrix-sons\" +install_root = \"_Modrix\" +sentinel = \"_Modrix/net6/Modrix.Loader.dll\" +proxy = \"version.dll\" + +[store] +kind = \"sotf-mods\" +base_url = \"https://api.sotf-mods.com\" +"; + let def = GameDef::from_toml_str(text, &inline()).unwrap(); + assert_eq!(def.park_root_binaries, Some(false)); + let launch = def.launch.expect("launch table parsed"); + assert_eq!(launch.mode, "steam"); + assert_eq!( + launch.env.get("WINEDLLOVERRIDES").map(String::as_str), + Some("version=n,b"), + "the Proton override is what makes a loader work off-Windows" + ); + let loader = def.mod_loader.expect("mod_loader table parsed"); + assert_eq!(loader.kind, NATIVE_LOADER_KIND); + assert!(loader.source.is_none(), "a native loader needs no source"); + let store = def.store.expect("store table parsed"); + assert_eq!(store.kind, "sotf-mods"); + assert_eq!(store.base_url, "https://api.sotf-mods.com"); + } + + #[test] + fn store_tables_are_rejected_when_incoherent() { + let base = "api_version = 3\nid = \"g\"\nname = \"G\"\n"; + // No kind: nothing selects a client, so the screen would show but never + // load. + let text = format!("{base}\n[store]\nkind = \"\"\nbase_url = \"https://x.example\"\n"); + assert!(GameDef::from_toml_str(&text, &inline()).is_err()); + // Plain http: a store install ends in code inside the game directory. + let text = + format!("{base}\n[store]\nkind = \"sotf-mods\"\nbase_url = \"http://x.example\"\n"); + assert!(GameDef::from_toml_str(&text, &inline()).is_err()); + // A trailing slash would build `…//api/mods`. + let text = + format!("{base}\n[store]\nkind = \"sotf-mods\"\nbase_url = \"https://x.example/\"\n"); + assert!(GameDef::from_toml_str(&text, &inline()).is_err()); + } + + #[test] + fn v3_tables_are_rejected_when_incoherent() { + let base = "api_version = 3\nid = \"g\"\nname = \"G\"\n"; + // steam launch without an appid has nothing to launch. + let text = format!("{base}\n[launch]\nmode = \"steam\"\n"); + assert!(GameDef::from_toml_str(&text, &inline()).is_err()); + // exe launch without an exe likewise. + let text = format!("{base}\n[launch]\nmode = \"exe\"\n"); + assert!(GameDef::from_toml_str(&text, &inline()).is_err()); + // An unknown mode is a typo, not a forward-compatible extension. + let text = format!("{base}\n[launch]\nmode = \"magic\"\n"); + assert!(GameDef::from_toml_str(&text, &inline()).is_err()); + // A non-native loader with no source would silently install nothing. + let text = format!( + "{base}\n[mod_loader]\nkind = \"redloader\"\ninstall_root = \"_Redloader\"\n\ + sentinel = \"_Redloader/net6/RedLoader.dll\"\n" + ); + assert!(GameDef::from_toml_str(&text, &inline()).is_err()); + } + + #[test] + fn v3_is_the_newest_supported_schema() { + let text = "api_version = 4\nid = \"g\"\nname = \"G\"\n"; + assert!( + GameDef::from_toml_str(text, &inline()).is_err(), + "a definition from a newer build must be rejected, not half-read" + ); + } + + #[test] + fn shipped_sonsoftheforest_definition_opts_out_of_parking() { + // Regression guard for a silent misdeploy: `Mods` is a single-component + // mod root, so without the explicit opt-out every payload DLL is parked + // to `.root/` and deployed to the game install directory, where the + // loader never looks. Deploy reports success; nothing loads. + let text = include_str!("../../../games/sonsoftheforest/game.toml"); + let path = std::path::Path::new("games/sonsoftheforest/game.toml"); + let def = GameDef::from_toml_str(text, path).unwrap(); + assert_eq!(def.api_version, 3); + assert_eq!(def.mod_root, "Mods"); + assert_eq!( + def.park_root_binaries, + Some(false), + "removing this silently breaks every Sons of the Forest mod" + ); + let loader = def.mod_loader.expect("declares a loader"); + assert_eq!(loader.kind, NATIVE_LOADER_KIND); + assert!( + loader.conflicts.iter().any(|c| c == "MelonLoader"), + "must refuse to install over a rival proxy owner" + ); + // The Mod Store tab is gated on this table alone, so losing it would + // silently remove the only in-app way to install a Sons mod. + let store = def.store.expect("declares a mod store"); + assert_eq!(store.kind, "sotf-mods"); + assert_eq!(store.base_url, "https://api.sotf-mods.com"); } } diff --git a/crates/modrix-core/src/launch.rs b/crates/modrix-core/src/launch.rs new file mode 100644 index 0000000..9064fdc --- /dev/null +++ b/crates/modrix-core/src/launch.rs @@ -0,0 +1,576 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Starting a game, managing its mod loader, and reading its log. +//! +//! Everything here is **fire-and-forget**. Modrix starts a game and stops +//! caring: no PID tracking, no restart watchdog, no supervision tree. Those +//! bring their own failure modes (orphaned children, zombie reaping, a manager +//! that thinks a game is running when it crashed) and nothing Modrix does +//! needs them. The log tail is a plain bounded read, polled by whoever wants +//! it, so a frontend that dies mid-tail leaves nothing behind. +//! +//! ## Why the environment matters +//! +//! A mod loader for a Windows game injects through a *proxy DLL* - a library +//! named after one the game already imports (`version.dll`), placed beside the +//! executable so the loader runs before the game does. On Windows the normal +//! DLL search order picks it up for free. +//! +//! Under Proton/Wine it does not: Wine resolves `version.dll` to its own +//! builtin unless `WINEDLLOVERRIDES` explicitly asks for the native file +//! first. Without that variable the loader is inert, the game starts perfectly, +//! and *no mods load* - with no error anywhere. That silent failure is the +//! single most confusing thing about modding a Windows game on Linux, so +//! [`launch_readiness`] reports it as a first-class condition rather than +//! letting a user discover it themselves. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +use crate::error::{Error, Result}; +use crate::gamedef::{LaunchDef, LoaderDef}; + +/// Maximum bytes read from a log in one [`tail_log`] call. A game log grows +/// without bound; a caller polling it must never be handed an arbitrarily +/// large buffer. +const MAX_LOG_READ: u64 = 1 << 20; + +/// Maximum lines returned in one [`tail_log`] call, whatever the caller asks. +const MAX_LOG_LINES: usize = 2000; + +/// Whether a game's mod loader is installed, and whether anything is in its way. +#[derive(Debug, Clone, serde::Serialize)] +pub struct LoaderStatus { + /// The loader's declared identity (`modrix-sons`, `redloader`, …). + pub kind: String, + /// Whether the loader's sentinel file is present. + pub installed: bool, + /// The installed version, when the loader records one. + pub version: Option, + /// A rival loader already owning the proxy slot. `Some` means installing + /// would brick both, so installation must refuse. + pub conflict: Option, + /// The loader's own directory. + pub install_root: PathBuf, + /// Whether generated interop assemblies are present. IL2CPP games cannot + /// even *compile* a mod until this is true. + pub interop_ready: bool, +} + +/// Whether a launch would actually produce a modded game. +#[derive(Debug, Clone, serde::Serialize)] +pub struct LaunchReadiness { + /// The environment the game needs, rendered as Steam launch options. + pub required_launch_options: Option, + /// Whether that environment reaches the game on this platform without + /// help. True on Windows (native DLL search order) and whenever the + /// definition asks for no environment at all. + pub env_reaches_game: bool, + /// A human-readable explanation when it does not. + pub warning: Option, +} + +/// A bounded window onto a game log. +#[derive(Debug, Clone, serde::Serialize)] +pub struct LogTail { + /// The log file read. + pub path: PathBuf, + /// Byte offset to pass as `since` next call to continue where this stopped. + pub next_cursor: u64, + /// The log restarted since `since` (it shrank). Loaders truncate on open, + /// so this is how a caller notices a new session rather than silently + /// reading garbage from the middle of a line. + pub truncated: bool, + /// The lines read. + pub lines: Vec, +} + +/// What a launch attempt did. +#[derive(Debug, Clone, serde::Serialize)] +pub struct LaunchOutcome { + /// The command Modrix ran, for the record. + pub command: String, + /// Whether a running instance was stopped first. + pub stopped_existing: bool, + /// Readiness at the moment of launch. + pub readiness: LaunchReadiness, +} + +/// Resolve a definition-relative path against the install directory. +/// +/// Definition paths are always `/`-separated; `Path::join` handles that on +/// Windows too, but a leading `/` or a `..` component would escape the install +/// directory, so both are refused. +fn resolve_in(install: &Path, rel: &str) -> Result { + let trimmed = rel.trim(); + if trimmed.is_empty() { + return Err(Error::NotFound { + kind: "loader path", + key: rel.to_owned(), + }); + } + let candidate = Path::new(trimmed); + let escapes = candidate.is_absolute() + || candidate + .components() + .any(|c| matches!(c, std::path::Component::ParentDir)); + if escapes { + return Err(Error::PathEscape { + path: candidate.to_path_buf(), + }); + } + Ok(install.join(candidate)) +} + +/// Report whether `def`'s loader is installed in `install`, and whether a +/// rival loader is in the way. +/// +/// Read-only: this never touches the game directory. +/// +/// # Errors +/// +/// Returns [`Error::PathEscape`] if the definition names a path outside the +/// install directory. +pub fn loader_status(install: &Path, def: &LoaderDef) -> Result { + let sentinel = resolve_in(install, &def.sentinel)?; + let installed = sentinel.exists(); + let install_root = resolve_in(install, &def.install_root)?; + + let version = def + .version_file + .as_deref() + .and_then(|rel| resolve_in(install, rel).ok()) + .and_then(|p| std::fs::read_to_string(p).ok()) + .map(|s| s.trim().to_owned()) + .filter(|s| !s.is_empty()); + + let interop_ready = def + .interop_dir + .as_deref() + .and_then(|rel| resolve_in(install, rel).ok()) + .is_some_and(|dir| dir_has_entries(&dir)); + + Ok(LoaderStatus { + kind: def.kind.clone(), + installed, + version, + // Our own presence is not a conflict with ourselves. + conflict: if installed { + None + } else { + first_conflict(install, def) + }, + install_root, + interop_ready, + }) +} + +/// Whether a directory exists and holds at least one entry. +fn dir_has_entries(dir: &Path) -> bool { + std::fs::read_dir(dir).is_ok_and(|mut it| it.next().is_some()) +} + +/// The first declared conflict present in the install directory. +/// +/// A game has exactly one proxy-DLL slot, so two loaders can never coexist: +/// whichever is loaded second never runs, and the user gets a game with half +/// its mods missing and no diagnostic. Refusing is the only safe answer. +fn first_conflict(install: &Path, def: &LoaderDef) -> Option { + def.conflicts + .iter() + .find(|rel| resolve_in(install, rel).is_ok_and(|p| p.exists())) + .cloned() +} + +/// Render a definition's environment as a Steam launch-options string. +/// +/// `BTreeMap` iteration is ordered, so the same definition always renders the +/// same string - which is what lets a caller compare it against what Steam +/// already has and skip a needless rewrite. +fn render_launch_options(env: &BTreeMap) -> Option { + if env.is_empty() { + return None; + } + let mut out = String::new(); + for (key, value) in env { + out.push_str(key); + out.push_str("=\""); + out.push_str(value); + out.push_str("\" "); + } + out.push_str("%command%"); + Some(out) +} + +/// Whether a launch on this platform will actually reach the game with the +/// environment the definition asks for. +#[must_use] +pub fn launch_readiness(def: &LaunchDef) -> LaunchReadiness { + let options = render_launch_options(&def.env); + // On Windows the proxy DLL is found by the normal search order and no + // environment is needed. Everywhere else the game is a Windows binary under + // Proton/Wine, and Steam owns the process - so Modrix cannot inject the + // variable by spawning, only the user's launch options can. + let native = cfg!(windows); + let needs_help = !native && options.is_some(); + LaunchReadiness { + warning: needs_help.then(|| { + let opts = options.clone().unwrap_or_default(); + format!( + "This game runs under Proton/Wine, where the mod loader's proxy DLL is ignored \ + unless Steam passes it through. Set the game's Steam launch options to: {opts} \ + Without it the game starts normally and no mods load, with no error." + ) + }), + env_reaches_game: !needs_help, + required_launch_options: options, + } +} + +/// Stop a running instance by image name. Best-effort: a game that is not +/// running is not an error. +fn stop_process(name: &str) -> bool { + use std::process::{Command, Stdio}; + // Match on the image name only. A path substring would also match an + // editor with a file open from the game directory, or Modrix itself. + let mut command = if cfg!(windows) { + let mut c = Command::new("taskkill"); + c.args(["/F", "/IM", name]); + c + } else { + let mut c = Command::new("pkill"); + c.args(["-f", name]); + c + }; + command + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .is_ok_and(|s| s.success()) +} + +/// Build the platform command that opens a `steam://` URL. +fn steam_url_command(url: &str) -> std::process::Command { + use std::process::Command; + if cfg!(windows) { + let mut c = Command::new("cmd"); + c.args(["/C", "start", "", url]); + c + } else if cfg!(target_os = "macos") { + let mut c = Command::new("open"); + c.arg(url); + c + } else { + let mut c = Command::new("xdg-open"); + c.arg(url); + c + } +} + +/// Start the game. +/// +/// Returns as soon as the launch has been handed off; it does not wait for the +/// game to appear, because there is no reliable cross-platform signal for that +/// and a caller who needs one should poll [`tail_log`]. +/// +/// # Errors +/// +/// Returns [`Error::Launch`] if the launch command could not be spawned, or +/// [`Error::PathEscape`] if the definition names an executable outside the +/// install directory. +pub fn launch(install: &Path, def: &LaunchDef, steam_appid: Option) -> Result { + use std::process::Stdio; + + let readiness = launch_readiness(def); + let stopped = def.process.as_deref().is_some_and(stop_process); + + let (mut command, shown) = match def.mode.as_str() { + "steam" => { + let appid = steam_appid.ok_or_else(|| Error::Launch { + message: "this game declares a Steam launch but has no steam_appid".to_owned(), + })?; + let url = format!("steam://rungameid/{appid}"); + (steam_url_command(&url), url) + } + "exe" => { + let rel = def.exe.as_deref().ok_or_else(|| Error::Launch { + message: "this game declares an exe launch but names no exe".to_owned(), + })?; + let exe = resolve_in(install, rel)?; + let mut c = std::process::Command::new(&exe); + c.args(&def.args).current_dir(install); + // Spawning directly DOES let us pass the environment through. + for (key, value) in &def.env { + c.env(key, value); + } + (c, exe.display().to_string()) + } + other => { + return Err(Error::Launch { + message: format!("unknown launch mode `{other}`"), + }); + } + }; + + command + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .map_err(|e| Error::Launch { + message: format!("could not start `{shown}`: {e}"), + })?; + + Ok(LaunchOutcome { + command: shown, + stopped_existing: stopped, + readiness, + }) +} + +/// Read up to `max_lines` lines from `path`, starting at byte offset `since`. +/// +/// Detects truncation (loaders open their log with create/truncate, so every +/// launch restarts it at zero) and rewinds rather than reading from the middle +/// of a line in a fresh, shorter file. +/// +/// # Errors +/// +/// Returns [`Error::Io`] if the file cannot be read. A *missing* log is not an +/// error - a game that has never run has no log - and yields an empty tail. +pub fn tail_log(path: &Path, since: u64, max_lines: usize) -> Result { + use std::io::{Read, Seek, SeekFrom}; + + let empty = |cursor: u64, truncated: bool| LogTail { + path: path.to_path_buf(), + next_cursor: cursor, + truncated, + lines: Vec::new(), + }; + + let Ok(mut file) = std::fs::File::open(path) else { + return Ok(empty(0, false)); + }; + let len = file.metadata().map_err(|e| Error::io(path, e))?.len(); + + // A shorter file than the caller's cursor means a new session. + let truncated = len < since; + let start = if truncated { 0 } else { since }; + if len <= start { + return Ok(empty(len, truncated)); + } + + // Read the tail-most window, never the whole file. + let available = len.saturating_sub(start); + let take = available.min(MAX_LOG_READ); + let from = len.saturating_sub(take); + file.seek(SeekFrom::Start(from)) + .map_err(|e| Error::io(path, e))?; + + let mut buf = Vec::new(); + file.take(take) + .read_to_end(&mut buf) + .map_err(|e| Error::io(path, e))?; + + let text = String::from_utf8_lossy(&buf); + let cap = max_lines.clamp(1, MAX_LOG_LINES); + let all: Vec<&str> = text.lines().collect(); + // Skip a leading partial line when the window started mid-file. + let skip_partial = usize::from(from > 0 && !buf.starts_with(b"\n")); + let body = all.get(skip_partial..).unwrap_or(&[]); + let keep = body.len().saturating_sub(cap); + let lines = body + .get(keep..) + .unwrap_or(&[]) + .iter() + .map(|s| (*s).to_owned()) + .collect(); + + Ok(LogTail { + path: path.to_path_buf(), + next_cursor: len, + truncated, + lines, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn loader_def() -> LoaderDef { + LoaderDef { + kind: "modrix-sons".to_owned(), + install_root: "_Modrix".to_owned(), + sentinel: "_Modrix/net6/Modrix.Loader.dll".to_owned(), + proxy: Some("version.dll".to_owned()), + interop_dir: Some("_Modrix/interop".to_owned()), + version_file: Some("_Modrix/version.txt".to_owned()), + conflicts: vec!["MelonLoader".to_owned(), "_Redloader".to_owned()], + source: None, + } + } + + fn touch(path: &Path) { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).unwrap(); + } + std::fs::write(path, b"x").unwrap(); + } + + #[test] + fn reports_a_missing_loader() { + let tmp = tempfile::tempdir().unwrap(); + let status = loader_status(tmp.path(), &loader_def()).unwrap(); + assert!(!status.installed); + assert!(status.conflict.is_none()); + assert!(!status.interop_ready); + assert!(status.version.is_none()); + } + + #[test] + fn reports_an_installed_loader_with_its_version() { + let tmp = tempfile::tempdir().unwrap(); + touch(&tmp.path().join("_Modrix/net6/Modrix.Loader.dll")); + std::fs::write(tmp.path().join("_Modrix/version.txt"), "1.2.3\n").unwrap(); + touch(&tmp.path().join("_Modrix/interop/Sons.dll")); + + let status = loader_status(tmp.path(), &loader_def()).unwrap(); + assert!(status.installed); + assert_eq!(status.version.as_deref(), Some("1.2.3")); + assert!(status.interop_ready, "interop assemblies were generated"); + } + + #[test] + fn detects_a_rival_loader_owning_the_proxy_slot() { + let tmp = tempfile::tempdir().unwrap(); + // MelonLoader is installed; ours is not. Installing over it would + // leave two loaders fighting for one version.dll and brick both. + std::fs::create_dir_all(tmp.path().join("MelonLoader")).unwrap(); + + let status = loader_status(tmp.path(), &loader_def()).unwrap(); + assert!(!status.installed); + assert_eq!(status.conflict.as_deref(), Some("MelonLoader")); + } + + #[test] + fn an_installed_loader_is_not_its_own_conflict() { + let tmp = tempfile::tempdir().unwrap(); + touch(&tmp.path().join("_Modrix/net6/Modrix.Loader.dll")); + std::fs::create_dir_all(tmp.path().join("MelonLoader")).unwrap(); + let status = loader_status(tmp.path(), &loader_def()).unwrap(); + assert!(status.installed); + assert!( + status.conflict.is_none(), + "conflicts only gate a fresh install" + ); + } + + #[test] + fn refuses_a_definition_path_that_escapes_the_install_dir() { + let tmp = tempfile::tempdir().unwrap(); + let mut def = loader_def(); + def.sentinel = "../../etc/passwd".to_owned(); + assert!(matches!( + loader_status(tmp.path(), &def), + Err(Error::PathEscape { .. }) + )); + } + + #[test] + fn renders_launch_options_deterministically() { + let mut env = BTreeMap::new(); + env.insert("WINEDLLOVERRIDES".to_owned(), "version=n,b".to_owned()); + env.insert("MANGOHUD".to_owned(), "1".to_owned()); + // BTreeMap ordering: MANGOHUD before WINEDLLOVERRIDES, every time. + assert_eq!( + render_launch_options(&env).as_deref(), + Some("MANGOHUD=\"1\" WINEDLLOVERRIDES=\"version=n,b\" %command%") + ); + assert!(render_launch_options(&BTreeMap::new()).is_none()); + } + + #[test] + fn tails_a_log_from_a_cursor() { + let tmp = tempfile::tempdir().unwrap(); + let log = tmp.path().join("Latest.log"); + std::fs::write(&log, "one\ntwo\nthree\n").unwrap(); + + let first = tail_log(&log, 0, 100).unwrap(); + assert_eq!(first.lines, ["one", "two", "three"]); + assert!(!first.truncated); + + // Nothing new yet. + let idle = tail_log(&log, first.next_cursor, 100).unwrap(); + assert!( + idle.lines.is_empty(), + "expected empty, got {:?}", + idle.lines + ); + assert_eq!(idle.next_cursor, first.next_cursor); + } + + #[test] + fn detects_a_truncated_log_as_a_new_session() { + let tmp = tempfile::tempdir().unwrap(); + let log = tmp.path().join("Latest.log"); + std::fs::write(&log, "old session, quite long indeed\n").unwrap(); + let first = tail_log(&log, 0, 100).unwrap(); + + // The loader truncates on open, so the next session starts at zero. + std::fs::write(&log, "new\n").unwrap(); + let second = tail_log(&log, first.next_cursor, 100).unwrap(); + assert!( + second.truncated, + "a shrunk log is a relaunch, not a corrupt read" + ); + assert_eq!(second.lines, ["new"]); + } + + #[test] + fn a_missing_log_is_not_an_error() { + let tmp = tempfile::tempdir().unwrap(); + let tail = tail_log(&tmp.path().join("never-ran.log"), 0, 10).unwrap(); + assert!( + tail.lines.is_empty(), + "expected empty, got {:?}", + tail.lines + ); + assert_eq!(tail.next_cursor, 0); + } + + #[test] + fn caps_the_number_of_lines_returned() { + let tmp = tempfile::tempdir().unwrap(); + let log = tmp.path().join("Latest.log"); + let body = (0..500).fold(String::new(), |mut acc, i| { + use std::fmt::Write as _; + let _ = writeln!(acc, "line {i}"); + acc + }); + std::fs::write(&log, body).unwrap(); + + let tail = tail_log(&log, 0, 10).unwrap(); + assert_eq!(tail.lines.len(), 10, "the newest lines, bounded"); + assert_eq!(tail.lines.last().map(String::as_str), Some("line 499")); + } + + #[test] + fn launch_readiness_flags_the_proton_override() { + let mut env = BTreeMap::new(); + env.insert("WINEDLLOVERRIDES".to_owned(), "version=n,b".to_owned()); + let def = LaunchDef { + mode: "steam".to_owned(), + exe: None, + args: Vec::new(), + env, + log: Some("_Modrix/Latest.log".to_owned()), + process: Some("SonsOfTheForest.exe".to_owned()), + }; + let readiness = launch_readiness(&def); + assert!(readiness.required_launch_options.is_some()); + // On Windows the proxy loads natively; elsewhere Steam must pass it. + assert_eq!(readiness.env_reaches_game, cfg!(windows)); + assert_eq!(readiness.warning.is_some(), !cfg!(windows)); + } +} diff --git a/crates/modrix-core/src/lib.rs b/crates/modrix-core/src/lib.rs index 359d680..3e0debf 100644 --- a/crates/modrix-core/src/lib.rs +++ b/crates/modrix-core/src/lib.rs @@ -27,6 +27,7 @@ pub mod external; mod gamedef; pub mod health; mod id; +pub mod launch; pub mod loadorder; pub mod logic; mod model; @@ -43,10 +44,12 @@ pub use engine::{Engine, GameCapabilities}; pub use error::{Error, Result}; pub use external::ExternalMod; pub use gamedef::{ - ExternalScanDef, GameDef, HealthDef, LoadOrderDef, LoaderCheckDef, PluginsTxtDef, RecommendDef, + ExternalScanDef, GameDef, HealthDef, LaunchDef, LoadOrderDef, LoaderCheckDef, LoaderDef, + LoaderSourceDef, PluginsTxtDef, RecommendDef, StoreDef, }; pub use health::{Issue, Severity}; pub use id::{GameId, ModId, ProfileId}; +pub use launch::{LaunchOutcome, LaunchReadiness, LoaderStatus, LogTail}; pub use model::{Game, LinkType, Mod, Profile}; pub use paths::Paths; pub use progress::{Progress, ProgressSnapshot}; diff --git a/crates/modrix-core/src/progress.rs b/crates/modrix-core/src/progress.rs index cda7789..383cdf6 100644 --- a/crates/modrix-core/src/progress.rs +++ b/crates/modrix-core/src/progress.rs @@ -11,7 +11,7 @@ use std::sync::Mutex; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; /// A point-in-time view of the running operation. -#[derive(Debug, Clone, serde::Serialize)] +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] pub struct ProgressSnapshot { /// Work units finished. pub done: u64, diff --git a/crates/modrix-core/src/rules.rs b/crates/modrix-core/src/rules.rs index c795377..cd955ca 100644 --- a/crates/modrix-core/src/rules.rs +++ b/crates/modrix-core/src/rules.rs @@ -188,7 +188,7 @@ mod tests { let mods = vec![m(1), m(2), m(3)]; let (order, cycle) = effective_order(&mods, &[]); assert_eq!(order, mods); - assert!(cycle.is_empty()); + assert_eq!(cycle, []); } #[test] @@ -201,7 +201,7 @@ mod tests { }]; let (order, cycle) = effective_order(&mods, &rules); assert_eq!(order, vec![m(2), m(1)]); - assert!(cycle.is_empty()); + assert_eq!(cycle, []); } #[test] @@ -244,7 +244,7 @@ mod tests { }]; let (order, cycle) = effective_order(&mods, &rules); assert_eq!(order, mods); - assert!(cycle.is_empty()); + assert_eq!(cycle, []); } #[test] diff --git a/crates/modrix-core/src/store.rs b/crates/modrix-core/src/store.rs index 47d68ea..25268d6 100644 --- a/crates/modrix-core/src/store.rs +++ b/crates/modrix-core/src/store.rs @@ -86,7 +86,7 @@ pub(crate) fn extract_zip(archive: &Path, dest: &Path) -> Result<()> { // `enclosed_name` returns None for any name that escapes the root. let Some(rel) = entry.enclosed_name() else { return Err(Error::PathEscape { - path: PathBuf::from(entry.name()), + path: PathBuf::from(entry.name().unwrap_or_default().into_owned()), }); }; let out = dest.join(&rel); @@ -294,7 +294,17 @@ fn make_owner_writable(path: &Path) -> Result<()> { fs::set_permissions(path, perms).map_err(|e| Error::io(path, e)) } -pub(crate) fn normalize_staged(dest: &Path, mod_root: &str, content_dirs: &[String]) -> Result<()> { +/// Rearrange a freshly extracted archive into the shape the deployer expects. +/// +/// `park_root` overrides whether top-level binaries are treated as loader +/// files (see [`crate::gamedef::GameDef::park_root_binaries`]); `None` keeps +/// the mod-root-shape inference that suits Bethesda and BepInEx layouts. +pub(crate) fn normalize_staged( + dest: &Path, + mod_root: &str, + content_dirs: &[String], + park_root: Option, +) -> Result<()> { let ctx = ContentCtx { mod_root, content_dirs, @@ -315,12 +325,17 @@ pub(crate) fn normalize_staged(dest: &Path, mod_root: &str, content_dirs: &[Stri return Ok(()); } if !mod_root.is_empty() { - // A single-component mod root (Bethesda's `Data`) sits beside the game - // binary, so a top-level .exe/.dll is a loader that belongs at the - // install root. A *nested* mod root (`BepInEx/plugins`) IS the plugin - // container: a top-level DLL there is the mod itself, and parking it - // would deploy the plugin to the game root where nothing loads it. - if !mod_root.contains('/') { + // Inference, when the definition does not decide: a single-component + // mod root (Bethesda's `Data`) sits beside the game binary, so a + // top-level .exe/.dll is a loader that belongs at the install root. A + // *nested* mod root (`BepInEx/plugins`) IS the plugin container: a + // top-level DLL there is the mod itself, and parking it would deploy + // the plugin to the game root where nothing loads it. + // + // The inference is wrong for a loader whose mod directory is a single + // component holding bare payload DLLs (Sons of the Forest's `Mods/`), + // which is why a definition can override it outright. + if park_root.unwrap_or(!mod_root.contains('/')) { // Park loader binaries first - the mod-root remap would otherwise // sweep them into `.unmanaged/` as generic extras. park_root_binaries(dest)?; @@ -875,7 +890,7 @@ mod tests { &dest.join("The One Ring Redux/Data/Scripts/OneRingScript.pex"), b"pex", ); - normalize_staged(&dest, "Data", &[]).unwrap(); + normalize_staged(&dest, "Data", &[], None).unwrap(); let rels: Vec<_> = resolve_files(&dest) .unwrap() @@ -906,7 +921,7 @@ mod tests { &dest.join("Shaders/CloudShadows/CloudShadows.hlsli"), b"hlsl", ); - normalize_staged(&dest, "Data", &[]).unwrap(); + normalize_staged(&dest, "Data", &[], None).unwrap(); let rels: Vec<_> = resolve_files(&dest) .unwrap() @@ -933,7 +948,7 @@ mod tests { // it. write(&dest.join("BepInEx/plugins/Tweaks/Tweaks.dll"), b"dll"); write(&dest.join("BepInEx/plugins/Tweaks/config.json"), b"json"); - normalize_staged(&dest, "", &[]).unwrap(); + normalize_staged(&dest, "", &[], None).unwrap(); let rels: Vec<_> = resolve_files(&dest) .unwrap() @@ -965,7 +980,7 @@ mod tests { b"a", ); write(&dest.join("README.md"), b"readme"); - normalize_staged(&dest, "BepInEx/plugins", &[]).unwrap(); + normalize_staged(&dest, "BepInEx/plugins", &[], None).unwrap(); let rels: Vec<_> = resolve_files(&dest) .unwrap() @@ -991,7 +1006,7 @@ mod tests { // - that deployed it beside the .exe where BepInEx never loads it. write(&dest.join("ECCLibrary.dll"), b"dll"); write(&dest.join("Assets/bundle"), b"a"); - normalize_staged(&dest, "BepInEx/plugins", &[]).unwrap(); + normalize_staged(&dest, "BepInEx/plugins", &[], None).unwrap(); assert!( !dest.join(".root").exists(), @@ -1008,6 +1023,58 @@ mod tests { ); } + #[test] + fn single_component_mod_root_can_opt_out_of_parking_binaries() { + let tmp = tempfile::tempdir().unwrap(); + let dest = tmp.path().join("staged"); + // A Sons of the Forest mod: the loader enumerates `Mods/*.dll` + // non-recursively for payloads but reads `Mods//manifest.json` for + // metadata, so the archive legitimately carries BOTH a bare top-level + // DLL and a folder. + // + // `Mods` is a single-component mod root, so the shape heuristic would + // park the DLL into `.root/` and deploy it to the game install + // directory - where the loader never looks. Deploy would report + // success and the game would load nothing. `park_root = Some(false)` + // is what makes this game work at all. + write(&dest.join("SolafiteMaskAura.dll"), b"dll"); + write(&dest.join("SolafiteMaskAura/manifest.json"), b"{}"); + normalize_staged(&dest, "Mods", &[], Some(false)).unwrap(); + + assert!( + !dest.join(".root").exists(), + "the payload DLL must not be parked to the install root" + ); + let rels: Vec<_> = resolve_files(&dest) + .unwrap() + .iter() + .map(|f| f.target_rel.clone()) + .collect(); + assert_eq!( + rels, + vec![ + "SolafiteMaskAura.dll".to_owned(), + "solafitemaskaura/manifest.json".to_owned(), + ] + ); + } + + #[test] + fn single_component_mod_root_still_parks_binaries_by_default() { + let tmp = tempfile::tempdir().unwrap(); + let dest = tmp.path().join("staged"); + // The opt-out must be exactly that: with `None` the Bethesda-shaped + // inference is unchanged, so SKSE's loader still lands in `.root/`. + write(&dest.join("skse64_loader.exe"), b"exe"); + write(&dest.join("Data/Scripts/x.pex"), b"pex"); + normalize_staged(&dest, "Data", &[], None).unwrap(); + + assert!( + dest.join(".root/skse64_loader.exe").is_file(), + "a loader binary must still be parked when the def does not opt out" + ); + } + #[test] fn nested_mod_root_leaves_a_multi_target_tree_alone() { let tmp = tempfile::tempdir().unwrap(); @@ -1016,7 +1083,7 @@ mod tests { // silently drop the config, so the tree is left as-is. write(&dest.join("BepInEx/plugins/Mod/mod.dll"), b"dll"); write(&dest.join("BepInEx/config/Mod.cfg"), b"cfg"); - normalize_staged(&dest, "BepInEx/plugins", &[]).unwrap(); + normalize_staged(&dest, "BepInEx/plugins", &[], None).unwrap(); assert!(dest.join("BepInEx/plugins/Mod/mod.dll").is_file()); assert!(dest.join("BepInEx/config/Mod.cfg").is_file()); } @@ -1029,7 +1096,7 @@ mod tests { // side directory (whatever it holds) must not be hoisted over it. write(&dest.join("Mod.esp"), b"esp"); write(&dest.join("Extras/Data/Optional.esp"), b"esp"); - normalize_staged(&dest, "Data", &[]).unwrap(); + normalize_staged(&dest, "Data", &[], None).unwrap(); assert!(dest.join("Mod.esp").is_file()); assert!(dest.join("Extras/Data/Optional.esp").is_file()); } @@ -1043,7 +1110,7 @@ mod tests { write(&dest.join("skse64_2_02_06/skse64_1_6_1170.dll"), b"dll"); write(&dest.join("skse64_2_02_06/Data/Scripts/Actor.pex"), b"pex"); write(&dest.join("skse64_2_02_06/src/skse64/main.cpp"), b"cpp"); - normalize_staged(&dest, "Data", &[]).unwrap(); + normalize_staged(&dest, "Data", &[], None).unwrap(); // Scripts became the mod root; loaders/src parked, never deployed. let rels: Vec<_> = resolve_files(&dest) @@ -1069,7 +1136,7 @@ mod tests { let dest = tmp.path().join("staged"); write(&dest.join("SkyUI.esp"), b"esp"); write(&dest.join("textures/ui.dds"), b"dds"); - normalize_staged(&dest, "Data", &[]).unwrap(); + normalize_staged(&dest, "Data", &[], None).unwrap(); let rels: Vec<_> = resolve_files(&dest) .unwrap() .iter() @@ -1087,7 +1154,7 @@ mod tests { let dest = tmp.path().join("staged"); write(&dest.join("MyMod-1.0/meshes/m.nif"), b"m"); write(&dest.join("MyMod-1.0/MyMod.esp"), b"e"); - normalize_staged(&dest, "Data", &[]).unwrap(); + normalize_staged(&dest, "Data", &[], None).unwrap(); assert!(dest.join("MyMod.esp").is_file()); assert!(dest.join("meshes/m.nif").is_file()); assert!(!dest.join("MyMod-1.0").exists()); @@ -1099,7 +1166,7 @@ mod tests { let dest = tmp.path().join("staged"); // A mod that IS just meshes must stay under meshes/. write(&dest.join("meshes/armor/a.nif"), b"m"); - normalize_staged(&dest, "Data", &[]).unwrap(); + normalize_staged(&dest, "Data", &[], None).unwrap(); let rels: Vec<_> = resolve_files(&dest) .unwrap() .iter() @@ -1153,7 +1220,7 @@ mod tests { let dest = tmp.path().join("staged"); extract_with_system(&archive, &dest).unwrap(); assert!(dest.join("inner/Data/Scripts/s.pex").is_file()); - normalize_staged(&dest, "Data", &[]).unwrap(); + normalize_staged(&dest, "Data", &[], None).unwrap(); assert!(dest.join("Scripts/s.pex").is_file()); } diff --git a/crates/modrix-download/Cargo.toml b/crates/modrix-download/Cargo.toml index 4ce4475..975bb24 100644 --- a/crates/modrix-download/Cargo.toml +++ b/crates/modrix-download/Cargo.toml @@ -17,7 +17,6 @@ hyper-util.workspace = true http-body-util.workspace = true tokio-rustls.workspace = true rustls.workspace = true -rustls-rustcrypto.workspace = true rustls-native-certs.workspace = true md-5.workspace = true sha2.workspace = true diff --git a/crates/modrix-download/src/control.rs b/crates/modrix-download/src/control.rs index 6e28360..a3dfd1c 100644 --- a/crates/modrix-download/src/control.rs +++ b/crates/modrix-download/src/control.rs @@ -261,9 +261,7 @@ mod tests { // 4100 bytes at 1024 => 5 pieces, last is 4 bytes. let mut c = Control::fresh(1024, 4100, String::new(), false).unwrap(); assert_eq!(c.done.len(), 5); - for d in &mut c.done { - *d = true; - } + c.done.fill(true); assert_eq!(c.bytes_done(), 4100); } } diff --git a/crates/modrix-download/src/http.rs b/crates/modrix-download/src/http.rs index cee2a16..77a24ff 100644 --- a/crates/modrix-download/src/http.rs +++ b/crates/modrix-download/src/http.rs @@ -1,8 +1,7 @@ // SPDX-License-Identifier: GPL-2.0-only -//! A small async HTTP/HTTPS client built on the pure-Rust, GPLv2-clean stack: -//! hyper for HTTP/1.1, rustls for TLS with the RustCrypto crypto provider, and -//! the OS trust store for roots. No reqwest, no ring (see `docs/ARCHITECTURE.md` -//! §11). One connection per request (a download manager is not high-QPS) with +//! A small async HTTP/HTTPS client: hyper for HTTP/1.1, rustls for TLS with +//! the ring crypto provider, and the OS trust store for roots (see +//! `docs/ARCHITECTURE.md` §11). One connection per request (a download manager is not high-QPS) with //! bounded redirect following. use std::sync::Arc; @@ -71,14 +70,14 @@ impl Response { } impl HttpClient { - /// Build a client with a rustls config using the RustCrypto provider and the + /// Build a client with a rustls config using the ring provider and the /// OS trust store. /// /// # Errors /// /// Returns [`Error::Tls`] if the TLS configuration cannot be built. pub fn new() -> Result { - let provider = Arc::new(rustls_rustcrypto::provider()); + let provider = Arc::new(rustls::crypto::ring::default_provider()); let mut roots = rustls::RootCertStore::empty(); let loaded = rustls_native_certs::load_native_certs(); for cert in loaded.certs { diff --git a/crates/modrix-download/src/lib.rs b/crates/modrix-download/src/lib.rs index f25f206..8866ae7 100644 --- a/crates/modrix-download/src/lib.rs +++ b/crates/modrix-download/src/lib.rs @@ -15,9 +15,8 @@ //! - [`NxmUri`] is retained purely as an identity parser (game/mod/file), not a //! download mechanism. //! -//! The HTTP stack is pure-Rust and GPLv2-clean - hyper + rustls with the -//! RustCrypto crypto provider and the OS trust store, never reqwest/ring (see -//! `docs/ARCHITECTURE.md` §11). Held to the Power of Ten reliability standard: +//! The HTTP stack is hyper + rustls with the ring crypto provider and the OS +//! trust store (see `docs/ARCHITECTURE.md` §11). Held to the Power of Ten reliability standard: //! panic-free on fallible paths, bounded loops, and offset writes via safe //! seek-once file handles (no `unsafe`, no `nix`). diff --git a/crates/modrix-download/src/types.rs b/crates/modrix-download/src/types.rs index 601ded8..0492526 100644 --- a/crates/modrix-download/src/types.rs +++ b/crates/modrix-download/src/types.rs @@ -78,7 +78,7 @@ pub enum DownloadState { } /// A point-in-time snapshot of a download (the `tellStatus` analog). -#[derive(Debug, Clone)] +#[derive(Debug, Clone, PartialEq, Eq)] pub struct DownloadStatus { /// The download's handle. pub id: DownloadId, diff --git a/crates/modrix-ecma335/Cargo.toml b/crates/modrix-ecma335/Cargo.toml new file mode 100644 index 0000000..3bccedd --- /dev/null +++ b/crates/modrix-ecma335/Cargo.toml @@ -0,0 +1,17 @@ +# SPDX-License-Identifier: GPL-2.0-only +[package] +name = "modrix-ecma335" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +description = "From-scratch ECMA-335 / PE32+ writer that emits .NET reference assemblies." + +[dependencies] +thiserror = { workspace = true } + +[dev-dependencies] + +[lints] +workspace = true diff --git a/crates/modrix-ecma335/src/builder.rs b/crates/modrix-ecma335/src/builder.rs new file mode 100644 index 0000000..3583c08 --- /dev/null +++ b/crates/modrix-ecma335/src/builder.rs @@ -0,0 +1,550 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! The public builder: collect a declarative description, then emit bytes. +//! +//! Nothing is encoded while the description is being collected. Members are +//! kept attached to the type that owns them and are only flattened into +//! `Field` / `MethodDef` rows by [`AssemblyBuilder::build`], because ECMA-335 +//! stores a type's member run as a start index and takes the end from the +//! *next* type's start. Grouping members by owner is therefore not a style +//! choice - interleaving them silently reassigns members to the wrong types - +//! so the API makes it impossible to get wrong. + +use std::collections::HashMap; + +use crate::encode::compress_unsigned; +use crate::error::{Error, Result}; +use crate::handles::{ + AssemblyRefId, CustomAttributeType, FieldId, HasCustomAttribute, MemberRefId, MemberRefParent, + MethodId, PropertyId, ResolutionScope, TypeDefId, TypeRefId, TypeSpecId, +}; +use crate::model::{ + AssemblyReference, Field, Method, Property, TypeDefinition, Version, method_attributes, +}; +use crate::signature::{MethodSignature, Type}; + +/// SHA-1, the only hash algorithm identifier in practical use. +pub const HASH_ALGORITHM_SHA1: u32 = 0x0000_8004; + +/// Namespace of `ReferenceAssemblyAttribute`. +const COMPILER_SERVICES: &str = "System.Runtime.CompilerServices"; +/// Namespace of `TargetFrameworkAttribute`. +const VERSIONING: &str = "System.Runtime.Versioning"; + +/// A `TypeRef` the caller asked for. +#[derive(Clone, Debug)] +pub(crate) struct TypeRefEntry { + pub(crate) scope: ResolutionScope, + pub(crate) namespace: String, + pub(crate) name: String, +} + +/// A `MemberRef` the caller asked for. +#[derive(Clone, Debug)] +pub(crate) struct MemberRefEntry { + pub(crate) parent: MemberRefParent, + pub(crate) name: String, + pub(crate) signature: Vec, +} + +/// A `CustomAttribute` the caller asked for. +#[derive(Clone, Debug)] +pub(crate) struct CustomAttributeEntry { + pub(crate) parent: HasCustomAttribute, + pub(crate) constructor: CustomAttributeType, + pub(crate) value: Vec, +} + +/// A type plus the members that belong to it. +#[derive(Clone, Debug)] +pub(crate) struct TypeEntry { + pub(crate) definition: TypeDefinition, + pub(crate) fields: Vec, + pub(crate) methods: Vec, + pub(crate) properties: Vec, +} + +/// Builds one .NET reference assembly. +/// +/// # Example +/// +/// ``` +/// use modrix_ecma335::{AssemblyBuilder, ResolutionScope, Version}; +/// use modrix_ecma335::model::{AssemblyReference, TypeDefinition, type_attributes}; +/// +/// let mut builder = AssemblyBuilder::new("MyLib", Version::new(1, 0, 0, 0)); +/// let corlib = builder.add_assembly_ref(AssemblyReference::core_library(9)); +/// let object = builder.add_type_ref(ResolutionScope::AssemblyRef(corlib), "System", "Object"); +/// builder.add_type_def(TypeDefinition::new( +/// "MyLib", +/// "Widget", +/// type_attributes::PUBLIC_CLASS, +/// Some(object.into()), +/// ))?; +/// let bytes = builder.build()?; +/// assert_eq!(&bytes[..2], b"MZ"); +/// # Ok::<(), modrix_ecma335::Error>(()) +/// ``` +#[derive(Clone, Debug)] +pub struct AssemblyBuilder { + pub(crate) name: String, + pub(crate) version: Version, + pub(crate) module_name: String, + pub(crate) mvid: [u8; 16], + pub(crate) hash_algorithm: u32, + pub(crate) flags: u32, + pub(crate) public_key: Vec, + pub(crate) culture: String, + pub(crate) assembly_refs: Vec, + pub(crate) type_refs: Vec, + pub(crate) type_specs: Vec>, + type_spec_index: HashMap, u32>, + pub(crate) types: Vec, + pub(crate) member_refs: Vec, + pub(crate) custom_attributes: Vec, +} + +impl AssemblyBuilder { + /// Starts an assembly named `name` at `version`. + /// + /// `` is pre-seeded as `TypeDef` row 1, as ECMA-335 II.22.37 + /// requires, and the module name defaults to `.dll`. The MVID is + /// derived deterministically from the name and version so that two runs + /// over the same input produce byte-identical files; call + /// [`AssemblyBuilder::set_mvid`] to override it. + #[must_use] + pub fn new(name: &str, version: Version) -> Self { + let module = TypeEntry { + definition: TypeDefinition::new(String::new(), "", 0, None), + fields: Vec::new(), + methods: Vec::new(), + properties: Vec::new(), + }; + Self { + module_name: format!("{name}.dll"), + mvid: derive_mvid(name, version), + name: name.to_owned(), + version, + hash_algorithm: HASH_ALGORITHM_SHA1, + flags: 0, + public_key: Vec::new(), + culture: String::new(), + assembly_refs: Vec::new(), + type_refs: Vec::new(), + type_specs: Vec::new(), + type_spec_index: HashMap::new(), + types: vec![module], + member_refs: Vec::new(), + custom_attributes: Vec::new(), + } + } + + /// Overrides the `Module.Name` string, which defaults to `.dll`. + pub fn set_module_name(&mut self, name: &str) { + name.clone_into(&mut self.module_name); + } + + /// Overrides the module version identifier. + pub fn set_mvid(&mut self, mvid: [u8; 16]) { + self.mvid = mvid; + } + + /// Sets `Assembly.PublicKey` and, implicitly, the identity the consumer + /// will match on. Leave empty for an unsigned reference assembly. + pub fn set_public_key(&mut self, key: Vec) { + self.public_key = key; + } + + /// Sets `Assembly.Culture`; empty means culture-neutral. + pub fn set_culture(&mut self, culture: &str) { + culture.clone_into(&mut self.culture); + } + + /// Sets `Assembly.Flags`. + pub fn set_assembly_flags(&mut self, flags: u32) { + self.flags = flags; + } + + /// Adds an `AssemblyRef` row. + /// + /// For net6.0 and later, exactly one of these must be + /// [`AssemblyReference::core_library`]: Roslyn will not accept + /// `mscorlib`, `netstandard` or `System.Private.CoreLib` as a substitute + /// and reports CS0012 for every imported type. + pub fn add_assembly_ref(&mut self, reference: AssemblyReference) -> AssemblyRefId { + let index = u32::try_from(self.assembly_refs.len()).unwrap_or(u32::MAX); + self.assembly_refs.push(reference); + AssemblyRefId(index) + } + + /// Adds a `TypeRef` row naming an imported type. + pub fn add_type_ref( + &mut self, + scope: ResolutionScope, + namespace: &str, + name: &str, + ) -> TypeRefId { + let index = u32::try_from(self.type_refs.len()).unwrap_or(u32::MAX); + self.type_refs.push(TypeRefEntry { + scope, + namespace: namespace.to_owned(), + name: name.to_owned(), + }); + TypeRefId(index) + } + + /// Interns a `TypeSpec` row for a constructed type. + /// + /// Only needed where a constructed type must be named by a *token*: a base + /// class, an interface, a `MemberRef` parent, or a custom-attribute type. + /// A `GENERICINST` that appears inside a field or method signature blob + /// needs no `TypeSpec` row at all. + /// + /// # Errors + /// + /// Propagates any [`Type::encode`] failure. + pub fn add_type_spec(&mut self, constructed: &Type) -> Result { + let mut signature = Vec::new(); + constructed.encode(&mut signature)?; + if let Some(existing) = self.type_spec_index.get(&signature) { + return Ok(TypeSpecId(*existing)); + } + let index = u32::try_from(self.type_specs.len()).unwrap_or(u32::MAX); + self.type_spec_index.insert(signature.clone(), index); + self.type_specs.push(signature); + Ok(TypeSpecId(index)) + } + + /// Adds a `TypeDef` row. + /// + /// # Errors + /// + /// Returns [`Error::DanglingHandle`] if the enclosing type handle does not + /// name a type of this assembly, or [`Error::NestedTypeHasNamespace`] if a + /// nested type carries a namespace (ECMA-335 requires it to be empty; the + /// namespace comes from the enclosing type). + pub fn add_type_def(&mut self, definition: TypeDefinition) -> Result { + if let Some(enclosing) = definition.enclosing { + self.check_type(enclosing)?; + if !definition.namespace.is_empty() { + return Err(Error::NestedTypeHasNamespace { + name: definition.name.clone(), + }); + } + } + let index = u32::try_from(self.types.len()).unwrap_or(u32::MAX); + self.types.push(TypeEntry { + definition, + fields: Vec::new(), + methods: Vec::new(), + properties: Vec::new(), + }); + Ok(TypeDefId(index)) + } + + /// Adds a field to `owner`. + /// + /// # Errors + /// + /// Returns [`Error::DanglingHandle`] if `owner` is not a type of this + /// assembly. + pub fn add_field(&mut self, owner: TypeDefId, field: Field) -> Result { + let entry = self.type_mut(owner)?; + let slot = u32::try_from(entry.fields.len()).unwrap_or(u32::MAX); + entry.fields.push(field); + Ok(FieldId { + owner: owner.0, + slot, + }) + } + + /// Adds a method to `owner`. `MethodDef.RVA` is always emitted as 0. + /// + /// # Errors + /// + /// Returns [`Error::DanglingHandle`] if `owner` is not a type of this + /// assembly. + pub fn add_method(&mut self, owner: TypeDefId, method: Method) -> Result { + let entry = self.type_mut(owner)?; + let slot = u32::try_from(entry.methods.len()).unwrap_or(u32::MAX); + entry.methods.push(method); + Ok(MethodId { + owner: owner.0, + slot, + }) + } + + /// Adds a property to `owner`, together with its accessor links. + /// + /// # Errors + /// + /// Returns [`Error::DanglingHandle`] if `owner` or either accessor handle + /// does not name a member of this assembly. + pub fn add_property(&mut self, owner: TypeDefId, property: Property) -> Result { + for accessor in [property.getter, property.setter].into_iter().flatten() { + self.check_method(accessor)?; + } + let entry = self.type_mut(owner)?; + let slot = u32::try_from(entry.properties.len()).unwrap_or(u32::MAX); + entry.properties.push(property); + Ok(PropertyId { + owner: owner.0, + slot, + }) + } + + /// Adds a `MemberRef` row, typically an imported attribute constructor. + /// + /// # Errors + /// + /// Returns [`Error::DanglingHandle`] if `parent` does not resolve, or + /// propagates a signature encoding failure. + pub fn add_member_ref( + &mut self, + parent: MemberRefParent, + name: &str, + signature: &MethodSignature, + ) -> Result { + self.check_member_ref_parent(parent)?; + let index = u32::try_from(self.member_refs.len()).unwrap_or(u32::MAX); + self.member_refs.push(MemberRefEntry { + parent, + name: name.to_owned(), + signature: signature.to_blob()?, + }); + Ok(MemberRefId(index)) + } + + /// Adds a `CustomAttribute` row. `value` is a raw attribute blob: the + /// `0x0001` prolog, the fixed constructor arguments, then a named-argument + /// count. + /// + /// # Errors + /// + /// Returns [`Error::DanglingHandle`] if the parent or the constructor does + /// not resolve. + pub fn add_custom_attribute( + &mut self, + parent: HasCustomAttribute, + constructor: CustomAttributeType, + value: Vec, + ) -> Result<()> { + self.check_custom_attribute_parent(parent)?; + match constructor { + CustomAttributeType::MethodDef(id) => self.check_method(id)?, + CustomAttributeType::MemberRef(id) => self.check_member_ref(id)?, + } + self.custom_attributes.push(CustomAttributeEntry { + parent, + constructor, + value, + }); + Ok(()) + } + + /// Stamps the assembly with `ReferenceAssemblyAttribute` and + /// `TargetFrameworkAttribute`, the two markers a real reference assembly + /// carries. `framework` is a moniker such as `.NETCoreApp,Version=v9.0`. + /// + /// # Errors + /// + /// Propagates the underlying `TypeRef` / `MemberRef` failures. + pub fn mark_reference_assembly( + &mut self, + corlib: AssemblyRefId, + framework: &str, + ) -> Result<()> { + let scope = ResolutionScope::AssemblyRef(corlib); + let marker = self.add_type_ref(scope, COMPILER_SERVICES, "ReferenceAssemblyAttribute"); + let target = self.add_type_ref(scope, VERSIONING, "TargetFrameworkAttribute"); + let no_args = MethodSignature::instance_method(Type::Void, Vec::new()); + let one_string = MethodSignature::instance_method(Type::Void, vec![Type::String]); + let marker_ctor = + self.add_member_ref(MemberRefParent::TypeRef(marker), ".ctor", &no_args)?; + let target_ctor = + self.add_member_ref(MemberRefParent::TypeRef(target), ".ctor", &one_string)?; + self.add_custom_attribute( + HasCustomAttribute::Assembly, + CustomAttributeType::MemberRef(marker_ctor), + attribute_blob_empty(), + )?; + self.add_custom_attribute( + HasCustomAttribute::Assembly, + CustomAttributeType::MemberRef(target_ctor), + attribute_blob_string(framework)?, + ) + } + + /// Convenience: adds a public parameterless instance constructor. + /// + /// # Errors + /// + /// Returns [`Error::DanglingHandle`] if `owner` does not resolve. + pub fn add_default_constructor(&mut self, owner: TypeDefId) -> Result { + self.add_method( + owner, + Method::new( + ".ctor", + method_attributes::PUBLIC_CONSTRUCTOR, + MethodSignature::instance_method(Type::Void, Vec::new()), + ), + ) + } + + /// Serialises the whole description into a PE32+ reference assembly. + /// + /// # Errors + /// + /// Returns an [`Error`] if any handle dangles, any literal field lacks its + /// `Constant` row, a heap or table exceeds its ceiling, or the image + /// layout overflows. + pub fn build(&self) -> Result> { + let image = crate::materialize::materialize(self)?; + crate::pe::write_image(&image) + } + + fn type_mut(&mut self, id: TypeDefId) -> Result<&mut TypeEntry> { + let rows = u32::try_from(self.types.len()).unwrap_or(u32::MAX); + usize::try_from(id.0) + .ok() + .and_then(|index| self.types.get_mut(index)) + .ok_or(Error::DanglingHandle { + kind: "TypeDef", + index: id.0, + rows, + }) + } + + fn check_type(&self, id: TypeDefId) -> Result<()> { + check(self.types.len(), id.0, "TypeDef") + } + + fn check_member_ref(&self, id: MemberRefId) -> Result<()> { + check(self.member_refs.len(), id.0, "MemberRef") + } + + fn check_method(&self, id: MethodId) -> Result<()> { + let methods = self + .types + .get(usize::try_from(id.owner).unwrap_or(usize::MAX)) + .map_or(0, |entry| entry.methods.len()); + check(self.types.len(), id.owner, "TypeDef")?; + check(methods, id.slot, "MethodDef") + } + + fn check_field(&self, id: FieldId) -> Result<()> { + let fields = self + .types + .get(usize::try_from(id.owner).unwrap_or(usize::MAX)) + .map_or(0, |entry| entry.fields.len()); + check(self.types.len(), id.owner, "TypeDef")?; + check(fields, id.slot, "Field") + } + + fn check_property(&self, id: PropertyId) -> Result<()> { + let properties = self + .types + .get(usize::try_from(id.owner).unwrap_or(usize::MAX)) + .map_or(0, |entry| entry.properties.len()); + check(self.types.len(), id.owner, "TypeDef")?; + check(properties, id.slot, "Property") + } + + fn check_member_ref_parent(&self, parent: MemberRefParent) -> Result<()> { + match parent { + MemberRefParent::TypeDef(id) => self.check_type(id), + MemberRefParent::TypeRef(id) => check(self.type_refs.len(), id.0, "TypeRef"), + MemberRefParent::TypeSpec(id) => check(self.type_specs.len(), id.0, "TypeSpec"), + MemberRefParent::MethodDef(id) => self.check_method(id), + } + } + + fn check_custom_attribute_parent(&self, parent: HasCustomAttribute) -> Result<()> { + match parent { + HasCustomAttribute::Assembly | HasCustomAttribute::Module => Ok(()), + HasCustomAttribute::TypeDef(id) => self.check_type(id), + HasCustomAttribute::TypeRef(id) => check(self.type_refs.len(), id.0, "TypeRef"), + HasCustomAttribute::Field(id) => self.check_field(id), + HasCustomAttribute::MethodDef(id) => self.check_method(id), + HasCustomAttribute::Property(id) => self.check_property(id), + HasCustomAttribute::AssemblyRef(id) => { + check(self.assembly_refs.len(), id.0, "AssemblyRef") + } + } + } +} + +/// Rejects a handle that names no row, which is the guard against writing a +/// dangling coded index. A dangling `TypeRef.ResolutionScope` does not produce +/// a diagnostic in Roslyn - it takes the compiler down with an +/// `ArgumentOutOfRangeException`. +fn check(rows: usize, index: u32, kind: &'static str) -> Result<()> { + let rows = u32::try_from(rows).unwrap_or(u32::MAX); + if index < rows { + Ok(()) + } else { + Err(Error::DanglingHandle { kind, index, rows }) + } +} + +/// The attribute blob for a constructor taking no arguments: prolog `0x0001` +/// then a zero named-argument count. +#[must_use] +pub fn attribute_blob_empty() -> Vec { + vec![0x01, 0x00, 0x00, 0x00] +} + +/// The attribute blob for a constructor taking one `string`. +/// +/// # Errors +/// +/// Returns [`Error::CompressedRange`] if the string is longer than a +/// compressed length prefix can describe. +pub fn attribute_blob_string(value: &str) -> Result> { + let mut blob = vec![0x01, 0x00]; + let bytes = value.as_bytes(); + compress_unsigned(&mut blob, u32::try_from(bytes.len()).unwrap_or(u32::MAX))?; + blob.extend_from_slice(bytes); + blob.extend_from_slice(&[0x00, 0x00]); + Ok(blob) +} + +/// Derives a stable, non-zero MVID from the assembly identity. +/// +/// A random GUID would make every build of the same input differ, which breaks +/// reproducible builds and content-addressed caching; the MVID only has to be +/// unique per distinct module, not unpredictable. +fn derive_mvid(name: &str, version: Version) -> [u8; 16] { + let mut mvid = [0_u8; 16]; + let mut hash: u64 = 0xCBF2_9CE4_8422_2325; + let mix = |byte: u8, hash: &mut u64| { + *hash ^= u64::from(byte); + *hash = hash.wrapping_mul(0x0000_0100_0000_01B3); + }; + for byte in name.as_bytes() { + mix(*byte, &mut hash); + } + for part in [ + version.major, + version.minor, + version.build, + version.revision, + ] { + for byte in part.to_le_bytes() { + mix(byte, &mut hash); + } + } + let low = hash.to_le_bytes(); + let high = hash.rotate_left(17).to_le_bytes(); + if let Some(slot) = mvid.get_mut(0..8) { + slot.copy_from_slice(&low); + } + if let Some(slot) = mvid.get_mut(8..16) { + slot.copy_from_slice(&high); + } + // The Module row requires a non-zero MVID; FNV-1a of a non-empty identity + // cannot be zero, but the fallback keeps that guarantee unconditional. + if mvid.iter().all(|byte| *byte == 0) { + mvid = [1_u8; 16]; + } + mvid +} diff --git a/crates/modrix-ecma335/src/emit.rs b/crates/modrix-ecma335/src/emit.rs new file mode 100644 index 0000000..7dc718c --- /dev/null +++ b/crates/modrix-ecma335/src/emit.rs @@ -0,0 +1,270 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Serialises resolved rows into the `#~` table stream. +//! +//! Column widths arrive as a single [`Widths`] value computed from the final +//! row counts and heap sizes. Nothing in this module may consult a running +//! length: every width is already fixed before the first byte is written. + +use crate::encode::{write_index, write_u16, write_u32, write_u64}; +use crate::error::Result; +use crate::materialize::Image; +use crate::rows::TableSet; +use crate::tables::{EMITTED_TABLES, SORTED_MASK, Widths, table}; + +/// Builds the complete `#~` stream: header, row counts, then row data. +/// +/// # Errors +/// +/// Returns [`crate::Error::IndexTooWide`] if any column was handed a value +/// that does not fit the width computed for it. +pub(crate) fn table_stream(image: &Image) -> Result> { + let widths = Widths::new( + image.strings.bytes().len(), + image.guids.count(), + image.blobs.bytes().len(), + image.counts, + ); + let mut out = Vec::new(); + write_u32(&mut out, 0); + out.push(2); + out.push(0); + out.push(widths.heap_sizes); + // ECMA-335 II.24.2.6 shows this reserved byte as 1, not 0. + out.push(1); + let valid = image.counts.valid_mask(); + write_u64(&mut out, valid); + write_u64(&mut out, SORTED_MASK); + for table_number in 0..64_u8 { + if valid & (1_u64 << table_number) != 0 { + write_u32(&mut out, image.counts.get(table_number)); + } + } + write_rows(&mut out, &image.tables, widths)?; + Ok(out) +} + +/// Writes every present table's rows in ascending table-number order. +fn write_rows(out: &mut Vec, tables: &TableSet, widths: Widths) -> Result<()> { + for table_number in EMITTED_TABLES { + write_table(out, tables, widths, table_number)?; + } + Ok(()) +} + +fn write_table(out: &mut Vec, tables: &TableSet, widths: Widths, number: u8) -> Result<()> { + match number { + table::MODULE => write_module(out, tables, widths), + table::TYPE_REF => write_type_refs(out, tables, widths), + table::TYPE_DEF => write_type_defs(out, tables, widths), + table::FIELD => write_fields(out, tables, widths), + table::METHOD_DEF => write_methods(out, tables, widths), + table::PARAM => write_params(out, tables, widths), + table::INTERFACE_IMPL => write_interface_impls(out, tables, widths), + table::MEMBER_REF => write_member_refs(out, tables, widths), + table::CONSTANT => write_constants(out, tables, widths), + table::CUSTOM_ATTRIBUTE => write_custom_attributes(out, tables, widths), + table::PROPERTY_MAP => write_property_maps(out, tables, widths), + table::PROPERTY => write_properties(out, tables, widths), + table::METHOD_SEMANTICS => write_method_semantics(out, tables, widths), + table::TYPE_SPEC => write_type_specs(out, tables, widths), + table::ASSEMBLY => write_assembly(out, tables, widths), + table::ASSEMBLY_REF => write_assembly_refs(out, tables, widths), + table::NESTED_CLASS => write_nested_classes(out, tables, widths), + table::GENERIC_PARAM => write_generic_params(out, tables, widths), + _ => Ok(()), + } +} + +fn write_module(out: &mut Vec, tables: &TableSet, widths: Widths) -> Result<()> { + for row in &tables.module { + write_u16(out, row.generation); + write_index(out, widths.string, row.name)?; + write_index(out, widths.guid, row.mvid)?; + write_index(out, widths.guid, row.enc_id)?; + write_index(out, widths.guid, row.enc_base_id)?; + } + Ok(()) +} + +fn write_type_refs(out: &mut Vec, tables: &TableSet, widths: Widths) -> Result<()> { + let scope = widths.resolution_scope; + for row in &tables.type_refs { + write_index(out, scope, row.resolution_scope)?; + write_index(out, widths.string, row.name)?; + write_index(out, widths.string, row.namespace)?; + } + Ok(()) +} + +fn write_type_defs(out: &mut Vec, tables: &TableSet, widths: Widths) -> Result<()> { + let extends = widths.type_def_or_ref; + let field = widths.field; + let method = widths.method_def; + for row in &tables.type_defs { + write_u32(out, row.flags); + write_index(out, widths.string, row.name)?; + write_index(out, widths.string, row.namespace)?; + write_index(out, extends, row.extends)?; + write_index(out, field, row.field_list)?; + write_index(out, method, row.method_list)?; + } + Ok(()) +} + +fn write_fields(out: &mut Vec, tables: &TableSet, widths: Widths) -> Result<()> { + for row in &tables.fields { + write_u16(out, row.flags); + write_index(out, widths.string, row.name)?; + write_index(out, widths.blob, row.signature)?; + } + Ok(()) +} + +fn write_methods(out: &mut Vec, tables: &TableSet, widths: Widths) -> Result<()> { + let param = widths.param; + for row in &tables.methods { + write_u32(out, row.rva); + write_u16(out, row.impl_flags); + write_u16(out, row.flags); + write_index(out, widths.string, row.name)?; + write_index(out, widths.blob, row.signature)?; + write_index(out, param, row.param_list)?; + } + Ok(()) +} + +fn write_params(out: &mut Vec, tables: &TableSet, widths: Widths) -> Result<()> { + for row in &tables.params { + write_u16(out, row.flags); + write_u16(out, row.sequence); + write_index(out, widths.string, row.name)?; + } + Ok(()) +} + +fn write_interface_impls(out: &mut Vec, tables: &TableSet, widths: Widths) -> Result<()> { + let class = widths.type_def; + let interface = widths.type_def_or_ref; + for row in &tables.interface_impls { + write_index(out, class, row.class)?; + write_index(out, interface, row.interface)?; + } + Ok(()) +} + +fn write_member_refs(out: &mut Vec, tables: &TableSet, widths: Widths) -> Result<()> { + let parent = widths.member_ref_parent; + for row in &tables.member_refs { + write_index(out, parent, row.class)?; + write_index(out, widths.string, row.name)?; + write_index(out, widths.blob, row.signature)?; + } + Ok(()) +} + +fn write_constants(out: &mut Vec, tables: &TableSet, widths: Widths) -> Result<()> { + let parent = widths.has_constant; + for row in &tables.constants { + out.push(row.kind); + out.push(0); + write_index(out, parent, row.parent)?; + write_index(out, widths.blob, row.value)?; + } + Ok(()) +} + +fn write_custom_attributes(out: &mut Vec, tables: &TableSet, widths: Widths) -> Result<()> { + let parent = widths.has_custom_attribute; + let constructor = widths.custom_attribute_type; + for row in &tables.custom_attributes { + write_index(out, parent, row.parent)?; + write_index(out, constructor, row.constructor)?; + write_index(out, widths.blob, row.value)?; + } + Ok(()) +} + +fn write_property_maps(out: &mut Vec, tables: &TableSet, widths: Widths) -> Result<()> { + let parent = widths.type_def; + let property = widths.property; + for row in &tables.property_maps { + write_index(out, parent, row.parent)?; + write_index(out, property, row.property_list)?; + } + Ok(()) +} + +fn write_properties(out: &mut Vec, tables: &TableSet, widths: Widths) -> Result<()> { + for row in &tables.properties { + write_u16(out, row.flags); + write_index(out, widths.string, row.name)?; + write_index(out, widths.blob, row.signature)?; + } + Ok(()) +} + +fn write_method_semantics(out: &mut Vec, tables: &TableSet, widths: Widths) -> Result<()> { + let method = widths.method_def; + let association = widths.has_semantics; + for row in &tables.method_semantics { + write_u16(out, row.semantics); + write_index(out, method, row.method)?; + write_index(out, association, row.association)?; + } + Ok(()) +} + +fn write_type_specs(out: &mut Vec, tables: &TableSet, widths: Widths) -> Result<()> { + for row in &tables.type_specs { + write_index(out, widths.blob, row.signature)?; + } + Ok(()) +} + +fn write_assembly(out: &mut Vec, tables: &TableSet, widths: Widths) -> Result<()> { + for row in &tables.assembly { + write_u32(out, row.hash_algorithm); + for part in row.version { + write_u16(out, part); + } + write_u32(out, row.flags); + write_index(out, widths.blob, row.public_key)?; + write_index(out, widths.string, row.name)?; + write_index(out, widths.string, row.culture)?; + } + Ok(()) +} + +fn write_assembly_refs(out: &mut Vec, tables: &TableSet, widths: Widths) -> Result<()> { + for row in &tables.assembly_refs { + for part in row.version { + write_u16(out, part); + } + write_u32(out, row.flags); + write_index(out, widths.blob, row.public_key_or_token)?; + write_index(out, widths.string, row.name)?; + write_index(out, widths.string, row.culture)?; + write_index(out, widths.blob, row.hash_value)?; + } + Ok(()) +} + +fn write_nested_classes(out: &mut Vec, tables: &TableSet, widths: Widths) -> Result<()> { + let type_def = widths.type_def; + for row in &tables.nested_classes { + write_index(out, type_def, row.nested)?; + write_index(out, type_def, row.enclosing)?; + } + Ok(()) +} + +fn write_generic_params(out: &mut Vec, tables: &TableSet, widths: Widths) -> Result<()> { + let owner = widths.type_or_method_def; + for row in &tables.generic_params { + write_u16(out, row.number); + write_u16(out, row.flags); + write_index(out, owner, row.owner)?; + write_index(out, widths.string, row.name)?; + } + Ok(()) +} diff --git a/crates/modrix-ecma335/src/encode.rs b/crates/modrix-ecma335/src/encode.rs new file mode 100644 index 0000000..1b38cef --- /dev/null +++ b/crates/modrix-ecma335/src/encode.rs @@ -0,0 +1,177 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Primitive encoders shared by the heaps, the signature blobs and the tables. +//! +//! Everything here is little-endian except the compressed integers, which +//! ECMA-335 II.23.2 defines big-endian so that the leading bits act as a +//! self-describing length prefix. + +use crate::error::{Error, Result}; + +/// Largest value ECMA-335's compressed unsigned integer encoding can hold. +pub const MAX_COMPRESSED_UNSIGNED: u32 = 0x1FFF_FFFF; + +/// Appends `value` to `out` in ECMA-335 II.23.2 compressed unsigned form. +/// +/// # Errors +/// +/// Returns [`Error::CompressedRange`] if `value` exceeds +/// [`MAX_COMPRESSED_UNSIGNED`]; the encoding steals the top three bits for the +/// length tag, so larger values are not representable at all. +pub fn compress_unsigned(out: &mut Vec, value: u32) -> Result<()> { + // Selecting big-endian bytes rather than shifting into `u8` keeps every + // narrowing conversion provably lossless. + let b = value.to_be_bytes(); + if value < 0x80 { + out.push(b[3]); + } else if value < 0x4000 { + out.push(0x80 | b[2]); + out.push(b[3]); + } else if value <= MAX_COMPRESSED_UNSIGNED { + out.push(0xC0 | b[0]); + out.push(b[1]); + out.push(b[2]); + out.push(b[3]); + } else { + return Err(Error::CompressedRange { value }); + } + Ok(()) +} + +/// Appends `value` to `out` in ECMA-335 II.23.2 compressed *signed* form. +/// +/// The sign bit is rotated into bit 0 so small negatives stay one byte. Only +/// `ArrayShape.LoBounds` needs this encoding. +/// +/// # Errors +/// +/// Returns [`Error::CompressedSignedRange`] if `value` falls outside +/// `-2^28 ..= 2^28 - 1`. +pub fn compress_signed(out: &mut Vec, value: i32) -> Result<()> { + const B6: i32 = (1 << 6) - 1; + const B13: i32 = (1 << 13) - 1; + const B28: i32 = (1 << 28) - 1; + + // An arithmetic right shift gives all-ones for negatives and all-zeros + // otherwise, which is exactly the sign bit that belongs in bit 0. + let sign = value >> 31; + if (value & !B6) == (sign & !B6) { + let n = (((value & B6) << 1) | (sign & 1)).cast_unsigned(); + out.push(n.to_be_bytes()[3]); + } else if (value & !B13) == (sign & !B13) { + let n = (0x8000 | ((value & B13) << 1) | (sign & 1)).cast_unsigned(); + let b = n.to_be_bytes(); + out.push(b[2]); + out.push(b[3]); + } else if (value & !B28) == (sign & !B28) { + let n = 0xC000_0000_u32 | (((value & B28) << 1) | (sign & 1)).cast_unsigned(); + out.extend_from_slice(&n.to_be_bytes()); + } else { + return Err(Error::CompressedSignedRange { value }); + } + Ok(()) +} + +/// Appends a little-endian `u16`. +pub(crate) fn write_u16(out: &mut Vec, value: u16) { + out.extend_from_slice(&value.to_le_bytes()); +} + +/// Appends a little-endian `u32`. +pub(crate) fn write_u32(out: &mut Vec, value: u32) { + out.extend_from_slice(&value.to_le_bytes()); +} + +/// Appends a little-endian `u64`. +pub(crate) fn write_u64(out: &mut Vec, value: u64) { + out.extend_from_slice(&value.to_le_bytes()); +} + +/// Appends a metadata index that occupies `width` bytes (2 or 4). +/// +/// # Errors +/// +/// Returns [`Error::IndexTooWide`] if a 2-byte column was asked to hold a +/// value above `u16::MAX`. That can only happen if a width was computed before +/// the row counts were final, which is the single most damaging bug class in +/// a metadata writer, so it is checked rather than truncated. +pub(crate) fn write_index(out: &mut Vec, width: u8, value: u32) -> Result<()> { + if width == 2 { + let narrow = u16::try_from(value).map_err(|_| Error::IndexTooWide { value })?; + write_u16(out, narrow); + } else { + write_u32(out, value); + } + Ok(()) +} + +/// Rounds `value` up to a multiple of `alignment`, or `None` on overflow. +pub(crate) fn align_up(value: usize, alignment: usize) -> Option { + let bump = value.checked_add(alignment.checked_sub(1)?)?; + bump.checked_div(alignment)?.checked_mul(alignment) +} + +/// Zero-pads `buf` so its length is a multiple of 4. +/// +/// Every metadata stream is 4-byte aligned and the padding counts towards the +/// size recorded in its stream header. +pub(crate) fn pad_to_four(buf: &mut Vec) { + while !buf.len().is_multiple_of(4) { + buf.push(0); + } +} + +#[cfg(test)] +mod tests { + use super::{align_up, compress_signed, compress_unsigned}; + + fn cu(value: u32) -> Vec { + let mut out = Vec::new(); + compress_unsigned(&mut out, value).unwrap(); + out + } + + fn cs(value: i32) -> Vec { + let mut out = Vec::new(); + compress_signed(&mut out, value).unwrap(); + out + } + + #[test] + fn compressed_unsigned_matches_spec_examples() { + assert_eq!(cu(0x00), vec![0x00]); + assert_eq!(cu(0x03), vec![0x03]); + assert_eq!(cu(0x7F), vec![0x7F]); + assert_eq!(cu(0x80), vec![0x80, 0x80]); + assert_eq!(cu(0x2E57), vec![0xAE, 0x57]); + assert_eq!(cu(0x3FFF), vec![0xBF, 0xFF]); + assert_eq!(cu(0x4000), vec![0xC0, 0x00, 0x40, 0x00]); + assert_eq!(cu(0x1FFF_FFFF), vec![0xDF, 0xFF, 0xFF, 0xFF]); + } + + #[test] + fn compressed_unsigned_rejects_out_of_range() { + let mut out = Vec::new(); + assert!(compress_unsigned(&mut out, 0x2000_0000).is_err()); + } + + #[test] + fn compressed_signed_matches_spec_examples() { + assert_eq!(cs(3), vec![0x06]); + assert_eq!(cs(-3), vec![0x7B]); + assert_eq!(cs(64), vec![0x80, 0x80]); + assert_eq!(cs(-64), vec![0x01]); + assert_eq!(cs(8192), vec![0xC0, 0x00, 0x40, 0x00]); + assert_eq!(cs(-8192), vec![0x80, 0x01]); + assert_eq!(cs(268_435_455), vec![0xDF, 0xFF, 0xFF, 0xFE]); + assert_eq!(cs(-268_435_456), vec![0xC0, 0x00, 0x00, 0x01]); + } + + #[test] + fn align_up_rounds_and_detects_overflow() { + assert_eq!(align_up(0, 512), Some(0)); + assert_eq!(align_up(1, 512), Some(512)); + assert_eq!(align_up(512, 512), Some(512)); + assert_eq!(align_up(513, 512), Some(1024)); + assert_eq!(align_up(usize::MAX, 512), None); + } +} diff --git a/crates/modrix-ecma335/src/error.rs b/crates/modrix-ecma335/src/error.rs new file mode 100644 index 0000000..02f5882 --- /dev/null +++ b/crates/modrix-ecma335/src/error.rs @@ -0,0 +1,135 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Errors raised while building a .NET reference assembly. + +/// Result alias for this crate. +pub type Result = core::result::Result; + +/// Why an assembly could not be emitted. +/// +/// Every variant is a *refusal to emit a corrupt file*. ECMA-335 metadata has +/// almost no redundancy, so a writer that silently truncated an index or wrote +/// a dangling row would produce a DLL that a compiler either mis-reads or +/// crashes on (a dangling `TypeRef.ResolutionScope` takes Roslyn down with an +/// `ArgumentOutOfRangeException`). Failing loudly here is the only way the +/// caller ever learns. +#[derive(Debug, thiserror::Error)] +#[non_exhaustive] +pub enum Error { + /// A value exceeded the range of ECMA-335's compressed-integer encoding. + #[error("value {value} exceeds the compressed-integer maximum of 0x1FFFFFFF")] + CompressedRange { + /// The value that could not be encoded. + value: u32, + }, + + /// A signed value exceeded the compressed-signed-integer encoding range. + #[error("value {value} is outside the compressed signed range -2^28..2^28-1")] + CompressedSignedRange { + /// The value that could not be encoded. + value: i32, + }, + + /// A type signature nested deeper than this writer will encode. The + /// encoder walks the type tree recursively, so an unbounded depth would be + /// unbounded stack use on caller-supplied input. + #[error("type signature nests deeper than the supported {limit} levels")] + TypeTooDeep { + /// The depth ceiling. + limit: u32, + }, + + /// A metadata table grew past what this writer will emit. Row indices are + /// 32-bit and heap offsets must stay addressable, so the ceiling is well + /// below `u32::MAX`. + #[error("the {table} table would hold {rows} rows, past the ceiling of {limit}")] + TableOverflow { + /// Human-readable table name. + table: &'static str, + /// The row count that was refused. + rows: usize, + /// The ceiling. + limit: usize, + }, + + /// A metadata heap grew past what this writer will emit. + #[error("the {heap} heap would grow to {size} bytes, past the ceiling of {limit}")] + HeapOverflow { + /// Heap name, for example `#Strings`. + heap: &'static str, + /// The size that was refused. + size: usize, + /// The ceiling. + limit: usize, + }, + + /// A string destined for `#Strings` contained an interior NUL, which would + /// silently truncate it because the heap is NUL-terminated. + #[error("the name `{name}` contains a NUL byte and cannot go in #Strings")] + NulInString { + /// The offending string, with the NUL rendered as an escape. + name: String, + }, + + /// A handle referred to a row that does not exist. This is the check that + /// stops rule 8 (every coded index must resolve) from being violated: a + /// handle minted by one builder and used in another would otherwise write + /// a dangling index. + #[error("{kind} handle #{index} does not name a row of this assembly ({rows} present)")] + DanglingHandle { + /// Which handle family, for example `TypeDef`. + kind: &'static str, + /// The zero-based handle value. + index: u32, + /// How many rows that table actually has. + rows: u32, + }, + + /// A coded index could not be formed because the row number does not fit + /// once the tag bits are shifted in. + #[error("row {row} of table 0x{table:02X} does not fit the {family} coded index")] + CodedIndexOverflow { + /// The coded-index family name. + family: &'static str, + /// The target table number. + table: u8, + /// The 1-based row. + row: u32, + }, + + /// A nested type carried a namespace. ECMA-335 requires a nested type's + /// `Namespace` to be the empty string - the namespace comes from the + /// enclosing type - and a non-empty one makes the type unresolvable under + /// its apparent name. + #[error("nested type `{name}` must have an empty namespace")] + NestedTypeHasNamespace { + /// The nested type's name. + name: String, + }, + + /// A `literal` field had no compile-time value. The reference still loads + /// and the member still resolves, so the failure surfaces only in the + /// *consuming* compiler as a bare `CS7038` with no useful location. + #[error("literal field `{name}` has no Constant row; consumers fail with CS7038")] + LiteralWithoutConstant { + /// The field's name. + name: String, + }, + + /// A two-byte metadata column was handed a value larger than `u16::MAX`. + /// The only way that happens is a column width computed before the row + /// counts and heap sizes were final, so it is reported rather than + /// truncated into a silently corrupt file. + #[error("value {value} does not fit the 2-byte metadata column it was written to")] + IndexTooWide { + /// The value that did not fit. + value: u32, + }, + + /// The image layout arithmetic overflowed, which means the requested + /// assembly is far larger than a PE file can describe. + #[error("image layout overflowed while computing {what}")] + LayoutOverflow { + /// Which quantity overflowed. + what: &'static str, + }, +} diff --git a/crates/modrix-ecma335/src/handles.rs b/crates/modrix-ecma335/src/handles.rs new file mode 100644 index 0000000..62d837a --- /dev/null +++ b/crates/modrix-ecma335/src/handles.rs @@ -0,0 +1,207 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Opaque handles to rows the builder has been asked to emit. +//! +//! Handles are zero-based positions in the builder's own vectors, never raw +//! metadata tokens. That matters for members: fields and methods are added +//! against their owning type and only get a table row number when [`build`] +//! flattens the types in order, because ECMA-335 requires each type's members +//! to be physically contiguous. A `FieldId` therefore names +//! `(type, position within that type)` and is resolved late. +//! +//! [`build`]: crate::AssemblyBuilder::build + +use crate::error::Result; +use crate::tables::{TYPE_DEF_OR_REF, table}; + +/// Handle to an `AssemblyRef` row. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct AssemblyRefId(pub(crate) u32); + +/// Handle to a `TypeRef` row. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct TypeRefId(pub(crate) u32); + +/// Handle to a `TypeSpec` row. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct TypeSpecId(pub(crate) u32); + +/// Handle to a `TypeDef` row. Handle 0 is always the `` pseudo-type. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct TypeDefId(pub(crate) u32); + +/// Handle to a `MemberRef` row. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct MemberRefId(pub(crate) u32); + +/// Handle to a `Field` row, as `(owning type, position within that type)`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct FieldId { + pub(crate) owner: u32, + pub(crate) slot: u32, +} + +/// Handle to a `MethodDef` row, as `(owning type, position within that type)`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct MethodId { + pub(crate) owner: u32, + pub(crate) slot: u32, +} + +/// Handle to a `Property` row, as `(owning type, position within that type)`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct PropertyId { + pub(crate) owner: u32, + pub(crate) slot: u32, +} + +impl TypeDefId { + /// The `` pseudo-type, which ECMA-335 requires as `TypeDef` row 1. + pub const MODULE: Self = Self(0); +} + +/// A token that can name a type: a definition, a reference, or a `TypeSpec`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum TypeDefOrRef { + /// A type defined in this assembly. + Definition(TypeDefId), + /// A type imported from another assembly. + Reference(TypeRefId), + /// A constructed type held in the `TypeSpec` table. + Specification(TypeSpecId), +} + +impl TypeDefOrRef { + /// The `(table, 1-based row)` this token names. + pub(crate) fn target(self) -> Option<(u8, u32)> { + let (table, index) = match self { + Self::Definition(id) => (table::TYPE_DEF, id.0), + Self::Reference(id) => (table::TYPE_REF, id.0), + Self::Specification(id) => (table::TYPE_SPEC, id.0), + }; + Some((table, index.checked_add(1)?)) + } + + /// The packed `TypeDefOrRef` coded index, as it appears both in table + /// columns and (compressed) inside signature blobs. + /// + /// # Errors + /// + /// Returns [`crate::Error::CodedIndexOverflow`] if the row number does not + /// survive being shifted left by the two tag bits. + pub fn coded_value(self) -> Result { + let (table, row) = self.target().ok_or(crate::Error::CodedIndexOverflow { + family: TYPE_DEF_OR_REF.name, + table: table::TYPE_DEF, + row: u32::MAX, + })?; + TYPE_DEF_OR_REF.encode(table, row) + } +} + +impl From for TypeDefOrRef { + fn from(id: TypeDefId) -> Self { + Self::Definition(id) + } +} + +impl From for TypeDefOrRef { + fn from(id: TypeRefId) -> Self { + Self::Reference(id) + } +} + +impl From for TypeDefOrRef { + fn from(id: TypeSpecId) -> Self { + Self::Specification(id) + } +} + +/// Where a `TypeRef` is resolved. +/// +/// For a net6.0-or-later reference assembly the corlib scope must be an +/// `AssemblyRef` naming `System.Runtime` with public key token +/// `b03f5f7f11d50a3a`; `mscorlib`, `netstandard` and `System.Private.CoreLib` +/// are all rejected by Roslyn with CS0012. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum ResolutionScope { + /// This module (`Module` row 1). + Module, + /// Another assembly. + AssemblyRef(AssemblyRefId), + /// The enclosing type of a nested type reference. + TypeRef(TypeRefId), +} + +/// What a `MemberRef` row hangs off. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum MemberRefParent { + /// A type defined here. + TypeDef(TypeDefId), + /// A type imported from elsewhere. + TypeRef(TypeRefId), + /// A constructed type. + TypeSpec(TypeSpecId), + /// A vararg call site on a local method. + MethodDef(MethodId), +} + +/// The constructor a `CustomAttribute` row invokes. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum CustomAttributeType { + /// A constructor defined in this assembly. + MethodDef(MethodId), + /// A constructor imported from another assembly. + MemberRef(MemberRefId), +} + +/// What a `CustomAttribute` row decorates. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum HasCustomAttribute { + /// The assembly itself; this is where `ReferenceAssemblyAttribute` and + /// `TargetFrameworkAttribute` go. + Assembly, + /// The module. + Module, + /// A type. + TypeDef(TypeDefId), + /// An imported type. + TypeRef(TypeRefId), + /// A field. + Field(FieldId), + /// A method. + MethodDef(MethodId), + /// A property. + Property(PropertyId), + /// A referenced assembly. + AssemblyRef(AssemblyRefId), +} + +#[cfg(test)] +mod tests { + use super::{TypeDefId, TypeDefOrRef, TypeRefId, TypeSpecId}; + + #[test] + fn coded_values_match_the_hand_worked_examples() { + // TypeDef row 7 -> (7 << 2) | 0 == 28; the enum field signature in the + // reference emitter encodes exactly this. + assert_eq!( + TypeDefOrRef::Definition(TypeDefId(6)) + .coded_value() + .unwrap(), + 28 + ); + // TypeRef row 1 -> (1 << 2) | 1 == 5. + assert_eq!( + TypeDefOrRef::Reference(TypeRefId(0)).coded_value().unwrap(), + 5 + ); + // TypeSpec row 1 -> (1 << 2) | 2 == 6. + assert_eq!( + TypeDefOrRef::Specification(TypeSpecId(0)) + .coded_value() + .unwrap(), + 6 + ); + } +} diff --git a/crates/modrix-ecma335/src/heaps.rs b/crates/modrix-ecma335/src/heaps.rs new file mode 100644 index 0000000..5ad00de --- /dev/null +++ b/crates/modrix-ecma335/src/heaps.rs @@ -0,0 +1,221 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! The four metadata heaps: `#Strings`, `#Blob`, `#GUID` and `#US`. +//! +//! Each heap is append-only and deduplicating. The two byte-addressed heaps +//! (`#Strings`, `#Blob`) both begin with a single `0x00` byte so that index 0 +//! means "the empty string" / "the empty blob" - metadata uses index 0 as the +//! neutral value for `Culture`, `PublicKey`, `HashValue` and a nested type's +//! namespace, so that first byte is load-bearing, not padding. + +use std::collections::HashMap; + +use crate::encode::compress_unsigned; +use crate::error::{Error, Result}; + +/// Ceiling on any one heap. Well under `u32::MAX` so every offset stays a +/// valid 4-byte index with room to spare. +const HEAP_LIMIT: usize = 0x1000_0000; + +/// The `#Strings` heap: NUL-terminated UTF-8, indexed by byte offset. +#[derive(Debug)] +pub(crate) struct StringHeap { + data: Vec, + seen: HashMap, +} + +impl StringHeap { + /// Creates a heap whose index 0 is already the empty string. + pub(crate) fn new() -> Self { + let mut seen = HashMap::new(); + seen.insert(String::new(), 0_u32); + Self { + data: vec![0], + seen, + } + } + + /// Interns `value`, returning its byte offset. + /// + /// # Errors + /// + /// Returns [`Error::NulInString`] if `value` contains an interior NUL (the + /// heap is NUL-terminated, so it would be silently truncated) or + /// [`Error::HeapOverflow`] if the heap would exceed its ceiling. + pub(crate) fn intern(&mut self, value: &str) -> Result { + if let Some(offset) = self.seen.get(value) { + return Ok(*offset); + } + if value.as_bytes().contains(&0) { + return Err(Error::NulInString { + name: value.escape_default().to_string(), + }); + } + let offset = u32::try_from(self.data.len()).map_err(|_| Error::HeapOverflow { + heap: "#Strings", + size: self.data.len(), + limit: HEAP_LIMIT, + })?; + self.data.extend_from_slice(value.as_bytes()); + self.data.push(0); + self.check_limit("#Strings")?; + self.seen.insert(value.to_owned(), offset); + Ok(offset) + } + + fn check_limit(&self, heap: &'static str) -> Result<()> { + if self.data.len() > HEAP_LIMIT { + return Err(Error::HeapOverflow { + heap, + size: self.data.len(), + limit: HEAP_LIMIT, + }); + } + Ok(()) + } + + /// The raw heap bytes, before stream padding. + pub(crate) fn bytes(&self) -> &[u8] { + &self.data + } +} + +/// The `#Blob` heap: each entry is a compressed length followed by its bytes, +/// indexed by the byte offset of the *length prefix*, not of the data. +#[derive(Debug)] +pub(crate) struct BlobHeap { + data: Vec, + seen: HashMap, u32>, +} + +impl BlobHeap { + /// Creates a heap whose index 0 is already the empty blob. + pub(crate) fn new() -> Self { + let mut seen = HashMap::new(); + seen.insert(Vec::new(), 0_u32); + Self { + data: vec![0], + seen, + } + } + + /// Interns `value`, returning the offset of its length prefix. + /// + /// # Errors + /// + /// Returns [`Error::HeapOverflow`] if the heap would exceed its ceiling, + /// or [`Error::CompressedRange`] if the blob is longer than a compressed + /// integer can describe. + pub(crate) fn intern(&mut self, value: &[u8]) -> Result { + if let Some(offset) = self.seen.get(value) { + return Ok(*offset); + } + let offset = u32::try_from(self.data.len()).map_err(|_| Error::HeapOverflow { + heap: "#Blob", + size: self.data.len(), + limit: HEAP_LIMIT, + })?; + let length = u32::try_from(value.len()).map_err(|_| Error::HeapOverflow { + heap: "#Blob", + size: value.len(), + limit: HEAP_LIMIT, + })?; + compress_unsigned(&mut self.data, length)?; + self.data.extend_from_slice(value); + if self.data.len() > HEAP_LIMIT { + return Err(Error::HeapOverflow { + heap: "#Blob", + size: self.data.len(), + limit: HEAP_LIMIT, + }); + } + self.seen.insert(value.to_vec(), offset); + Ok(offset) + } + + /// The raw heap bytes, before stream padding. + pub(crate) fn bytes(&self) -> &[u8] { + &self.data + } +} + +/// The `#GUID` heap: a bare array of 16-byte GUIDs indexed by *1-based +/// ordinal*, not by byte offset. Index 0 means "no GUID". +#[derive(Debug, Default)] +pub(crate) struct GuidHeap { + data: Vec, +} + +impl GuidHeap { + /// Appends a GUID and returns its 1-based ordinal. + /// + /// # Errors + /// + /// Returns [`Error::HeapOverflow`] if the heap would exceed its ceiling. + pub(crate) fn add(&mut self, guid: [u8; 16]) -> Result { + self.data.extend_from_slice(&guid); + if self.data.len() > HEAP_LIMIT { + return Err(Error::HeapOverflow { + heap: "#GUID", + size: self.data.len(), + limit: HEAP_LIMIT, + }); + } + u32::try_from(self.count()).map_err(|_| Error::HeapOverflow { + heap: "#GUID", + size: self.data.len(), + limit: HEAP_LIMIT, + }) + } + + /// How many GUIDs the heap holds. The `HeapSizes` bit for `#GUID` keys off + /// this count, not off the byte length. + pub(crate) fn count(&self) -> usize { + self.data.len().checked_div(16).unwrap_or(0) + } + + /// The raw heap bytes, before stream padding. + pub(crate) fn bytes(&self) -> &[u8] { + &self.data + } +} + +#[cfg(test)] +mod tests { + use super::{BlobHeap, GuidHeap, StringHeap}; + + #[test] + fn string_heap_starts_with_the_empty_string_and_dedupes() { + let mut heap = StringHeap::new(); + assert_eq!(heap.intern("").unwrap(), 0); + let first = heap.intern("MyLib").unwrap(); + assert_eq!(first, 1); + assert_eq!(heap.intern("MyLib").unwrap(), first); + assert_eq!(heap.bytes(), b"\0MyLib\0"); + } + + #[test] + fn string_heap_rejects_interior_nul() { + let mut heap = StringHeap::new(); + assert!(heap.intern("bad\0name").is_err()); + } + + #[test] + fn blob_heap_indexes_the_length_prefix() { + let mut heap = BlobHeap::new(); + assert_eq!(heap.intern(&[]).unwrap(), 0); + let sig = heap.intern(&[0x06, 0x08]).unwrap(); + assert_eq!(sig, 1); + assert_eq!(heap.bytes(), &[0x00, 0x02, 0x06, 0x08]); + assert_eq!(heap.intern(&[0x06, 0x08]).unwrap(), sig); + } + + #[test] + fn guid_heap_is_one_based_by_ordinal() { + let mut heap = GuidHeap::default(); + assert_eq!(heap.count(), 0); + assert_eq!(heap.add([7; 16]).unwrap(), 1); + assert_eq!(heap.add([9; 16]).unwrap(), 2); + assert_eq!(heap.count(), 2); + assert_eq!(heap.bytes().len(), 32); + } +} diff --git a/crates/modrix-ecma335/src/lib.rs b/crates/modrix-ecma335/src/lib.rs new file mode 100644 index 0000000..398c6a9 --- /dev/null +++ b/crates/modrix-ecma335/src/lib.rs @@ -0,0 +1,113 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! A from-scratch ECMA-335 / PE32+ writer that emits .NET **reference +//! assemblies**: types, fields and method signatures, with no method bodies. +//! +//! ## Why this exists +//! +//! An IL2CPP game ships no managed assemblies, so there is nothing for a mod +//! author to compile against. Modrix reconstructs the missing surface from the +//! game's own metadata, and this crate is the last stage of that pipeline: it +//! turns a type model into a real DLL that `csc` accepts as a `-r:` reference. +//! Shelling out to the .NET SDK was rejected - it would make mod development +//! depend on a toolchain the user may not have - so the container, the +//! metadata tables and the signature blobs are all written here, in pure safe +//! Rust with no dependencies beyond `thiserror`. +//! +//! ## What "reference assembly" buys +//! +//! Every `MethodDef.RVA` is 0. That is what keeps the output at a couple of +//! kilobytes with a single section, no imports, no relocations and no entry +//! point - and it is legal, because a compiler only ever reads signatures. +//! The file is deliberately **not** loadable by the CLR; it is a compile-time +//! artefact. +//! +//! ## The rules that are not optional +//! +//! Each of these was established by ablation - removing it and watching what +//! broke - and each fails in a way that points nowhere near the cause: +//! +//! | Rule | Symptom when violated | +//! |------|-----------------------| +//! | An `Assembly` row must exist | `CS1509: ... is not an assembly` | +//! | The corlib reference must be `System.Runtime` with token `b03f5f7f11d50a3a` | `CS0012` on every imported type | +//! | Literal fields need a `Constant` row | the *consumer* fails with a bare `CS7038` | +//! | The metadata version length must be a multiple of 4 | `CS0009: Read out of bounds` | +//! | `#Blob` must be present | `CS0009: Read out of bounds` | +//! | Coded indices widen at `1 << (16 - tag_bits)` | silent corruption past 16 384 types | +//! | Member runs must be contiguous per owning type | members bind to the wrong type | +//! | Every coded index must resolve | Roslyn crashes with `ArgumentOutOfRangeException` | +//! +//! ## Example +//! +//! ``` +//! use modrix_ecma335::{AssemblyBuilder, ResolutionScope, Version}; +//! use modrix_ecma335::model::{ +//! AssemblyReference, Field, Method, TypeDefinition, field_attributes, +//! method_attributes, type_attributes, +//! }; +//! use modrix_ecma335::signature::{MethodSignature, Type}; +//! +//! let mut builder = AssemblyBuilder::new("MyLib", Version::new(1, 0, 0, 0)); +//! let corlib = builder.add_assembly_ref(AssemblyReference::core_library(9)); +//! let scope = ResolutionScope::AssemblyRef(corlib); +//! let object = builder.add_type_ref(scope, "System", "Object"); +//! +//! let widget = builder.add_type_def(TypeDefinition::new( +//! "MyLib", +//! "Widget", +//! type_attributes::PUBLIC_CLASS, +//! Some(object.into()), +//! ))?; +//! builder.add_field(widget, Field::new("Value", field_attributes::PUBLIC, Type::I4))?; +//! builder.add_default_constructor(widget)?; +//! builder.add_method( +//! widget, +//! Method::new( +//! "Add", +//! method_attributes::PUBLIC_STATIC, +//! MethodSignature::static_method(Type::I4, vec![Type::I4, Type::I4]), +//! ), +//! )?; +//! +//! let dll = builder.build()?; +//! assert_eq!(&dll[..2], b"MZ"); +//! # Ok::<(), modrix_ecma335::Error>(()) +//! ``` + +// Every public item is part of a byte-format contract, so an undocumented one +// is a gap in the format's only prose description. +#![deny(missing_docs)] + +mod builder; +mod emit; +pub mod encode; +mod error; +mod handles; +mod heaps; +mod materialize; +mod metadata; +pub mod model; +mod pe; +mod rows; +pub mod signature; +mod tables; + +#[cfg(test)] +mod verify; + +#[cfg(test)] +mod tests; + +pub use builder::{ + AssemblyBuilder, HASH_ALGORITHM_SHA1, attribute_blob_empty, attribute_blob_string, +}; +pub use error::{Error, Result}; +pub use handles::{ + AssemblyRefId, CustomAttributeType, FieldId, HasCustomAttribute, MemberRefId, MemberRefParent, + MethodId, PropertyId, ResolutionScope, TypeDefId, TypeDefOrRef, TypeRefId, TypeSpecId, +}; +pub use model::{ + AssemblyReference, CORE_LIBRARY_NAME, CORE_LIBRARY_PUBLIC_KEY_TOKEN, Constant, Field, + GenericParameter, Method, Parameter, Property, TypeDefinition, Version, +}; +pub use signature::{MethodSignature, Type}; diff --git a/crates/modrix-ecma335/src/materialize.rs b/crates/modrix-ecma335/src/materialize.rs new file mode 100644 index 0000000..bf600f4 --- /dev/null +++ b/crates/modrix-ecma335/src/materialize.rs @@ -0,0 +1,619 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Turns the builder's declarative description into resolved metadata rows. +//! +//! This is where handles become 1-based row numbers and strings become heap +//! offsets. It runs to completion *before* any width is computed, which is the +//! whole point: an ECMA-335 column is 2 or 4 bytes depending on final row +//! counts, so nothing may be serialised until every row exists. + +use crate::builder::AssemblyBuilder; +use crate::error::{Error, Result}; +use crate::handles::{ + CustomAttributeType, FieldId, HasCustomAttribute, MemberRefParent, MethodId, PropertyId, + ResolutionScope, +}; +use crate::heaps::{BlobHeap, GuidHeap, StringHeap}; +use crate::model::{Constant, field_attributes}; +use crate::rows::{ + AssemblyRefRow, AssemblyRow, ConstantRow, CustomAttributeRow, FieldRow, GenericParamRow, + InterfaceImplRow, MemberRefRow, MethodDefRow, MethodSemanticsRow, ModuleRow, NestedClassRow, + ParamRow, PropertyMapRow, PropertyRow, TableSet, TypeDefRow, TypeRefRow, TypeSpecRow, +}; +use crate::signature::{element_type, field_signature, property_signature}; +use crate::tables::{ + CUSTOM_ATTRIBUTE_TYPE, HAS_CONSTANT, HAS_CUSTOM_ATTRIBUTE, HAS_SEMANTICS, MEMBER_REF_PARENT, + RESOLUTION_SCOPE, RowCounts, TYPE_OR_METHOD_DEF, table, +}; + +/// Ceiling on rows in any one table. Far above anything a real interop +/// assembly needs, and far below where 32-bit row arithmetic gets risky. +const MAX_ROWS: usize = 0x00FF_FFFF; + +/// `MethodSemantics.Semantics` value for a property setter. +const SEMANTICS_SETTER: u16 = 0x0001; +/// `MethodSemantics.Semantics` value for a property getter. +const SEMANTICS_GETTER: u16 = 0x0002; + +/// A fully resolved assembly: rows, heaps and final row counts. +pub(crate) struct Image { + pub(crate) tables: TableSet, + pub(crate) strings: StringHeap, + pub(crate) blobs: BlobHeap, + pub(crate) guids: GuidHeap, + pub(crate) counts: RowCounts, +} + +/// Where each type's member runs start, so a `(type, slot)` handle can be +/// turned into an absolute row number. +struct MemberLayout { + fields: Vec, + methods: Vec, + properties: Vec, +} + +/// Resolves the builder's description into [`Image`]. +/// +/// # Errors +/// +/// Propagates heap and table overflow, dangling handles, literal fields with +/// no constant, and signature encoding failures. +pub(crate) fn materialize(builder: &AssemblyBuilder) -> Result { + let mut state = Materializer::new(builder)?; + state.emit_module()?; + state.emit_type_refs()?; + state.emit_types()?; + state.emit_type_specs()?; + state.emit_member_refs()?; + state.emit_custom_attributes()?; + state.emit_assembly()?; + state.emit_assembly_refs()?; + state.sort_tables(); + state.finish() +} + +struct Materializer<'a> { + builder: &'a AssemblyBuilder, + tables: TableSet, + strings: StringHeap, + blobs: BlobHeap, + guids: GuidHeap, + layout: MemberLayout, +} + +impl<'a> Materializer<'a> { + fn new(builder: &'a AssemblyBuilder) -> Result { + Ok(Self { + layout: plan_members(builder)?, + builder, + tables: TableSet::default(), + strings: StringHeap::new(), + blobs: BlobHeap::new(), + guids: GuidHeap::default(), + }) + } + + fn emit_module(&mut self) -> Result<()> { + let name = self.strings.intern(&self.builder.module_name)?; + let mvid = self.guids.add(self.builder.mvid)?; + self.tables.module.push(ModuleRow { + generation: 0, + name, + mvid, + enc_id: 0, + enc_base_id: 0, + }); + Ok(()) + } + + fn emit_type_refs(&mut self) -> Result<()> { + for entry in &self.builder.type_refs { + let scope = match entry.scope { + ResolutionScope::Module => RESOLUTION_SCOPE.encode(table::MODULE, 1)?, + ResolutionScope::AssemblyRef(id) => { + RESOLUTION_SCOPE.encode(table::ASSEMBLY_REF, row(id.0)?)? + } + ResolutionScope::TypeRef(id) => { + RESOLUTION_SCOPE.encode(table::TYPE_REF, row(id.0)?)? + } + }; + let row = TypeRefRow { + resolution_scope: scope, + name: self.strings.intern(&entry.name)?, + namespace: self.strings.intern(&entry.namespace)?, + }; + self.tables.type_refs.push(row); + } + Ok(()) + } + + fn emit_types(&mut self) -> Result<()> { + for (index, entry) in self.builder.types.iter().enumerate() { + let type_index = u32::try_from(index).unwrap_or(u32::MAX); + let definition = &entry.definition; + let extends = match definition.extends { + Some(token) => token.coded_value()?, + None => 0, + }; + let row = TypeDefRow { + flags: definition.flags, + name: self.strings.intern(&definition.name)?, + namespace: self.strings.intern(&definition.namespace)?, + extends, + field_list: start_of(&self.layout.fields, type_index)?, + method_list: start_of(&self.layout.methods, type_index)?, + }; + self.tables.type_defs.push(row); + self.emit_fields(type_index)?; + self.emit_methods(type_index)?; + self.emit_properties(type_index)?; + self.emit_type_relations(type_index)?; + } + Ok(()) + } + + fn emit_fields(&mut self, type_index: u32) -> Result<()> { + let Some(entry) = self.builder.types.get(as_index(type_index)) else { + return Ok(()); + }; + for (slot, field) in entry.fields.iter().enumerate() { + let literal = field.flags & field_attributes::LITERAL != 0; + if literal && field.constant.is_none() { + return Err(Error::LiteralWithoutConstant { + name: field.name.clone(), + }); + } + let signature = field_signature(&field.field_type)?; + let mut flags = field.flags; + if field.constant.is_some() { + flags |= field_attributes::HAS_DEFAULT; + } + let row = FieldRow { + flags, + name: self.strings.intern(&field.name)?, + signature: self.blobs.intern(&signature)?, + }; + self.tables.fields.push(row); + if let Some(constant) = field.constant.as_ref() { + let field_row = self.field_row(FieldId { + owner: type_index, + slot: u32::try_from(slot).unwrap_or(u32::MAX), + })?; + self.emit_constant(HAS_CONSTANT.encode(table::FIELD, field_row)?, constant)?; + } + } + Ok(()) + } + + fn emit_constant(&mut self, parent: u32, constant: &Constant) -> Result<()> { + let (kind, bytes) = encode_constant(constant); + let value = self.blobs.intern(&bytes)?; + self.tables.constants.push(ConstantRow { + kind, + parent, + value, + }); + Ok(()) + } + + fn emit_methods(&mut self, type_index: u32) -> Result<()> { + let Some(entry) = self.builder.types.get(as_index(type_index)) else { + return Ok(()); + }; + for (slot, method) in entry.methods.iter().enumerate() { + let signature = method.signature.to_blob()?; + let param_list = row(u32::try_from(self.tables.params.len()).unwrap_or(u32::MAX))?; + let row_data = MethodDefRow { + // A reference assembly carries no IL, so every body RVA is 0. + rva: 0, + impl_flags: method.impl_flags, + flags: method.flags, + name: self.strings.intern(&method.name)?, + signature: self.blobs.intern(&signature)?, + param_list, + }; + self.tables.methods.push(row_data); + for (position, parameter) in method.parameters.iter().enumerate() { + let sequence = u16::try_from(position.saturating_add(1)).unwrap_or(u16::MAX); + let name = self.strings.intern(¶meter.name)?; + self.tables.params.push(ParamRow { + flags: parameter.flags, + sequence, + name, + }); + } + let method_row = self.method_row(MethodId { + owner: type_index, + slot: u32::try_from(slot).unwrap_or(u32::MAX), + })?; + let owner = TYPE_OR_METHOD_DEF.encode(table::METHOD_DEF, method_row)?; + self.emit_generic_params(owner, &method.generic_parameters)?; + } + Ok(()) + } + + fn emit_properties(&mut self, type_index: u32) -> Result<()> { + let Some(entry) = self.builder.types.get(as_index(type_index)) else { + return Ok(()); + }; + if entry.properties.is_empty() { + return Ok(()); + } + self.tables.property_maps.push(PropertyMapRow { + parent: row(type_index)?, + property_list: start_of(&self.layout.properties, type_index)?, + }); + for (slot, property) in entry.properties.iter().enumerate() { + let signature = property_signature( + property.has_this, + &property.property_type, + &property.index_parameters, + )?; + let row_data = PropertyRow { + flags: property.flags, + name: self.strings.intern(&property.name)?, + signature: self.blobs.intern(&signature)?, + }; + self.tables.properties.push(row_data); + let property_row = self.property_row(PropertyId { + owner: type_index, + slot: u32::try_from(slot).unwrap_or(u32::MAX), + })?; + let association = HAS_SEMANTICS.encode(table::PROPERTY, property_row)?; + self.emit_semantics(association, SEMANTICS_GETTER, property.getter)?; + self.emit_semantics(association, SEMANTICS_SETTER, property.setter)?; + } + Ok(()) + } + + fn emit_semantics( + &mut self, + association: u32, + semantics: u16, + accessor: Option, + ) -> Result<()> { + let Some(accessor) = accessor else { + return Ok(()); + }; + let method = self.method_row(accessor)?; + self.tables.method_semantics.push(MethodSemanticsRow { + semantics, + method, + association, + }); + Ok(()) + } + + /// Interfaces, nesting and type-level generic parameters. + fn emit_type_relations(&mut self, type_index: u32) -> Result<()> { + let Some(entry) = self.builder.types.get(as_index(type_index)) else { + return Ok(()); + }; + let class = row(type_index)?; + for interface in &entry.definition.interfaces { + self.tables.interface_impls.push(InterfaceImplRow { + class, + interface: interface.coded_value()?, + }); + } + if let Some(enclosing) = entry.definition.enclosing { + self.tables.nested_classes.push(NestedClassRow { + nested: class, + enclosing: row(enclosing.0)?, + }); + } + let owner = TYPE_OR_METHOD_DEF.encode(table::TYPE_DEF, class)?; + let parameters = entry.definition.generic_parameters.clone(); + self.emit_generic_params(owner, ¶meters) + } + + fn emit_generic_params( + &mut self, + owner: u32, + parameters: &[crate::model::GenericParameter], + ) -> Result<()> { + for (position, parameter) in parameters.iter().enumerate() { + let number = u16::try_from(position).unwrap_or(u16::MAX); + let name = self.strings.intern(¶meter.name)?; + self.tables.generic_params.push(GenericParamRow { + number, + flags: parameter.flags, + owner, + name, + }); + } + Ok(()) + } + + fn emit_type_specs(&mut self) -> Result<()> { + for signature in &self.builder.type_specs { + let blob = self.blobs.intern(signature)?; + self.tables.type_specs.push(TypeSpecRow { signature: blob }); + } + Ok(()) + } + + fn emit_member_refs(&mut self) -> Result<()> { + for entry in &self.builder.member_refs { + let class = match entry.parent { + MemberRefParent::TypeDef(id) => { + MEMBER_REF_PARENT.encode(table::TYPE_DEF, row(id.0)?)? + } + MemberRefParent::TypeRef(id) => { + MEMBER_REF_PARENT.encode(table::TYPE_REF, row(id.0)?)? + } + MemberRefParent::TypeSpec(id) => { + MEMBER_REF_PARENT.encode(table::TYPE_SPEC, row(id.0)?)? + } + MemberRefParent::MethodDef(id) => { + MEMBER_REF_PARENT.encode(table::METHOD_DEF, self.method_row(id)?)? + } + }; + let row_data = MemberRefRow { + class, + name: self.strings.intern(&entry.name)?, + signature: self.blobs.intern(&entry.signature)?, + }; + self.tables.member_refs.push(row_data); + } + Ok(()) + } + + fn emit_custom_attributes(&mut self) -> Result<()> { + for entry in &self.builder.custom_attributes { + let parent = self.custom_attribute_parent(entry.parent)?; + let constructor = match entry.constructor { + CustomAttributeType::MethodDef(id) => { + CUSTOM_ATTRIBUTE_TYPE.encode(table::METHOD_DEF, self.method_row(id)?)? + } + CustomAttributeType::MemberRef(id) => { + CUSTOM_ATTRIBUTE_TYPE.encode(table::MEMBER_REF, row(id.0)?)? + } + }; + let value = self.blobs.intern(&entry.value)?; + self.tables.custom_attributes.push(CustomAttributeRow { + parent, + constructor, + value, + }); + } + Ok(()) + } + + fn custom_attribute_parent(&self, parent: HasCustomAttribute) -> Result { + let (target, row_number) = match parent { + HasCustomAttribute::Assembly => (table::ASSEMBLY, 1), + HasCustomAttribute::Module => (table::MODULE, 1), + HasCustomAttribute::TypeDef(id) => (table::TYPE_DEF, row(id.0)?), + HasCustomAttribute::TypeRef(id) => (table::TYPE_REF, row(id.0)?), + HasCustomAttribute::AssemblyRef(id) => (table::ASSEMBLY_REF, row(id.0)?), + HasCustomAttribute::Field(id) => (table::FIELD, self.field_row(id)?), + HasCustomAttribute::MethodDef(id) => (table::METHOD_DEF, self.method_row(id)?), + HasCustomAttribute::Property(id) => (table::PROPERTY, self.property_row(id)?), + }; + HAS_CUSTOM_ATTRIBUTE.encode(target, row_number) + } + + fn emit_assembly(&mut self) -> Result<()> { + let version = self.builder.version; + let row_data = AssemblyRow { + hash_algorithm: self.builder.hash_algorithm, + version: [ + version.major, + version.minor, + version.build, + version.revision, + ], + flags: self.builder.flags, + public_key: self.blobs.intern(&self.builder.public_key)?, + name: self.strings.intern(&self.builder.name)?, + culture: self.strings.intern(&self.builder.culture)?, + }; + self.tables.assembly.push(row_data); + Ok(()) + } + + fn emit_assembly_refs(&mut self) -> Result<()> { + for entry in &self.builder.assembly_refs { + let version = entry.version; + let row_data = AssemblyRefRow { + version: [ + version.major, + version.minor, + version.build, + version.revision, + ], + flags: entry.flags, + public_key_or_token: self.blobs.intern(&entry.public_key_or_token)?, + name: self.strings.intern(&entry.name)?, + culture: self.strings.intern(&entry.culture)?, + hash_value: 0, + }; + self.tables.assembly_refs.push(row_data); + } + Ok(()) + } + + /// Applies the sort order ECMA-335 II.24.2.6 mandates for the tables named + /// in the `Sorted` bitmask. Readers binary-search these. + fn sort_tables(&mut self) { + self.tables.constants.sort_by_key(|row| row.parent); + self.tables.custom_attributes.sort_by_key(|row| row.parent); + self.tables + .interface_impls + .sort_by_key(|row| (row.class, row.interface)); + self.tables + .method_semantics + .sort_by_key(|row| row.association); + self.tables.nested_classes.sort_by_key(|row| row.nested); + self.tables + .generic_params + .sort_by_key(|row| (row.owner, row.number)); + } + + fn field_row(&self, id: FieldId) -> Result { + member_row(&self.layout.fields, id.owner, id.slot, "Field") + } + + fn method_row(&self, id: MethodId) -> Result { + member_row(&self.layout.methods, id.owner, id.slot, "MethodDef") + } + + fn property_row(&self, id: PropertyId) -> Result { + member_row(&self.layout.properties, id.owner, id.slot, "Property") + } + + fn finish(self) -> Result { + let counts = count_rows(&self.tables)?; + Ok(Image { + tables: self.tables, + strings: self.strings, + blobs: self.blobs, + guids: self.guids, + counts, + }) + } +} + +/// Walks the types once to fix where each type's `Field`, `MethodDef` and +/// `Property` runs begin. +/// +/// ECMA-335 stores only the start of each run and infers the end from the next +/// row's start, so the runs must be contiguous and non-decreasing. Computing +/// them up front is what lets member handles stay `(type, slot)` pairs. +fn plan_members(builder: &AssemblyBuilder) -> Result { + let mut layout = MemberLayout { + fields: Vec::with_capacity(builder.types.len()), + methods: Vec::with_capacity(builder.types.len()), + properties: Vec::with_capacity(builder.types.len()), + }; + let (mut fields, mut methods, mut properties) = (0_usize, 0_usize, 0_usize); + for entry in &builder.types { + layout.fields.push(row(count(fields, "Field")?)?); + layout.methods.push(row(count(methods, "MethodDef")?)?); + layout.properties.push(row(count(properties, "Property")?)?); + fields = fields.saturating_add(entry.fields.len()); + methods = methods.saturating_add(entry.methods.len()); + properties = properties.saturating_add(entry.properties.len()); + } + count(fields, "Field")?; + count(methods, "MethodDef")?; + count(properties, "Property")?; + Ok(layout) +} + +fn member_row(starts: &[u32], owner: u32, slot: u32, kind: &'static str) -> Result { + let rows = u32::try_from(starts.len()).unwrap_or(u32::MAX); + let start = starts + .get(as_index(owner)) + .copied() + .ok_or(Error::DanglingHandle { + kind: "TypeDef", + index: owner, + rows, + })?; + start.checked_add(slot).ok_or(Error::DanglingHandle { + kind, + index: slot, + rows, + }) +} + +fn start_of(starts: &[u32], type_index: u32) -> Result { + let rows = u32::try_from(starts.len()).unwrap_or(u32::MAX); + starts + .get(as_index(type_index)) + .copied() + .ok_or(Error::DanglingHandle { + kind: "TypeDef", + index: type_index, + rows, + }) +} + +fn count(rows: usize, table: &'static str) -> Result { + if rows > MAX_ROWS { + return Err(Error::TableOverflow { + table, + rows, + limit: MAX_ROWS, + }); + } + u32::try_from(rows).map_err(|_| Error::TableOverflow { + table, + rows, + limit: MAX_ROWS, + }) +} + +/// Converts a 0-based handle into a 1-based metadata row number. +fn row(index: u32) -> Result { + index.checked_add(1).ok_or(Error::LayoutOverflow { + what: "a metadata row number", + }) +} + +fn as_index(value: u32) -> usize { + usize::try_from(value).unwrap_or(usize::MAX) +} + +fn count_rows(tables: &TableSet) -> Result { + let mut counts = RowCounts::default(); + counts.set(table::MODULE, count(tables.module.len(), "Module")?); + counts.set(table::TYPE_REF, count(tables.type_refs.len(), "TypeRef")?); + counts.set(table::TYPE_DEF, count(tables.type_defs.len(), "TypeDef")?); + counts.set(table::FIELD, count(tables.fields.len(), "Field")?); + counts.set(table::METHOD_DEF, count(tables.methods.len(), "MethodDef")?); + counts.set(table::PARAM, count(tables.params.len(), "Param")?); + let interfaces = count(tables.interface_impls.len(), "InterfaceImpl")?; + counts.set(table::INTERFACE_IMPL, interfaces); + counts.set( + table::MEMBER_REF, + count(tables.member_refs.len(), "MemberRef")?, + ); + counts.set(table::CONSTANT, count(tables.constants.len(), "Constant")?); + let attributes = count(tables.custom_attributes.len(), "CustomAttribute")?; + counts.set(table::CUSTOM_ATTRIBUTE, attributes); + counts.set( + table::PROPERTY_MAP, + count(tables.property_maps.len(), "PropertyMap")?, + ); + counts.set(table::PROPERTY, count(tables.properties.len(), "Property")?); + let semantics = count(tables.method_semantics.len(), "MethodSemantics")?; + counts.set(table::METHOD_SEMANTICS, semantics); + counts.set( + table::TYPE_SPEC, + count(tables.type_specs.len(), "TypeSpec")?, + ); + counts.set(table::ASSEMBLY, count(tables.assembly.len(), "Assembly")?); + let refs = count(tables.assembly_refs.len(), "AssemblyRef")?; + counts.set(table::ASSEMBLY_REF, refs); + let nested = count(tables.nested_classes.len(), "NestedClass")?; + counts.set(table::NESTED_CLASS, nested); + let generics = count(tables.generic_params.len(), "GenericParam")?; + counts.set(table::GENERIC_PARAM, generics); + Ok(counts) +} + +/// The `(Constant.Type, Constant.Value)` pair for a compile-time value. +fn encode_constant(constant: &Constant) -> (u8, Vec) { + match constant { + Constant::Boolean(value) => (element_type::BOOLEAN, vec![u8::from(*value)]), + Constant::Char(value) => (element_type::CHAR, value.to_le_bytes().to_vec()), + Constant::I1(value) => (element_type::I1, value.to_le_bytes().to_vec()), + Constant::U1(value) => (element_type::U1, value.to_le_bytes().to_vec()), + Constant::I2(value) => (element_type::I2, value.to_le_bytes().to_vec()), + Constant::U2(value) => (element_type::U2, value.to_le_bytes().to_vec()), + Constant::I4(value) => (element_type::I4, value.to_le_bytes().to_vec()), + Constant::U4(value) => (element_type::U4, value.to_le_bytes().to_vec()), + Constant::I8(value) => (element_type::I8, value.to_le_bytes().to_vec()), + Constant::U8(value) => (element_type::U8, value.to_le_bytes().to_vec()), + Constant::R4(value) => (element_type::R4, value.to_le_bytes().to_vec()), + Constant::R8(value) => (element_type::R8, value.to_le_bytes().to_vec()), + Constant::String(value) => ( + element_type::STRING, + value.encode_utf16().flat_map(u16::to_le_bytes).collect(), + ), + // A null literal is encoded as ELEMENT_TYPE_CLASS with a 4-byte zero. + Constant::NullReference => (element_type::CLASS, vec![0, 0, 0, 0]), + } +} diff --git a/crates/modrix-ecma335/src/metadata.rs b/crates/modrix-ecma335/src/metadata.rs new file mode 100644 index 0000000..acc735e --- /dev/null +++ b/crates/modrix-ecma335/src/metadata.rs @@ -0,0 +1,162 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! The metadata root: the `BSJB` signature, the version string, and the five +//! stream headers followed by the stream bodies. +//! +//! Two details here are load-bearing and neither is obvious: +//! +//! * The root's `Length` field - the size of the version string - **must be a +//! multiple of 4**. Readers compute the stream-header array's position as +//! `16 + Length`, so an unpadded 11 for `"v4.0.30319\0"` makes Roslyn abort +//! with `CS0009: Read out of bounds`. +//! * A stream header's `Offset` is relative to the `B` of `BSJB`, not to the +//! file or to the section. + +use crate::encode::{align_up, pad_to_four, write_u16, write_u32}; +use crate::error::{Error, Result}; +use crate::materialize::Image; + +/// Metadata root signature, `BSJB` in little-endian byte order. +pub(crate) const SIGNATURE: u32 = 0x424A_5342; + +/// The version string every .NET assembly since v4 carries, NUL included. +const VERSION_STRING: &[u8] = b"v4.0.30319\0"; + +/// One `#`-prefixed stream. +struct Stream { + name: &'static str, + data: Vec, +} + +/// Builds the metadata root for `image`. +/// +/// # Errors +/// +/// Propagates table-serialisation failures, or returns +/// [`Error::LayoutOverflow`] if the stream offsets do not fit a `u32`. +pub(crate) fn metadata_root(image: &Image) -> Result> { + let streams = build_streams(image)?; + let version_length = align_up(VERSION_STRING.len(), 4).ok_or(Error::LayoutOverflow { + what: "the metadata version string length", + })?; + let headers: usize = streams + .iter() + .map(|stream| header_size(stream.name)) + .try_fold(0_usize, usize::checked_add) + .ok_or(Error::LayoutOverflow { + what: "the stream header block", + })?; + let mut root = Vec::new(); + write_root_header(&mut root, version_length, streams.len())?; + let first = [16_usize, version_length, 4, headers] + .into_iter() + .try_fold(0_usize, usize::checked_add) + .ok_or(Error::LayoutOverflow { + what: "the first stream offset", + })?; + write_stream_headers(&mut root, &streams, first)?; + for stream in &streams { + root.extend_from_slice(&stream.data); + } + Ok(root) +} + +fn write_root_header(root: &mut Vec, version_length: usize, streams: usize) -> Result<()> { + write_u32(root, SIGNATURE); + write_u16(root, 1); + write_u16(root, 1); + write_u32(root, 0); + let length = u32::try_from(version_length).map_err(|_| Error::LayoutOverflow { + what: "the metadata version string length", + })?; + write_u32(root, length); + root.extend_from_slice(VERSION_STRING); + root.resize( + root.len() + .checked_sub(VERSION_STRING.len()) + .and_then(|base| base.checked_add(version_length)) + .ok_or(Error::LayoutOverflow { + what: "the metadata version string padding", + })?, + 0, + ); + write_u16(root, 0); + write_u16( + root, + u16::try_from(streams).map_err(|_| Error::LayoutOverflow { + what: "the stream count", + })?, + ); + Ok(()) +} + +fn write_stream_headers(root: &mut Vec, streams: &[Stream], first: usize) -> Result<()> { + let mut offset = first; + for stream in streams { + let start = u32::try_from(offset).map_err(|_| Error::LayoutOverflow { + what: "a stream offset", + })?; + let size = u32::try_from(stream.data.len()).map_err(|_| Error::LayoutOverflow { + what: "a stream size", + })?; + write_u32(root, start); + write_u32(root, size); + root.extend_from_slice(stream.name.as_bytes()); + root.push(0); + while !root.len().is_multiple_of(4) { + root.push(0); + } + offset = offset + .checked_add(stream.data.len()) + .ok_or(Error::LayoutOverflow { + what: "a stream offset", + })?; + } + Ok(()) +} + +/// A stream header is 8 bytes of offset/size plus a NUL-terminated name padded +/// to a 4-byte boundary. +fn header_size(name: &str) -> usize { + let name_field = align_up(name.len().saturating_add(1), 4).unwrap_or(4); + name_field.saturating_add(8) +} + +/// Assembles the five streams in Roslyn's order. `#Blob` in particular must be +/// present even when it holds only its leading zero byte: omitting it yields +/// `CS0009: Read out of bounds`. +fn build_streams(image: &Image) -> Result> { + let mut tables = crate::emit::table_stream(image)?; + pad_to_four(&mut tables); + let mut strings = image.strings.bytes().to_vec(); + pad_to_four(&mut strings); + // A reference assembly holds no IL, so the user-string heap is just its + // mandatory leading zero byte. + let mut user_strings = vec![0_u8]; + pad_to_four(&mut user_strings); + let mut guids = image.guids.bytes().to_vec(); + pad_to_four(&mut guids); + let mut blobs = image.blobs.bytes().to_vec(); + pad_to_four(&mut blobs); + Ok(vec![ + Stream { + name: "#~", + data: tables, + }, + Stream { + name: "#Strings", + data: strings, + }, + Stream { + name: "#US", + data: user_strings, + }, + Stream { + name: "#GUID", + data: guids, + }, + Stream { + name: "#Blob", + data: blobs, + }, + ]) +} diff --git a/crates/modrix-ecma335/src/model.rs b/crates/modrix-ecma335/src/model.rs new file mode 100644 index 0000000..c27671f --- /dev/null +++ b/crates/modrix-ecma335/src/model.rs @@ -0,0 +1,464 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! The declarative shapes callers hand to [`AssemblyBuilder`]. +//! +//! [`AssemblyBuilder`]: crate::AssemblyBuilder + +use crate::handles::{MethodId, TypeDefId, TypeDefOrRef}; +use crate::signature::{MethodSignature, Type}; + +/// `TypeAttributes` bits (ECMA-335 II.23.1.15). +pub mod type_attributes { + /// Visible outside the assembly. + pub const PUBLIC: u32 = 0x0000_0001; + /// A public type nested in another type. + pub const NESTED_PUBLIC: u32 = 0x0000_0002; + /// A private type nested in another type. + pub const NESTED_PRIVATE: u32 = 0x0000_0003; + /// Sequential field layout. + pub const SEQUENTIAL_LAYOUT: u32 = 0x0000_0008; + /// Explicit field layout. + pub const EXPLICIT_LAYOUT: u32 = 0x0000_0010; + /// The type is an interface. + pub const INTERFACE: u32 = 0x0000_0020; + /// The type cannot be instantiated directly. + pub const ABSTRACT: u32 = 0x0000_0080; + /// The type cannot be derived from. + pub const SEALED: u32 = 0x0000_0100; + /// The name carries meaning to tools. + pub const SPECIAL_NAME: u32 = 0x0000_0400; + /// The name carries meaning to the runtime. + pub const RT_SPECIAL_NAME: u32 = 0x0000_0800; + /// Static initialisers may run lazily. + pub const BEFORE_FIELD_INIT: u32 = 0x0010_0000; + + /// A plain `public class`. + pub const PUBLIC_CLASS: u32 = PUBLIC | BEFORE_FIELD_INIT; + /// A `public interface`. + pub const PUBLIC_INTERFACE: u32 = PUBLIC | INTERFACE | ABSTRACT; + /// A `public struct` or `public enum`. + pub const PUBLIC_VALUE_TYPE: u32 = PUBLIC | SEALED; +} + +/// `FieldAttributes` bits (ECMA-335 II.23.1.5). +pub mod field_attributes { + /// Private field. + pub const PRIVATE: u16 = 0x0001; + /// Assembly-visible field. + pub const ASSEMBLY: u16 = 0x0003; + /// Protected field. + pub const FAMILY: u16 = 0x0004; + /// Public field. + pub const PUBLIC: u16 = 0x0006; + /// `static`. + pub const STATIC: u16 = 0x0010; + /// `readonly`. + pub const INIT_ONLY: u16 = 0x0020; + /// `const`; requires a `Constant` row. + pub const LITERAL: u16 = 0x0040; + /// The name carries meaning to tools. + pub const SPECIAL_NAME: u16 = 0x0200; + /// The name carries meaning to the runtime. + pub const RT_SPECIAL_NAME: u16 = 0x0400; + /// A `Constant` row supplies the value. + pub const HAS_DEFAULT: u16 = 0x8000; + + /// The `value__` field every enum must declare first. + pub const ENUM_BACKING: u16 = PUBLIC | SPECIAL_NAME | RT_SPECIAL_NAME; + /// An enum member. + pub const ENUM_MEMBER: u16 = PUBLIC | STATIC | LITERAL; +} + +/// `MethodImplAttributes` bits (II.23.1.11). +pub mod method_impl { + /// The body is IL. The default. + pub const IL: u16 = 0x0000; + /// The body lives in the runtime rather than in this assembly. + /// + /// Legal with no RVA, which is what lets a body-less reference assembly + /// still *load*: the CLR rejects an ordinary method with no RVA at type + /// load time, taking the whole assembly with it. + pub const INTERNAL_CALL: u16 = 0x1000; +} + +/// `MethodAttributes` and `MethodImplAttributes` bits (II.23.1.10, II.23.1.11). +pub mod method_attributes { + /// Private method. + pub const PRIVATE: u16 = 0x0001; + /// Protected method. + pub const FAMILY: u16 = 0x0004; + /// Public method. + pub const PUBLIC: u16 = 0x0006; + /// `static`. + pub const STATIC: u16 = 0x0010; + /// `sealed` override. + pub const FINAL: u16 = 0x0020; + /// `virtual`. + pub const VIRTUAL: u16 = 0x0040; + /// Hide by name *and* signature, which is what C# emits. + pub const HIDE_BY_SIG: u16 = 0x0080; + /// Occupies a new vtable slot. + pub const NEW_SLOT: u16 = 0x0100; + /// No body. + pub const ABSTRACT: u16 = 0x0400; + /// The name carries meaning to tools. + pub const SPECIAL_NAME: u16 = 0x0800; + /// The name carries meaning to the runtime. + pub const RT_SPECIAL_NAME: u16 = 0x1000; + + /// A public instance method. + pub const PUBLIC_INSTANCE: u16 = PUBLIC | HIDE_BY_SIG; + /// A public static method. + pub const PUBLIC_STATIC: u16 = PUBLIC | STATIC | HIDE_BY_SIG; + /// A public constructor. + pub const PUBLIC_CONSTRUCTOR: u16 = PUBLIC | HIDE_BY_SIG | SPECIAL_NAME | RT_SPECIAL_NAME; + /// A new public virtual method. + pub const PUBLIC_VIRTUAL: u16 = PUBLIC | HIDE_BY_SIG | NEW_SLOT | VIRTUAL; + /// An interface method. + pub const INTERFACE_METHOD: u16 = PUBLIC | HIDE_BY_SIG | NEW_SLOT | VIRTUAL | ABSTRACT; + /// A property accessor. + pub const PROPERTY_ACCESSOR: u16 = PUBLIC | HIDE_BY_SIG | SPECIAL_NAME; +} + +/// A four-part assembly version. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Version { + /// Major component. + pub major: u16, + /// Minor component. + pub minor: u16, + /// Build component. + pub build: u16, + /// Revision component. + pub revision: u16, +} + +impl Version { + /// Builds a version from its four components. + #[must_use] + pub const fn new(major: u16, minor: u16, build: u16, revision: u16) -> Self { + Self { + major, + minor, + build, + revision, + } + } +} + +/// The name of the core library every net6.0-or-later reference must import. +pub const CORE_LIBRARY_NAME: &str = "System.Runtime"; + +/// The ECMA public key token `System.Runtime` is signed with. Roslyn matches +/// on name plus token; an empty or wrong token yields CS0012 for every type. +pub const CORE_LIBRARY_PUBLIC_KEY_TOKEN: [u8; 8] = [0xB0, 0x3F, 0x5F, 0x7F, 0x11, 0xD5, 0x0A, 0x3A]; + +/// An `AssemblyRef` row to emit. +#[derive(Clone, Debug)] +pub struct AssemblyReference { + /// Simple name, without extension. + pub name: String, + /// Referenced version. A mismatch against the real assembly is only a + /// CS1701 warning, so this is the soft part of the identity. + pub version: Version, + /// The 8-byte public key *token*, or the full key when + /// `AssemblyFlags.PublicKey` is set. + pub public_key_or_token: Vec, + /// `AssemblyFlags`; 0 means the blob above holds a token. + pub flags: u32, + /// Culture name; empty means neutral. + pub culture: String, +} + +impl AssemblyReference { + /// The corlib reference a net6.0-or-later assembly must carry. + /// + /// `framework_major` is the .NET major version: 9 produces + /// `System.Runtime, Version=9.0.0.0`. + #[must_use] + pub fn core_library(framework_major: u16) -> Self { + Self { + name: CORE_LIBRARY_NAME.to_owned(), + version: Version::new(framework_major, 0, 0, 0), + public_key_or_token: CORE_LIBRARY_PUBLIC_KEY_TOKEN.to_vec(), + flags: 0, + culture: String::new(), + } + } +} + +/// A generic parameter on a type or a method. +#[derive(Clone, Debug)] +pub struct GenericParameter { + /// Parameter name, for example `T`. + pub name: String, + /// `GenericParamAttributes`; 0 for an unconstrained parameter. + pub flags: u16, +} + +impl GenericParameter { + /// An unconstrained parameter. + #[must_use] + pub fn new(name: impl Into) -> Self { + Self { + name: name.into(), + flags: 0, + } + } +} + +/// A compile-time constant, emitted as a `Constant` row. +/// +/// Enum literal fields **must** have one. Without it the reference still loads +/// and the member still resolves, but the consuming compiler fails to emit +/// with a bare `CS7038`, which points nowhere. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub enum Constant { + /// `bool`. + Boolean(bool), + /// `char`. + Char(u16), + /// `sbyte`. + I1(i8), + /// `byte`. + U1(u8), + /// `short`. + I2(i16), + /// `ushort`. + U2(u16), + /// `int`. + I4(i32), + /// `uint`. + U4(u32), + /// `long`. + I8(i64), + /// `ulong`. + U8(u64), + /// `float`. + R4(f32), + /// `double`. + R8(f64), + /// A UTF-16 string literal. + String(String), + /// A null reference. + NullReference, +} + +/// A type to define. +#[derive(Clone, Debug)] +pub struct TypeDefinition { + /// Namespace; **must** be empty for a nested type, whose namespace comes + /// from its enclosing type instead. + pub namespace: String, + /// Type name; generic types use the arity suffix, for example ``Box`1``. + pub name: String, + /// `TypeAttributes`. + pub flags: u32, + /// Base type; `None` for interfaces and for ``. + pub extends: Option, + /// Interfaces this type implements. + pub interfaces: Vec, + /// Generic parameters, in declaration order. + pub generic_parameters: Vec, + /// Enclosing type for a nested type, which produces a `NestedClass` row. + pub enclosing: Option, +} + +impl TypeDefinition { + /// A top-level type with no interfaces and no generic parameters. + #[must_use] + pub fn new( + namespace: impl Into, + name: impl Into, + flags: u32, + extends: Option, + ) -> Self { + Self { + namespace: namespace.into(), + name: name.into(), + flags, + extends, + interfaces: Vec::new(), + generic_parameters: Vec::new(), + enclosing: None, + } + } + + /// Nests this type inside `enclosing`. + /// + /// The namespace of a nested type must stay empty - it is inherited from + /// the enclosing type - so this clears it. + #[must_use] + pub fn nested_in(mut self, enclosing: TypeDefId) -> Self { + self.enclosing = Some(enclosing); + self.namespace = String::new(); + self + } + + /// Adds an implemented interface. + #[must_use] + pub fn with_interface(mut self, interface: TypeDefOrRef) -> Self { + self.interfaces.push(interface); + self + } + + /// Adds a generic parameter. + #[must_use] + pub fn with_generic_parameter(mut self, parameter: GenericParameter) -> Self { + self.generic_parameters.push(parameter); + self + } +} + +/// A field to define. +#[derive(Clone, Debug)] +pub struct Field { + /// Field name. + pub name: String, + /// `FieldAttributes`. + pub flags: u16, + /// Field type. + pub field_type: Type, + /// Compile-time value; required for `LITERAL` fields. + pub constant: Option, +} + +impl Field { + /// A field with no constant. + #[must_use] + pub fn new(name: impl Into, flags: u16, field_type: Type) -> Self { + Self { + name: name.into(), + flags, + field_type, + constant: None, + } + } + + /// Attaches a compile-time value and sets `HAS_DEFAULT`. + #[must_use] + pub fn with_constant(mut self, value: Constant) -> Self { + self.constant = Some(value); + self + } +} + +/// A named method parameter. Emitting these is optional - Roslyn synthesises +/// names when the `Param` table is absent - but without them callers lose +/// named arguments and `IntelliSense`. +#[derive(Clone, Debug)] +pub struct Parameter { + /// Parameter name. + pub name: String, + /// `ParamAttributes`. + pub flags: u16, +} + +impl Parameter { + /// A plain by-value parameter. + #[must_use] + pub fn new(name: impl Into) -> Self { + Self { + name: name.into(), + flags: 0, + } + } +} + +/// A method to define. A reference assembly carries no bodies, so every +/// `MethodDef.RVA` is written as 0. +#[derive(Clone, Debug)] +pub struct Method { + /// Method name; constructors are `.ctor` / `.cctor`. + pub name: String, + /// `MethodAttributes`. + pub flags: u16, + /// `MethodImplAttributes`; 0 means IL and managed. + pub impl_flags: u16, + /// The method's signature. + pub signature: MethodSignature, + /// Parameter names, in sequence order starting at 1. + pub parameters: Vec, + /// Generic parameters, in declaration order. + pub generic_parameters: Vec, +} + +impl Method { + /// A method with no named parameters and no generic parameters. + #[must_use] + pub fn new(name: impl Into, flags: u16, signature: MethodSignature) -> Self { + Self { + name: name.into(), + flags, + impl_flags: 0, + signature, + parameters: Vec::new(), + generic_parameters: Vec::new(), + } + } + + /// Adds a named parameter; sequence numbers follow the insertion order. + #[must_use] + pub fn with_parameter(mut self, parameter: Parameter) -> Self { + self.parameters.push(parameter); + self + } + + /// Adds a generic parameter and raises the signature's arity to match. + #[must_use] + pub fn with_generic_parameter(mut self, parameter: GenericParameter) -> Self { + self.generic_parameters.push(parameter); + self.signature.generic_parameter_count = + u32::try_from(self.generic_parameters.len()).unwrap_or(u32::MAX); + self + } +} + +/// A property to define, together with its accessors. +#[derive(Clone, Debug)] +pub struct Property { + /// Property name. + pub name: String, + /// `PropertyAttributes`; 0 for an ordinary property. + pub flags: u16, + /// Property type. + pub property_type: Type, + /// `true` for an instance property. + pub has_this: bool, + /// Indexer parameter types. + pub index_parameters: Vec, + /// The `get` accessor, if any. + pub getter: Option, + /// The `set` accessor, if any. + pub setter: Option, +} + +impl Property { + /// An instance property with no indexer parameters. + #[must_use] + pub fn new(name: impl Into, property_type: Type) -> Self { + Self { + name: name.into(), + flags: 0, + property_type, + has_this: true, + index_parameters: Vec::new(), + getter: None, + setter: None, + } + } + + /// Attaches the `get` accessor. + #[must_use] + pub fn with_getter(mut self, getter: MethodId) -> Self { + self.getter = Some(getter); + self + } + + /// Attaches the `set` accessor. + #[must_use] + pub fn with_setter(mut self, setter: MethodId) -> Self { + self.setter = Some(setter); + self + } +} diff --git a/crates/modrix-ecma335/src/pe.rs b/crates/modrix-ecma335/src/pe.rs new file mode 100644 index 0000000..90a2a4a --- /dev/null +++ b/crates/modrix-ecma335/src/pe.rs @@ -0,0 +1,219 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! The PE32+ container: DOS stub, COFF header, optional header, one `.text` +//! section holding the CLI header and the metadata root. +//! +//! A reference assembly needs no import table, no IAT, no `.reloc` section, no +//! debug directory and no entry point - the file is only ever *read* by a +//! compiler, never loaded by the OS. That reduces the whole container to a +//! fixed 0x200-byte header block plus one section. + +use crate::encode::{align_up, write_u16, write_u32, write_u64}; +use crate::error::{Error, Result}; +use crate::materialize::Image; + +/// PE file alignment: the granularity of raw section data. +const FILE_ALIGNMENT: u32 = 0x200; +/// PE section alignment: the granularity of section RVAs in memory. +const SECTION_ALIGNMENT: u32 = 0x2000; +/// RVA of the single `.text` section. +const TEXT_RVA: u32 = 0x2000; +/// Size of `IMAGE_COR20_HEADER`. +const CLI_HEADER_SIZE: u32 = 72; +/// `COMIMAGE_FLAGS_ILONLY`. `STRONGNAMESIGNED` is deliberately not set: there +/// is no signature blob to back it. +const COR20_FLAGS: u32 = 0x0000_0001; +/// Number of data directories in the optional header. +const DATA_DIRECTORIES: u32 = 16; +/// Index of the CLI header data directory. +const CLI_DIRECTORY: u32 = 14; + +/// The 128-byte DOS header and stub. Only `e_lfanew` at 0x3C is load-bearing; +/// the rest is the conventional "cannot be run in DOS mode" stub every real +/// toolchain emits, kept so the file looks unremarkable to other tools. +const DOS_HEADER: [u8; 128] = [ + 0x4D, 0x5A, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, + 0xB8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, + 0x0E, 0x1F, 0xBA, 0x0E, 0x00, 0xB4, 0x09, 0xCD, 0x21, 0xB8, 0x01, 0x4C, 0xCD, 0x21, 0x54, 0x68, + 0x69, 0x73, 0x20, 0x70, 0x72, 0x6F, 0x67, 0x72, 0x61, 0x6D, 0x20, 0x63, 0x61, 0x6E, 0x6E, 0x6F, + 0x74, 0x20, 0x62, 0x65, 0x20, 0x72, 0x75, 0x6E, 0x20, 0x69, 0x6E, 0x20, 0x44, 0x4F, 0x53, 0x20, + 0x6D, 0x6F, 0x64, 0x65, 0x2E, 0x0D, 0x0D, 0x0A, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +]; + +/// Sizes the whole image once so every header field can be filled in. +struct Layout { + /// Bytes of real content in `.text`. + text_virtual: u32, + /// `.text` raw size, rounded to the file alignment. + text_raw: u32, + /// Where the headers end and `.text` begins in the file. + headers: u32, + /// Total mapped size, rounded to the section alignment. + image: u32, + /// Byte length of the optional header. + optional: u16, +} + +/// Emits the finished reference assembly. +/// +/// # Errors +/// +/// Propagates metadata failures, or returns [`Error::LayoutOverflow`] if the +/// image is too large for the 32-bit PE size fields. +pub(crate) fn write_image(image: &Image) -> Result> { + let metadata = crate::metadata::metadata_root(image)?; + let metadata_size = u32::try_from(metadata.len()).map_err(|_| Error::LayoutOverflow { + what: "the metadata size", + })?; + let layout = plan(metadata_size)?; + let mut out = Vec::new(); + out.extend_from_slice(&DOS_HEADER); + out.extend_from_slice(b"PE\0\0"); + write_coff_header(&mut out, &layout); + write_optional_header(&mut out, &layout); + write_section_table(&mut out, &layout); + resize_to(&mut out, layout.headers)?; + write_cli_header(&mut out, metadata_size); + out.extend_from_slice(&metadata); + let total = layout + .headers + .checked_add(layout.text_raw) + .ok_or(Error::LayoutOverflow { + what: "the file size", + })?; + resize_to(&mut out, total)?; + Ok(out) +} + +fn plan(metadata_size: u32) -> Result { + let overflow = || Error::LayoutOverflow { + what: "the section layout", + }; + let optional_size = 24_u32 + .checked_add(88) + .and_then(|base| base.checked_add(DATA_DIRECTORIES.checked_mul(8)?)) + .ok_or_else(overflow)?; + let header_bytes = 0x80_u32 + .checked_add(4) + .and_then(|base| base.checked_add(20)) + .and_then(|base| base.checked_add(optional_size)) + .and_then(|base| base.checked_add(40)) + .ok_or_else(overflow)?; + let virtual_size = CLI_HEADER_SIZE + .checked_add(metadata_size) + .ok_or_else(overflow)?; + Ok(Layout { + text_virtual: virtual_size, + text_raw: align32(virtual_size, FILE_ALIGNMENT).ok_or_else(overflow)?, + headers: align32(header_bytes, FILE_ALIGNMENT).ok_or_else(overflow)?, + image: align32( + TEXT_RVA.checked_add(virtual_size).ok_or_else(overflow)?, + SECTION_ALIGNMENT, + ) + .ok_or_else(overflow)?, + optional: u16::try_from(optional_size).map_err(|_| overflow())?, + }) +} + +fn write_coff_header(out: &mut Vec, layout: &Layout) { + // AMD64 paired with the PE32+ magic below; Roslyn accepts either that or + // the I386/PE32 pairing the real reference packs use. + write_u16(out, 0x8664); + write_u16(out, 1); + // Zero timestamp keeps the output reproducible. + write_u32(out, 0); + write_u32(out, 0); + write_u32(out, 0); + write_u16(out, layout.optional); + // EXECUTABLE_IMAGE | LARGE_ADDRESS_AWARE | DLL. + write_u16(out, 0x2022); +} + +fn write_optional_header(out: &mut Vec, layout: &Layout) { + write_u16(out, 0x020B); + out.push(48); + out.push(0); + write_u32(out, layout.text_raw); + write_u32(out, 0); + write_u32(out, 0); + write_u32(out, 0); + write_u32(out, TEXT_RVA); + write_u64(out, 0x0000_0001_8000_0000); + write_u32(out, SECTION_ALIGNMENT); + write_u32(out, FILE_ALIGNMENT); + for field in [4_u16, 0, 0, 0, 4, 0] { + write_u16(out, field); + } + write_u32(out, 0); + write_u32(out, layout.image); + write_u32(out, layout.headers); + write_u32(out, 0); + write_u16(out, 3); + // HIGH_ENTROPY_VA | DYNAMIC_BASE | NX_COMPAT | NO_SEH | TERMINAL_SERVER_AWARE. + write_u16(out, 0x8560); + for field in [0x0040_0000_u64, 0x4000, 0x0010_0000, 0x2000] { + write_u64(out, field); + } + write_u32(out, 0); + write_u32(out, DATA_DIRECTORIES); + write_data_directories(out); +} + +fn write_data_directories(out: &mut Vec) { + for index in 0..DATA_DIRECTORIES { + if index == CLI_DIRECTORY { + write_u32(out, TEXT_RVA); + write_u32(out, CLI_HEADER_SIZE); + } else { + write_u32(out, 0); + write_u32(out, 0); + } + } +} + +fn write_section_table(out: &mut Vec, layout: &Layout) { + out.extend_from_slice(b".text\0\0\0"); + write_u32(out, layout.text_virtual); + write_u32(out, TEXT_RVA); + write_u32(out, layout.text_raw); + write_u32(out, layout.headers); + write_u32(out, 0); + write_u32(out, 0); + write_u16(out, 0); + write_u16(out, 0); + // CNT_CODE | MEM_EXECUTE | MEM_READ. + write_u32(out, 0x6000_0020); +} + +fn write_cli_header(out: &mut Vec, metadata_size: u32) { + write_u32(out, CLI_HEADER_SIZE); + write_u16(out, 2); + write_u16(out, 5); + write_u32(out, TEXT_RVA.saturating_add(CLI_HEADER_SIZE)); + write_u32(out, metadata_size); + write_u32(out, COR20_FLAGS); + // No entry point, no resources, no strong-name signature, and none of the + // trailing directories: a reference assembly has nothing to put in them. + for _ in 0..13 { + write_u32(out, 0); + } +} + +fn align32(value: u32, alignment: u32) -> Option { + let aligned = align_up( + usize::try_from(value).ok()?, + usize::try_from(alignment).ok()?, + )?; + u32::try_from(aligned).ok() +} + +fn resize_to(out: &mut Vec, size: u32) -> Result<()> { + let target = usize::try_from(size).map_err(|_| Error::LayoutOverflow { + what: "the file size", + })?; + if out.len() < target { + out.resize(target, 0); + } + Ok(()) +} diff --git a/crates/modrix-ecma335/src/rows.rs b/crates/modrix-ecma335/src/rows.rs new file mode 100644 index 0000000..65a2e94 --- /dev/null +++ b/crates/modrix-ecma335/src/rows.rs @@ -0,0 +1,190 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Fully resolved metadata rows: every handle already turned into a row +//! number, every string and blob already turned into a heap index. +//! +//! These structs are the boundary between the two halves of the crate. The +//! writer materialises them and serialises them; the test-only reader parses +//! them back out of the finished bytes and re-checks every reference. Sharing +//! the struct - but not the code that produces it - is what makes the +//! round-trip a real check rather than a tautology. + +/// `Module` (0x00). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct ModuleRow { + pub(crate) generation: u16, + pub(crate) name: u32, + pub(crate) mvid: u32, + pub(crate) enc_id: u32, + pub(crate) enc_base_id: u32, +} + +/// `TypeRef` (0x01). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct TypeRefRow { + pub(crate) resolution_scope: u32, + pub(crate) name: u32, + pub(crate) namespace: u32, +} + +/// `TypeDef` (0x02). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct TypeDefRow { + pub(crate) flags: u32, + pub(crate) name: u32, + pub(crate) namespace: u32, + pub(crate) extends: u32, + /// 1-based index of this type's first `Field` row. The run ends where the + /// next type's start begins, so these must be non-decreasing. + pub(crate) field_list: u32, + /// 1-based index of this type's first `MethodDef` row. + pub(crate) method_list: u32, +} + +/// `Field` (0x04). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct FieldRow { + pub(crate) flags: u16, + pub(crate) name: u32, + pub(crate) signature: u32, +} + +/// `MethodDef` (0x06). `rva` is always 0: a reference assembly has no bodies. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct MethodDefRow { + pub(crate) rva: u32, + pub(crate) impl_flags: u16, + pub(crate) flags: u16, + pub(crate) name: u32, + pub(crate) signature: u32, + pub(crate) param_list: u32, +} + +/// `Param` (0x08). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct ParamRow { + pub(crate) flags: u16, + pub(crate) sequence: u16, + pub(crate) name: u32, +} + +/// `InterfaceImpl` (0x09), sorted by `class`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct InterfaceImplRow { + pub(crate) class: u32, + pub(crate) interface: u32, +} + +/// `MemberRef` (0x0A). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct MemberRefRow { + pub(crate) class: u32, + pub(crate) name: u32, + pub(crate) signature: u32, +} + +/// `Constant` (0x0B), sorted by `parent`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct ConstantRow { + pub(crate) kind: u8, + pub(crate) parent: u32, + pub(crate) value: u32, +} + +/// `CustomAttribute` (0x0C), sorted by `parent`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct CustomAttributeRow { + pub(crate) parent: u32, + pub(crate) constructor: u32, + pub(crate) value: u32, +} + +/// `PropertyMap` (0x15). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct PropertyMapRow { + pub(crate) parent: u32, + pub(crate) property_list: u32, +} + +/// `Property` (0x17). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct PropertyRow { + pub(crate) flags: u16, + pub(crate) name: u32, + pub(crate) signature: u32, +} + +/// `MethodSemantics` (0x18), sorted by `association`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct MethodSemanticsRow { + pub(crate) semantics: u16, + pub(crate) method: u32, + pub(crate) association: u32, +} + +/// `TypeSpec` (0x1B). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct TypeSpecRow { + pub(crate) signature: u32, +} + +/// `Assembly` (0x20). Exactly one row, and it is mandatory: without it Roslyn +/// treats the file as a netmodule and reports CS1509. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct AssemblyRow { + pub(crate) hash_algorithm: u32, + pub(crate) version: [u16; 4], + pub(crate) flags: u32, + pub(crate) public_key: u32, + pub(crate) name: u32, + pub(crate) culture: u32, +} + +/// `AssemblyRef` (0x23). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct AssemblyRefRow { + pub(crate) version: [u16; 4], + pub(crate) flags: u32, + pub(crate) public_key_or_token: u32, + pub(crate) name: u32, + pub(crate) culture: u32, + pub(crate) hash_value: u32, +} + +/// `NestedClass` (0x29), sorted by `nested`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct NestedClassRow { + pub(crate) nested: u32, + pub(crate) enclosing: u32, +} + +/// `GenericParam` (0x2A), sorted by `(owner, number)`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct GenericParamRow { + pub(crate) number: u16, + pub(crate) flags: u16, + pub(crate) owner: u32, + pub(crate) name: u32, +} + +/// Every table of one assembly, with all indices resolved. +#[derive(Clone, Debug, Default)] +pub(crate) struct TableSet { + pub(crate) module: Vec, + pub(crate) type_refs: Vec, + pub(crate) type_defs: Vec, + pub(crate) fields: Vec, + pub(crate) methods: Vec, + pub(crate) params: Vec, + pub(crate) interface_impls: Vec, + pub(crate) member_refs: Vec, + pub(crate) constants: Vec, + pub(crate) custom_attributes: Vec, + pub(crate) property_maps: Vec, + pub(crate) properties: Vec, + pub(crate) method_semantics: Vec, + pub(crate) type_specs: Vec, + pub(crate) assembly: Vec, + pub(crate) assembly_refs: Vec, + pub(crate) nested_classes: Vec, + pub(crate) generic_params: Vec, +} diff --git a/crates/modrix-ecma335/src/signature.rs b/crates/modrix-ecma335/src/signature.rs new file mode 100644 index 0000000..a0a680f --- /dev/null +++ b/crates/modrix-ecma335/src/signature.rs @@ -0,0 +1,470 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! The type model and the signature-blob encoder (ECMA-335 II.23.2). +//! +//! A signature blob is a self-contained byte string: it never uses metadata +//! table indices, only *compressed* `TypeDefOrRef` coded indices. That is why +//! signatures can be encoded before column widths are known, and why a +//! `GENERICINST` inside a field or method signature needs no `TypeSpec` row - +//! a `TypeSpec` is only required where a generic instantiation must be named +//! by a metadata *token* (a base class, an interface, a `MemberRef` parent). + +use crate::encode::{compress_signed, compress_unsigned}; +use crate::error::{Error, Result}; +use crate::handles::TypeDefOrRef; + +/// ECMA-335 `ELEMENT_TYPE_*` constants (II.23.1.16). +pub mod element_type { + /// Terminator. + pub const END: u8 = 0x00; + /// `void`. + pub const VOID: u8 = 0x01; + /// `System.Boolean`. + pub const BOOLEAN: u8 = 0x02; + /// `System.Char`. + pub const CHAR: u8 = 0x03; + /// `System.SByte`. + pub const I1: u8 = 0x04; + /// `System.Byte`. + pub const U1: u8 = 0x05; + /// `System.Int16`. + pub const I2: u8 = 0x06; + /// `System.UInt16`. + pub const U2: u8 = 0x07; + /// `System.Int32`. + pub const I4: u8 = 0x08; + /// `System.UInt32`. + pub const U4: u8 = 0x09; + /// `System.Int64`. + pub const I8: u8 = 0x0A; + /// `System.UInt64`. + pub const U8: u8 = 0x0B; + /// `System.Single`. + pub const R4: u8 = 0x0C; + /// `System.Double`. + pub const R8: u8 = 0x0D; + /// `System.String`. + pub const STRING: u8 = 0x0E; + /// Unmanaged pointer. + pub const PTR: u8 = 0x0F; + /// Managed reference (`ref`/`out`). + pub const BYREF: u8 = 0x10; + /// Value type named by a `TypeDefOrRef`. + pub const VALUETYPE: u8 = 0x11; + /// Reference type named by a `TypeDefOrRef`. + pub const CLASS: u8 = 0x12; + /// Generic parameter of the enclosing *type*. + pub const VAR: u8 = 0x13; + /// Multi-dimensional array. + pub const ARRAY: u8 = 0x14; + /// Generic instantiation. + pub const GENERICINST: u8 = 0x15; + /// `System.TypedReference`. + pub const TYPEDBYREF: u8 = 0x16; + /// `System.IntPtr`. + pub const I: u8 = 0x18; + /// `System.UIntPtr`. + pub const U: u8 = 0x19; + /// Function pointer. + pub const FNPTR: u8 = 0x1B; + /// `System.Object`. + pub const OBJECT: u8 = 0x1C; + /// Vector (single-dimension, zero-based) array. + pub const SZARRAY: u8 = 0x1D; + /// Generic parameter of the enclosing *method*. + pub const MVAR: u8 = 0x1E; + /// Required custom modifier. + pub const CMOD_REQD: u8 = 0x1F; + /// Optional custom modifier. + pub const CMOD_OPT: u8 = 0x20; +} + +/// Leading byte of a `Field` signature (II.23.2.4). +pub const FIELD_SIGNATURE: u8 = 0x06; +/// Leading byte of a `Property` signature (II.23.2.5), before `HASTHIS`. +pub const PROPERTY_SIGNATURE: u8 = 0x08; +/// `HASTHIS` bit of a calling convention byte. +pub const CALLCONV_HASTHIS: u8 = 0x20; +/// `EXPLICITTHIS` bit of a calling convention byte. +pub const CALLCONV_EXPLICITTHIS: u8 = 0x40; +/// `GENERIC` bit of a calling convention byte. +pub const CALLCONV_GENERIC: u8 = 0x10; +/// `VARARG` calling convention. +pub const CALLCONV_VARARG: u8 = 0x05; + +/// How deep a type tree this encoder will walk. Signatures are caller-built, +/// so the depth is bounded rather than trusted (Power of Ten rule 1). +pub const MAX_TYPE_DEPTH: u32 = 64; + +/// A type as it appears inside a signature blob. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum Type { + /// `void`; only valid as a return type. + Void, + /// `bool`. + Boolean, + /// `char`. + Char, + /// `sbyte`. + I1, + /// `byte`. + U1, + /// `short`. + I2, + /// `ushort`. + U2, + /// `int`. + I4, + /// `uint`. + U4, + /// `long`. + I8, + /// `ulong`. + U8, + /// `float`. + R4, + /// `double`. + R8, + /// `string`. + String, + /// `object`. + Object, + /// `nint` / `System.IntPtr`. + IntPtr, + /// `nuint` / `System.UIntPtr`. + UIntPtr, + /// `System.TypedReference`. + TypedByRef, + /// A reference type named by a token. + Class(TypeDefOrRef), + /// A value type or enum named by a token. + ValueType(TypeDefOrRef), + /// A vector array (`T[]`). + SzArray(Box), + /// A multi-dimensional array. + Array { + /// Element type. + element: Box, + /// Number of dimensions. + rank: u32, + /// Leading dimension sizes; may be shorter than `rank`. + sizes: Vec, + /// Leading dimension lower bounds; may be shorter than `rank`. + lower_bounds: Vec, + }, + /// A managed reference (`ref T` / `out T`). + ByRef(Box), + /// An unmanaged pointer (`T*`). + Ptr(Box), + /// A generic instantiation such as `Box`. + GenericInstance { + /// `true` for a generic value type, `false` for a generic class. + value_type: bool, + /// The *open* generic type definition. + definition: TypeDefOrRef, + /// The type arguments. + arguments: Vec, + }, + /// The zero-based generic parameter of the enclosing type (`!0`). + TypeParameter(u32), + /// The zero-based generic parameter of the enclosing method (`!!0`). + MethodParameter(u32), + /// A required custom modifier applied to another type. + RequiredModifier(TypeDefOrRef, Box), + /// An optional custom modifier applied to another type. + OptionalModifier(TypeDefOrRef, Box), +} + +impl Type { + /// Wraps `self` in `T[]`. + #[must_use] + pub fn array(self) -> Self { + Self::SzArray(Box::new(self)) + } + + /// Wraps `self` in `ref T`. + #[must_use] + pub fn by_ref(self) -> Self { + Self::ByRef(Box::new(self)) + } + + /// Wraps `self` in `T*`. + #[must_use] + pub fn pointer(self) -> Self { + Self::Ptr(Box::new(self)) + } + + /// Appends this type's signature encoding to `out`. + /// + /// # Errors + /// + /// Returns [`Error::TypeTooDeep`] past [`MAX_TYPE_DEPTH`] nesting levels, + /// [`Error::CompressedRange`] if a generic-parameter number or array shape + /// is too large to compress, or [`Error::CodedIndexOverflow`] if a token + /// cannot be packed. + pub fn encode(&self, out: &mut Vec) -> Result<()> { + self.encode_at(out, 0) + } + + fn encode_at(&self, out: &mut Vec, depth: u32) -> Result<()> { + if depth >= MAX_TYPE_DEPTH { + return Err(Error::TypeTooDeep { + limit: MAX_TYPE_DEPTH, + }); + } + if let Some(primitive) = self.primitive_byte() { + out.push(primitive); + return Ok(()); + } + let next = depth.saturating_add(1); + match self { + Self::Class(token) => Self::encode_token(out, element_type::CLASS, *token), + Self::ValueType(token) => Self::encode_token(out, element_type::VALUETYPE, *token), + Self::SzArray(element) => { + Self::encode_wrapped(out, element_type::SZARRAY, element, next) + } + Self::ByRef(inner) => Self::encode_wrapped(out, element_type::BYREF, inner, next), + Self::Ptr(inner) => Self::encode_wrapped(out, element_type::PTR, inner, next), + Self::TypeParameter(index) => Self::encode_indexed(out, element_type::VAR, *index), + Self::MethodParameter(index) => Self::encode_indexed(out, element_type::MVAR, *index), + Self::RequiredModifier(token, inner) => { + Self::encode_modifier(out, element_type::CMOD_REQD, *token, inner, next) + } + Self::OptionalModifier(token, inner) => { + Self::encode_modifier(out, element_type::CMOD_OPT, *token, inner, next) + } + Self::GenericInstance { + value_type, + definition, + arguments, + } => Self::encode_generic(out, *value_type, *definition, arguments, next), + Self::Array { + element, + rank, + sizes, + lower_bounds, + } => { + out.push(element_type::ARRAY); + element.encode_at(out, next)?; + encode_array_shape(out, *rank, sizes, lower_bounds) + } + _ => Ok(()), + } + } + + /// The single-byte encoding for the primitive cases, if this is one. + fn primitive_byte(&self) -> Option { + Some(match self { + Self::Void => element_type::VOID, + Self::Boolean => element_type::BOOLEAN, + Self::Char => element_type::CHAR, + Self::I1 => element_type::I1, + Self::U1 => element_type::U1, + Self::I2 => element_type::I2, + Self::U2 => element_type::U2, + Self::I4 => element_type::I4, + Self::U4 => element_type::U4, + Self::I8 => element_type::I8, + Self::U8 => element_type::U8, + Self::R4 => element_type::R4, + Self::R8 => element_type::R8, + Self::String => element_type::STRING, + Self::Object => element_type::OBJECT, + Self::IntPtr => element_type::I, + Self::UIntPtr => element_type::U, + Self::TypedByRef => element_type::TYPEDBYREF, + _ => return None, + }) + } + + fn encode_token(out: &mut Vec, tag: u8, token: TypeDefOrRef) -> Result<()> { + out.push(tag); + compress_unsigned(out, token.coded_value()?) + } + + fn encode_wrapped(out: &mut Vec, tag: u8, inner: &Self, depth: u32) -> Result<()> { + out.push(tag); + inner.encode_at(out, depth) + } + + fn encode_indexed(out: &mut Vec, tag: u8, index: u32) -> Result<()> { + out.push(tag); + compress_unsigned(out, index) + } + + fn encode_modifier( + out: &mut Vec, + tag: u8, + token: TypeDefOrRef, + inner: &Self, + depth: u32, + ) -> Result<()> { + out.push(tag); + compress_unsigned(out, token.coded_value()?)?; + inner.encode_at(out, depth) + } + + fn encode_generic( + out: &mut Vec, + value_type: bool, + definition: TypeDefOrRef, + arguments: &[Self], + depth: u32, + ) -> Result<()> { + out.push(element_type::GENERICINST); + out.push(if value_type { + element_type::VALUETYPE + } else { + element_type::CLASS + }); + compress_unsigned(out, definition.coded_value()?)?; + compress_unsigned(out, u32::try_from(arguments.len()).unwrap_or(u32::MAX))?; + for argument in arguments { + argument.encode_at(out, depth)?; + } + Ok(()) + } +} + +/// Encodes an `ArrayShape` (II.23.2.13). +fn encode_array_shape( + out: &mut Vec, + rank: u32, + sizes: &[u32], + lower_bounds: &[i32], +) -> Result<()> { + compress_unsigned(out, rank)?; + compress_unsigned(out, u32::try_from(sizes.len()).unwrap_or(u32::MAX))?; + for size in sizes { + compress_unsigned(out, *size)?; + } + compress_unsigned(out, u32::try_from(lower_bounds.len()).unwrap_or(u32::MAX))?; + for bound in lower_bounds { + compress_signed(out, *bound)?; + } + Ok(()) +} + +/// A `MethodDefSig` / `MethodRefSig` (II.23.2.1, II.23.2.2). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct MethodSignature { + /// Instance methods set `HASTHIS`. + pub has_this: bool, + /// Set `EXPLICITTHIS` when the `this` pointer is an explicit parameter. + pub explicit_this: bool, + /// `true` for the `VARARG` convention. + pub vararg: bool, + /// Generic arity; non-zero sets the `GENERIC` bit. + pub generic_parameter_count: u32, + /// Return type. + pub return_type: Type, + /// Parameter types, excluding `this` and the return type. + pub parameters: Vec, +} + +impl MethodSignature { + /// A `static` method signature. + #[must_use] + pub fn static_method(return_type: Type, parameters: Vec) -> Self { + Self { + has_this: false, + explicit_this: false, + vararg: false, + generic_parameter_count: 0, + return_type, + parameters, + } + } + + /// An instance method signature (`HASTHIS`). + #[must_use] + pub fn instance_method(return_type: Type, parameters: Vec) -> Self { + Self { + has_this: true, + ..Self::static_method(return_type, parameters) + } + } + + /// Sets the generic arity, which turns on the `GENERIC` calling-convention + /// bit and emits the arity ahead of the parameter count. + #[must_use] + pub fn with_generic_parameters(mut self, count: u32) -> Self { + self.generic_parameter_count = count; + self + } + + /// The calling-convention byte this signature starts with. + #[must_use] + pub fn calling_convention(&self) -> u8 { + let mut byte = if self.vararg { CALLCONV_VARARG } else { 0x00 }; + if self.generic_parameter_count > 0 { + byte |= CALLCONV_GENERIC; + } + if self.has_this { + byte |= CALLCONV_HASTHIS; + } + if self.explicit_this { + byte |= CALLCONV_EXPLICITTHIS; + } + byte + } + + /// Encodes the complete signature blob. + /// + /// # Errors + /// + /// Propagates any [`Type::encode`] failure. + pub fn to_blob(&self) -> Result> { + let mut out = vec![self.calling_convention()]; + if self.generic_parameter_count > 0 { + compress_unsigned(&mut out, self.generic_parameter_count)?; + } + compress_unsigned( + &mut out, + u32::try_from(self.parameters.len()).unwrap_or(u32::MAX), + )?; + self.return_type.encode(&mut out)?; + for parameter in &self.parameters { + parameter.encode(&mut out)?; + } + Ok(out) + } +} + +/// Encodes a `FieldSig`: the `0x06` marker followed by the field's type. +/// +/// # Errors +/// +/// Propagates any [`Type::encode`] failure. +pub fn field_signature(field_type: &Type) -> Result> { + let mut out = vec![FIELD_SIGNATURE]; + field_type.encode(&mut out)?; + Ok(out) +} + +/// Encodes a `PropertySig`. +/// +/// # Errors +/// +/// Propagates any [`Type::encode`] failure. +pub fn property_signature( + has_this: bool, + property_type: &Type, + index_parameters: &[Type], +) -> Result> { + let marker = if has_this { + PROPERTY_SIGNATURE | CALLCONV_HASTHIS + } else { + PROPERTY_SIGNATURE + }; + let mut out = vec![marker]; + compress_unsigned( + &mut out, + u32::try_from(index_parameters.len()).unwrap_or(u32::MAX), + )?; + property_type.encode(&mut out)?; + for parameter in index_parameters { + parameter.encode(&mut out)?; + } + Ok(out) +} diff --git a/crates/modrix-ecma335/src/tables.rs b/crates/modrix-ecma335/src/tables.rs new file mode 100644 index 0000000..a8f91ca --- /dev/null +++ b/crates/modrix-ecma335/src/tables.rs @@ -0,0 +1,470 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Metadata table numbers, coded-index families and column widths. +//! +//! Column widths are the highest-risk part of an ECMA-335 writer because a +//! wrong width does not fail - it shifts every subsequent byte of the table +//! stream, producing a file that parses into nonsense. Two rules make it work: +//! +//! 1. Widths are derived **only** from final row counts and final heap sizes, +//! never from a running total. +//! 2. A coded index widens at `1 << (16 - tag_bits)`, **not** at `1 << 16`. +//! `TypeDefOrRef` spends 2 bits on its tag, so it widens at 16 384 rows - +//! a threshold a plausible assembly actually crosses. + +/// ECMA-335 Partition II table numbers. +pub(crate) mod table { + /// `Module` (II.22.30). + pub(crate) const MODULE: u8 = 0x00; + /// `TypeRef` (II.22.38). + pub(crate) const TYPE_REF: u8 = 0x01; + /// `TypeDef` (II.22.37). + pub(crate) const TYPE_DEF: u8 = 0x02; + /// `Field` (II.22.15). + pub(crate) const FIELD: u8 = 0x04; + /// `MethodDef` (II.22.26). + pub(crate) const METHOD_DEF: u8 = 0x06; + /// `Param` (II.22.33). + pub(crate) const PARAM: u8 = 0x08; + /// `InterfaceImpl` (II.22.23). + pub(crate) const INTERFACE_IMPL: u8 = 0x09; + /// `MemberRef` (II.22.25). + pub(crate) const MEMBER_REF: u8 = 0x0A; + /// `Constant` (II.22.9). + pub(crate) const CONSTANT: u8 = 0x0B; + /// `CustomAttribute` (II.22.10). + pub(crate) const CUSTOM_ATTRIBUTE: u8 = 0x0C; + /// `DeclSecurity` (II.22.11); never emitted, needed for coded-index tags. + pub(crate) const DECL_SECURITY: u8 = 0x0E; + /// `StandAloneSig` (II.22.36); never emitted, needed for tags. + pub(crate) const STAND_ALONE_SIG: u8 = 0x11; + /// `Event` (II.22.13); never emitted, needed for tags. + pub(crate) const EVENT: u8 = 0x14; + /// `PropertyMap` (II.22.35). + pub(crate) const PROPERTY_MAP: u8 = 0x15; + /// `Property` (II.22.34). + pub(crate) const PROPERTY: u8 = 0x17; + /// `MethodSemantics` (II.22.28). + pub(crate) const METHOD_SEMANTICS: u8 = 0x18; + /// `ModuleRef` (II.22.31); never emitted, needed for tags. + pub(crate) const MODULE_REF: u8 = 0x1A; + /// `TypeSpec` (II.22.39). + pub(crate) const TYPE_SPEC: u8 = 0x1B; + /// `Assembly` (II.22.2). + pub(crate) const ASSEMBLY: u8 = 0x20; + /// `AssemblyRef` (II.22.5). + pub(crate) const ASSEMBLY_REF: u8 = 0x23; + /// `File` (II.22.19); never emitted, needed for tags. + pub(crate) const FILE: u8 = 0x26; + /// `ExportedType` (II.22.14); never emitted, needed for tags. + pub(crate) const EXPORTED_TYPE: u8 = 0x27; + /// `ManifestResource` (II.22.24); never emitted, needed for tags. + pub(crate) const MANIFEST_RESOURCE: u8 = 0x28; + /// `NestedClass` (II.22.32). + pub(crate) const NESTED_CLASS: u8 = 0x29; + /// `GenericParam` (II.22.20). + pub(crate) const GENERIC_PARAM: u8 = 0x2A; + /// `MethodSpec` (II.22.29); never emitted, needed for tags. + pub(crate) const METHOD_SPEC: u8 = 0x2B; + /// `GenericParamConstraint` (II.22.21); never emitted, needed for tags. + pub(crate) const GENERIC_PARAM_CONSTRAINT: u8 = 0x2C; +} + +/// The tables this writer emits, in the ascending order the `#~` stream +/// requires. Row data follows the same order, contiguous and unpadded. +pub(crate) const EMITTED_TABLES: [u8; 18] = [ + table::MODULE, + table::TYPE_REF, + table::TYPE_DEF, + table::FIELD, + table::METHOD_DEF, + table::PARAM, + table::INTERFACE_IMPL, + table::MEMBER_REF, + table::CONSTANT, + table::CUSTOM_ATTRIBUTE, + table::PROPERTY_MAP, + table::PROPERTY, + table::METHOD_SEMANTICS, + table::TYPE_SPEC, + table::ASSEMBLY, + table::ASSEMBLY_REF, + table::NESTED_CLASS, + table::GENERIC_PARAM, +]; + +/// The `Sorted` bitmask Roslyn writes: exactly the tables ECMA-335 requires to +/// be sorted by their key column. +pub(crate) const SORTED_MASK: u64 = 0x0000_1600_3301_FA00; + +/// One coded-index family: a tag width plus the table each tag value selects. +/// +/// The slot position *is* the tag value, so unused tags are `None` +/// (`CustomAttributeType` leaves 0, 1 and 4 unused). +#[derive(Clone, Copy, Debug)] +pub(crate) struct CodedIndex { + /// Family name, used in diagnostics. + pub(crate) name: &'static str, + /// How many low bits hold the tag. + pub(crate) tag_bits: u8, + /// Tag value -> table number. + pub(crate) tags: &'static [Option], +} + +impl CodedIndex { + /// Row count at which this family switches from 2-byte to 4-byte columns. + /// + /// This is `1 << (16 - tag_bits)`. Using `1 << 16` here instead is the + /// classic silent-corruption bug: `TypeDefOrRef` would stay two bytes past + /// 16 383 rows and every row after it would be misparsed. + pub(crate) const fn threshold(self) -> u32 { + 1_u32 << (16_u8.saturating_sub(self.tag_bits)) + } + + /// Packs a 1-based `row` of `table` into this family's encoding. + /// + /// # Errors + /// + /// Returns [`crate::Error::CodedIndexOverflow`] if `table` is not part of + /// this family or the shifted row would not fit in 32 bits. + pub(crate) fn encode(self, table: u8, row: u32) -> crate::Result { + let tag = self + .tags + .iter() + .position(|slot| *slot == Some(table)) + .and_then(|tag| u32::try_from(tag).ok()) + .ok_or(crate::Error::CodedIndexOverflow { + family: self.name, + table, + row, + })?; + row.checked_shl(u32::from(self.tag_bits)) + .filter(|shifted| (shifted >> self.tag_bits) == row) + .and_then(|shifted| shifted.checked_add(tag)) + .ok_or(crate::Error::CodedIndexOverflow { + family: self.name, + table, + row, + }) + } + + /// Splits a coded index back into `(table, row)`; `row` 0 means nil. + #[cfg(test)] + pub(crate) fn decode(self, value: u32) -> Option<(u8, u32)> { + let tag_mask = (1_u32 << self.tag_bits).saturating_sub(1); + let tag = usize::try_from(value & tag_mask).ok()?; + let table = (*self.tags.get(tag)?)?; + Some((table, value >> self.tag_bits)) + } +} + +/// `TypeDefOrRef`: the family used by `Extends`, `InterfaceImpl.Interface` and +/// every `CLASS`/`VALUETYPE` token inside a signature blob. +pub(crate) const TYPE_DEF_OR_REF: CodedIndex = CodedIndex { + name: "TypeDefOrRef", + tag_bits: 2, + tags: &[ + Some(table::TYPE_DEF), + Some(table::TYPE_REF), + Some(table::TYPE_SPEC), + ], +}; + +/// `HasConstant`: the parent of a `Constant` row. +pub(crate) const HAS_CONSTANT: CodedIndex = CodedIndex { + name: "HasConstant", + tag_bits: 2, + tags: &[ + Some(table::FIELD), + Some(table::PARAM), + Some(table::PROPERTY), + ], +}; + +/// `HasCustomAttribute`: the widest family at 5 tag bits, so it widens at only +/// 2 048 rows. +pub(crate) const HAS_CUSTOM_ATTRIBUTE: CodedIndex = CodedIndex { + name: "HasCustomAttribute", + tag_bits: 5, + tags: &[ + Some(table::METHOD_DEF), + Some(table::FIELD), + Some(table::TYPE_REF), + Some(table::TYPE_DEF), + Some(table::PARAM), + Some(table::INTERFACE_IMPL), + Some(table::MEMBER_REF), + Some(table::MODULE), + Some(table::DECL_SECURITY), + Some(table::PROPERTY), + Some(table::EVENT), + Some(table::STAND_ALONE_SIG), + Some(table::MODULE_REF), + Some(table::TYPE_SPEC), + Some(table::ASSEMBLY), + Some(table::ASSEMBLY_REF), + Some(table::FILE), + Some(table::EXPORTED_TYPE), + Some(table::MANIFEST_RESOURCE), + Some(table::GENERIC_PARAM), + Some(table::METHOD_SPEC), + Some(table::GENERIC_PARAM_CONSTRAINT), + ], +}; + +/// `CustomAttributeType`: only tags 2 and 3 are defined. +pub(crate) const CUSTOM_ATTRIBUTE_TYPE: CodedIndex = CodedIndex { + name: "CustomAttributeType", + tag_bits: 3, + tags: &[ + None, + None, + Some(table::METHOD_DEF), + Some(table::MEMBER_REF), + None, + ], +}; + +/// `MemberRefParent`: the owner of a `MemberRef` row. +pub(crate) const MEMBER_REF_PARENT: CodedIndex = CodedIndex { + name: "MemberRefParent", + tag_bits: 3, + tags: &[ + Some(table::TYPE_DEF), + Some(table::TYPE_REF), + Some(table::MODULE_REF), + Some(table::METHOD_DEF), + Some(table::TYPE_SPEC), + ], +}; + +/// `HasSemantics`: what a `MethodSemantics` row attaches to. +pub(crate) const HAS_SEMANTICS: CodedIndex = CodedIndex { + name: "HasSemantics", + tag_bits: 1, + tags: &[Some(table::EVENT), Some(table::PROPERTY)], +}; + +/// `TypeOrMethodDef`: what owns a `GenericParam` row. +pub(crate) const TYPE_OR_METHOD_DEF: CodedIndex = CodedIndex { + name: "TypeOrMethodDef", + tag_bits: 1, + tags: &[Some(table::TYPE_DEF), Some(table::METHOD_DEF)], +}; + +/// `ResolutionScope`: where a `TypeRef` is looked up. +pub(crate) const RESOLUTION_SCOPE: CodedIndex = CodedIndex { + name: "ResolutionScope", + tag_bits: 2, + tags: &[ + Some(table::MODULE), + Some(table::MODULE_REF), + Some(table::ASSEMBLY_REF), + Some(table::TYPE_REF), + ], +}; + +/// `MethodDefOrRef`: modelled for completeness; used by `MethodImpl` and +/// `MethodSpec`, neither of which a reference assembly needs. +#[cfg(test)] +pub(crate) const METHOD_DEF_OR_REF: CodedIndex = CodedIndex { + name: "MethodDefOrRef", + tag_bits: 1, + tags: &[Some(table::METHOD_DEF), Some(table::MEMBER_REF)], +}; + +/// `HasFieldMarshall`: modelled for completeness. +#[cfg(test)] +pub(crate) const HAS_FIELD_MARSHALL: CodedIndex = CodedIndex { + name: "HasFieldMarshall", + tag_bits: 1, + tags: &[Some(table::FIELD), Some(table::PARAM)], +}; + +/// `HasDeclSecurity`: modelled for completeness. +#[cfg(test)] +pub(crate) const HAS_DECL_SECURITY: CodedIndex = CodedIndex { + name: "HasDeclSecurity", + tag_bits: 2, + tags: &[ + Some(table::TYPE_DEF), + Some(table::METHOD_DEF), + Some(table::ASSEMBLY), + ], +}; + +/// `MemberForwarded`: modelled for completeness. +#[cfg(test)] +pub(crate) const MEMBER_FORWARDED: CodedIndex = CodedIndex { + name: "MemberForwarded", + tag_bits: 1, + tags: &[Some(table::FIELD), Some(table::METHOD_DEF)], +}; + +/// `Implementation`: modelled for completeness. +#[cfg(test)] +pub(crate) const IMPLEMENTATION: CodedIndex = CodedIndex { + name: "Implementation", + tag_bits: 2, + tags: &[ + Some(table::FILE), + Some(table::ASSEMBLY_REF), + Some(table::EXPORTED_TYPE), + ], +}; + +/// Every family, for exhaustive width testing. +#[cfg(test)] +pub(crate) const ALL_CODED_INDICES: [CodedIndex; 13] = [ + TYPE_DEF_OR_REF, + HAS_CONSTANT, + HAS_CUSTOM_ATTRIBUTE, + CUSTOM_ATTRIBUTE_TYPE, + MEMBER_REF_PARENT, + HAS_SEMANTICS, + TYPE_OR_METHOD_DEF, + RESOLUTION_SCOPE, + METHOD_DEF_OR_REF, + HAS_FIELD_MARSHALL, + HAS_DECL_SECURITY, + MEMBER_FORWARDED, + IMPLEMENTATION, +]; + +/// Final row counts for all 64 tables, the sole input to every width decision. +#[derive(Clone, Copy, Debug)] +pub(crate) struct RowCounts { + counts: [u32; 64], +} + +impl Default for RowCounts { + fn default() -> Self { + Self { counts: [0; 64] } + } +} + +impl RowCounts { + /// Records `rows` for `table`. + pub(crate) fn set(&mut self, table: u8, rows: u32) { + if let Some(slot) = self.counts.get_mut(usize::from(table)) { + *slot = rows; + } + } + + /// Row count for `table`, or 0 when the table is absent. + pub(crate) fn get(self, table: u8) -> u32 { + self.counts.get(usize::from(table)).copied().unwrap_or(0) + } + + /// The `Valid` bitmask: bit N set iff table N has at least one row. + pub(crate) fn valid_mask(self) -> u64 { + let mut mask = 0_u64; + for (index, rows) in self.counts.iter().enumerate() { + if *rows > 0 && index < 64 { + mask |= 1_u64 << index; + } + } + mask + } + + /// Width of a *simple* index into `table`: 2 bytes below 65 536 rows. + pub(crate) fn simple_width(self, table: u8) -> u8 { + if self.get(table) >= (1 << 16) { 4 } else { 2 } + } + + /// Width of a coded index: 4 bytes as soon as *any* table in the family + /// reaches the family's threshold. + pub(crate) fn coded_width(self, family: CodedIndex) -> u8 { + let threshold = family.threshold(); + let wide = family + .tags + .iter() + .flatten() + .any(|table| self.get(*table) >= threshold); + if wide { 4 } else { 2 } + } +} + +/// Every column width one assembly needs, resolved once from final row counts +/// and final heap sizes. +/// +/// The widths are materialised into fields rather than recomputed per column +/// so that no serialisation step can accidentally consult a row count that has +/// moved on. It is also small enough to pass by value. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Widths { + /// `#Strings` index width. + pub(crate) string: u8, + /// `#GUID` index width. + pub(crate) guid: u8, + /// `#Blob` index width. + pub(crate) blob: u8, + /// The `HeapSizes` byte the three heap widths encode to. + pub(crate) heap_sizes: u8, + /// Simple index into `Field`. + pub(crate) field: u8, + /// Simple index into `MethodDef`. + pub(crate) method_def: u8, + /// Simple index into `Param`. + pub(crate) param: u8, + /// Simple index into `TypeDef`. + pub(crate) type_def: u8, + /// Simple index into `Property`. + pub(crate) property: u8, + /// `TypeDefOrRef` coded index. + pub(crate) type_def_or_ref: u8, + /// `ResolutionScope` coded index. + pub(crate) resolution_scope: u8, + /// `HasConstant` coded index. + pub(crate) has_constant: u8, + /// `HasCustomAttribute` coded index. + pub(crate) has_custom_attribute: u8, + /// `CustomAttributeType` coded index. + pub(crate) custom_attribute_type: u8, + /// `MemberRefParent` coded index. + pub(crate) member_ref_parent: u8, + /// `HasSemantics` coded index. + pub(crate) has_semantics: u8, + /// `TypeOrMethodDef` coded index. + pub(crate) type_or_method_def: u8, +} + +impl Widths { + /// Derives widths from final heap sizes and final row counts. + pub(crate) fn new(strings: usize, guids: usize, blobs: usize, rows: RowCounts) -> Self { + let mut heap_sizes = 0_u8; + if strings >= (1 << 16) { + heap_sizes |= 0x01; + } + if guids >= (1 << 16) { + heap_sizes |= 0x02; + } + if blobs >= (1 << 16) { + heap_sizes |= 0x04; + } + Self::from_heap_sizes(heap_sizes, rows) + } + + /// Rebuilds widths from an already-encoded `HeapSizes` byte. The reader + /// uses this so it derives widths exactly the way the writer did. + pub(crate) fn from_heap_sizes(heap_sizes: u8, rows: RowCounts) -> Self { + Self { + string: if heap_sizes & 0x01 == 0 { 2 } else { 4 }, + guid: if heap_sizes & 0x02 == 0 { 2 } else { 4 }, + blob: if heap_sizes & 0x04 == 0 { 2 } else { 4 }, + heap_sizes, + field: rows.simple_width(table::FIELD), + method_def: rows.simple_width(table::METHOD_DEF), + param: rows.simple_width(table::PARAM), + type_def: rows.simple_width(table::TYPE_DEF), + property: rows.simple_width(table::PROPERTY), + type_def_or_ref: rows.coded_width(TYPE_DEF_OR_REF), + resolution_scope: rows.coded_width(RESOLUTION_SCOPE), + has_constant: rows.coded_width(HAS_CONSTANT), + has_custom_attribute: rows.coded_width(HAS_CUSTOM_ATTRIBUTE), + custom_attribute_type: rows.coded_width(CUSTOM_ATTRIBUTE_TYPE), + member_ref_parent: rows.coded_width(MEMBER_REF_PARENT), + has_semantics: rows.coded_width(HAS_SEMANTICS), + type_or_method_def: rows.coded_width(TYPE_OR_METHOD_DEF), + } + } +} diff --git a/crates/modrix-ecma335/src/tests/csc.rs b/crates/modrix-ecma335/src/tests/csc.rs new file mode 100644 index 0000000..ecaf642 --- /dev/null +++ b/crates/modrix-ecma335/src/tests/csc.rs @@ -0,0 +1,292 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! L3: the real oracle. Compile C# against the emitted DLL with the actual +//! Roslyn compiler from an installed .NET SDK. +//! +//! Everything else in this crate is self-referential - the writer and the +//! reader can agree on a wrong answer. Roslyn cannot be talked around: it is +//! the consumer the output exists for, and its diagnostics are the ground +//! truth for whether an `Assembly` row, a `Constant` row or a coded-index +//! width is right. +//! +//! The test skips itself when no SDK is installed, so CI without .NET is +//! still green. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +use super::fixtures::full_surface_targeting; +use super::scale::synthetic_targeting; +use crate::builder::AssemblyBuilder; + +/// Where a probe compilation happens and what it needs. +struct Toolchain { + dotnet: PathBuf, + csc: PathBuf, + reference_pack: PathBuf, + framework_major: u16, +} + +/// Locates an SDK, or `None` when this machine has no .NET installed. +fn toolchain() -> Option { + let root = dotnet_root()?; + let dotnet = which_dotnet()?; + let sdk = newest_child(&root.join("sdk"))?; + let csc = sdk.join("Roslyn/bincore/csc.dll"); + if !csc.is_file() { + return None; + } + let preferred = version_key(&sdk).first().copied().unwrap_or(0); + let (reference_pack, framework_major) = reference_pack( + &root.join("packs/Microsoft.NETCore.App.Ref"), + u16::try_from(preferred).unwrap_or(0), + )?; + Some(Toolchain { + dotnet, + csc, + reference_pack, + framework_major, + }) +} + +fn dotnet_root() -> Option { + let mut candidates: Vec = Vec::new(); + if let Ok(root) = std::env::var("DOTNET_ROOT") { + candidates.push(PathBuf::from(root)); + } + candidates.push(PathBuf::from("/usr/share/dotnet")); + candidates.push(PathBuf::from("/usr/lib/dotnet")); + candidates.push(PathBuf::from("/usr/local/share/dotnet")); + candidates + .into_iter() + .find(|path| path.join("sdk").is_dir()) +} + +fn which_dotnet() -> Option { + let path = PathBuf::from("dotnet"); + Command::new(&path) + .arg("--version") + .output() + .ok() + .filter(|output| output.status.success()) + .map(|_| path) +} + +/// The highest-versioned child directory, compared numerically - `10.0.110` +/// sorts *below* `9.0.119` as a string, which would silently pick the wrong SDK. +fn newest_child(directory: &Path) -> Option { + let mut entries: Vec<(Vec, PathBuf)> = std::fs::read_dir(directory) + .ok()? + .filter_map(Result::ok) + .map(|entry| entry.path()) + .filter(|path| path.is_dir()) + .map(|path| (version_key(&path), path)) + .collect(); + entries.sort(); + entries.pop().map(|(_, path)| path) +} + +/// Splits a directory name such as `10.0.110` into comparable components. +fn version_key(path: &Path) -> Vec { + path.file_name() + .map(|name| name.to_string_lossy().to_string()) + .unwrap_or_default() + .split(['.', '-']) + .map(|part| part.parse::().unwrap_or(0)) + .collect() +} + +/// Finds a reference pack and the framework major version it targets, so the +/// emitted `AssemblyRef` version matches and no CS1701 warning appears. +fn reference_pack(packs: &Path, preferred_major: u16) -> Option<(PathBuf, u16)> { + let mut found: Vec<(u16, PathBuf)> = Vec::new(); + for version in std::fs::read_dir(packs).ok()?.filter_map(Result::ok) { + let ref_dir = version.path().join("ref"); + let Ok(entries) = std::fs::read_dir(&ref_dir) else { + continue; + }; + for moniker in entries.filter_map(Result::ok) { + let name = moniker.file_name().to_string_lossy().to_string(); + if let Some(major) = framework_major(&name) { + found.push((major, moniker.path())); + } + } + } + if let Some((major, path)) = found.iter().find(|(major, _)| *major == preferred_major) { + return Some((path.clone(), *major)); + } + found.sort_by_key(|(major, _)| *major); + found.pop().map(|(major, path)| (path, major)) +} + +/// `net9.0` -> `9`. +fn framework_major(moniker: &str) -> Option { + let rest = moniker.strip_prefix("net")?; + let (major, _) = rest.split_once('.')?; + major.parse().ok() +} + +/// Runs `csc` over `source`, referencing `emitted` plus the whole reference +/// pack, and returns `(success, combined output)`. +fn compile(tools: &Toolchain, workspace: &Path, emitted: &Path, source: &Path) -> (bool, String) { + let mut command = Command::new(&tools.dotnet); + command + .arg("exec") + .arg(&tools.csc) + .arg("-nologo") + .arg("-nostdlib+") + .arg("-target:library") + .arg(format!("-out:{}", workspace.join("probe.dll").display())) + .arg(format!("-r:{}", emitted.display())); + for entry in std::fs::read_dir(&tools.reference_pack) + .into_iter() + .flatten() + .filter_map(Result::ok) + { + let path = entry.path(); + if path.extension().is_some_and(|extension| extension == "dll") { + command.arg(format!("-r:{}", path.display())); + } + } + command.arg(source); + let output = command.output().expect("csc must be runnable"); + let mut text = String::from_utf8_lossy(&output.stdout).into_owned(); + text.push_str(&String::from_utf8_lossy(&output.stderr)); + (output.status.success(), text) +} + +/// Emits `builder`, writes `probe`, compiles, and asserts csc exited 0. +#[expect( + clippy::print_stdout, + reason = "the compiler's own transcript is the result this test exists to produce" +)] +fn expect_compiles(tools: &Toolchain, builder: &AssemblyBuilder, name: &str, probe: &str) { + let workspace = + std::env::temp_dir().join(format!("modrix-ecma335-{name}-{}", std::process::id())); + std::fs::create_dir_all(&workspace).expect("temp directory"); + let emitted = workspace.join("Emitted.dll"); + // L0 runs on the csc fixtures too, so a failure here is attributed to the + // writer before Roslyn is ever started. + let (bytes, _) = super::fixtures::emit_and_verify(builder); + std::fs::write(&emitted, &bytes).expect("write dll"); + let source = workspace.join("probe.cs"); + std::fs::write(&source, probe).expect("write probe"); + + let (ok, output) = compile(tools, &workspace, &emitted, &source); + println!("--- csc transcript for `{name}` ---"); + println!("emitted: {}", emitted.display()); + println!("exit ok: {ok}"); + println!( + "{}", + if output.is_empty() { + "(no output)" + } else { + &output + } + ); + // Setting MODRIX_ECMA335_KEEP leaves the emitted DLL and the probe on disk + // so a failure can be pulled apart with an external metadata dumper. + if std::env::var_os("MODRIX_ECMA335_KEEP").is_none() { + let _ = std::fs::remove_dir_all(&workspace); + } + assert!(ok, "csc rejected the emitted assembly:\n{output}"); + assert!( + output.is_empty(), + "csc accepted the assembly but emitted diagnostics:\n{output}" + ); +} + +const FULL_SURFACE_PROBE: &str = r#"using System; + +public static class Probe +{ + public static string Run() + { + Type a = typeof(MyLib.IThing); + Type b = typeof(MyLib.Widget); + Type c = typeof(MyLib.Box); + + MyLib.Widget w = new MyLib.Widget(); + w.Go(); + MyLib.IThing t = w; + t.Go(); + w.Value = 7; + w.Tags = new string[] { "tag" }; + w.DoThing("s"); + w.Count = 5; + int count = w.Count; + int sum = MyLib.Widget.Add(1, 2); + + int x = 1, y = 2; + MyLib.Widget.Swap(ref x, ref y); + + MyLib.Box boxed = MyLib.Box.Make("inner"); + string got = boxed.Get(); + MyLib.Box ints = w.IntBox; + + MyLib.Widget.Inner nested = new MyLib.Widget.Inner(); + nested.Z = 3; + + MyLib.Point p = new MyLib.Point(); + p.X = 1; + p.Y = 2; + + MyLib.Color colour = MyLib.Color.Blue; + MyLib.Color other = MyLib.Color.Red; + + return string.Concat( + a, b, c, count, sum, x, y, got, ints, nested.Z, p.X, p.Y, colour, other, w.Tags[0]); + } +} +"#; + +const SCALE_PROBE: &str = r"using System; + +public static class ScaleProbe +{ + public static string Run() + { + Type first = typeof(Bulk.T000000); + Type last = typeof(Bulk.T020005); + Bulk.T000000 a = new Bulk.T000000(); + Bulk.T020005 b = new Bulk.T020005(); + a.F000000 = 1; + b.F020005 = 2; + a.M000000(); + b.M020005(); + return string.Concat(first, last, a.F000000, b.F020005); + } +} +"; + +/// The headline check: a full-surface reference assembly compiles clean. +#[test] +fn roslyn_accepts_the_full_surface_assembly() { + let Some(tools) = toolchain() else { + return; + }; + let builder = full_surface_targeting(tools.framework_major, false); + expect_compiles(&tools, &builder, "full", FULL_SURFACE_PROBE); +} + +/// The same assembly with the two reference-assembly marker attributes, which +/// adds the `MemberRef` and `CustomAttribute` tables to the mix. +#[test] +fn roslyn_accepts_the_marked_reference_assembly() { + let Some(tools) = toolchain() else { + return; + }; + let builder = full_surface_targeting(tools.framework_major, true); + expect_compiles(&tools, &builder, "marked", FULL_SURFACE_PROBE); +} + +/// The width oracle: 20 007 types force 4-byte `TypeDefOrRef` coded indices +/// and a `#Strings` heap over 64 KB. Roslyn resolving both the first and the +/// last type is the only external proof that the threshold is right. +#[test] +fn roslyn_resolves_the_first_and_last_type_past_the_coded_index_threshold() { + let Some(tools) = toolchain() else { + return; + }; + let builder = synthetic_targeting(20_007, 0, tools.framework_major); + expect_compiles(&tools, &builder, "scale", SCALE_PROBE); +} diff --git a/crates/modrix-ecma335/src/tests/fixtures.rs b/crates/modrix-ecma335/src/tests/fixtures.rs new file mode 100644 index 0000000..5292817 --- /dev/null +++ b/crates/modrix-ecma335/src/tests/fixtures.rs @@ -0,0 +1,352 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Shared fixtures: one assembly that exercises every feature the writer +//! supports, plus the L0 helper that every test runs on its output. + +use crate::builder::AssemblyBuilder; +use crate::handles::{AssemblyRefId, ResolutionScope, TypeDefId, TypeDefOrRef, TypeRefId}; +use crate::model::{ + AssemblyReference, Field, GenericParameter, Method, Parameter, Property, TypeDefinition, + Version, field_attributes, method_attributes, type_attributes, +}; +use crate::signature::{MethodSignature, Type}; +use crate::verify::{Parsed, parse}; + +/// The core-library reference plus the base types every fixture imports. +pub(crate) struct Corlib { + pub(crate) assembly: AssemblyRefId, + pub(crate) object: TypeRefId, + pub(crate) value_type: TypeRefId, + pub(crate) enumeration: TypeRefId, +} + +/// Adds the `System.Runtime` reference and the three base-type `TypeRef` rows, +/// targeting .NET 9. +pub(crate) fn add_corlib(builder: &mut AssemblyBuilder) -> Corlib { + add_corlib_targeting(builder, 9) +} + +/// The same, for a caller that must match an installed reference pack. +pub(crate) fn add_corlib_targeting(builder: &mut AssemblyBuilder, major: u16) -> Corlib { + let corlib = builder.add_assembly_ref(AssemblyReference::core_library(major)); + let scope = ResolutionScope::AssemblyRef(corlib); + Corlib { + assembly: corlib, + object: builder.add_type_ref(scope, "System", "Object"), + value_type: builder.add_type_ref(scope, "System", "ValueType"), + enumeration: builder.add_type_ref(scope, "System", "Enum"), + } +} + +/// The full-surface fixture: an interface, an open generic class, a class with +/// fields, a property, a virtual method and a generic method, a nested class, a +/// struct, and an enum with literal members. +pub(crate) fn full_surface() -> AssemblyBuilder { + full_surface_targeting(9, false) +} + +/// The same assembly, stamped with `ReferenceAssemblyAttribute` and +/// `TargetFrameworkAttribute` the way a real reference assembly is. +pub(crate) fn full_surface_marked() -> AssemblyBuilder { + full_surface_targeting(9, true) +} + +/// The fixture, bound to a specific .NET major version so it can be compiled +/// against that version's reference pack without a CS1701 identity warning. +pub(crate) fn full_surface_targeting(major: u16, mark: bool) -> AssemblyBuilder { + let mut builder = AssemblyBuilder::new("MyLib", Version::new(1, 0, 0, 0)); + let corlib = add_corlib_targeting(&mut builder, major); + let thing = add_interface(&mut builder); + let boxed = add_box(&mut builder, corlib.object); + let widget = add_widget(&mut builder, &corlib, thing, boxed); + add_inner(&mut builder, corlib.object, widget); + add_point(&mut builder, corlib.value_type); + add_color(&mut builder, corlib.enumeration); + if mark { + builder + .mark_reference_assembly(corlib.assembly, &format!(".NETCoreApp,Version=v{major}.0")) + .unwrap(); + } + builder +} + +fn add_interface(builder: &mut AssemblyBuilder) -> TypeDefId { + let thing = builder + .add_type_def(TypeDefinition::new( + "MyLib", + "IThing", + type_attributes::PUBLIC_INTERFACE, + None, + )) + .unwrap(); + builder + .add_method( + thing, + Method::new( + "Go", + method_attributes::INTERFACE_METHOD, + MethodSignature::instance_method(Type::Void, Vec::new()), + ), + ) + .unwrap(); + thing +} + +fn add_box(builder: &mut AssemblyBuilder, object: TypeRefId) -> TypeDefId { + let boxed = builder + .add_type_def( + TypeDefinition::new( + "MyLib", + "Box`1", + type_attributes::PUBLIC_CLASS, + Some(object.into()), + ) + .with_generic_parameter(GenericParameter::new("T")), + ) + .unwrap(); + builder + .add_field( + boxed, + Field::new("Item", field_attributes::PUBLIC, Type::TypeParameter(0)), + ) + .unwrap(); + builder.add_default_constructor(boxed).unwrap(); + builder + .add_method( + boxed, + Method::new( + "Get", + method_attributes::PUBLIC_INSTANCE, + MethodSignature::instance_method(Type::TypeParameter(0), Vec::new()), + ), + ) + .unwrap(); + let open = box_of(boxed, Type::TypeParameter(0)); + builder + .add_method( + boxed, + Method::new( + "Make", + method_attributes::PUBLIC_STATIC, + MethodSignature::static_method(open, vec![Type::TypeParameter(0)]), + ) + .with_parameter(Parameter::new("v")), + ) + .unwrap(); + boxed +} + +/// ``Box`1`` as it appears inside a signature blob - no `TypeSpec` +/// row is needed for a `GENERICINST` that is not referenced by a token. +pub(crate) fn box_of(definition: TypeDefId, argument: Type) -> Type { + Type::GenericInstance { + value_type: false, + definition: TypeDefOrRef::Definition(definition), + arguments: vec![argument], + } +} + +fn add_widget( + builder: &mut AssemblyBuilder, + corlib: &Corlib, + thing: TypeDefId, + boxed: TypeDefId, +) -> TypeDefId { + let widget = builder + .add_type_def( + TypeDefinition::new( + "MyLib", + "Widget", + type_attributes::PUBLIC_CLASS, + Some(corlib.object.into()), + ) + .with_interface(TypeDefOrRef::Definition(thing)), + ) + .unwrap(); + add_widget_fields(builder, widget, boxed); + add_widget_methods(builder, widget); + widget +} + +fn add_widget_fields(builder: &mut AssemblyBuilder, widget: TypeDefId, boxed: TypeDefId) { + let public = field_attributes::PUBLIC; + builder + .add_field(widget, Field::new("Value", public, Type::I4)) + .unwrap(); + builder + .add_field(widget, Field::new("Tags", public, Type::String.array())) + .unwrap(); + builder + .add_field( + widget, + Field::new("IntBox", public, box_of(boxed, Type::I4)), + ) + .unwrap(); + builder + .add_field( + widget, + Field::new("_count", field_attributes::PRIVATE, Type::I4), + ) + .unwrap(); +} + +fn add_widget_methods(builder: &mut AssemblyBuilder, widget: TypeDefId) { + builder.add_default_constructor(widget).unwrap(); + builder + .add_method( + widget, + Method::new( + "Go", + method_attributes::PUBLIC_VIRTUAL | method_attributes::FINAL, + MethodSignature::instance_method(Type::Void, Vec::new()), + ), + ) + .unwrap(); + let getter = builder + .add_method( + widget, + Method::new( + "get_Count", + method_attributes::PROPERTY_ACCESSOR, + MethodSignature::instance_method(Type::I4, Vec::new()), + ), + ) + .unwrap(); + let setter = builder + .add_method( + widget, + Method::new( + "set_Count", + method_attributes::PROPERTY_ACCESSOR, + MethodSignature::instance_method(Type::Void, vec![Type::I4]), + ) + .with_parameter(Parameter::new("value")), + ) + .unwrap(); + add_widget_statics(builder, widget); + builder + .add_property( + widget, + Property::new("Count", Type::I4) + .with_getter(getter) + .with_setter(setter), + ) + .unwrap(); +} + +fn add_widget_statics(builder: &mut AssemblyBuilder, widget: TypeDefId) { + builder + .add_method( + widget, + Method::new( + "DoThing", + method_attributes::PUBLIC_INSTANCE, + MethodSignature::instance_method(Type::Void, vec![Type::String]), + ) + .with_parameter(Parameter::new("s")), + ) + .unwrap(); + builder + .add_method( + widget, + Method::new( + "Add", + method_attributes::PUBLIC_STATIC, + MethodSignature::static_method(Type::I4, vec![Type::I4, Type::I4]), + ) + .with_parameter(Parameter::new("a")) + .with_parameter(Parameter::new("b")), + ) + .unwrap(); + builder + .add_method( + widget, + Method::new( + "Swap", + method_attributes::PUBLIC_STATIC, + MethodSignature::static_method( + Type::Void, + vec![ + Type::MethodParameter(0).by_ref(), + Type::MethodParameter(0).by_ref(), + ], + ), + ) + .with_generic_parameter(GenericParameter::new("T")) + .with_parameter(Parameter::new("a")) + .with_parameter(Parameter::new("b")), + ) + .unwrap(); +} + +fn add_inner(builder: &mut AssemblyBuilder, object: TypeRefId, widget: TypeDefId) { + let inner = builder + .add_type_def( + TypeDefinition::new( + "", + "Inner", + type_attributes::NESTED_PUBLIC | type_attributes::BEFORE_FIELD_INIT, + Some(object.into()), + ) + .nested_in(widget), + ) + .unwrap(); + builder + .add_field(inner, Field::new("Z", field_attributes::PUBLIC, Type::I4)) + .unwrap(); + builder.add_default_constructor(inner).unwrap(); +} + +fn add_point(builder: &mut AssemblyBuilder, value_type: TypeRefId) { + let point = builder + .add_type_def(TypeDefinition::new( + "MyLib", + "Point", + type_attributes::PUBLIC_VALUE_TYPE, + Some(value_type.into()), + )) + .unwrap(); + for name in ["X", "Y"] { + builder + .add_field(point, Field::new(name, field_attributes::PUBLIC, Type::I4)) + .unwrap(); + } +} + +fn add_color(builder: &mut AssemblyBuilder, enumeration: TypeRefId) { + use crate::model::Constant; + let color = builder + .add_type_def(TypeDefinition::new( + "MyLib", + "Color", + type_attributes::PUBLIC_VALUE_TYPE, + Some(enumeration.into()), + )) + .unwrap(); + builder + .add_field( + color, + Field::new("value__", field_attributes::ENUM_BACKING, Type::I4), + ) + .unwrap(); + let literal = Type::ValueType(TypeDefOrRef::Definition(color)); + for (name, value) in [("Red", 0_i32), ("Blue", 1)] { + builder + .add_field( + color, + Field::new(name, field_attributes::ENUM_MEMBER, literal.clone()) + .with_constant(Constant::I4(value)), + ) + .unwrap(); + } +} + +/// Emits, re-parses and fully validates an assembly. Every test funnels its +/// output through here, so L0 runs on all of them. +pub(crate) fn emit_and_verify(builder: &AssemblyBuilder) -> (Vec, Parsed) { + let bytes = builder.build().expect("the fixture must build"); + let parsed = parse(&bytes).expect("emitted bytes must re-parse"); + parsed + .check_references() + .expect("every reference must resolve"); + (bytes, parsed) +} diff --git a/crates/modrix-ecma335/src/tests/mod.rs b/crates/modrix-ecma335/src/tests/mod.rs new file mode 100644 index 0000000..c1572d4 --- /dev/null +++ b/crates/modrix-ecma335/src/tests/mod.rs @@ -0,0 +1,19 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Validation, layered from cheapest to most authoritative. +//! +//! * [`widths`] pins the coded-index threshold arithmetic directly. It is the +//! only check that cannot be fooled by the writer and the reader sharing a +//! wrong assumption. +//! * [`roundtrip`] (L0) re-parses emitted bytes and proves every reference +//! resolves. +//! * [`scale`] (L1) drives the row counts across the 16 384-row `TypeDefOrRef` +//! boundary and past a 64 KB `#Strings` heap, where a wrong width stops +//! being theoretical. +//! * [`csc`] (L3) is the real oracle: it compiles C# against the emitted DLL +//! with the actual Roslyn compiler from the .NET SDK. + +mod csc; +mod fixtures; +mod roundtrip; +mod scale; +mod widths; diff --git a/crates/modrix-ecma335/src/tests/roundtrip.rs b/crates/modrix-ecma335/src/tests/roundtrip.rs new file mode 100644 index 0000000..8c075d3 --- /dev/null +++ b/crates/modrix-ecma335/src/tests/roundtrip.rs @@ -0,0 +1,450 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! L0: emit, re-parse, and prove every row and reference survived. + +use super::fixtures::{add_corlib, box_of, emit_and_verify, full_surface, full_surface_marked}; +use crate::builder::AssemblyBuilder; +use crate::handles::{HasCustomAttribute, TypeDefOrRef}; +use crate::model::{ + CORE_LIBRARY_NAME, CORE_LIBRARY_PUBLIC_KEY_TOKEN, Constant, Field, Method, TypeDefinition, + Version, field_attributes, method_attributes, type_attributes, +}; +use crate::signature::{MethodSignature, Type}; +use crate::tables::table; + +#[test] +fn the_full_surface_assembly_round_trips() { + let (bytes, parsed) = emit_and_verify(&full_surface()); + assert_eq!(bytes.get(..2), Some(b"MZ".as_slice())); + // Seven types: , IThing, Box`1, Widget, Inner, Point, Color. + assert_eq!(parsed.counts.get(table::TYPE_DEF), 7); + assert_eq!( + parsed.type_def_name(1).unwrap(), + (String::new(), "".to_owned()) + ); + assert_eq!( + parsed.type_def_name(2).unwrap(), + ("MyLib".to_owned(), "IThing".to_owned()) + ); + assert_eq!( + parsed.type_def_name(7).unwrap(), + ("MyLib".to_owned(), "Color".to_owned()) + ); +} + +#[test] +fn all_five_streams_are_present_in_roslyns_order() { + let (_, parsed) = emit_and_verify(&full_surface()); + assert_eq!( + parsed.stream_names, + vec!["#~", "#Strings", "#US", "#GUID", "#Blob"] + ); +} + +/// The metadata root's `Length` field is read as `16 + Length` to find the +/// stream headers, so an unpadded 11 makes Roslyn abort with CS0009. +#[test] +fn the_metadata_version_length_is_a_multiple_of_four() { + let (_, parsed) = emit_and_verify(&full_surface()); + assert_eq!(parsed.version_length % 4, 0); + assert_eq!(parsed.version_length, 12); +} + +#[test] +fn the_assembly_row_and_corlib_reference_are_exactly_right() { + let (_, parsed) = emit_and_verify(&full_surface()); + assert_eq!(parsed.counts.get(table::ASSEMBLY), 1); + let assembly = parsed.tables.assembly.first().copied().unwrap(); + assert_eq!(parsed.string(assembly.name).unwrap(), "MyLib"); + assert_eq!(assembly.version, [1, 0, 0, 0]); + + assert_eq!( + parsed.assembly_ref_names().unwrap(), + vec![CORE_LIBRARY_NAME] + ); + let reference = parsed.tables.assembly_refs.first().copied().unwrap(); + assert_eq!(reference.version, [9, 0, 0, 0]); + assert_eq!( + parsed.blob(reference.public_key_or_token).unwrap(), + CORE_LIBRARY_PUBLIC_KEY_TOKEN.to_vec() + ); +} + +/// Enum literals without a `Constant` row make the *consumer* fail with a bare +/// CS7038, so the writer refuses to emit one. +#[test] +fn enum_literals_get_constant_rows() { + let (_, parsed) = emit_and_verify(&full_surface()); + assert_eq!(parsed.counts.get(table::CONSTANT), 2); + let values: Vec> = parsed + .tables + .constants + .iter() + .map(|row| parsed.blob(row.value).unwrap()) + .collect(); + assert!(values.contains(&vec![0, 0, 0, 0])); + assert!(values.contains(&vec![1, 0, 0, 0])); + assert!( + parsed.tables.constants.windows(2).all(|pair| { + pair.first().map(|row| row.parent) <= pair.get(1).map(|row| row.parent) + }) + ); +} + +#[test] +fn a_literal_field_without_a_constant_is_refused() { + let mut builder = AssemblyBuilder::new("Bad", Version::new(1, 0, 0, 0)); + let corlib = add_corlib(&mut builder); + let color = builder + .add_type_def(TypeDefinition::new( + "Bad", + "Color", + type_attributes::PUBLIC_VALUE_TYPE, + Some(corlib.enumeration.into()), + )) + .unwrap(); + builder + .add_field( + color, + Field::new("value__", field_attributes::ENUM_BACKING, Type::I4), + ) + .unwrap(); + builder + .add_field( + color, + Field::new( + "Red", + field_attributes::ENUM_MEMBER, + Type::ValueType(TypeDefOrRef::Definition(color)), + ), + ) + .unwrap(); + assert!(matches!( + builder.build(), + Err(crate::Error::LiteralWithoutConstant { .. }) + )); +} + +/// Member runs are the invariant that makes `(type, slot)` handles safe: each +/// type's start must be where the previous type's run ended. +#[test] +fn member_runs_are_contiguous_and_in_type_order() { + let (_, parsed) = emit_and_verify(&full_surface()); + let starts: Vec = parsed + .tables + .type_defs + .iter() + .map(|row| row.field_list) + .collect(); + // owns nothing, IThing owns nothing, Box owns one field. + assert_eq!(starts.first().copied(), Some(1)); + assert_eq!(starts.get(1).copied(), Some(1)); + assert_eq!(starts.get(2).copied(), Some(1)); + assert_eq!(starts.get(3).copied(), Some(2)); + let last = starts.last().copied().unwrap(); + assert!(last <= parsed.counts.get(table::FIELD).saturating_add(1)); +} + +#[test] +fn nested_types_carry_no_namespace_and_get_a_nested_class_row() { + let (_, parsed) = emit_and_verify(&full_surface()); + assert_eq!(parsed.counts.get(table::NESTED_CLASS), 1); + let nested = parsed.tables.nested_classes.first().copied().unwrap(); + let (namespace, name) = parsed.type_def_name(nested.nested).unwrap(); + assert_eq!(name, "Inner"); + assert!(namespace.is_empty(), "expected empty, got {namespace:?}"); + let (_, enclosing) = parsed.type_def_name(nested.enclosing).unwrap(); + assert_eq!(enclosing, "Widget"); +} + +#[test] +fn a_nested_type_with_a_namespace_is_refused() { + let mut builder = AssemblyBuilder::new("Bad", Version::new(1, 0, 0, 0)); + let corlib = add_corlib(&mut builder); + let outer = builder + .add_type_def(TypeDefinition::new( + "Bad", + "Outer", + type_attributes::PUBLIC_CLASS, + Some(corlib.object.into()), + )) + .unwrap(); + let mut inner = TypeDefinition::new( + "Bad", + "Inner", + type_attributes::NESTED_PUBLIC, + Some(corlib.object.into()), + ); + inner.enclosing = Some(outer); + assert!(matches!( + builder.add_type_def(inner), + Err(crate::Error::NestedTypeHasNamespace { .. }) + )); +} + +#[test] +fn generic_parameters_land_on_both_types_and_methods() { + let (_, parsed) = emit_and_verify(&full_surface()); + // One on Box`1, one on Widget.Swap. + assert_eq!(parsed.counts.get(table::GENERIC_PARAM), 2); + for row in &parsed.tables.generic_params { + assert_eq!(parsed.string(row.name).unwrap(), "T"); + assert_eq!(row.number, 0); + } +} + +#[test] +fn properties_produce_a_map_and_two_semantics_rows() { + let (_, parsed) = emit_and_verify(&full_surface()); + assert_eq!(parsed.counts.get(table::PROPERTY_MAP), 1); + assert_eq!(parsed.counts.get(table::PROPERTY), 1); + assert_eq!(parsed.counts.get(table::METHOD_SEMANTICS), 2); + let property = parsed.tables.properties.first().copied().unwrap(); + assert_eq!(parsed.string(property.name).unwrap(), "Count"); + // PROPERTY | HASTHIS, zero index parameters, ELEMENT_TYPE_I4. + assert_eq!( + parsed.blob(property.signature).unwrap(), + vec![0x28, 0x00, 0x08] + ); +} + +/// A `GENERICINST` inside a field signature needs no `TypeSpec` row; the +/// fixture uses `Box` as a field type and emits zero of them. +#[test] +fn generic_instances_in_signatures_need_no_type_spec() { + let (_, parsed) = emit_and_verify(&full_surface()); + assert_eq!(parsed.counts.get(table::TYPE_SPEC), 0); + let signatures: Vec> = parsed + .tables + .fields + .iter() + .map(|row| parsed.blob(row.signature).unwrap()) + .collect(); + // FIELD, GENERICINST, CLASS, TypeDefOrRef(Box`1 == row 3 -> 12), 1 arg, I4. + assert!(signatures.contains(&vec![0x06, 0x15, 0x12, 0x0C, 0x01, 0x08])); + // FIELD, SZARRAY, STRING. + assert!(signatures.contains(&vec![0x06, 0x1D, 0x0E])); +} + +#[test] +fn method_signatures_match_the_hand_worked_encodings() { + let (_, parsed) = emit_and_verify(&full_surface()); + let blobs: Vec> = parsed + .tables + .methods + .iter() + .map(|row| parsed.blob(row.signature).unwrap()) + .collect(); + // instance void .ctor() + assert!(blobs.contains(&vec![0x20, 0x00, 0x01])); + // static int32 Add(int32, int32) + assert!(blobs.contains(&vec![0x00, 0x02, 0x08, 0x08, 0x08])); + // static void Swap(!!0&, !!0&) + assert!(blobs.contains(&vec![ + 0x10, 0x01, 0x02, 0x01, 0x10, 0x1E, 0x00, 0x10, 0x1E, 0x00 + ])); +} + +#[test] +fn the_reference_assembly_markers_round_trip() { + let (_, parsed) = emit_and_verify(&full_surface_marked()); + assert_eq!(parsed.counts.get(table::CUSTOM_ATTRIBUTE), 2); + assert_eq!(parsed.counts.get(table::MEMBER_REF), 2); + let values: Vec> = parsed + .tables + .custom_attributes + .iter() + .map(|row| parsed.blob(row.value).unwrap()) + .collect(); + assert!(values.contains(&vec![0x01, 0x00, 0x00, 0x00])); + assert!(values.iter().any(|value| value.len() > 4)); +} + +#[test] +fn output_is_byte_for_byte_reproducible() { + let builder = full_surface(); + assert_eq!(builder.build().unwrap(), builder.build().unwrap()); + assert_eq!(full_surface().build().unwrap(), builder.build().unwrap()); +} + +#[test] +fn a_custom_attribute_on_a_member_resolves() { + let mut builder = AssemblyBuilder::new("Attrs", Version::new(1, 0, 0, 0)); + let corlib = add_corlib(&mut builder); + let holder = builder + .add_type_def(TypeDefinition::new( + "Attrs", + "Holder", + type_attributes::PUBLIC_CLASS, + Some(corlib.object.into()), + )) + .unwrap(); + let ctor = builder.add_default_constructor(holder).unwrap(); + let field = builder + .add_field( + holder, + Field::new("Value", field_attributes::PUBLIC, Type::I4), + ) + .unwrap(); + builder + .add_custom_attribute( + HasCustomAttribute::Field(field), + crate::handles::CustomAttributeType::MethodDef(ctor), + crate::builder::attribute_blob_empty(), + ) + .unwrap(); + let (_, parsed) = emit_and_verify(&builder); + assert_eq!(parsed.counts.get(table::CUSTOM_ATTRIBUTE), 1); +} + +/// Signature coverage for the element types the fixture does not reach. +#[test] +fn the_remaining_element_types_encode_and_survive() { + let mut builder = AssemblyBuilder::new("Wide", Version::new(1, 0, 0, 0)); + let corlib = add_corlib(&mut builder); + let holder = builder + .add_type_def( + TypeDefinition::new( + "Wide", + "Holder`1", + type_attributes::PUBLIC_CLASS, + Some(corlib.object.into()), + ) + .with_generic_parameter(crate::model::GenericParameter::new("T")), + ) + .unwrap(); + for (name, field_type) in exotic_field_types(holder) { + builder + .add_field( + holder, + Field::new(name, field_attributes::PUBLIC, field_type), + ) + .unwrap(); + } + builder + .add_method( + holder, + Method::new( + "Roundtrip", + method_attributes::PUBLIC_STATIC, + MethodSignature::static_method(Type::TypedByRef, vec![Type::Void.pointer()]), + ), + ) + .unwrap(); + let (_, parsed) = emit_and_verify(&builder); + assert_eq!(parsed.counts.get(table::FIELD), 20); +} + +fn exotic_field_types(holder: crate::handles::TypeDefId) -> Vec<(&'static str, Type)> { + vec![ + ("Bool", Type::Boolean), + ("Char", Type::Char), + ("SByte", Type::I1), + ("Byte", Type::U1), + ("Short", Type::I2), + ("UShort", Type::U2), + ("Int", Type::I4), + ("UInt", Type::U4), + ("Long", Type::I8), + ("ULong", Type::U8), + ("Float", Type::R4), + ("Double", Type::R8), + ("Str", Type::String), + ("Obj", Type::Object), + ("NInt", Type::IntPtr), + ("NUInt", Type::UIntPtr), + ("Ptr", Type::I4.pointer()), + ("Vector", Type::I4.array()), + ("Var", Type::TypeParameter(0)), + ("Nested", box_of(holder, Type::String).array()), + ] +} + +#[test] +fn multi_dimensional_arrays_encode_their_shape() { + let mut blob = Vec::new(); + Type::Array { + element: Box::new(Type::I4), + rank: 2, + sizes: vec![3, 4], + lower_bounds: vec![-1, 0], + } + .encode(&mut blob) + .unwrap(); + // ARRAY, I4, rank 2, 2 sizes {3,4}, 2 lower bounds {-1, 0}. The bounds are + // compressed *signed*: -1 rotates its sign bit into bit 0, giving 0x7F. + assert_eq!( + blob, + vec![0x14, 0x08, 0x02, 0x02, 0x03, 0x04, 0x02, 0x7F, 0x00] + ); +} + +#[test] +fn custom_modifiers_wrap_the_type_they_modify() { + let mut blob = Vec::new(); + Type::RequiredModifier( + TypeDefOrRef::Definition(crate::handles::TypeDefId::MODULE), + Box::new(Type::I4), + ) + .encode(&mut blob) + .unwrap(); + // CMOD_REQD, TypeDefOrRef(TypeDef row 1 -> 4), I4. + assert_eq!(blob, vec![0x1F, 0x04, 0x08]); +} + +#[test] +fn deeply_nested_types_are_rejected_rather_than_overflowing_the_stack() { + let mut deep = Type::I4; + for _ in 0..(crate::signature::MAX_TYPE_DEPTH.saturating_add(2)) { + deep = deep.array(); + } + let mut blob = Vec::new(); + assert!(matches!( + deep.encode(&mut blob), + Err(crate::Error::TypeTooDeep { .. }) + )); +} + +#[test] +fn every_constant_kind_encodes() { + let kinds = [ + Constant::Boolean(true), + Constant::Char(0x0078), + Constant::I1(-1), + Constant::U1(2), + Constant::I2(-3), + Constant::U2(4), + Constant::I4(-5), + Constant::U4(6), + Constant::I8(-7), + Constant::U8(8), + Constant::R4(1.5), + Constant::R8(2.5), + Constant::String("hi".to_owned()), + Constant::NullReference, + ]; + let mut builder = AssemblyBuilder::new("Consts", Version::new(1, 0, 0, 0)); + let corlib = add_corlib(&mut builder); + let holder = builder + .add_type_def(TypeDefinition::new( + "Consts", + "Holder", + type_attributes::PUBLIC_CLASS, + Some(corlib.object.into()), + )) + .unwrap(); + for (index, constant) in kinds.into_iter().enumerate() { + builder + .add_field( + holder, + Field::new( + format!("F{index}"), + field_attributes::PUBLIC | field_attributes::STATIC, + Type::I4, + ) + .with_constant(constant), + ) + .unwrap(); + } + let (_, parsed) = emit_and_verify(&builder); + assert_eq!(parsed.counts.get(table::CONSTANT), 14); +} diff --git a/crates/modrix-ecma335/src/tests/scale.rs b/crates/modrix-ecma335/src/tests/scale.rs new file mode 100644 index 0000000..660a9c9 --- /dev/null +++ b/crates/modrix-ecma335/src/tests/scale.rs @@ -0,0 +1,143 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! L1: synthetic assemblies sized to sit exactly on the width thresholds. +//! +//! 16 384 `TypeDef` rows is where `TypeDefOrRef` stops fitting in two bytes. +//! Below it nothing in this crate ever exercises a 4-byte coded index; above +//! it, every row of every table shifts. A writer with the `1 << 16` bug +//! produces a perfectly plausible file at 16 383 types and garbage at 16 384, +//! which is why the boundary is walked one row at a time. + +use super::fixtures::{add_corlib_targeting, emit_and_verify}; +use crate::builder::AssemblyBuilder; +use crate::handles::TypeRefId; +use crate::model::{ + Field, Method, TypeDefinition, Version, field_attributes, method_attributes, type_attributes, +}; +use crate::signature::{MethodSignature, Type}; +use crate::tables::{RowCounts, TYPE_DEF_OR_REF, table}; + +/// Builds an assembly with exactly `total` `TypeDef` rows, `` +/// included, each type carrying one field, a constructor and one method. +pub(crate) fn synthetic(total: u32, name_padding: usize) -> AssemblyBuilder { + synthetic_targeting(total, name_padding, 9) +} + +/// The same, bound to a specific .NET major version for the csc oracle. +pub(crate) fn synthetic_targeting(total: u32, name_padding: usize, major: u16) -> AssemblyBuilder { + let mut builder = AssemblyBuilder::new("Scale", Version::new(1, 0, 0, 0)); + let corlib = add_corlib_targeting(&mut builder, major); + let pad = "P".repeat(name_padding); + for index in 0..total.saturating_sub(1) { + add_synthetic_type(&mut builder, corlib.object, index, &pad); + } + builder +} + +fn add_synthetic_type(builder: &mut AssemblyBuilder, object: TypeRefId, index: u32, pad: &str) { + let type_id = builder + .add_type_def(TypeDefinition::new( + "Bulk", + format!("T{index:06}{pad}"), + type_attributes::PUBLIC_CLASS, + Some(object.into()), + )) + .unwrap(); + builder + .add_field( + type_id, + Field::new( + format!("F{index:06}{pad}"), + field_attributes::PUBLIC, + Type::I4, + ), + ) + .unwrap(); + builder.add_default_constructor(type_id).unwrap(); + builder + .add_method( + type_id, + Method::new( + format!("M{index:06}{pad}"), + method_attributes::PUBLIC_INSTANCE, + MethodSignature::instance_method(Type::Void, Vec::new()), + ), + ) + .unwrap(); +} + +/// Asserts that the first and the last user type survived the round trip, and +/// returns the parsed image so callers can check widths. +fn check_scale(total: u32, name_padding: usize) -> crate::verify::Parsed { + let (_, parsed) = emit_and_verify(&synthetic(total, name_padding)); + assert_eq!(parsed.counts.get(table::TYPE_DEF), total); + let pad = "P".repeat(name_padding); + let (namespace, first) = parsed.type_def_name(2).unwrap(); + assert_eq!(namespace, "Bulk"); + assert_eq!(first, format!("T{:06}{pad}", 0)); + let (_, last) = parsed.type_def_name(total).unwrap(); + assert_eq!(last, format!("T{:06}{pad}", total.saturating_sub(2))); + parsed +} + +/// What width the reader had to use for `TypeDefOrRef` in a parsed image. +fn type_def_or_ref_width(parsed: &crate::verify::Parsed) -> u8 { + let mut counts = RowCounts::default(); + counts.set(table::TYPE_DEF, parsed.counts.get(table::TYPE_DEF)); + counts.set(table::TYPE_REF, parsed.counts.get(table::TYPE_REF)); + counts.set(table::TYPE_SPEC, parsed.counts.get(table::TYPE_SPEC)); + counts.coded_width(TYPE_DEF_OR_REF) +} + +#[test] +fn a_single_type_assembly_round_trips() { + let parsed = check_scale(2, 0); + assert_eq!(parsed.counts.get(table::FIELD), 1); + assert_eq!(parsed.counts.get(table::METHOD_DEF), 2); +} + +#[test] +fn just_below_the_coded_index_threshold() { + let parsed = check_scale(16_383, 0); + assert_eq!(type_def_or_ref_width(&parsed), 2); +} + +#[test] +fn exactly_at_the_coded_index_threshold() { + let parsed = check_scale(16_384, 0); + assert_eq!(type_def_or_ref_width(&parsed), 4); +} + +#[test] +fn just_above_the_coded_index_threshold() { + let parsed = check_scale(16_385, 0); + assert_eq!(type_def_or_ref_width(&parsed), 4); +} + +#[test] +fn well_past_the_coded_index_threshold() { + let parsed = check_scale(20_007, 0); + assert_eq!(type_def_or_ref_width(&parsed), 4); + assert_eq!(parsed.counts.get(table::FIELD), 20_006); + assert_eq!(parsed.counts.get(table::METHOD_DEF), 40_012); +} + +/// A `#Strings` heap over 64 KB sets `HeapSizes` bit 0x01 and turns every +/// string column into a 4-byte index. The padding here forces that at a type +/// count far below the coded-index threshold, so the two effects are separable. +#[test] +fn a_large_string_heap_widens_string_indices() { + let small = check_scale(64, 0); + assert_eq!(small.heap_sizes & 0x01, 0); + + let large = check_scale(600, 40); + assert_eq!( + large.heap_sizes & 0x01, + 0x01, + "a #Strings heap of {} bytes must set HeapSizes bit 0x01", + large.strings.len() + ); + assert!(large.strings.len() >= (1 << 16)); + // Only the string bit flips: the heap is large, the tables are not. + assert_eq!(large.heap_sizes & 0x04, 0); + assert_eq!(type_def_or_ref_width(&large), 2); +} diff --git a/crates/modrix-ecma335/src/tests/widths.rs b/crates/modrix-ecma335/src/tests/widths.rs new file mode 100644 index 0000000..b767e61 --- /dev/null +++ b/crates/modrix-ecma335/src/tests/widths.rs @@ -0,0 +1,113 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Direct tests on the column-width arithmetic. +//! +//! Everything else in this crate agrees with itself by construction: the +//! writer and the round-trip reader both call [`RowCounts::coded_width`], so a +//! wrong threshold would produce a file that reads back perfectly and is still +//! unreadable by Roslyn. These assertions pin the threshold to hard-coded +//! numbers taken from the spec, with no shared helper in the loop. + +use crate::tables::{ + ALL_CODED_INDICES, CUSTOM_ATTRIBUTE_TYPE, HAS_CONSTANT, HAS_CUSTOM_ATTRIBUTE, HAS_SEMANTICS, + MEMBER_REF_PARENT, RESOLUTION_SCOPE, RowCounts, TYPE_DEF_OR_REF, TYPE_OR_METHOD_DEF, table, +}; + +#[test] +fn thresholds_are_two_to_the_sixteen_minus_tag_bits() { + assert_eq!(TYPE_DEF_OR_REF.threshold(), 16_384); + assert_eq!(HAS_CONSTANT.threshold(), 16_384); + assert_eq!(RESOLUTION_SCOPE.threshold(), 16_384); + assert_eq!(MEMBER_REF_PARENT.threshold(), 8_192); + assert_eq!(CUSTOM_ATTRIBUTE_TYPE.threshold(), 8_192); + assert_eq!(HAS_CUSTOM_ATTRIBUTE.threshold(), 2_048); + assert_eq!(HAS_SEMANTICS.threshold(), 32_768); + assert_eq!(TYPE_OR_METHOD_DEF.threshold(), 32_768); +} + +/// The whole point: 65 536 is the threshold for a *simple* index. Using it for +/// a coded index leaves `TypeDefOrRef` two bytes wide for four times too long. +#[test] +fn no_coded_family_widens_at_the_simple_index_threshold() { + for family in ALL_CODED_INDICES { + assert!( + family.threshold() < (1 << 16), + "{} must widen before 65536", + family.name + ); + } +} + +#[test] +fn every_family_flips_exactly_at_its_threshold() { + for family in ALL_CODED_INDICES { + let threshold = family.threshold(); + for target in family.tags.iter().flatten() { + let mut counts = RowCounts::default(); + + counts.set(*target, threshold.saturating_sub(1)); + assert_eq!( + counts.coded_width(family), + 2, + "{} at {} rows of table 0x{target:02X}", + family.name, + threshold.saturating_sub(1) + ); + + counts.set(*target, threshold); + assert_eq!( + counts.coded_width(family), + 4, + "{} at {threshold} rows of table 0x{target:02X}", + family.name + ); + + counts.set(*target, threshold.saturating_add(1)); + assert_eq!( + counts.coded_width(family), + 4, + "{} at {} rows of table 0x{target:02X}", + family.name, + threshold.saturating_add(1) + ); + } + } +} + +#[test] +fn simple_indices_flip_at_sixty_five_thousand_five_hundred_and_thirty_six() { + let mut counts = RowCounts::default(); + counts.set(table::FIELD, 65_535); + assert_eq!(counts.simple_width(table::FIELD), 2); + counts.set(table::FIELD, 65_536); + assert_eq!(counts.simple_width(table::FIELD), 4); + counts.set(table::FIELD, 65_537); + assert_eq!(counts.simple_width(table::FIELD), 4); +} + +/// A family widens when *any* of its member tables crosses, not only the one +/// a particular row happens to point at. +#[test] +fn a_family_widens_from_any_member_table() { + let mut counts = RowCounts::default(); + counts.set(table::TYPE_SPEC, TYPE_DEF_OR_REF.threshold()); + assert_eq!(counts.coded_width(TYPE_DEF_OR_REF), 4); + assert_eq!(counts.coded_width(HAS_CONSTANT), 2); +} + +#[test] +fn encode_and_decode_are_inverse() { + for family in ALL_CODED_INDICES { + for target in family.tags.iter().flatten() { + for row in [1_u32, 2, 4095, 16_383, 16_384, 1_000_000] { + let encoded = family.encode(*target, row).unwrap(); + assert_eq!(family.decode(encoded), Some((*target, row))); + } + } + } +} + +#[test] +fn encode_rejects_a_table_outside_the_family() { + assert!(TYPE_DEF_OR_REF.encode(table::ASSEMBLY_REF, 1).is_err()); + assert!(CUSTOM_ATTRIBUTE_TYPE.encode(table::TYPE_DEF, 1).is_err()); +} diff --git a/crates/modrix-ecma335/src/verify.rs b/crates/modrix-ecma335/src/verify.rs new file mode 100644 index 0000000..fa6eff7 --- /dev/null +++ b/crates/modrix-ecma335/src/verify.rs @@ -0,0 +1,857 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! A test-only reader that parses this crate's own output back into rows. +//! +//! This exists because ECMA-335 metadata has essentially no redundancy: a +//! wrong column width or a dangling index produces a file that is *structurally +//! plausible* and silently wrong. Re-parsing the bytes with an independent +//! walker and then proving that every coded index lands on a present, in-range +//! row is the cheapest way to catch that class of bug without a .NET toolchain +//! in the loop. +//! +//! It deliberately shares only the row *structs* with the writer, never the +//! code that fills them in. + +use crate::rows::{ + AssemblyRefRow, AssemblyRow, ConstantRow, CustomAttributeRow, FieldRow, GenericParamRow, + InterfaceImplRow, MemberRefRow, MethodDefRow, MethodSemanticsRow, ModuleRow, NestedClassRow, + ParamRow, PropertyMapRow, PropertyRow, TableSet, TypeDefRow, TypeRefRow, TypeSpecRow, +}; +use crate::tables::{ + CUSTOM_ATTRIBUTE_TYPE, CodedIndex, EMITTED_TABLES, HAS_CONSTANT, HAS_CUSTOM_ATTRIBUTE, + HAS_SEMANTICS, MEMBER_REF_PARENT, RESOLUTION_SCOPE, RowCounts, TYPE_DEF_OR_REF, + TYPE_OR_METHOD_DEF, Widths, table, +}; + +/// Reader result; the message is a human-readable failure for a test to print. +pub(crate) type VResult = core::result::Result; + +/// A byte cursor that never indexes and never panics. +struct Cursor<'a> { + data: &'a [u8], + position: usize, +} + +impl<'a> Cursor<'a> { + fn new(data: &'a [u8]) -> Self { + Self { data, position: 0 } + } + + fn seek(&mut self, position: usize) -> VResult<()> { + if position > self.data.len() { + return Err(format!( + "seek to {position} past end of {} bytes", + self.data.len() + )); + } + self.position = position; + Ok(()) + } + + fn take(&mut self, count: usize) -> VResult<&'a [u8]> { + let end = self + .position + .checked_add(count) + .ok_or_else(|| "cursor overflow".to_owned())?; + let slice = self + .data + .get(self.position..end) + .ok_or_else(|| format!("read of {count} bytes at {} ran past end", self.position))?; + self.position = end; + Ok(slice) + } + + fn u8(&mut self) -> VResult { + Ok(u8::from_le_bytes(read_array::<1>(self.take(1)?)?)) + } + + fn u16(&mut self) -> VResult { + Ok(u16::from_le_bytes(read_array::<2>(self.take(2)?)?)) + } + + fn u32(&mut self) -> VResult { + Ok(u32::from_le_bytes(read_array::<4>(self.take(4)?)?)) + } + + fn u64(&mut self) -> VResult { + Ok(u64::from_le_bytes(read_array::<8>(self.take(8)?)?)) + } + + fn index(&mut self, width: u8) -> VResult { + if width == 2 { + Ok(u32::from(self.u16()?)) + } else { + self.u32() + } + } + + fn skip(&mut self, count: usize) -> VResult<()> { + self.take(count).map(|_| ()) + } +} + +fn read_array(slice: &[u8]) -> VResult<[u8; N]> { + <[u8; N]>::try_from(slice).map_err(|_| format!("expected {N} bytes, found {}", slice.len())) +} + +/// Everything the reader recovered from an emitted assembly. +pub(crate) struct Parsed { + pub(crate) heap_sizes: u8, + pub(crate) counts: RowCounts, + pub(crate) tables: TableSet, + pub(crate) strings: Vec, + pub(crate) blobs: Vec, + pub(crate) guids: Vec, + pub(crate) version_length: u32, + pub(crate) stream_names: Vec, +} + +impl Parsed { + /// Resolves a `#Strings` offset. + pub(crate) fn string(&self, offset: u32) -> VResult { + let start = usize::try_from(offset).map_err(|_| "string offset overflow".to_owned())?; + let tail = self + .strings + .get(start..) + .ok_or_else(|| format!("#Strings offset {offset} is past the heap"))?; + let end = tail + .iter() + .position(|byte| *byte == 0) + .ok_or_else(|| format!("#Strings entry at {offset} is not NUL-terminated"))?; + let bytes = tail + .get(..end) + .ok_or_else(|| "string slice vanished".to_owned())?; + String::from_utf8(bytes.to_vec()).map_err(|error| format!("#Strings not UTF-8: {error}")) + } + + /// Resolves a `#Blob` offset, skipping its compressed length prefix. + pub(crate) fn blob(&self, offset: u32) -> VResult> { + let start = usize::try_from(offset).map_err(|_| "blob offset overflow".to_owned())?; + let tail = self + .blobs + .get(start..) + .ok_or_else(|| format!("#Blob offset {offset} is past the heap"))?; + let (length, header) = decompress(tail)?; + let from = header; + let to = from + .checked_add(usize::try_from(length).map_err(|_| "blob length overflow".to_owned())?) + .ok_or_else(|| "blob length overflow".to_owned())?; + Ok(tail + .get(from..to) + .ok_or_else(|| format!("#Blob entry at {offset} runs past the heap"))? + .to_vec()) + } + + /// The namespace and name of a 1-based `TypeDef` row. + pub(crate) fn type_def_name(&self, row: u32) -> VResult<(String, String)> { + let index = + usize::try_from(row.saturating_sub(1)).map_err(|_| "type row overflow".to_owned())?; + let entry = self + .tables + .type_defs + .get(index) + .ok_or_else(|| format!("TypeDef row {row} does not exist"))?; + Ok((self.string(entry.namespace)?, self.string(entry.name)?)) + } + + /// How many GUIDs the `#GUID` heap holds. + pub(crate) fn guid_count(&self) -> u32 { + u32::try_from(self.guids.len().checked_div(16).unwrap_or(0)).unwrap_or(u32::MAX) + } +} + +/// Reads a compressed unsigned integer, returning `(value, bytes consumed)`. +fn decompress(data: &[u8]) -> VResult<(u32, usize)> { + let first = *data + .first() + .ok_or_else(|| "compressed integer is empty".to_owned())?; + if first & 0x80 == 0 { + return Ok((u32::from(first), 1)); + } + if first & 0x40 == 0 { + let second = *data + .get(1) + .ok_or_else(|| "truncated 2-byte compressed integer".to_owned())?; + return Ok(((u32::from(first & 0x3F) << 8) | u32::from(second), 2)); + } + let bytes = data + .get(..4) + .ok_or_else(|| "truncated 4-byte compressed integer".to_owned())?; + let mut value = u32::from(first & 0x1F); + for byte in bytes.iter().skip(1) { + value = (value << 8) | u32::from(*byte); + } + Ok((value, 4)) +} + +/// Parses a finished reference assembly. +pub(crate) fn parse(image: &[u8]) -> VResult { + let metadata = locate_metadata(image)?; + parse_metadata(&metadata) +} + +/// Walks the PE container to the metadata root and returns just that blob. +fn locate_metadata(image: &[u8]) -> VResult> { + let mut cursor = Cursor::new(image); + if cursor.take(2)? != b"MZ" { + return Err("missing MZ signature".to_owned()); + } + cursor.seek(0x3C)?; + let pe_offset = usize::try_from(cursor.u32()?).map_err(|_| "e_lfanew overflow".to_owned())?; + cursor.seek(pe_offset)?; + if cursor.take(4)? != b"PE\0\0" { + return Err("missing PE signature".to_owned()); + } + cursor.skip(2)?; + let section_count = cursor.u16()?; + cursor.skip(12)?; + let optional_size = usize::from(cursor.u16()?); + cursor.skip(2)?; + let optional_start = cursor.position; + if cursor.u16()? != 0x020B { + return Err("optional header is not PE32+".to_owned()); + } + // Data directory 14 is the CLI header; it sits 112 bytes into the + // optional header, after the 24 standard and 88 Windows-specific fields. + cursor.seek( + optional_start + .checked_add(112) + .and_then(|base| base.checked_add(14usize.checked_mul(8)?)) + .ok_or_else(|| "optional header overflow".to_owned())?, + )?; + let cli_rva = cursor.u32()?; + let sections = read_sections(&mut cursor, optional_start, optional_size, section_count)?; + read_metadata_blob(image, §ions, cli_rva) +} + +/// A `.text`-style section, reduced to what RVA translation needs. +struct Section { + virtual_address: u32, + virtual_size: u32, + raw_size: u32, + raw_pointer: u32, +} + +fn read_sections( + cursor: &mut Cursor<'_>, + optional_start: usize, + optional_size: usize, + count: u16, +) -> VResult> { + cursor.seek( + optional_start + .checked_add(optional_size) + .ok_or_else(|| "section table overflow".to_owned())?, + )?; + let mut sections = Vec::new(); + for _ in 0..count { + cursor.skip(8)?; + let virtual_size = cursor.u32()?; + let virtual_address = cursor.u32()?; + let raw_size = cursor.u32()?; + let raw_pointer = cursor.u32()?; + cursor.skip(16)?; + sections.push(Section { + virtual_address, + virtual_size, + raw_size, + raw_pointer, + }); + } + Ok(sections) +} + +fn rva_to_offset(sections: &[Section], rva: u32) -> VResult { + for section in sections { + let span = section.virtual_size.max(section.raw_size); + let end = section.virtual_address.saturating_add(span); + if rva >= section.virtual_address && rva < end { + let delta = rva.saturating_sub(section.virtual_address); + return usize::try_from(section.raw_pointer.saturating_add(delta)) + .map_err(|_| "file offset overflow".to_owned()); + } + } + Err(format!("RVA 0x{rva:08X} is in no section")) +} + +fn read_metadata_blob(image: &[u8], sections: &[Section], cli_rva: u32) -> VResult> { + let mut cursor = Cursor::new(image); + cursor.seek(rva_to_offset(sections, cli_rva)?)?; + if cursor.u32()? != 72 { + return Err("CLI header size is not 72".to_owned()); + } + cursor.skip(4)?; + let metadata_rva = cursor.u32()?; + let metadata_size = + usize::try_from(cursor.u32()?).map_err(|_| "metadata size overflow".to_owned())?; + cursor.seek(rva_to_offset(sections, metadata_rva)?)?; + Ok(cursor.take(metadata_size)?.to_vec()) +} + +fn parse_metadata(metadata: &[u8]) -> VResult { + let mut cursor = Cursor::new(metadata); + if cursor.u32()? != crate::metadata::SIGNATURE { + return Err("metadata root is not BSJB".to_owned()); + } + cursor.skip(4)?; + cursor.skip(4)?; + let version_length = cursor.u32()?; + if !version_length.is_multiple_of(4) { + return Err(format!( + "metadata version length {version_length} is not a multiple of 4" + )); + } + cursor.skip(usize::try_from(version_length).map_err(|_| "version overflow".to_owned())?)?; + cursor.skip(2)?; + let stream_count = cursor.u16()?; + let mut streams = Vec::new(); + for _ in 0..stream_count { + streams.push(read_stream_header(&mut cursor)?); + } + let mut parsed = assemble(metadata, &streams)?; + parsed.version_length = version_length; + Ok(parsed) +} + +/// A parsed stream header: name plus the bytes it covers. +struct StreamHeader { + name: String, + offset: usize, + size: usize, +} + +fn read_stream_header(cursor: &mut Cursor<'_>) -> VResult { + let offset = usize::try_from(cursor.u32()?).map_err(|_| "stream offset overflow".to_owned())?; + let size = usize::try_from(cursor.u32()?).map_err(|_| "stream size overflow".to_owned())?; + let mut name = Vec::new(); + loop { + let byte = cursor.u8()?; + if byte == 0 { + break; + } + name.push(byte); + } + while !cursor.position.is_multiple_of(4) { + cursor.skip(1)?; + } + Ok(StreamHeader { + name: String::from_utf8(name).map_err(|error| format!("stream name: {error}"))?, + offset, + size, + }) +} + +fn slice_stream(metadata: &[u8], header: &StreamHeader) -> VResult> { + let end = header + .offset + .checked_add(header.size) + .ok_or_else(|| "stream extent overflow".to_owned())?; + Ok(metadata + .get(header.offset..end) + .ok_or_else(|| format!("stream `{}` runs past the metadata root", header.name))? + .to_vec()) +} + +fn assemble(metadata: &[u8], streams: &[StreamHeader]) -> VResult { + let named = |wanted: &str| -> VResult> { + streams + .iter() + .find(|header| header.name == wanted) + .ok_or_else(|| format!("stream `{wanted}` is missing")) + .and_then(|header| slice_stream(metadata, header)) + }; + let tables_stream = named("#~")?; + let strings = named("#Strings")?; + let blobs = named("#Blob")?; + let guids = named("#GUID")?; + named("#US")?; + let (heap_sizes, counts, tables) = parse_tables(&tables_stream)?; + Ok(Parsed { + heap_sizes, + counts, + tables, + strings, + blobs, + guids, + version_length: 0, + stream_names: streams.iter().map(|header| header.name.clone()).collect(), + }) +} + +fn parse_tables(stream: &[u8]) -> VResult<(u8, RowCounts, TableSet)> { + let mut cursor = Cursor::new(stream); + cursor.skip(4)?; + let major = cursor.u8()?; + let minor = cursor.u8()?; + if (major, minor) != (2, 0) { + return Err(format!("unexpected table schema version {major}.{minor}")); + } + let heap_sizes = cursor.u8()?; + if cursor.u8()? != 1 { + return Err("#~ reserved byte at offset 7 is not 1".to_owned()); + } + let valid = cursor.u64()?; + cursor.skip(8)?; + let mut counts = RowCounts::default(); + for table_number in 0..64_u8 { + if valid & (1_u64 << table_number) != 0 { + counts.set(table_number, cursor.u32()?); + } + } + for table_number in 0..64_u8 { + if valid & (1_u64 << table_number) != 0 && !EMITTED_TABLES.contains(&table_number) { + return Err(format!("unexpected table 0x{table_number:02X} present")); + } + } + let widths = Widths::from_heap_sizes(heap_sizes, counts); + let tables = read_all_tables(&mut cursor, counts, widths)?; + Ok((heap_sizes, counts, tables)) +} + +fn rows_of(counts: RowCounts, table_number: u8) -> usize { + usize::try_from(counts.get(table_number)).unwrap_or(0) +} + +fn read_all_tables( + cursor: &mut Cursor<'_>, + counts: RowCounts, + widths: Widths, +) -> VResult { + let mut tables = TableSet::default(); + read_core_tables(cursor, counts, widths, &mut tables)?; + read_member_tables(cursor, counts, widths, &mut tables)?; + read_tail_tables(cursor, counts, widths, &mut tables)?; + Ok(tables) +} + +fn read_core_tables( + cursor: &mut Cursor<'_>, + counts: RowCounts, + widths: Widths, + tables: &mut TableSet, +) -> VResult<()> { + for _ in 0..rows_of(counts, table::MODULE) { + tables.module.push(ModuleRow { + generation: cursor.u16()?, + name: cursor.index(widths.string)?, + mvid: cursor.index(widths.guid)?, + enc_id: cursor.index(widths.guid)?, + enc_base_id: cursor.index(widths.guid)?, + }); + } + let scope = widths.resolution_scope; + for _ in 0..rows_of(counts, table::TYPE_REF) { + tables.type_refs.push(TypeRefRow { + resolution_scope: cursor.index(scope)?, + name: cursor.index(widths.string)?, + namespace: cursor.index(widths.string)?, + }); + } + let extends = widths.type_def_or_ref; + let field = widths.field; + let method = widths.method_def; + for _ in 0..rows_of(counts, table::TYPE_DEF) { + tables.type_defs.push(TypeDefRow { + flags: cursor.u32()?, + name: cursor.index(widths.string)?, + namespace: cursor.index(widths.string)?, + extends: cursor.index(extends)?, + field_list: cursor.index(field)?, + method_list: cursor.index(method)?, + }); + } + Ok(()) +} + +fn read_member_tables( + cursor: &mut Cursor<'_>, + counts: RowCounts, + widths: Widths, + tables: &mut TableSet, +) -> VResult<()> { + for _ in 0..rows_of(counts, table::FIELD) { + tables.fields.push(FieldRow { + flags: cursor.u16()?, + name: cursor.index(widths.string)?, + signature: cursor.index(widths.blob)?, + }); + } + let param = widths.param; + for _ in 0..rows_of(counts, table::METHOD_DEF) { + tables.methods.push(MethodDefRow { + rva: cursor.u32()?, + impl_flags: cursor.u16()?, + flags: cursor.u16()?, + name: cursor.index(widths.string)?, + signature: cursor.index(widths.blob)?, + param_list: cursor.index(param)?, + }); + } + for _ in 0..rows_of(counts, table::PARAM) { + tables.params.push(ParamRow { + flags: cursor.u16()?, + sequence: cursor.u16()?, + name: cursor.index(widths.string)?, + }); + } + let class = widths.type_def; + let interface = widths.type_def_or_ref; + for _ in 0..rows_of(counts, table::INTERFACE_IMPL) { + tables.interface_impls.push(InterfaceImplRow { + class: cursor.index(class)?, + interface: cursor.index(interface)?, + }); + } + let parent = widths.member_ref_parent; + for _ in 0..rows_of(counts, table::MEMBER_REF) { + tables.member_refs.push(MemberRefRow { + class: cursor.index(parent)?, + name: cursor.index(widths.string)?, + signature: cursor.index(widths.blob)?, + }); + } + Ok(()) +} + +fn read_tail_tables( + cursor: &mut Cursor<'_>, + counts: RowCounts, + widths: Widths, + tables: &mut TableSet, +) -> VResult<()> { + let constant_parent = widths.has_constant; + for _ in 0..rows_of(counts, table::CONSTANT) { + let kind = cursor.u8()?; + cursor.skip(1)?; + tables.constants.push(ConstantRow { + kind, + parent: cursor.index(constant_parent)?, + value: cursor.index(widths.blob)?, + }); + } + let attribute_parent = widths.has_custom_attribute; + let constructor = widths.custom_attribute_type; + for _ in 0..rows_of(counts, table::CUSTOM_ATTRIBUTE) { + tables.custom_attributes.push(CustomAttributeRow { + parent: cursor.index(attribute_parent)?, + constructor: cursor.index(constructor)?, + value: cursor.index(widths.blob)?, + }); + } + read_property_tables(cursor, counts, widths, tables)?; + for _ in 0..rows_of(counts, table::TYPE_SPEC) { + tables.type_specs.push(TypeSpecRow { + signature: cursor.index(widths.blob)?, + }); + } + read_identity_tables(cursor, counts, widths, tables) +} + +fn read_property_tables( + cursor: &mut Cursor<'_>, + counts: RowCounts, + widths: Widths, + tables: &mut TableSet, +) -> VResult<()> { + let type_def = widths.type_def; + let property = widths.property; + for _ in 0..rows_of(counts, table::PROPERTY_MAP) { + tables.property_maps.push(PropertyMapRow { + parent: cursor.index(type_def)?, + property_list: cursor.index(property)?, + }); + } + for _ in 0..rows_of(counts, table::PROPERTY) { + tables.properties.push(PropertyRow { + flags: cursor.u16()?, + name: cursor.index(widths.string)?, + signature: cursor.index(widths.blob)?, + }); + } + let method = widths.method_def; + let association = widths.has_semantics; + for _ in 0..rows_of(counts, table::METHOD_SEMANTICS) { + tables.method_semantics.push(MethodSemanticsRow { + semantics: cursor.u16()?, + method: cursor.index(method)?, + association: cursor.index(association)?, + }); + } + Ok(()) +} + +fn read_identity_tables( + cursor: &mut Cursor<'_>, + counts: RowCounts, + widths: Widths, + tables: &mut TableSet, +) -> VResult<()> { + for _ in 0..rows_of(counts, table::ASSEMBLY) { + let hash_algorithm = cursor.u32()?; + let version = read_version(cursor)?; + tables.assembly.push(AssemblyRow { + hash_algorithm, + version, + flags: cursor.u32()?, + public_key: cursor.index(widths.blob)?, + name: cursor.index(widths.string)?, + culture: cursor.index(widths.string)?, + }); + } + for _ in 0..rows_of(counts, table::ASSEMBLY_REF) { + let version = read_version(cursor)?; + tables.assembly_refs.push(AssemblyRefRow { + version, + flags: cursor.u32()?, + public_key_or_token: cursor.index(widths.blob)?, + name: cursor.index(widths.string)?, + culture: cursor.index(widths.string)?, + hash_value: cursor.index(widths.blob)?, + }); + } + let type_def = widths.type_def; + for _ in 0..rows_of(counts, table::NESTED_CLASS) { + tables.nested_classes.push(NestedClassRow { + nested: cursor.index(type_def)?, + enclosing: cursor.index(type_def)?, + }); + } + let owner = widths.type_or_method_def; + for _ in 0..rows_of(counts, table::GENERIC_PARAM) { + tables.generic_params.push(GenericParamRow { + number: cursor.u16()?, + flags: cursor.u16()?, + owner: cursor.index(owner)?, + name: cursor.index(widths.string)?, + }); + } + Ok(()) +} + +fn read_version(cursor: &mut Cursor<'_>) -> VResult<[u16; 4]> { + Ok([cursor.u16()?, cursor.u16()?, cursor.u16()?, cursor.u16()?]) +} + +impl Parsed { + /// Proves that every reference in every row lands somewhere real. + /// + /// This is the check that would have caught a coded index computed with a + /// `1 << 16` threshold, a heap index written at the wrong width, or a + /// `ResolutionScope` pointing at an `AssemblyRef` row that was never + /// emitted - the last of which does not produce a compiler diagnostic, it + /// produces a compiler crash. + pub(crate) fn check_references(&self) -> VResult<()> { + self.check_module()?; + self.check_type_refs()?; + self.check_type_defs()?; + self.check_member_runs()?; + self.check_members()?; + self.check_relations()?; + self.check_identity()?; + Ok(()) + } + + fn coded(&self, family: CodedIndex, value: u32, what: &str) -> VResult<()> { + if value == 0 { + return Ok(()); + } + let (target, row) = family + .decode(value) + .ok_or_else(|| format!("{what}: coded index {value} has an undefined tag"))?; + let rows = self.counts.get(target); + if row == 0 || row > rows { + return Err(format!( + "{what}: {} index names row {row} of table 0x{target:02X}, which has {rows} rows", + family.name + )); + } + Ok(()) + } + + fn simple(&self, target: u8, row: u32, what: &str) -> VResult<()> { + let rows = self.counts.get(target); + if row == 0 || row > rows { + return Err(format!( + "{what}: index names row {row} of table 0x{target:02X}, which has {rows} rows" + )); + } + Ok(()) + } + + fn check_module(&self) -> VResult<()> { + let row = self + .tables + .module + .first() + .ok_or_else(|| "the Module table is empty".to_owned())?; + self.string(row.name)?; + if row.mvid == 0 || row.mvid > self.guid_count() { + return Err(format!("Module.Mvid ordinal {} is out of range", row.mvid)); + } + Ok(()) + } + + fn check_type_refs(&self) -> VResult<()> { + for (index, row) in self.tables.type_refs.iter().enumerate() { + let what = format!("TypeRef row {}", index.saturating_add(1)); + self.coded(RESOLUTION_SCOPE, row.resolution_scope, &what)?; + self.string(row.name)?; + self.string(row.namespace)?; + } + Ok(()) + } + + fn check_type_defs(&self) -> VResult<()> { + for (index, row) in self.tables.type_defs.iter().enumerate() { + let what = format!("TypeDef row {}", index.saturating_add(1)); + self.coded(TYPE_DEF_OR_REF, row.extends, &what)?; + self.string(row.name)?; + self.string(row.namespace)?; + } + Ok(()) + } + + /// The member-run invariant: starts must be non-decreasing and must stop + /// at `rowcount + 1`, because a run ends where the next row's start begins. + fn check_member_runs(&self) -> VResult<()> { + let fields = self.counts.get(table::FIELD); + let methods = self.counts.get(table::METHOD_DEF); + check_run( + self.tables.type_defs.iter().map(|row| row.field_list), + fields, + "TypeDef.FieldList", + )?; + check_run( + self.tables.type_defs.iter().map(|row| row.method_list), + methods, + "TypeDef.MethodList", + )?; + check_run( + self.tables.methods.iter().map(|row| row.param_list), + self.counts.get(table::PARAM), + "MethodDef.ParamList", + )?; + check_run( + self.tables + .property_maps + .iter() + .map(|row| row.property_list), + self.counts.get(table::PROPERTY), + "PropertyMap.PropertyList", + ) + } + + fn check_members(&self) -> VResult<()> { + for row in &self.tables.fields { + self.string(row.name)?; + self.blob(row.signature)?; + } + for row in &self.tables.methods { + self.string(row.name)?; + self.blob(row.signature)?; + if row.rva != 0 { + return Err("a reference assembly must have MethodDef.RVA == 0".to_owned()); + } + } + for row in &self.tables.params { + self.string(row.name)?; + } + for row in &self.tables.properties { + self.string(row.name)?; + self.blob(row.signature)?; + } + for row in &self.tables.type_specs { + self.blob(row.signature)?; + } + Ok(()) + } + + fn check_relations(&self) -> VResult<()> { + for row in &self.tables.interface_impls { + self.simple(table::TYPE_DEF, row.class, "InterfaceImpl.Class")?; + self.coded(TYPE_DEF_OR_REF, row.interface, "InterfaceImpl.Interface")?; + } + for row in &self.tables.member_refs { + self.coded(MEMBER_REF_PARENT, row.class, "MemberRef.Class")?; + self.string(row.name)?; + self.blob(row.signature)?; + } + for row in &self.tables.constants { + self.coded(HAS_CONSTANT, row.parent, "Constant.Parent")?; + self.blob(row.value)?; + } + for row in &self.tables.custom_attributes { + self.coded(HAS_CUSTOM_ATTRIBUTE, row.parent, "CustomAttribute.Parent")?; + self.coded( + CUSTOM_ATTRIBUTE_TYPE, + row.constructor, + "CustomAttribute.Type", + )?; + self.blob(row.value)?; + } + for row in &self.tables.method_semantics { + self.simple(table::METHOD_DEF, row.method, "MethodSemantics.Method")?; + self.coded( + HAS_SEMANTICS, + row.association, + "MethodSemantics.Association", + )?; + } + for row in &self.tables.property_maps { + self.simple(table::TYPE_DEF, row.parent, "PropertyMap.Parent")?; + } + Ok(()) + } + + fn check_identity(&self) -> VResult<()> { + for row in &self.tables.assembly { + self.string(row.name)?; + self.string(row.culture)?; + self.blob(row.public_key)?; + } + for row in &self.tables.assembly_refs { + self.string(row.name)?; + self.string(row.culture)?; + self.blob(row.public_key_or_token)?; + self.blob(row.hash_value)?; + } + for row in &self.tables.nested_classes { + self.simple(table::TYPE_DEF, row.nested, "NestedClass.NestedClass")?; + self.simple(table::TYPE_DEF, row.enclosing, "NestedClass.EnclosingClass")?; + } + for row in &self.tables.generic_params { + self.coded(TYPE_OR_METHOD_DEF, row.owner, "GenericParam.Owner")?; + self.string(row.name)?; + } + Ok(()) + } + + /// The identity of the core-library reference, if one is present. + pub(crate) fn assembly_ref_names(&self) -> VResult> { + self.tables + .assembly_refs + .iter() + .map(|row| self.string(row.name)) + .collect() + } +} + +fn check_run(starts: impl Iterator, rows: u32, what: &'static str) -> VResult<()> { + let limit = rows.saturating_add(1); + let mut previous = 0_u32; + for (index, start) in starts.enumerate() { + if start < previous { + return Err(format!( + "{what}: row {} starts at {start}, before the previous run's {previous}", + index.saturating_add(1) + )); + } + if start == 0 || start > limit { + return Err(format!( + "{what}: row {} starts at {start}, outside 1..={limit}", + index.saturating_add(1) + )); + } + previous = start; + } + Ok(()) +} diff --git a/crates/modrix-gui/Cargo.toml b/crates/modrix-gui/Cargo.toml index 31ea92c..2ca3ca8 100644 --- a/crates/modrix-gui/Cargo.toml +++ b/crates/modrix-gui/Cargo.toml @@ -1,7 +1,7 @@ # SPDX-License-Identifier: GPL-2.0-only [package] name = "modrix-gui" -description = "Modrix graphical frontend (Iced)." +description = "Modrix graphical frontend (Rune, native GPU UI)." version.workspace = true edition.workspace = true rust-version.workspace = true @@ -17,14 +17,17 @@ modrix-core.workspace = true modrix-download.workspace = true modrix-ipc.workspace = true modrix-service.workspace = true -iced.workspace = true -tokio.workspace = true -tracing.workspace = true -tracing-subscriber.workspace = true -rfd.workspace = true modrix-plugin.workspace = true modrix-registry.workspace = true modrix-update.workspace = true +rune.workspace = true +rune-kit.workspace = true +anyhow.workspace = true +serde_json.workspace = true +serde.workspace = true +tokio.workspace = true +tracing.workspace = true +tracing-subscriber.workspace = true image.workspace = true [lints] diff --git a/crates/modrix-gui/src/actions.rs b/crates/modrix-gui/src/actions.rs new file mode 100644 index 0000000..e16b400 --- /dev/null +++ b/crates/modrix-gui/src/actions.rs @@ -0,0 +1,598 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! What the user can do. Each action updates the UI optimistically where it +//! is safe to, then queues the real engine call on the engine thread. + +use std::path::{Path, PathBuf}; + +use modrix_core::{Engine, GameDef, GameId, ModId, ProfileId}; +use modrix_service::InstallOutcome; + +use crate::bus::{Event, Reply}; +use crate::state::{App, DupPrompt, Pane, SortKey, Tone}; + +/// Engine results as display strings. +fn err(e: impl std::fmt::Display) -> String { + e.to_string() +} + +impl App { + /// The active profile id, if any. + #[must_use] + pub fn profile_id(&self) -> Option { + self.lib.profile.as_ref().map(|p| p.id) + } + + /// Switch the active profile. + pub fn pick_profile(&mut self, name: &str) { + let Some(profile) = self.lib.profiles.iter().find(|p| p.name == name).cloned() else { + return; + }; + self.lib.profile = Some(profile.clone()); + self.run( + false, + Box::new(move |e| { + e.set_active_profile(profile.id) + .map(|()| Reply::Quiet) + .map_err(err) + }), + ); + } + + /// Create a profile named by the form field. + pub fn create_profile(&mut self) { + let name = self.form.profile_name.text.trim().to_owned(); + let Some(game) = self.lib.game else { + return; + }; + if name.is_empty() { + return; + } + self.form.profile_name = rune::TextEdit::default(); + self.run( + false, + Box::new(move |e| { + let profile = e.create_profile(game, &name).map_err(err)?; + Ok(Reply::Note( + Tone::Ok, + format!("Profile {} created", profile.name), + )) + }), + ); + } + + /// Enable or disable one mod. + pub fn set_mod_enabled(&mut self, id: ModId, on: bool) { + let Some(profile) = self.profile_id() else { + return; + }; + if on { + self.lib.enabled.insert(id); + } else { + self.lib.enabled.remove(&id); + } + self.run( + false, + Box::new(move |e| { + e.set_enabled(profile, id, on) + .map(|()| Reply::Quiet) + .map_err(err) + }), + ); + } + + /// Enable or disable a set of mods with one summary note. + pub fn set_many_enabled(&mut self, ids: Vec, on: bool) { + let Some(profile) = self.profile_id() else { + return; + }; + for id in &ids { + if on { + self.lib.enabled.insert(*id); + } else { + self.lib.enabled.remove(id); + } + } + let count = ids.len(); + self.run( + false, + Box::new(move |e| { + for id in ids { + e.set_enabled(profile, id, on).map_err(err)?; + } + let verb = if on { "enabled" } else { "disabled" }; + Ok(Reply::Note(Tone::Ok, format!("{count} mods {verb}"))) + }), + ); + } + + /// Enable every disabled mod. + pub fn enable_all(&mut self) { + let ids: Vec = self + .lib + .mods + .iter() + .filter(|m| !self.lib.enabled.contains(&m.id)) + .map(|m| m.id) + .collect(); + self.set_many_enabled(ids, true); + } + + /// Delete the selected mods. + pub fn delete_selected(&mut self) { + let ids = self.selected_mod_ids(); + let count = ids.len(); + self.confirm_delete = false; + self.mod_sel.clear(); + self.lib.mods.retain(|m| !ids.contains(&m.id)); + self.run( + false, + Box::new(move |e| { + for id in ids { + e.delete_mod(id).map_err(err)?; + } + Ok(Reply::Note(Tone::Ok, format!("{count} mods deleted"))) + }), + ); + } + + /// Reinstall the selected mods from their archives. + pub fn reinstall_selected(&mut self) { + let ids = self.selected_mod_ids(); + if ids.is_empty() { + return; + } + self.mod_sel.clear(); + self.run(true, Box::new(move |e| run_reinstall_many(e, &ids))); + } + + /// Deploy the active profile. + pub fn deploy(&mut self) { + let Some(profile) = self.profile_id() else { + return; + }; + self.popup = None; + self.run( + true, + Box::new(move |e| { + let r = e.deploy(profile).map_err(err)?; + Ok(Reply::Note( + Tone::Ok, + format!( + "Deployed: {} added, {} removed, {} unchanged", + r.added(), + r.removed(), + r.unchanged() + ), + )) + }), + ); + } + + /// Start the selected game. A launch that cannot pass the loader's + /// environment on this platform says what to add to its launch options. + pub fn launch(&mut self) { + let Some(game) = self.game() else { + return; + }; + let (id, name) = (game.id, game.name.clone()); + self.popup = None; + self.run( + false, + Box::new(move |e| { + let r = e.launch(id).map_err(err)?; + Ok(match r.readiness.warning { + Some(warning) => Reply::Note(Tone::Info, warning), + None => Reply::Note(Tone::Ok, format!("Started {name}")), + }) + }), + ); + } + + /// Undeploy (purge) the active profile. + pub fn purge(&mut self) { + let Some(profile) = self.profile_id() else { + return; + }; + self.popup = None; + self.run( + true, + Box::new(move |e| { + let r = e.undeploy(profile).map_err(err)?; + Ok(Reply::Note( + Tone::Ok, + format!("Purged: {} files restored", r.removed()), + )) + }), + ); + } + + /// Verify the deployment. + pub fn verify(&mut self) { + let Some(profile) = self.profile_id() else { + return; + }; + self.popup = None; + self.run( + true, + Box::new(move |e| { + let r = e.verify(profile).map_err(err)?; + Ok(if r.is_clean() { + Reply::Note(Tone::Ok, format!("Verified: {} files healthy", r.checked())) + } else { + Reply::Note( + Tone::Error, + format!( + "Verify: {} of {} files changed", + r.issues().len(), + r.checked() + ), + ) + }) + }), + ); + } + + /// LOOT-style plugin sort. + pub fn auto_sort(&mut self) { + let Some(profile) = self.profile_id() else { + return; + }; + self.run( + true, + Box::new(move |e| { + let plugins = e.auto_sort_plugins(profile).map_err(err)?; + Ok(Reply::Note( + Tone::Ok, + format!("Load order sorted: {} plugins", plugins.len()), + )) + }), + ); + } + + /// Flip a plugin's activation. + pub fn toggle_plugin(&mut self, index: usize) { + if let Some(plugin) = self.lib.plugins.get_mut(index) { + plugin.enabled = !plugin.enabled; + self.commit_plugin_order(); + } + } + + /// Persist the current plugin order. + pub fn commit_plugin_order(&mut self) { + let Some(profile) = self.profile_id() else { + return; + }; + let order: Vec<(String, bool)> = self + .lib + .plugins + .iter() + .map(|p| (p.name.clone(), p.enabled)) + .collect(); + self.run( + false, + Box::new(move |e| { + e.set_plugin_order(profile, &order) + .map(|()| Reply::Quiet) + .map_err(err) + }), + ); + } + + /// Move the selected plugins one step (`delta` is -1 or +1). + pub fn move_plugins(&mut self, delta: i8) { + let len = self.lib.plugins.len(); + let mut indices: Vec = self.plugin_sel.items.iter().copied().collect(); + if indices.is_empty() || len == 0 { + return; + } + if delta > 0 { + indices.sort_unstable_by(|a, b| b.cmp(a)); + } else { + indices.sort_unstable(); + } + let last = len.saturating_sub(1); + if indices + .iter() + .any(|i| (delta < 0 && *i == 0) || (delta > 0 && *i >= last)) + { + return; + } + let mut moved = std::collections::BTreeSet::new(); + for i in indices { + let target = if delta < 0 { + i.saturating_sub(1) + } else { + i.saturating_add(1) + }; + self.lib.plugins.swap(i, target); + moved.insert(target); + } + self.plugin_sel.cursor = self.plugin_sel.cursor.map(|c| step(c, delta, len)); + self.plugin_sel.items = moved; + self.commit_plugin_order(); + } + + /// Move one plugin from `from` to `to` (drag and drop). + pub fn move_plugin_to(&mut self, from: usize, to: usize) { + let len = self.lib.plugins.len(); + if from == to || from >= len || to >= len { + return; + } + let moved = self.lib.plugins.remove(from); + self.lib.plugins.insert(to, moved); + self.plugin_sel.only(to); + self.commit_plugin_order(); + } + + /// `winner`'s files override `loser`'s. + pub fn set_rule(&mut self, loser: ModId, winner: ModId) { + let Some(profile) = self.profile_id() else { + return; + }; + self.run( + false, + Box::new(move |e| { + e.set_mod_rule(profile, loser, winner) + .map(|()| Reply::Quiet) + .map_err(err) + }), + ); + } + + /// Remove the rule between a pair. + pub fn clear_rule(&mut self, a: ModId, b: ModId) { + let Some(profile) = self.profile_id() else { + return; + }; + self.run( + false, + Box::new(move |e| { + e.clear_mod_rule(profile, a, b) + .map(|()| Reply::Quiet) + .map_err(err) + }), + ); + } + + /// Pin a target path to a provider (`None` returns it to the rules). + pub fn pin_file(&mut self, target: String, provider: Option) { + let Some(profile) = self.profile_id() else { + return; + }; + self.popup = None; + self.run( + false, + Box::new(move |e| { + e.set_file_override(profile, &target, provider) + .map(|()| Reply::Quiet) + .map_err(err) + }), + ); + } + + /// Cancel a download. + pub fn cancel_download(&mut self, id: modrix_download::DownloadId) { + if let Some(service) = &self.service + && let Err(error) = service.manager().cancel(id) + { + let text = error.to_string(); + self.note(Tone::Error, text); + } + } + + /// Sort the Mods table by a column (again flips direction). + pub fn sort_by(&mut self, key: SortKey) { + let (current, ascending) = self.mod_sort; + self.mod_sort = if current == key { + (key, !ascending) + } else { + (key, true) + }; + self.mod_sel.clear(); + self.sort_mods(); + } + + /// A list row was clicked: plain selects, Ctrl toggles, Shift extends. + pub fn row_click(&mut self, pane: Pane, index: usize, mods: rune::Mods) { + self.focus_pane = pane; + let sel = match pane { + Pane::Mods => &mut self.mod_sel, + Pane::Plugins => &mut self.plugin_sel, + }; + if mods.shift { + sel.range_to(index); + } else if mods.cmd || mods.ctrl { + sel.toggle(index); + } else if sel.items.len() == 1 && sel.items.contains(&index) { + sel.clear(); + } else { + sel.only(index); + } + } + + /// Hash dropped or picked archives off-thread, then install or prompt. + pub fn install_files(&mut self, paths: Vec) { + if self.lib.game.is_none() { + self.note(Tone::Error, "Register a game first"); + return; + } + let bus = self.bus.clone(); + let spawned = std::thread::Builder::new() + .name("modrix-hash".to_owned()) + .spawn(move || { + let items = paths + .into_iter() + .take(256) + .filter(|p| p.exists()) + .map(|p| { + let hash = if p.is_dir() { + None + } else { + modrix_core::sha256_file(&p).ok() + }; + (p, hash) + }) + .collect(); + bus.send(Event::Hashed(items)); + }); + if let Err(error) = spawned { + self.note(Tone::Error, error.to_string()); + } + } + + /// Hashes are in: queue an install (or a duplicate prompt) per archive. + pub fn on_hashed(&mut self, items: Vec<(PathBuf, Option)>) { + let Some(game) = self.lib.game else { + return; + }; + for (path, hash) in items { + self.run( + true, + Box::new(move |e| install_or_prompt(e, game, &path, hash.as_deref())), + ); + } + } + + /// Duplicate prompt accepted: reinstall the existing mod. + pub fn dup_confirm(&mut self) { + if self.dup_queue.is_empty() { + return; + } + let prompt = self.dup_queue.remove(0); + self.run( + true, + Box::new(move |e| run_reinstall_many(e, &[prompt.existing])), + ); + } + + /// Duplicate prompt dismissed. + pub fn dup_cancel(&mut self) { + if !self.dup_queue.is_empty() { + self.dup_queue.remove(0); + } + } + + /// Register a game from the manual form. + pub fn add_game(&mut self) { + let install = PathBuf::from(self.form.install_path.text.trim()); + if !install.is_dir() { + return self.note( + Tone::Error, + format!("{} is not a folder", install.display()), + ); + } + let def = match self.chosen_def() { + Ok(def) => def, + Err(error) => return self.note(Tone::Error, error), + }; + self.form.install_path = rune::TextEdit::default(); + self.form.def_path = rune::TextEdit::default(); + self.run( + false, + Box::new(move |e| register(e, &def, &install, "manual")), + ); + } + + /// Register a detected install and switch to it. + pub fn add_detected(&mut self, index: usize) { + let Some(found) = self.detected.get(index).cloned() else { + return; + }; + let def = match GameDef::from_toml_str(&found.def.toml, Path::new("")) { + Ok(def) => def, + Err(error) => return self.note(Tone::Error, error.to_string()), + }; + self.run( + false, + Box::new(move |e| register(e, &def, &found.install, "steam")), + ); + } + + fn chosen_def(&self) -> Result { + let explicit = self.form.def_path.text.trim(); + if !explicit.is_empty() { + return GameDef::from_file(Path::new(explicit)).map_err(err); + } + let id = self + .form + .def_id + .as_deref() + .ok_or("Pick a game definition")?; + let choice = self + .defs + .iter() + .find(|d| d.id == id) + .ok_or("Pick a game definition")?; + GameDef::from_toml_str(&choice.toml, Path::new("")).map_err(err) + } + + /// Detected installs not yet registered. + #[must_use] + pub fn unregistered_detected(&self) -> Vec<(usize, &crate::state::Detected)> { + self.detected + .iter() + .enumerate() + .filter(|(_, d)| !self.lib.games.iter().any(|g| g.plugin_id == d.def.id)) + .collect() + } +} + +/// Step an index by `delta`, clamped to `0..len`. +#[must_use] +pub fn step(index: usize, delta: i8, len: usize) -> usize { + if delta < 0 { + index.saturating_sub(1) + } else { + index.saturating_add(1).min(len.saturating_sub(1)) + } +} + +fn register(e: &Engine, def: &GameDef, install: &Path, store: &str) -> Result { + let game = e.add_game(def, install, store).map_err(err)?; + e.set_active_game(game.id).map_err(err)?; + Ok(Reply::SelectGame(game.id, format!("{} added", game.name))) +} + +fn install_or_prompt( + e: &Engine, + game: GameId, + path: &Path, + hash: Option<&str>, +) -> Result { + if let Some(hash) = hash { + let existing = e.find_by_archive_hash(game, hash).map_err(err)?; + if let Some(m) = existing.into_iter().next() { + return Ok(Reply::Duplicate(DupPrompt { + path: path.to_path_buf(), + existing: m.id, + existing_name: m.name, + })); + } + } + match modrix_service::install_file(e, game, path) { + Ok(InstallOutcome::Installed { name, configurable }) => Ok(Reply::Note( + Tone::Ok, + if configurable { + format!("{name} installed, options set to defaults") + } else { + format!("{name} installed") + }, + )), + Ok(other) => Err(format!("Install did not finish: {other:?}")), + Err(error) => Err(format!("{error:#}")), + } +} + +/// Reinstall each mod from its archive, re-run FOMOD defaults, re-enable. +fn run_reinstall_many(e: &Engine, ids: &[ModId]) -> Result { + let mut done: usize = 0; + for id in ids { + let fresh = e.reinstall_mod(*id).map_err(err)?; + modrix_service::fomod_pass(e, &fresh).map_err(|e| format!("{e:#}"))?; + if let Ok(profile) = e.active_profile(fresh.game_id) { + e.set_enabled(profile.id, fresh.id, true).map_err(err)?; + } + done = done.saturating_add(1); + } + Ok(Reply::Note(Tone::Ok, format!("{done} mods reinstalled"))) +} diff --git a/crates/modrix-gui/src/app.rs b/crates/modrix-gui/src/app.rs deleted file mode 100644 index 15f6c9d..0000000 --- a/crates/modrix-gui/src/app.rs +++ /dev/null @@ -1,2526 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -//! Application state and update logic. -//! -//! The GUI is a thin face over [`modrix_core::Engine`] plus the embedded -//! [`modrix_service::Service`] (the same service `modrix serve` hosts), so a -//! browser hand-off installs mods while the window is open. All business -//! logic stays in the engine; this module only shuttles state. - -use std::collections::{HashMap, HashSet}; -use std::path::PathBuf; -use std::sync::{Arc, Mutex}; -use std::time::Duration; - -use iced::{Subscription, Task, Theme}; -use modrix_core::plugins::GamePlugin; -use modrix_core::{Engine, Game, GameDef, GameId, Mod, ModId, Paths, Profile, ProfileId}; -use modrix_download::{DownloadId, DownloadState, DownloadStatus}; -use modrix_plugin::fomod; -use modrix_service::{Binding, InstallOutcome, Service}; - -use crate::theme; - -/// A sortable column of the Mods table. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum SortKey { - /// Install time (timestamp, falling back to mod id) - the default. - /// Descending shows the most recently installed first. - Installed, - /// Alphabetical by name. - Name, - /// Enabled first. - Enabled, - /// By version string. - Version, - /// By source (nexus/local). - Source, -} - -/// Which list has keyboard focus. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Pane { - /// The Mods table. - Mods, - /// The Load Order (plugins) list. - Plugins, -} - -/// A multi-selection over a list: selected indices, a fixed **anchor** (where -/// a Shift-range starts), and a moving **cursor** (where it currently ends). -#[derive(Debug, Clone, Default)] -pub struct Selection { - /// Selected indices. - pub items: std::collections::BTreeSet, - /// The fixed end of a Shift-range (set by plain clicks/moves). - pub anchor: Option, - /// The moving end (last row touched). - pub cursor: Option, -} - -impl Selection { - /// Clear everything. - pub fn clear(&mut self) { - self.items.clear(); - self.anchor = None; - self.cursor = None; - } - - /// Select exactly `index` (plain click / arrow move). - pub fn only(&mut self, index: usize) { - self.items.clear(); - self.items.insert(index); - self.anchor = Some(index); - self.cursor = Some(index); - } - - /// Toggle `index` (Ctrl semantics); it becomes the new anchor. - pub fn toggle(&mut self, index: usize) { - if !self.items.remove(&index) { - self.items.insert(index); - } - self.anchor = Some(index); - self.cursor = Some(index); - } - - /// Extend from the fixed anchor to `index` (Shift semantics). The anchor - /// does not move, so repeated extensions grow the same range. - pub fn range_to(&mut self, index: usize) { - let anchor = self.anchor.or(self.cursor).unwrap_or(index); - let (lo, hi) = (anchor.min(index), anchor.max(index)); - self.items = (lo..=hi).collect(); - self.anchor = Some(anchor); - self.cursor = Some(index); - } - - /// Keep only indices below `len` (after the list shrinks). - pub fn retain_below(&mut self, len: usize) { - self.items.retain(|i| *i < len); - self.anchor = self.anchor.filter(|a| *a < len); - self.cursor = self.cursor.filter(|c| *c < len); - } -} - -/// Simultaneously-active downloads (matches `modrix serve`). -const MAX_CONCURRENT: u8 = 4; - -/// Notifications kept before the oldest are dropped. -const MAX_NOTES: usize = 200; - -/// How long an event notification stays before it expires on its own. Live -/// conditions (health issues) are not subject to this - they clear when fixed. -const NOTE_TTL: Duration = Duration::from_mins(5); - -/// Which main view is showing. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Screen { - /// Overview cards. - Dashboard, - /// Registered games + registration form. - Games, - /// The mod table for the selected game. - Mods, - /// Reorderable enabled-mod list + conflicts. - LoadOrder, - /// Conflict resolution: rules and per-file overrides. - Conflicts, - /// Live download list + hand-off state. - Downloads, - /// Paths, service, extension pairing. - Settings, -} - -/// A selectable game definition (built-in or discovered on disk). -#[derive(Debug, Clone)] -pub struct DefChoice { - /// Display name (the definition's `name`). - pub name: String, - /// The raw `game.toml` text. - pub toml: String, -} - -impl PartialEq for DefChoice { - fn eq(&self, other: &Self) -> bool { - self.name == other.name - } -} -impl Eq for DefChoice {} - -/// One community plugin from the registry index, as the Games screen shows it. -#[derive(Debug, Clone)] -pub struct RegistryChoice { - /// Stable plugin id (= game id). - pub id: String, - /// Display name. - pub name: String, - /// Registry version. - pub version: String, - /// The full index entry (needed to install). - pub entry: modrix_registry::IndexEntry, -} - -/// An installed plugin row for the Settings screen. -#[derive(Debug, Clone)] -pub struct InstalledPlugin { - /// Stable plugin id. - pub id: String, - /// Display name. - pub name: String, - /// Installed version. - pub version: String, -} - -/// A supported game found installed on disk by `install_probe`, whether or not -/// it is registered yet. Lets the Games screen offer a one-click add + switch. -#[derive(Debug, Clone)] -pub struct Detected { - /// The definition that matched. - pub def: DefChoice, - /// Its stable id (`skyrimse`), for matching against registered games. - pub id: String, - /// The detected install directory. - pub install: PathBuf, - /// Steam AppID, when known. - pub appid: Option, -} -impl std::fmt::Display for DefChoice { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str(&self.name) - } -} - -/// A game entry for the sidebar picker. -#[derive(Debug, Clone)] -pub struct GameChoice { - /// The game's id. - pub id: GameId, - /// Its display name. - pub name: String, -} - -impl PartialEq for GameChoice { - fn eq(&self, other: &Self) -> bool { - self.id == other.id - } -} -impl Eq for GameChoice {} -impl std::fmt::Display for GameChoice { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str(&self.name) - } -} - -/// Notification severity. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Tone { - /// Completed. - Ok, - /// Failed. - Error, - /// Informational. - Info, -} - -/// One entry in the notification center. Notes are *events* (an install -/// finished, an action failed) - they expire after [`NOTE_TTL`] or on "Clear -/// all". Live *conditions* (health issues, conflicts) are never stored as -/// notes; the panel renders them straight from [`App::health`] so they -/// disappear the moment they are resolved. -#[derive(Debug, Clone)] -pub struct Note { - /// Severity. - pub tone: Tone, - /// The message. - pub text: String, - /// When the event happened (drives expiry). - pub at: std::time::Instant, -} - -/// A duplicate-install prompt: the user dropped an archive whose content hash -/// matches a mod that is already installed. Modal - resolved by -/// [`Message::DupConfirm`] (reinstall the existing mod) or [`Message::DupCancel`]. -#[derive(Debug, Clone)] -pub struct DupPrompt { - /// The archive the user tried to install. - pub path: PathBuf, - /// The already-installed mod with the same content. - pub existing: ModId, - /// Its display name. - pub existing_name: String, -} - -/// The loopback pairing the browser extension needs. -#[derive(Debug, Clone)] -pub struct Link { - /// Bound port. - pub port: u16, - /// Per-session token. - pub token: String, -} - -/// The FOMOD wizard modal. -#[derive(Debug, Clone)] -pub struct Wizard { - /// The mod being configured. - pub mod_id: ModId, - /// Its display name. - pub mod_name: String, - /// Its staged tree (image lookups resolve against it). - pub staged_path: PathBuf, - /// The parsed installer. - pub installer: fomod::Installer, - /// Current selections. - pub selections: fomod::Selections, - /// Position within the *visible* steps. - pub step: usize, - /// The option under the cursor / last touched - drives the preview pane. - pub focus: Option<(usize, usize, usize)>, - /// Files present in the install (drives fileDependency conditions). - pub present: fomod::Present, -} - -impl Wizard { - /// Indices of steps visible under the current selections. - #[must_use] - pub fn visible_steps(&self) -> Vec { - let flags = fomod::flags_of(&self.installer, &self.selections, &self.present); - self.installer - .steps - .iter() - .enumerate() - .filter(|(_, s)| { - s.visible - .as_ref() - .is_none_or(|d| d.eval(&flags, &self.present)) - }) - .map(|(i, _)| i) - .collect() - } -} - -/// Form inputs, kept separate from engine-derived state so a refresh never -/// clobbers what the user is typing. -#[derive(Debug, Clone, Default)] -pub struct Forms { - /// Chosen built-in/discovered definition. - pub def_choice: Option, - /// Alternative: an explicit path to a `game.toml`. - pub def_path: String, - /// The game's install directory. - pub install_path: String, - /// Name for a new profile. - pub profile_name: String, -} - -/// The in-app updater's state machine (a newer GitHub release, if any, and -/// whether its installer is currently being fetched/launched). -#[derive(Debug, Clone, Default)] -pub enum UpdateState { - /// No newer release known (up to date, offline, or not yet checked). - #[default] - Idle, - /// A newer release is available and offered to the user. - Available(modrix_update::UpdateInfo), - /// The update's installer is downloading / launching. - Installing(modrix_update::UpdateInfo), -} - -/// The whole GUI state. -pub struct App { - /// The embedded hand-off service (None until boot finishes). - pub service: Option, - /// Extension pairing when this process is the primary instance. - pub link: Option, - /// True when another instance holds the loopback port. - pub already_running: bool, - /// Fatal boot failure, rendered full-screen. - pub boot_error: Option, - /// Current view. - pub screen: Screen, - /// Registered games. - pub games: Vec, - /// The game being managed. - pub selected_game: Option, - /// Profiles of the selected game. - pub profiles: Vec, - /// Its active profile. - pub active_profile: Option, - /// All staged mods of the selected game. - pub mods: Vec, - /// Mods present in the game dir that Modrix did not deploy - shown - /// read-only so the user sees they are there but cannot manage them. - pub external: Vec, - /// Enabled mods in load order. - pub order: Vec, - /// The profile's plugin (.esp/.esm/.esl) load order. - pub plugins: Vec, - /// Download snapshots, newest first. - pub downloads: Vec, - /// Install phase of each completed download. - pub outcomes: HashMap, - /// Download ids whose outcome was already notified. - pub outcome_seen: HashSet, - /// Selected mod rows in the Mods table (indices into `mods`). - pub mod_sel: Selection, - /// Selected plugin rows in the Load Order (indices into `plugins`). - pub plugin_sel: Selection, - /// Which list owns the keyboard, set by the last click. - pub focus_pane: Pane, - /// Live modifier-key state (drives Shift/Ctrl-click selection). - pub modifiers: iced::keyboard::Modifiers, - /// Mods table sort: (column, ascending). - pub mod_sort: (SortKey, bool), - /// Mods list viewport: (scroll offset, visible height). - pub mods_view: Option<(f32, f32)>, - /// Plugins list viewport: (scroll offset, visible height). - pub plugins_view: Option<(f32, f32)>, - /// Load-order drag: (source index, current hover index). - pub drag: Option<(usize, usize)>, - /// Pairwise mod conflicts with their rule state, worst-first. - pub conflicts: Vec, - /// The conflict pair whose file list is expanded. - pub expanded_conflict: Option<(ModId, ModId)>, - /// Plugins (.esp/.esm/.esl) each mod ships, staged-tree top level. - pub plugin_counts: HashMap, - /// Setup health issues, worst-first. - pub health: Vec, - /// What the selected game supports (drives which tabs show). - pub capabilities: Option, - /// Resolved artwork per game (Steam library cache / CDN mirror). - pub art: HashMap, - /// Games whose artwork fetch is already underway (no duplicate tasks). - art_requested: HashSet, - /// The game whose art currently drives the accent (so a switch re-derives). - accent_for: Option, - /// The engine's live progress sink (shared before the engine exists so - /// boot-time crash recovery reports too). - pub progress: std::sync::Arc, - /// Latest progress snapshot (polled every tick). - pub op: Option, - /// Notification center entries, newest first. - pub notes: Vec, - /// Notifications not yet seen. - pub unread: usize, - /// Whether the notification panel is open. - pub notes_open: bool, - /// The in-app update state (a newer release, and whether it is installing). - pub update: UpdateState, - /// Pending duplicate-install prompts (the first is the open modal). - pub dup_queue: Vec, - /// The FOMOD wizard, when open. - pub wizard: Option, - /// FOMOD mods awaiting their first options review (opened one at a time). - pub wizard_queue: Vec, - /// Mods already offered a wizard this session (no re-nagging). - pub prompted: HashSet, - /// A slow engine action is in flight. - pub busy: bool, - /// Selectable game definitions. - pub defs: Vec, - /// Stable ids of `defs`, index-aligned (drives "already supported"). - pub def_ids: Vec, - /// Supported games found installed on disk (from `install_probe`). - pub detected: Vec, - /// Community plugins available in the registry (fetched at boot). - pub registry: Vec, - /// Locally installed registry plugins (Settings screen). - pub installed_plugins: Vec, - /// Form fields. - pub form: Forms, - /// The engine's resolved on-disk locations (shown in Settings). - pub paths: Option, - /// The fixed dark theme. - pub theme: Theme, -} - -/// Everything the boot task hands back. -#[derive(Debug, Clone)] -pub struct Booted { - service: Service, - link: Option, - defs: Vec, - def_ids: Vec, - detected: Vec, - paths: Paths, -} - -/// All UI events. -#[derive(Debug, Clone)] -pub enum Message { - /// The service finished (or failed) starting. - Booted(Result), - /// Switch view. - Navigate(Screen), - /// Periodic refresh. - Tick, - /// Sidebar game picker. - GamePicked(GameChoice), - /// Profile picker. - ProfilePicked(String), - /// New-profile name input. - ProfileNameChanged(String), - /// Create the named profile. - CreateProfile, - /// Enable/disable a mod in the active profile. - ToggleMod(ModId, bool), - /// A list row was clicked - updates the selection using the live - /// modifier state (Shift = range, Ctrl = toggle). - RowClick { - /// Which list. - pane: Pane, - /// Row index. - index: usize, - }, - /// Click-away: clear the active list's selection. - ClearSelection, - /// A key was pressed while a list had focus. - Key(iced::keyboard::Key, iced::keyboard::Modifiers), - /// The modifier-key state changed. - Modifiers(iced::keyboard::Modifiers), - /// Sort the Mods table by a column (clicking again flips direction). - SortBy(SortKey), - /// A list was scrolled: (pane, offset y, viewport height). - Scrolled(Pane, f32, f32), - /// Enable every currently disabled mod. - EnableAll, - /// Enable/disable all selected mods. - SetSelectedEnabled(bool), - /// Delete all selected mods. - DeleteSelected, - /// Reinstall all selected mods from their archives. - ReinstallSelected, - /// Toggle a plugin's activation. - TogglePlugin(usize), - /// Auto-sort the plugin load order (LOOT-style). - AutoSort, - /// Rule that `winner`'s files override `loser`'s. - SetRule { - /// The overridden mod. - loser: ModId, - /// The overriding mod. - winner: ModId, - }, - /// Remove the rule between a pair. - ClearRule(ModId, ModId), - /// Expand/collapse a conflict pair's file list. - ExpandConflict(ModId, ModId), - /// Pin a target path to a provider (`None` returns it to the rules). - PinFile { - /// Target path relative to the deploy root. - target: String, - /// The providing mod, or `None` to clear the pin. - provider: Option, - }, - /// Move the current selection up/down by one (arrow buttons/keys). - MoveSelection { - /// Which list. - pane: Pane, - /// -1 up, +1 down. - delta: i8, - }, - /// Begin dragging a row. - DragStart(Pane, usize), - /// The cursor entered another row while dragging. - DragOver(usize), - /// The drag ended; commit the current order. - DragEnd, - /// Deploy the active profile. - Deploy, - /// Undeploy (purge) the active profile. - Purge, - /// Verify the deployment. - Verify, - /// A background engine action finished. - ActionFinished(Result), - /// Definition picker. - DefPicked(DefChoice), - /// Definition path input. - DefPathChanged(String), - /// Install path input. - InstallPathChanged(String), - /// Register the game. - AddGame, - /// Register a detected install (index into `detected`) and switch to it. - AddDetected(usize), - /// The registry index finished loading (at boot, or after a change). - RegistryLoaded(Result, String>), - /// The GitHub update check finished (at boot, or when re-checked manually). - UpdateChecked(Result, String>), - /// Re-run the update check on demand (Settings button). - CheckUpdates, - /// Download and launch the installer for the pending update. - StartUpdate, - /// The update installer was launched (Ok) or failed to (Err). - UpdateApplied(Result<(), String>), - /// Install game support from the registry (index into `registry`). - InstallSupport(usize), - /// A registry plugin finished installing. - SupportInstalled(Result), - /// Remove an installed registry plugin by id. - UninstallPlugin(String), - /// Remove every installed plugin no registered game uses. - GcPlugins, - /// Open the file picker for local archives. - PickFiles, - /// Files chosen in the picker. - FilesPicked(Vec), - /// A file was dropped onto the window. - FileDropped(PathBuf), - /// A candidate archive was hashed off-thread; decide install vs duplicate - /// prompt. - InstallChecked { - /// The archive to install. - path: PathBuf, - /// Its content hash (`None` if hashing failed or it is a directory). - hash: Option, - }, - /// Duplicate prompt: reinstall the existing mod from this archive. - DupConfirm, - /// Duplicate prompt: keep the existing mod, do nothing. - DupCancel, - /// Staged plugin counts computed on a worker task. - PluginCounts(HashMap), - /// Switch the visual theme (by stable id) and persist the choice. - ThemePicked(String), - /// A game's artwork finished resolving. - ArtResolved(GameId, crate::artwork::ArtSet), - /// Swallow a click (keeps overlay panels from dismissing themselves). - NoOp, - /// Cancel a download. - CancelDownload(DownloadId), - /// Copy text to the clipboard. - CopyText(String), - /// Open/close the notification panel. - ToggleNotes, - /// Empty the notification center. - ClearNotes, - /// Open the FOMOD wizard for a mod. - Configure(ModId), - /// Wizard: preview an option (hover). - WizardHover { - /// Step index (absolute). - step: usize, - /// Group index. - group: usize, - /// Plugin index. - plugin: usize, - }, - /// Wizard: select all (or none) of a group's usable options. - WizardGroupSet { - /// Step index (absolute). - step: usize, - /// Group index. - group: usize, - /// True = check all usable; false = keep only Required. - all: bool, - }, - /// Wizard: toggle a plugin. - WizardPick { - /// Step index (absolute). - step: usize, - /// Group index. - group: usize, - /// Plugin index. - plugin: usize, - }, - /// Wizard: next page. - WizardNext, - /// Wizard: previous page. - WizardBack, - /// Wizard: apply the chosen options. - WizardFinish, - /// Wizard: close without applying. - WizardCancel, -} - -/// A long-running engine action executed off the UI thread. -#[derive(Debug, Clone)] -enum Action { - Deploy(ProfileId), - Undeploy(ProfileId), - Verify(ProfileId), - Install { - game: GameId, - path: PathBuf, - }, - ReinstallMany(Vec), - AutoSortPlugins(ProfileId), - ApplyWizard { - mod_id: ModId, - staged: PathBuf, - installer: Box, - selections: fomod::Selections, - present: fomod::Present, - }, -} - -/// The screen to open on. `MODRIX_GUI_SCREEN` overrides for development and -/// screenshot tooling; users just get the dashboard. -fn initial_screen() -> Screen { - match std::env::var("MODRIX_GUI_SCREEN").as_deref() { - Ok("games") => Screen::Games, - Ok("mods") => Screen::Mods, - Ok("loadorder") => Screen::LoadOrder, - Ok("conflicts") => Screen::Conflicts, - Ok("downloads") => Screen::Downloads, - Ok("settings") => Screen::Settings, - _ => Screen::Dashboard, - } -} - -/// Restore the persisted theme choice before the first frame renders. -fn load_theme_pref() { - let Ok(paths) = Paths::resolve() else { - return; - }; - let Ok(text) = std::fs::read_to_string(paths.config_dir().join("gui.toml")) else { - return; - }; - for line in text.lines().take(64) { - if let Some(rest) = line.trim().strip_prefix("theme") - && let Some(value) = rest.trim().strip_prefix('=') - { - theme::set_theme(value.trim().trim_matches('"')); - return; - } - } -} - -/// Persist the theme choice (best-effort - a failed write only means the -/// next launch opens on the default). -fn save_theme_pref(paths: &Paths, id: &str) { - let dir = paths.config_dir(); - let _ = std::fs::create_dir_all(dir); - let _ = std::fs::write(dir.join("gui.toml"), format!("theme = \"{id}\"\n")); -} - -/// Initial state + the boot task. -pub fn boot() -> (App, Task) { - load_theme_pref(); - let app = App { - service: None, - link: None, - already_running: false, - boot_error: None, - screen: initial_screen(), - games: Vec::new(), - selected_game: None, - profiles: Vec::new(), - active_profile: None, - mods: Vec::new(), - external: Vec::new(), - order: Vec::new(), - plugins: Vec::new(), - downloads: Vec::new(), - outcomes: HashMap::new(), - outcome_seen: HashSet::new(), - mod_sel: Selection::default(), - plugin_sel: Selection::default(), - focus_pane: Pane::Mods, - modifiers: iced::keyboard::Modifiers::default(), - mod_sort: (SortKey::Installed, true), - mods_view: None, - plugins_view: None, - drag: None, - conflicts: Vec::new(), - expanded_conflict: None, - plugin_counts: HashMap::new(), - health: Vec::new(), - capabilities: None, - art: HashMap::new(), - art_requested: HashSet::new(), - accent_for: None, - progress: std::sync::Arc::new(modrix_core::Progress::default()), - op: None, - notes: Vec::new(), - unread: 0, - notes_open: false, - update: UpdateState::Idle, - dup_queue: Vec::new(), - wizard: None, - wizard_queue: Vec::new(), - prompted: HashSet::new(), - busy: false, - defs: Vec::new(), - def_ids: Vec::new(), - detected: Vec::new(), - registry: Vec::new(), - installed_plugins: Vec::new(), - form: Forms::default(), - paths: None, - theme: theme::app_theme(), - }; - let progress = std::sync::Arc::clone(&app.progress); - ( - app, - Task::perform(async move { start_service(&progress) }, Message::Booted), - ) -} - -/// Ticks for live refresh + window file drops. -pub fn subscription(app: &App) -> Subscription { - // `listen_with` takes a plain fn pointer (no captures); `on_key` ignores - // navigation keys while the wizard is open. - let events = iced::event::listen_with(|event, _status, _window| match event { - iced::Event::Window(iced::window::Event::FileDropped(path)) => { - Some(Message::FileDropped(path)) - } - iced::Event::Keyboard(iced::keyboard::Event::KeyPressed { key, modifiers, .. }) => { - Some(Message::Key(key, modifiers)) - } - iced::Event::Keyboard(iced::keyboard::Event::ModifiersChanged(modifiers)) => { - Some(Message::Modifiers(modifiers)) - } - _ => None, - }); - // The tick runs from the very start: it drives the boot/recovery - // progress display before the service exists. Faster while an operation - // is live so the bar and status line feel alive. - let period = if app.op.is_some() || app.service.is_none() { - Duration::from_millis(150) - } else { - // Idle: the per-tick refresh is SQLite-only (no filesystem walks), - // and 2s keeps background wakeups rare on a loaded system. - Duration::from_secs(2) - }; - Subscription::batch([events, iced::time::every(period).map(|_| Message::Tick)]) -} - -/// The stable scrollable id for a pane's list. -fn scroll_id(pane: Pane) -> iced::widget::scrollable::Id { - match pane { - Pane::Mods => iced::widget::scrollable::Id::new("mods-list"), - Pane::Plugins => iced::widget::scrollable::Id::new("plugins-list"), - } -} - -/// Case-insensitive name ordering. -fn compare_names(a: &str, b: &str) -> std::cmp::Ordering { - a.to_ascii_lowercase().cmp(&b.to_ascii_lowercase()) -} - -/// Step an index by `delta` (clamped to `0..len`). -fn step(index: usize, delta: i8, len: usize) -> usize { - if delta < 0 { - index.saturating_sub(1) - } else { - index.saturating_add(1).min(len.saturating_sub(1)) - } -} - -/// Open the engine, start the download manager, and bind the loopback -/// listener so browser hand-offs reach this window. Must run on the -/// executor (the listener and stager are spawned onto it). -fn start_service(progress: &std::sync::Arc) -> Result { - let paths = Paths::resolve().map_err(|e| e.to_string())?; - let mut engine = Engine::open_with_progress(&paths, std::sync::Arc::clone(progress)) - .map_err(|e| e.to_string())?; - // Tier-2 plugins (game.lua) hook in before the engine is shared. - modrix_plugin::register_lua_logic(&mut engine); - let lockfile = paths.instance_lock(); - let (defs, def_ids) = discover_defs(&paths); - let detected = detect_installs(&defs); - let service = Service::new(engine, MAX_CONCURRENT).map_err(|e| format!("{e:#}"))?; - let link = match service - .bind(&lockfile, modrix_ipc::DEFAULT_PORT) - .map_err(|e| format!("{e:#}"))? - { - Binding::Primary { port, token, .. } => Some(Link { port, token }), - Binding::AlreadyRunning => None, - }; - Ok(Booted { - service, - link, - defs, - def_ids, - detected, - paths, - }) -} - -/// Probe every known definition's `install_probe` and return the games found -/// installed on disk. Best-effort filesystem reads (Steam metadata); a -/// definition that isn't installed simply doesn't appear. -fn detect_installs(defs: &[DefChoice]) -> Vec { - let mut out = Vec::new(); - for choice in defs { - let Ok(def) = GameDef::from_toml_str(&choice.toml, std::path::Path::new("")) - else { - continue; - }; - if let Some(install) = modrix_core::detect::detect_install(&def) { - out.push(Detected { - def: choice.clone(), - id: def.id, - install, - appid: def.steam_appid, - }); - } - } - out -} - -/// Every definition this installation can register a game from - built-ins, -/// user definitions, installed plugins - via core's catalog. Returns the -/// choices plus their index-aligned stable ids. -fn discover_defs(paths: &Paths) -> (Vec, Vec) { - let entries = modrix_core::defcat::discover_defs(paths); - let ids = entries.iter().map(|e| e.def.id.clone()).collect(); - let defs = entries - .into_iter() - .map(|entry| DefChoice { - name: entry.def.name, - toml: entry.toml, - }) - .collect(); - (defs, ids) -} - -/// Fetch the registry index into the Games screen's choice list. -async fn fetch_registry(paths: Paths) -> Result, String> { - let client = - modrix_registry::RegistryClient::new(modrix_registry::RegistrySource::resolve(), &paths) - .map_err(|e| e.to_string())?; - let index = client.index(false).await.map_err(|e| e.to_string())?; - Ok(index - .plugins - .into_iter() - .map(|entry| RegistryChoice { - id: entry.id.clone(), - name: entry.name.clone(), - version: entry.version.clone(), - entry, - }) - .collect()) -} - -/// Check GitHub Releases for a newer build (offline / private repo / up to date -/// all resolve to "no update", so this never disrupts startup). -fn spawn_update_check() -> Task { - Task::perform( - async { modrix_update::check(env!("CARGO_PKG_VERSION")).await }, - |result| Message::UpdateChecked(result.map_err(|e| e.to_string())), - ) -} - -/// Download the pending update's installer and launch it. On success the caller -/// quits so the installer can replace the running executable. -async fn run_update( - info: modrix_update::UpdateInfo, - dir: std::path::PathBuf, -) -> Result<(), String> { - let installer = modrix_update::download(&info, &dir) - .await - .map_err(|e| e.to_string())?; - modrix_update::apply(&installer).map_err(|e| e.to_string()) -} - -/// The update loop: route each message to its handler. -pub fn update(app: &mut App, message: Message) -> Task { - match message { - Message::Booted(result) => return app.on_booted(result), - Message::Navigate(screen) => return app.on_navigate(screen), - Message::Tick => { - app.op = app.progress.snapshot(); - app.refresh(); - app.expire_notes(); - return app.spawn_art_fetches(); - } - Message::GamePicked(choice) => { - app.select_game(choice.id); - app.mod_sel.clear(); - app.plugin_sel.clear(); - app.refresh(); - // The new game's conflicts/health/external decide tab visibility. - return app.refresh_heavy(); - } - Message::ProfilePicked(name) => app.on_profile_picked(&name), - Message::ProfileNameChanged(name) => app.form.profile_name = name, - Message::CreateProfile => app.on_create_profile(), - Message::ToggleMod(id, on) => return app.on_toggle_mod(id, on), - Message::RowClick { pane, index } => { - let (ctrl, shift) = (app.modifiers.control(), app.modifiers.shift()); - app.on_row_click(pane, index, ctrl, shift); - } - Message::ClearSelection => app.active_selection().clear(), - Message::Key(key, mods) => { - app.modifiers = mods; - return app.on_key(&key, mods); - } - Message::Modifiers(mods) => app.modifiers = mods, - - Message::EnableAll => return app.on_enable_all(), - Message::SetSelectedEnabled(on) => return app.on_set_selected(on), - Message::DeleteSelected => app.on_delete_selected(), - Message::ReinstallSelected => return app.on_reinstall_selected(), - Message::TogglePlugin(index) => app.on_toggle_plugin(index), - Message::AutoSort => return app.on_auto_sort(), - Message::MoveSelection { pane, delta } => { - app.on_move_selection(pane, delta); - return app.ensure_visible(pane); - } - Message::DragStart(pane, index) => { - app.focus_pane = pane; - app.drag = Some((index, index)); - } - Message::DragOver(index) => app.on_drag_over(index), - Message::DragEnd => app.on_drag_end(), - Message::Deploy => return app.on_profile_action(Action::Deploy), - Message::Purge => return app.on_profile_action(Action::Undeploy), - Message::Verify => return app.on_profile_action(Action::Verify), - Message::ActionFinished(result) => return app.on_action_finished(result), - Message::DefPicked(choice) => app.on_def_picked(choice), - Message::DefPathChanged(path) => app.form.def_path = path, - Message::InstallPathChanged(path) => app.form.install_path = path, - Message::AddGame => app.on_add_game(), - Message::AddDetected(index) => app.on_add_detected(index), - Message::CancelDownload(id) => app.on_cancel_download(id), - Message::CopyText(text) => return iced::clipboard::write(text), - other => return update_files(app, other), - } - Task::none() -} - -/// File-install, duplicate-prompt, and worker-result messages, split out of -/// [`update`] (which is at the function-length lint's ceiling). -fn update_files(app: &mut App, message: Message) -> Task { - match message { - Message::PickFiles => pick_files(), - Message::FilesPicked(paths) => app.on_install_files(paths), - Message::FileDropped(path) => app.on_install_files(vec![path]), - Message::InstallChecked { path, hash } => app.on_install_checked(path, hash), - Message::DupConfirm => app.on_dup_confirm(), - Message::DupCancel => { - if !app.dup_queue.is_empty() { - app.dup_queue.remove(0); - } - Task::none() - } - Message::PluginCounts(counts) => { - app.plugin_counts = counts; - Task::none() - } - Message::RegistryLoaded(result) => { - app.on_registry_loaded(result); - Task::none() - } - Message::UpdateChecked(result) => { - app.on_update_checked(result); - Task::none() - } - Message::CheckUpdates => spawn_update_check(), - Message::StartUpdate => app.on_start_update(), - Message::UpdateApplied(result) => app.on_update_applied(result), - Message::InstallSupport(index) => app.on_install_support(index), - Message::SupportInstalled(result) => app.on_support_installed(result), - Message::UninstallPlugin(id) => { - app.on_uninstall_plugin(&id); - Task::none() - } - Message::GcPlugins => { - app.on_gc_plugins(); - Task::none() - } - Message::ThemePicked(id) => { - app.on_theme_picked(&id); - Task::none() - } - Message::ArtResolved(game, art) => { - app.art.insert(game, art); - // The selected game's art just landed - derive its accent now. - if app.selected_game == Some(game) { - app.apply_accent(); - } - Task::none() - } - Message::NoOp => Task::none(), - other => update_overlay(app, other), - } -} - -/// Notification-center, wizard, conflict, sort, and scroll messages, split -/// out of [`update`]. -fn update_overlay(app: &mut App, message: Message) -> Task { - match message { - Message::SortBy(key) => app.on_sort_by(key), - Message::SetRule { loser, winner } => { - return app.on_rule_change(|e, p| e.set_mod_rule(p, loser, winner)); - } - Message::ClearRule(a, b) => return app.on_rule_change(|e, p| e.clear_mod_rule(p, a, b)), - Message::ExpandConflict(a, b) => { - app.expanded_conflict = if app.expanded_conflict == Some((a, b)) { - None - } else { - Some((a, b)) - }; - } - Message::PinFile { target, provider } => { - return app.on_rule_change(|e, p| e.set_file_override(p, &target, provider)); - } - Message::Scrolled(pane, offset, height) => match pane { - Pane::Mods => app.mods_view = Some((offset, height)), - Pane::Plugins => app.plugins_view = Some((offset, height)), - }, - Message::ToggleNotes => { - app.notes_open = !app.notes_open; - app.unread = 0; - } - Message::ClearNotes => { - app.notes.clear(); - app.unread = 0; - app.notes_open = false; - } - Message::Configure(id) => app.on_configure(id), - Message::WizardHover { - step, - group, - plugin, - } => { - if let Some(wizard) = &mut app.wizard { - wizard.focus = Some((step, group, plugin)); - } - } - Message::WizardGroupSet { step, group, all } => app.on_wizard_group_set(step, group, all), - Message::WizardPick { - step, - group, - plugin, - } => app.on_wizard_pick(step, group, plugin), - Message::WizardNext => app.on_wizard_step(1), - Message::WizardBack => app.on_wizard_step(-1), - Message::WizardFinish => return app.on_wizard_finish(), - Message::WizardCancel => app.on_wizard_cancel(), - _ => {} - } - Task::none() -} - -fn pick_files() -> Task { - Task::perform( - async { - rfd::AsyncFileDialog::new() - .add_filter("mod archives", &["zip", "7z", "rar", "tar", "gz"]) - .set_title("Add mods") - .pick_files() - .await - .unwrap_or_default() - .iter() - .map(|f| f.path().to_path_buf()) - .collect() - }, - Message::FilesPicked, - ) -} - -impl App { - fn on_booted(&mut self, result: Result) -> Task { - match result { - Ok(booted) => { - self.already_running = booted.link.is_none(); - self.link = booted.link; - self.defs = booted.defs; - self.def_ids = booted.def_ids; - self.detected = booted.detected; - self.paths = Some(booted.paths); - self.service = Some(booted.service); - self.refresh_installed_plugins(); - self.refresh(); - Task::batch([ - self.refresh_heavy(), - self.spawn_registry_fetch(), - spawn_update_check(), - ]) - } - Err(error) => { - self.boot_error = Some(error); - Task::none() - } - } - } - - /// Load the registry index in the background (offline is fine - the - /// section simply stays empty). - fn spawn_registry_fetch(&self) -> Task { - let Some(paths) = self.paths.clone() else { - return Task::none(); - }; - Task::perform(fetch_registry(paths), Message::RegistryLoaded) - } - - fn on_registry_loaded(&mut self, result: Result, String>) { - match result { - Ok(choices) => self.registry = choices, - // Offline or private registry without an override: not an error - // worth a notification, the section just stays empty. - Err(error) => tracing::debug!(%error, "registry index unavailable"), - } - } - - fn on_update_checked(&mut self, result: Result, String>) { - match result { - Ok(Some(info)) => { - let version = info.version.clone(); - self.update = UpdateState::Available(info); - self.note( - Tone::Info, - format!("Update available: v{version} - install it in Settings"), - ); - } - Ok(None) => tracing::debug!("no update available"), - Err(error) => tracing::debug!(%error, "update check failed"), - } - } - - fn on_start_update(&mut self) -> Task { - let UpdateState::Available(info) = &self.update else { - return Task::none(); - }; - let info = info.clone(); - let Some(paths) = self.paths.clone() else { - return Task::none(); - }; - if !info.can_self_install() { - self.note( - Tone::Info, - "This platform installs updates manually - see the release page.".to_owned(), - ); - return Task::none(); - } - self.note(Tone::Info, format!("Downloading v{}…", info.version)); - let dir = paths.cache_dir().join("updates"); - self.update = UpdateState::Installing(info.clone()); - Task::perform(run_update(info, dir), Message::UpdateApplied) - } - - fn on_update_applied(&mut self, result: Result<(), String>) -> Task { - match result { - // The installer is running; quit so it can replace this executable. - Ok(()) => iced::exit(), - Err(error) => { - // Roll back to "available" so the user can retry. - if let UpdateState::Installing(info) = &self.update { - self.update = UpdateState::Available(info.clone()); - } - self.note(Tone::Error, format!("Update failed: {error}")); - Task::none() - } - } - } - - /// Registry entries whose game support is not installed locally yet, - /// paired with their index into `registry`. - #[must_use] - pub fn available_support(&self) -> Vec<(usize, &RegistryChoice)> { - self.registry - .iter() - .enumerate() - .filter(|(_, r)| !self.def_ids.contains(&r.id)) - .collect() - } - - fn on_install_support(&mut self, index: usize) -> Task { - let Some(choice) = self.registry.get(index).cloned() else { - return Task::none(); - }; - let Some(paths) = self.paths.clone() else { - return Task::none(); - }; - self.busy = true; - Task::perform( - async move { - let client = modrix_registry::RegistryClient::new( - modrix_registry::RegistrySource::resolve(), - &paths, - ) - .map_err(|e| e.to_string())?; - client - .install(&choice.entry) - .await - .map_err(|e| e.to_string())?; - Ok(choice.id) - }, - Message::SupportInstalled, - ) - } - - /// Support installed: rescan definitions and detection; when the game is - /// found on disk and not yet registered, register and switch to it - - /// the "pick a game, its plugin just works" flow. - fn on_support_installed(&mut self, result: Result) -> Task { - self.busy = false; - let id = match result { - Ok(id) => id, - Err(error) => { - self.note(Tone::Error, format!("Plugin install failed: {error}")); - return Task::none(); - } - }; - self.note(Tone::Ok, format!("{id} support installed")); - if let Some(paths) = self.paths.clone() { - let (defs, def_ids) = discover_defs(&paths); - self.defs = defs; - self.def_ids = def_ids; - self.detected = detect_installs(&self.defs); - } - self.refresh_installed_plugins(); - let found = self - .detected - .iter() - .position(|d| d.id == id) - .filter(|_| !self.games.iter().any(|g| g.plugin_id == id)); - if let Some(index) = found { - self.on_add_detected(index); - } - Task::none() - } - - /// Start artwork resolution for any game that has none yet (each game - /// once per session; results land via [`Message::ArtResolved`]). - fn spawn_art_fetches(&mut self) -> Task { - let Some(paths) = &self.paths else { - return Task::none(); - }; - let cache = paths.cache_dir().to_path_buf(); - let mut tasks = Vec::new(); - for game in &self.games { - let Some(appid) = game.steam_appid else { - continue; - }; - if !self.art_requested.insert(game.id) { - continue; - } - let id = game.id; - let cache = cache.clone(); - tasks.push(Task::perform( - crate::artwork::resolve(appid, cache), - move |art| Message::ArtResolved(id, art), - )); - } - Task::batch(tasks) - } - - /// Whether a screen applies to the selected game. Load Order exists only - /// for games with a load-order strategy; Conflicts always applies to - /// those, and to other games only while real conflicts (or blockers) - /// exist. Hidden screens leave the nav entirely. - #[must_use] - pub fn screen_visible(&self, screen: Screen) -> bool { - match screen { - Screen::LoadOrder => self.capabilities.is_none_or(|c| c.load_order), - Screen::Conflicts => { - self.capabilities.is_none_or(|c| c.load_order) - || !self.conflicts.is_empty() - || self.health.iter().any(|i| i.blocking) - } - _ => true, - } - } - - /// Switch the theme live and remember the choice for the next launch. - fn on_theme_picked(&mut self, id: &str) { - theme::set_theme(id); - self.theme = theme::app_theme(); - if let Some(paths) = &self.paths { - save_theme_pref(paths, id); - } - } - - fn refresh_installed_plugins(&mut self) { - let Some(paths) = &self.paths else { - return; - }; - self.installed_plugins = modrix_registry::installed_at(paths) - .into_iter() - .map(|m| InstalledPlugin { - id: m.id, - name: m.name, - version: m.version, - }) - .collect(); - } - - fn on_uninstall_plugin(&mut self, id: &str) { - let Some(paths) = self.paths.clone() else { - return; - }; - let referenced: Vec = self.games.iter().map(|g| g.plugin_id.clone()).collect(); - let client = modrix_registry::RegistryClient::new( - modrix_registry::RegistrySource::resolve(), - &paths, - ); - match client.and_then(|c| c.uninstall(id, &referenced).map(|()| c)) { - Ok(_) => self.note(Tone::Ok, format!("{id} removed")), - Err(error) => self.note(Tone::Error, error.to_string()), - } - let (defs, def_ids) = discover_defs(&paths); - self.defs = defs; - self.def_ids = def_ids; - self.refresh_installed_plugins(); - } - - fn on_gc_plugins(&mut self) { - let Some(paths) = self.paths.clone() else { - return; - }; - let referenced: Vec = self.games.iter().map(|g| g.plugin_id.clone()).collect(); - let client = modrix_registry::RegistryClient::new( - modrix_registry::RegistrySource::resolve(), - &paths, - ); - match client.and_then(|c| c.gc(&referenced)) { - Ok(removed) if removed.is_empty() => { - self.note(Tone::Info, "No unused plugins".to_owned()); - } - Ok(removed) => { - self.note(Tone::Ok, format!("Removed unused: {}", removed.join(", "))); - } - Err(error) => self.note(Tone::Error, error.to_string()), - } - let (defs, def_ids) = discover_defs(&paths); - self.defs = defs; - self.def_ids = def_ids; - self.refresh_installed_plugins(); - } - - fn on_navigate(&mut self, screen: Screen) -> Task { - // Screens the selected game does not support are not navigable - // (their nav entries are hidden; this also blocks keyboard paths). - if !self.screen_visible(screen) { - return Task::none(); - } - self.screen = screen; - self.notes_open = false; - if matches!(screen, Screen::LoadOrder | Screen::Conflicts) { - return self.refresh_heavy(); - } - Task::none() - } - - /// Re-pull downloads and engine state. Never blocks: if the engine is - /// mid-deploy the refresh silently waits for the next tick. - fn refresh(&mut self) { - if let Some(service) = &self.service { - let mut downloads = service.manager().list(); - downloads.sort_by_key(|d| std::cmp::Reverse(d.id)); - self.outcomes = downloads - .iter() - .filter(|d| d.state == DownloadState::Complete) - .filter_map(|d| service.install_outcome(d.id).map(|o| (d.id, o))) - .collect(); - self.downloads = downloads; - self.notify_new_outcomes(); - } - self.refresh_engine(); - self.sync_accent(); - } - - /// Keep the accent in step with the selected game: when the selection - /// changes, re-derive from that game's art (falling back to the theme's - /// own accent until the art resolves). - fn sync_accent(&mut self) { - if self.accent_for == self.selected_game { - return; - } - self.accent_for = self.selected_game; - self.apply_accent(); - } - - /// Set the accent from the selected game's swatches (or clear it). - fn apply_accent(&mut self) { - let accent = self - .selected_game - .and_then(|id| self.art.get(&id)) - .and_then(|art| theme::GameAccent::from_swatches(&art.swatches)); - theme::set_game_accent(accent); - // Rebuild the iced palette so its built-in widgets track the accent. - self.theme = theme::app_theme(); - } - - /// Turn newly finished installs into notifications. - fn notify_new_outcomes(&mut self) { - let new: Vec<(DownloadId, InstallOutcome)> = self - .outcomes - .iter() - .filter(|(id, _)| !self.outcome_seen.contains(*id)) - .map(|(id, o)| (*id, o.clone())) - .collect(); - for (id, outcome) in new { - self.outcome_seen.insert(id); - match outcome { - InstallOutcome::Installed { name, configurable } => { - let text = if configurable { - format!("{name} installed · options set to defaults") - } else { - format!("{name} installed") - }; - self.note(Tone::Ok, text); - } - InstallOutcome::Failed(error) => { - self.note(Tone::Error, format!("Install failed: {error}")); - } - InstallOutcome::NoGame => { - self.note(Tone::Info, "Download kept: no game matched".to_owned()); - } - } - } - } - - fn refresh_engine(&mut self) { - let Some(service) = self.service.clone() else { - return; - }; - let Ok(engine) = service.engine().try_lock() else { - return; - }; - let games = match engine.games() { - Ok(games) => games, - Err(error) => { - let text = error.to_string(); - drop(engine); - self.note(Tone::Error, text); - return; - } - }; - self.selected_game = self - .selected_game - .filter(|id| games.iter().any(|g| g.id == *id)) - // Nothing selected this session means we just booted: reopen on the - // game last worked on. Only the first tick pays for this query - - // afterwards the selection is Some and this branch is never taken. - .or_else(|| engine.active_game().ok().flatten().map(|g| g.id)) - .or_else(|| games.first().map(|g| g.id)); - self.games = games; - let Some(game) = self.selected_game else { - self.profiles = Vec::new(); - self.active_profile = None; - self.mods = Vec::new(); - self.external = Vec::new(); - self.order = Vec::new(); - return; - }; - self.profiles = engine.profiles(game).unwrap_or_default(); - self.active_profile = engine.active_profile(game).ok(); - self.mods = engine.mods(game).unwrap_or_default(); - // Note: the external scan (a filesystem walk) deliberately lives in - // refresh_heavy, not here - this runs every tick. - self.order = match &self.active_profile { - Some(profile) => engine.enabled_mods(profile.id).unwrap_or_default(), - None => Vec::new(), - }; - if self.capabilities.is_none() { - self.capabilities = engine.capabilities(game).ok(); - } - drop(engine); - self.apply_mod_sort(); - self.mod_sel.retain_below(self.mods.len()); - if !self.screen_visible(self.screen) { - self.screen = Screen::Dashboard; - } - self.queue_unreviewed_fomods(); - } - - /// Recompute the plugin load order, conflicts, and health - the - /// expensive pass, so it runs only after a mutation or a Load Order - /// visit, never per tick. The staged-tree walk (plugin counts) runs on a - /// worker task so a big library cannot stall the UI thread. - fn refresh_heavy(&mut self) -> Task { - let Some(service) = self.service.clone() else { - return Task::none(); - }; - let Some(profile) = self.active_profile.as_ref().map(|p| p.id) else { - self.plugins = Vec::new(); - self.health = Vec::new(); - self.conflicts = Vec::new(); - return Task::none(); - }; - let Ok(engine) = service.engine().try_lock() else { - return Task::none(); - }; - self.plugins = engine.plugins(profile).unwrap_or_default(); - self.health = engine.health(profile).unwrap_or_default(); - self.conflicts = engine.mod_conflicts(profile).unwrap_or_default(); - // The external scan walks the game directory - heavy-pass work, so a - // per-tick refresh never touches the disk for it. - if let Some(game) = self.selected_game { - self.external = engine.external_mods(game).unwrap_or_default(); - } - drop(engine); - self.plugin_sel.retain_below(self.plugins.len()); - self.spawn_plugin_counts() - } - - /// Count staged plugins per mod off the UI thread (it walks every staged - /// tree, which can be thousands of directory reads on a big library). - fn spawn_plugin_counts(&self) -> Task { - let items: Vec<(ModId, PathBuf)> = self - .mods - .iter() - .map(|m| (m.id, m.staged_path.clone())) - .collect(); - Task::perform( - async move { - tokio::task::spawn_blocking(move || { - items - .iter() - .map(|(id, path)| (*id, staged_plugin_count(path))) - .collect::>() - }) - .await - .unwrap_or_default() - }, - Message::PluginCounts, - ) - } - - /// The display name of a mod, for ids referenced by conflicts/rules. - #[must_use] - pub fn mod_name(&self, id: ModId) -> String { - self.mods - .iter() - .find(|m| m.id == id) - .map_or_else(|| id.to_string(), |m| m.name.clone()) - } - - /// A rule/override changed: persist it and re-evaluate conflicts/health. - fn on_rule_change( - &mut self, - act: impl FnOnce(&Engine, ProfileId) -> modrix_core::Result<()>, - ) -> Task { - let Some(profile) = self.active_profile.clone() else { - return Task::none(); - }; - if self.with_engine(|e| act(e, profile.id)).is_some() { - return self.refresh_heavy(); - } - Task::none() - } - - /// The selection for whichever list currently has focus. - fn active_selection(&mut self) -> &mut Selection { - match self.focus_pane { - Pane::Mods => &mut self.mod_sel, - Pane::Plugins => &mut self.plugin_sel, - } - } - - /// Offer the options wizard once for every FOMOD mod whose defaults were - /// applied automatically (`fomod-auto`) - the popup the installer earned. - fn queue_unreviewed_fomods(&mut self) { - let pending: Vec = self - .mods - .iter() - .filter(|m| m.install_state == "fomod-auto" && !self.prompted.contains(&m.id)) - .map(|m| m.id) - .collect(); - for id in pending { - self.prompted.insert(id); - self.wizard_queue.push(id); - } - self.open_next_wizard(); - } - - /// Pop the next queued mod into the wizard, if none is open. - fn open_next_wizard(&mut self) { - while self.wizard.is_none() && !self.wizard_queue.is_empty() { - let id = self.wizard_queue.remove(0); - self.on_configure(id); - } - } - - /// Closing the wizard without applying accepts the defaults: mark the mod - /// reviewed so it is not offered again, then continue the queue. - fn on_wizard_cancel(&mut self) { - if let Some(wizard) = self.wizard.take() { - let id = wizard.mod_id; - let _ = self.with_engine(|e| e.set_install_state(id, "fomod")); - } - self.open_next_wizard(); - } - - /// Run a quick engine call, reporting failures as notifications. - fn with_engine(&mut self, act: impl FnOnce(&Engine) -> modrix_core::Result) -> Option { - let outcome = { - let service = self.service.as_ref()?; - match service.engine().try_lock() { - Ok(engine) => act(&engine).map_err(|e| e.to_string()), - Err(_) => Err("engine busy, try again".to_owned()), - } - }; - match outcome { - Ok(value) => Some(value), - Err(error) => { - self.note(Tone::Error, error); - None - } - } - } - - fn on_profile_picked(&mut self, name: &str) { - let Some(profile) = self.profiles.iter().find(|p| p.name == name).cloned() else { - return; - }; - if self - .with_engine(|e| e.set_active_profile(profile.id)) - .is_some() - { - self.refresh(); - } - } - - fn on_create_profile(&mut self) { - let name = self.form.profile_name.trim().to_owned(); - let Some(game) = self.selected_game else { - return; - }; - if name.is_empty() { - return; - } - if let Some(profile) = self.with_engine(|e| e.create_profile(game, &name)) { - self.note(Tone::Ok, format!("Profile “{}” created", profile.name)); - self.form.profile_name.clear(); - self.refresh(); - } - } - - fn on_toggle_mod(&mut self, id: ModId, on: bool) -> Task { - let Some(profile) = self.active_profile.clone() else { - return Task::none(); - }; - if self - .with_engine(|e| e.set_enabled(profile.id, id, on)) - .is_some() - { - self.refresh(); - return self.refresh_heavy(); - } - Task::none() - } - - fn on_enable_all(&mut self) -> Task { - let Some(profile) = self.active_profile.clone() else { - return Task::none(); - }; - let disabled: Vec = self - .mods - .iter() - .filter(|m| !self.order.iter().any(|e| e.id == m.id)) - .map(|m| m.id) - .collect(); - let count = disabled.len(); - let done = self.with_engine(|e| { - for id in disabled { - e.set_enabled(profile.id, id, true)?; - } - Ok(()) - }); - if done.is_some() { - self.note(Tone::Ok, format!("{count} mods enabled")); - self.refresh(); - return self.refresh_heavy(); - } - Task::none() - } - - /// The mod ids currently selected in the Mods table. - fn selected_mod_ids(&self) -> Vec { - self.mod_sel - .items - .iter() - .filter_map(|i| self.mods.get(*i).map(|m| m.id)) - .collect() - } - - fn on_set_selected(&mut self, on: bool) -> Task { - let Some(profile) = self.active_profile.clone() else { - return Task::none(); - }; - let ids = self.selected_mod_ids(); - let count = ids.len(); - let done = self.with_engine(|e| { - for id in ids { - e.set_enabled(profile.id, id, on)?; - } - Ok(()) - }); - if done.is_some() { - let verb = if on { "enabled" } else { "disabled" }; - self.note(Tone::Ok, format!("{count} mods {verb}")); - self.refresh(); - return self.refresh_heavy(); - } - Task::none() - } - - fn on_delete_selected(&mut self) { - let ids = self.selected_mod_ids(); - let count = ids.len(); - let done = self.with_engine(|e| { - for id in ids { - e.delete_mod(id)?; - } - Ok(()) - }); - if done.is_some() { - self.note(Tone::Ok, format!("{count} mods deleted")); - self.mod_sel.clear(); - self.refresh(); - } - } - - fn on_reinstall_selected(&mut self) -> Task { - let ids = self.selected_mod_ids(); - if ids.is_empty() { - return Task::none(); - } - self.mod_sel.clear(); - self.spawn_action(Action::ReinstallMany(ids)) - } - - /// A row was clicked: plain = select only, Ctrl = toggle, Shift = range. - /// A plain click on an already-selected row deselects everything - - /// consistent with Vortex and common list controls. - fn on_row_click(&mut self, pane: Pane, index: usize, ctrl: bool, shift: bool) { - self.focus_pane = pane; - let sel = self.active_selection(); - if shift { - sel.range_to(index); - } else if ctrl { - sel.toggle(index); - } else if sel.items.contains(&index) { - sel.clear(); - } else { - sel.only(index); - } - } - - /// Keyboard control for the visible list. Arrows move the cursor, - /// Shift extends, Ctrl(+Shift) moves the selected plugin(s), Ctrl+A - /// selects everything, Escape clears. Scrolls to keep the cursor - /// visible. - fn on_key( - &mut self, - key: &iced::keyboard::Key, - mods: iced::keyboard::Modifiers, - ) -> Task { - use iced::keyboard::{Key, key::Named}; - // The wizard owns the keyboard; other screens have text inputs. - let pane = match (self.wizard.is_some(), self.screen) { - (false, Screen::Mods) => Pane::Mods, - (false, Screen::LoadOrder) => Pane::Plugins, - _ => return Task::none(), - }; - self.focus_pane = pane; - if mods.control() - && let Key::Character(c) = key - && c.as_str().eq_ignore_ascii_case("a") - { - let len = self.list_len(pane); - let sel = self.active_selection(); - sel.items = (0..len).collect(); - sel.anchor = Some(0); - sel.cursor = len.checked_sub(1); - return Task::none(); - } - let delta: i8 = match key { - Key::Named(Named::ArrowUp) => -1, - Key::Named(Named::ArrowDown) => 1, - Key::Named(Named::Escape) => { - self.active_selection().clear(); - return Task::none(); - } - _ => return Task::none(), - }; - if mods.control() && pane == Pane::Plugins { - // Ctrl moves the selected plugins; Ctrl+Shift moves a block. - self.on_move_selection(Pane::Plugins, delta); - } else if mods.shift() { - self.extend_cursor(delta); - } else { - self.move_cursor(delta); - } - self.ensure_visible(pane) - } - - /// Scroll the pane so its cursor row stays inside the viewport. - fn ensure_visible(&self, pane: Pane) -> Task { - use iced::widget::scrollable; - let (row_height, view, cursor) = match pane { - Pane::Mods => (40.0_f32, self.mods_view, self.mod_sel.cursor), - Pane::Plugins => (50.0_f32, self.plugins_view, self.plugin_sel.cursor), - }; - let Some(cursor) = cursor else { - return Task::none(); - }; - #[expect(clippy::cast_precision_loss, reason = "list indices are small")] - let top = cursor as f32 * row_height; - let target = match view { - None => Some(top.max(0.0)), - Some((offset, _)) if top < offset => Some(top), - Some((offset, height)) if top + row_height > offset + height => { - Some((top + row_height - height).max(0.0)) - } - Some(_) => None, - }; - match target { - Some(y) => { - scrollable::scroll_to(scroll_id(pane), scrollable::AbsoluteOffset { x: 0.0, y }) - } - None => Task::none(), - } - } - - fn on_sort_by(&mut self, key: SortKey) { - let (current, ascending) = self.mod_sort; - self.mod_sort = if current == key { - (key, !ascending) - } else { - (key, true) - }; - self.mod_sel.clear(); - self.apply_mod_sort(); - } - - /// Sort `self.mods` by the chosen column (stable; name tiebreak). - fn apply_mod_sort(&mut self) { - let enabled: std::collections::HashSet = self.order.iter().map(|m| m.id).collect(); - let (key, ascending) = self.mod_sort; - self.mods.sort_by(|a, b| { - let ord = match key { - // True install chronology: rows that predate the provenance - // migration have no timestamp and sort first (they really were - // installed earlier); id breaks ties within the same second. - SortKey::Installed => (a.created_at.unwrap_or(i64::MIN), a.id) - .cmp(&(b.created_at.unwrap_or(i64::MIN), b.id)), - SortKey::Name => compare_names(&a.name, &b.name), - SortKey::Enabled => enabled - .contains(&b.id) - .cmp(&enabled.contains(&a.id)) - .then_with(|| compare_names(&a.name, &b.name)), - SortKey::Version => a - .version - .cmp(&b.version) - .then_with(|| compare_names(&a.name, &b.name)), - SortKey::Source => a - .source - .cmp(&b.source) - .then_with(|| compare_names(&a.name, &b.name)), - }; - if ascending { ord } else { ord.reverse() } - }); - } - - fn list_len(&self, pane: Pane) -> usize { - match pane { - Pane::Mods => self.mods.len(), - Pane::Plugins => self.plugins.len(), - } - } - - fn move_cursor(&mut self, delta: i8) { - let len = self.list_len(self.focus_pane); - if len == 0 { - return; - } - let sel = self.active_selection(); - let next = step(sel.cursor.unwrap_or(0), delta, len); - sel.only(next); - } - - fn extend_cursor(&mut self, delta: i8) { - let len = self.list_len(self.focus_pane); - if len == 0 { - return; - } - let sel = self.active_selection(); - let next = step(sel.cursor.unwrap_or(0), delta, len); - sel.range_to(next); - } - - fn on_toggle_plugin(&mut self, index: usize) { - let Some(plugin) = self.plugins.get_mut(index) else { - return; - }; - plugin.enabled = !plugin.enabled; - self.commit_plugin_order(); - } - - fn on_auto_sort(&mut self) -> Task { - match self.active_profile.clone() { - Some(profile) => self.spawn_action(Action::AutoSortPlugins(profile.id)), - None => Task::none(), - } - } - - /// Move the focused list's current selection by `delta`, keeping the - /// moved rows selected and the cursor on them (so the pointer stays put - /// relative to the row for arrow-button clicks). - fn on_move_selection(&mut self, pane: Pane, delta: i8) { - self.focus_pane = pane; - match pane { - Pane::Mods => {} // mod order is derived from the plugin order now - Pane::Plugins => self.move_plugins(delta), - } - } - - fn move_plugins(&mut self, delta: i8) { - let len = self.plugins.len(); - let mut indices: Vec = self.plugin_sel.items.iter().copied().collect(); - if indices.is_empty() - && let Some(c) = self.plugin_sel.cursor - { - indices.push(c); - } - if indices.is_empty() || len == 0 { - return; - } - // Moving down processes bottom-first; up processes top-first. - if delta > 0 { - indices.sort_by(|a, b| b.cmp(a)); - } else { - indices.sort_unstable(); - } - // Bail if a block edge is already at the boundary. - let at_edge = indices - .iter() - .any(|i| (delta < 0 && *i == 0) || (delta > 0 && *i >= len.saturating_sub(1))); - if at_edge { - return; - } - let mut moved = std::collections::BTreeSet::new(); - for i in indices { - let target = if delta < 0 { - i.saturating_sub(1) - } else { - i.saturating_add(1) - }; - self.plugins.swap(i, target); - moved.insert(target); - } - let cursor = self.plugin_sel.cursor.map(|c| step(c, delta, len)); - self.plugin_sel.items = moved; - self.plugin_sel.cursor = cursor; - self.commit_plugin_order(); - } - - fn on_drag_over(&mut self, index: usize) { - if let Some((from, _)) = self.drag - && index < self.plugins.len() - { - self.drag = Some((from, index)); - } - } - - fn on_drag_end(&mut self) { - let Some((from, to)) = self.drag.take() else { - return; - }; - if from != to && from < self.plugins.len() && to < self.plugins.len() { - let moved = self.plugins.remove(from); - self.plugins.insert(to, moved); - self.plugin_sel.only(to); - self.commit_plugin_order(); - } - } - - fn commit_plugin_order(&mut self) { - let Some(profile) = self.active_profile.clone() else { - return; - }; - let order: Vec<(String, bool)> = self - .plugins - .iter() - .map(|p| (p.name.clone(), p.enabled)) - .collect(); - if self - .with_engine(|e| e.set_plugin_order(profile.id, &order)) - .is_some() - { - // Re-pull so master-tier partitioning and health re-evaluate, - // but keep the user's cursor. - let cursor = self.plugin_sel.cursor; - self.refresh(); - self.plugin_sel.cursor = cursor.filter(|c| *c < self.plugins.len()); - } - } - - fn on_profile_action(&mut self, make: impl FnOnce(ProfileId) -> Action) -> Task { - let Some(profile) = self.active_profile.clone() else { - return Task::none(); - }; - self.spawn_action(make(profile.id)) - } - - /// Installing starts with an off-thread content hash so an archive that is - /// already installed raises the duplicate prompt instead of silently - /// staging a second copy. - fn on_install_files(&mut self, paths: Vec) -> Task { - if self.selected_game.is_none() { - self.note(Tone::Error, "Register a game first".to_owned()); - return Task::none(); - } - let tasks: Vec> = paths - .into_iter() - .filter(|p| p.exists()) - .map(|path| { - Task::perform( - async move { - let hash = if path.is_dir() { - None - } else { - let for_hash = path.clone(); - tokio::task::spawn_blocking(move || { - modrix_core::sha256_file(&for_hash).ok() - }) - .await - .ok() - .flatten() - }; - (path, hash) - }, - |(path, hash)| Message::InstallChecked { path, hash }, - ) - }) - .collect(); - Task::batch(tasks) - } - - /// The archive's hash is in: install it, or raise the duplicate prompt if - /// this exact content is already staged for the selected game. - fn on_install_checked(&mut self, path: PathBuf, hash: Option) -> Task { - let Some(game) = self.selected_game else { - return Task::none(); - }; - let existing = hash - .and_then(|h| self.with_engine(|e| e.find_by_archive_hash(game, &h))) - .and_then(|mods| mods.into_iter().next()); - match existing { - Some(m) => { - self.dup_queue.push(DupPrompt { - path, - existing: m.id, - existing_name: m.name, - }); - Task::none() - } - None => self.spawn_action(Action::Install { game, path }), - } - } - - /// Duplicate prompt accepted: reinstall the existing mod (fresh staging - /// from its archive - same content as the file the user just dropped). - fn on_dup_confirm(&mut self) -> Task { - if self.dup_queue.is_empty() { - return Task::none(); - } - let prompt = self.dup_queue.remove(0); - self.spawn_action(Action::ReinstallMany(vec![prompt.existing])) - } - - /// Run a slow engine action on a worker thread so the UI stays live. - fn spawn_action(&mut self, action: Action) -> Task { - let Some(service) = self.service.clone() else { - return Task::none(); - }; - self.busy = true; - let engine = Arc::clone(service.engine()); - Task::perform( - async move { - match tokio::task::spawn_blocking(move || run_action(&engine, &action)).await { - Ok(result) => result, - Err(error) => Err(format!("engine worker crashed: {error}")), - } - }, - Message::ActionFinished, - ) - } - - fn on_action_finished(&mut self, result: Result) -> Task { - self.busy = false; - match result { - Ok(text) => self.note(Tone::Ok, text), - Err(text) => self.note(Tone::Error, text), - } - self.refresh(); - // Always re-evaluate health/conflicts after a mutation so the bell and - // notification panel reflect the new truth (a fixed issue disappears). - self.refresh_heavy() - } - - /// Make `game` the one being managed and remember it, so the next launch - /// reopens here instead of defaulting to the first-registered game. - fn select_game(&mut self, game: GameId) { - self.selected_game = Some(game); - // The new game decides which tabs exist and what is external. - self.capabilities = None; - self.external = Vec::new(); - let _ = self.with_engine(|e| e.set_active_game(game)); - } - - /// A definition was picked in the register form: adopt it and, if that game - /// was detected on disk and no path is typed yet, pre-fill its install path. - fn on_def_picked(&mut self, choice: DefChoice) { - if self.form.install_path.trim().is_empty() - && let Some(found) = self.detected.iter().find(|d| d.def == choice) - { - self.form.install_path = found.install.display().to_string(); - } - self.form.def_choice = Some(choice); - } - - fn on_add_game(&mut self) { - let install = PathBuf::from(self.form.install_path.trim()); - if !install.is_dir() { - return self.note( - Tone::Error, - format!("{} is not a directory", install.display()), - ); - } - let def = match self.load_chosen_def() { - Ok(def) => def, - Err(error) => return self.note(Tone::Error, error), - }; - if let Some(game) = self.with_engine(|e| e.add_game(&def, &install, "manual")) { - self.note(Tone::Ok, format!("{} registered", game.name)); - self.select_game(game.id); - self.form.install_path.clear(); - self.form.def_path.clear(); - self.refresh(); - } - } - - /// Register a detected install with one click and switch to it. Store kind - /// is `steam` since detection came from the Steam library metadata. - fn on_add_detected(&mut self, index: usize) { - let Some(found) = self.detected.get(index).cloned() else { - return; - }; - let parsed = GameDef::from_toml_str(&found.def.toml, std::path::Path::new("")); - let def = match parsed { - Ok(def) => def, - Err(error) => return self.note(Tone::Error, error.to_string()), - }; - let install = found.install; - if let Some(game) = self.with_engine(|e| e.add_game(&def, &install, "steam")) { - let message = format!("{} added from {}", game.name, install.display()); - self.note(Tone::Ok, message); - self.select_game(game.id); - self.refresh(); - } - } - - /// Detected installs not yet registered (matched by stable id), paired with - /// their index into `detected` for the add message. Drives the Games - /// screen's "found installed" section. - pub fn unregistered_detected(&self) -> Vec<(usize, &Detected)> { - self.detected - .iter() - .enumerate() - .filter(|(_, d)| !self.games.iter().any(|g| g.plugin_id == d.id)) - .collect() - } - - fn load_chosen_def(&self) -> Result { - let explicit = self.form.def_path.trim(); - if !explicit.is_empty() { - return GameDef::from_file(std::path::Path::new(explicit)).map_err(|e| e.to_string()); - } - match &self.form.def_choice { - Some(choice) => { - GameDef::from_toml_str(&choice.toml, std::path::Path::new("")) - .map_err(|e| e.to_string()) - } - None => Err("Pick a game definition".to_owned()), - } - } - - fn on_cancel_download(&mut self, id: DownloadId) { - let Some(service) = &self.service else { - return; - }; - if let Err(error) = service.manager().cancel(id) { - self.note(Tone::Error, error.to_string()); - } - self.refresh(); - } - - fn on_configure(&mut self, id: ModId) { - let Some(m) = self.mods.iter().find(|m| m.id == id).cloned() else { - return; - }; - let present = self - .with_engine(|e| Ok(modrix_service::present_files(e, m.game_id))) - .unwrap_or_default(); - match fomod::parse(&m.staged_path) { - Ok(Some(installer)) => { - let selections = fomod::defaults(&installer, &present); - self.wizard = Some(Wizard { - mod_id: m.id, - mod_name: m.name, - staged_path: m.staged_path, - installer, - selections, - step: 0, - focus: None, - present, - }); - } - Ok(None) => self.note(Tone::Info, "No installer options in this mod".to_owned()), - Err(error) => self.note(Tone::Error, error.to_string()), - } - } - - /// Check every usable option in a group, or uncheck all but Required. - fn on_wizard_group_set(&mut self, step: usize, group: usize, all: bool) { - let Some(wizard) = &mut self.wizard else { - return; - }; - let flags = fomod::flags_of(&wizard.installer, &wizard.selections, &wizard.present); - let Some(g) = wizard - .installer - .steps - .get(step) - .and_then(|s| s.groups.get(group)) - else { - return; - }; - if g.kind == fomod::GroupKind::All { - return; - } - let picked: std::collections::BTreeSet = g - .plugins - .iter() - .enumerate() - .filter(|(_, p)| { - let kind = fomod::plugin_kind(&p.kind, &flags, &wizard.present); - if all { - kind != fomod::PluginKind::NotUsable - } else { - kind == fomod::PluginKind::Required - } - }) - .map(|(i, _)| i) - .collect(); - if let Some(sel) = wizard - .selections - .get_mut(step) - .and_then(|s| s.get_mut(group)) - { - *sel = picked; - } - } - - fn on_wizard_pick(&mut self, step: usize, group: usize, plugin: usize) { - let Some(wizard) = &mut self.wizard else { - return; - }; - wizard.focus = Some((step, group, plugin)); - let Some(kind) = wizard - .installer - .steps - .get(step) - .and_then(|s| s.groups.get(group)) - .map(|g| g.kind) - else { - return; - }; - let Some(sel) = wizard - .selections - .get_mut(step) - .and_then(|s| s.get_mut(group)) - else { - return; - }; - match kind { - fomod::GroupKind::All => {} - fomod::GroupKind::ExactlyOne => { - sel.clear(); - sel.insert(plugin); - } - fomod::GroupKind::AtMostOne => { - let had = sel.remove(&plugin); - sel.clear(); - if !had { - sel.insert(plugin); - } - } - fomod::GroupKind::Any => { - if !sel.remove(&plugin) { - sel.insert(plugin); - } - } - fomod::GroupKind::AtLeastOne => { - // The group cannot become empty (Vortex parity). - if sel.contains(&plugin) { - if sel.len() > 1 { - sel.remove(&plugin); - } - } else { - sel.insert(plugin); - } - } - } - } - - fn on_wizard_step(&mut self, delta: i8) { - let Some(wizard) = &mut self.wizard else { - return; - }; - let pages = wizard.visible_steps().len().max(1); - let next = if delta < 0 { - wizard.step.saturating_sub(1) - } else { - wizard.step.saturating_add(1) - }; - wizard.step = next.min(pages.saturating_sub(1)); - } - - fn on_wizard_finish(&mut self) -> Task { - let Some(wizard) = self.wizard.take() else { - return Task::none(); - }; - let Some(m) = self.mods.iter().find(|m| m.id == wizard.mod_id).cloned() else { - return Task::none(); - }; - self.spawn_action(Action::ApplyWizard { - mod_id: wizard.mod_id, - staged: m.staged_path, - installer: Box::new(wizard.installer), - selections: wizard.selections, - present: wizard.present, - }) - } - - fn note(&mut self, tone: Tone, text: String) { - self.notes.insert( - 0, - Note { - tone, - text, - at: std::time::Instant::now(), - }, - ); - self.notes.truncate(MAX_NOTES); - if !self.notes_open { - self.unread = self.unread.saturating_add(1); - } - } - - /// Drop event notifications past their TTL so the panel never shows stale - /// news. Runs every tick; live conditions are rendered from `health` - /// directly and are not involved. - fn expire_notes(&mut self) { - self.notes.retain(|n| n.at.elapsed() < NOTE_TTL); - self.unread = self.unread.min(self.notes.len()); - } -} - -/// Plugins at the top level of a staged tree (bounded scan). -fn staged_plugin_count(staged: &std::path::Path) -> usize { - let Ok(entries) = std::fs::read_dir(staged) else { - return 0; - }; - entries - .flatten() - .take(512) - .filter(|e| { - modrix_core::esp::is_plugin_name(&e.file_name().to_string_lossy()) && e.path().is_file() - }) - .count() -} - -fn run_install(engine: &Engine, game: GameId, path: &std::path::Path) -> Result { - match modrix_service::install_file(engine, game, path) { - Ok(InstallOutcome::Installed { name, configurable }) => Ok(if configurable { - format!("{name} installed · options set to defaults") - } else { - format!("{name} installed") - }), - Ok(other) => Err(format!("install did not finish: {other:?}")), - Err(error) => Err(format!("{error:#}")), - } -} - -/// Materialize a wizard's resolved file operations and mark the mod reviewed. -fn apply_wizard( - engine: &Engine, - mod_id: ModId, - staged: &std::path::Path, - ops: &[fomod::FileOp], -) -> Result { - let placed = fomod::apply(staged, ops).map_err(|e| e.to_string())?; - engine - .set_install_state(mod_id, "fomod") - .map_err(|e| e.to_string())?; - Ok(format!( - "Options applied · {placed} files · deploy to update" - )) -} - -/// Execute one slow action while holding the engine lock (worker thread). -/// Reinstall each mod from its archive, re-run FOMOD defaults, and re-enable. -fn run_reinstall_many(engine: &Engine, ids: &[ModId]) -> Result { - let mut done: usize = 0; - for id in ids { - let fresh = engine.reinstall_mod(*id).map_err(|e| e.to_string())?; - modrix_service::fomod_pass(engine, &fresh).map_err(|e| format!("{e:#}"))?; - if let Ok(profile) = engine.active_profile(fresh.game_id) { - let _ = engine.set_enabled(profile.id, fresh.id, true); - } - done = done.saturating_add(1); - } - Ok(format!("{done} mods reinstalled")) -} - -fn run_action(engine: &Mutex, action: &Action) -> Result { - let engine = engine - .lock() - .map_err(|_| "engine lock poisoned".to_owned())?; - match action { - Action::Deploy(profile) => engine - .deploy(*profile) - .map(|r| { - format!( - "Deployed · {} added · {} removed · {} unchanged", - r.added(), - r.removed(), - r.unchanged() - ) - }) - .map_err(|e| e.to_string()), - Action::Undeploy(profile) => engine - .undeploy(*profile) - .map(|r| format!("Purged · {} files restored", r.removed())) - .map_err(|e| e.to_string()), - Action::Verify(profile) => engine - .verify(*profile) - .map(|r| { - if r.is_clean() { - format!("Verified · {} files healthy", r.checked()) - } else { - format!( - "Verify: {} of {} files changed", - r.issues().len(), - r.checked() - ) - } - }) - .map_err(|e| e.to_string()), - Action::Install { game, path } => run_install(&engine, *game, path), - Action::ReinstallMany(ids) => run_reinstall_many(&engine, ids), - Action::AutoSortPlugins(profile) => { - let plugins = engine - .auto_sort_plugins(*profile) - .map_err(|e| e.to_string())?; - Ok(format!("Load order sorted · {} plugins", plugins.len())) - } - Action::ApplyWizard { - mod_id, - staged, - installer, - selections, - present, - } => { - let ops = fomod::resolve(installer, selections, present); - apply_wizard(&engine, *mod_id, staged, &ops) - } - } -} diff --git a/crates/modrix-gui/src/art.rs b/crates/modrix-gui/src/art.rs new file mode 100644 index 0000000..bd6efc4 --- /dev/null +++ b/crates/modrix-gui/src/art.rs @@ -0,0 +1,389 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Game artwork: Steam's own library images, turned into the UI's identity. +//! +//! Steam keeps each installed game's store art under +//! `/appcache/librarycache//`, so no network and no API key are +//! needed. A missing file is fetched once from Steam's public CDN. +//! +//! * `library_hero.jpg`: the wide, text-free background. It fills the top of +//! the window, and a soft copy (blurred, dimmed) tints the whole backdrop. +//! Its vibrant swatches become the accent colour. +//! * `library_600x900.jpg`: the portrait cover, on the game switcher. +//! * `logo.png`: the transparent title art, on the overview hero. +//! +//! Decoding and resizing run on a blocking worker, never on the UI thread. + +use std::path::{Path, PathBuf}; + +use image::RgbaImage; +use image::imageops::{self, FilterType}; + +/// Decoded RGBA: width, height, bytes. +pub type Rgba = (u32, u32, Vec); + +/// Art decoded off the UI thread, ready to upload. +#[derive(Debug, Default)] +pub struct ArtData { + /// The wide hero, sharp. + pub hero: Option, + /// The hero, blurred and dimmed, for the full-window backdrop. + pub soft: Option, + /// The portrait cover. + pub cover: Option, + /// The transparent logo. + pub logo: Option, + /// Vibrant swatches (sRGB, 0..1), most representative first. + pub swatches: Vec<[f32; 3]>, + /// The backdrop baked flat, keyed `(dark, calm)` (see `bake`). + pub bands: Vec<((bool, bool), Rgba)>, +} + +/// Art the view draws. +#[derive(Debug, Clone, Default)] +pub struct ArtSet { + /// The wide hero. + pub hero: Option, + /// The baked backdrop bands, keyed `(dark, calm)`. + pub bands: Vec<((bool, bool), rune::Pixels)>, + /// The portrait cover. + pub cover: Option, + /// The logo. + pub logo: Option, + /// Vibrant swatches, linear colour. + pub swatches: Vec, +} + +impl ArtSet { + /// The baked backdrop for an appearance and screen kind. + #[must_use] + pub fn band(&self, dark: bool, calm: bool) -> Option<&rune::Pixels> { + self.bands + .iter() + .find(|(key, _)| *key == (dark, calm)) + .map(|(_, px)| px) + } + + /// Upload decoded art into pixel buffers. + #[must_use] + pub fn from_data(data: ArtData) -> ArtSet { + let upload = |img: Option| { + img.map(|(w, h, bytes)| { + let pixels = rune::Pixels::new(); + pixels.set(w, h, bytes); + pixels + }) + }; + ArtSet { + hero: upload(data.hero), + bands: data + .bands + .into_iter() + .filter_map(|(key, img)| upload(Some(img)).map(|px| (key, px))) + .collect(), + cover: upload(data.cover), + logo: upload(data.logo), + swatches: data + .swatches + .into_iter() + .map(|c| srgb(c[0], c[1], c[2])) + .collect(), + } + } +} + +/// An sRGB colour (0..1 channels) as Rune's linear colour. +#[must_use] +pub fn srgb(r: f32, g: f32, b: f32) -> rune::Color { + use rune::color::srgb_decode; + rune::Color { + r: srgb_decode(r), + g: srgb_decode(g), + b: srgb_decode(b), + a: 1.0, + } +} + +/// Largest artwork file fetched from the CDN. +const MAX_ART_BYTES: usize = 4 * 1024 * 1024; +/// Hero width kept for drawing. +const HERO_W: u32 = 1920; +/// Soft backdrop width (it is blurred, so small is fine). +const SOFT_W: u32 = 480; + +/// Locate (or fetch once) each asset, then decode it on a blocking worker. +pub async fn resolve(appid: i64, cache_dir: PathBuf) -> ArtData { + let dir = cache_dir.join("artwork").join(appid.to_string()); + if let Err(error) = std::fs::create_dir_all(&dir) { + tracing::debug!(%error, "artwork cache unavailable"); + } + let hero = asset(appid, "library_hero.jpg", &dir).await; + let cover = asset(appid, "library_600x900.jpg", &dir).await; + let logo = asset(appid, "logo.png", &dir).await; + tokio::task::spawn_blocking(move || { + decode_all(hero.as_deref(), cover.as_deref(), logo.as_deref()) + }) + .await + .unwrap_or_default() +} + +/// Art already in a local Steam library cache, decoded now (snapshot scenes). +#[must_use] +pub fn local(appid: i64) -> ArtData { + let find = |file: &str| { + modrix_core::detect::steam_roots() + .into_iter() + .take(16) + .map(|root| { + root.join("appcache/librarycache") + .join(appid.to_string()) + .join(file) + }) + .find(|p| p.is_file()) + }; + decode_all( + find("library_hero.jpg").as_deref(), + find("library_600x900.jpg").as_deref(), + find("logo.png").as_deref(), + ) +} + +fn decode_all(hero: Option<&Path>, cover: Option<&Path>, logo: Option<&Path>) -> ArtData { + let hero_img = hero.and_then(|p| image::open(p).ok()); + let mut data = ArtData::default(); + if let Some(img) = &hero_img { + data.swatches = swatches(&img.to_rgba8()); + let sharp = fit_width(img, HERO_W); + data.soft = Some(soften(img)); + data.hero = Some(into_rgba(sharp)); + let colors: Vec = data + .swatches + .iter() + .map(|c| srgb(c[0], c[1], c[2])) + .collect(); + data.bands = crate::bake::all(&crate::bake::Sources { + hero: data.hero.as_ref(), + soft: data.soft.as_ref(), + swatches: &colors, + }); + } + data.cover = cover + .and_then(|p| image::open(p).ok()) + .map(|img| into_rgba(img.resize_exact(360, 540, FilterType::Lanczos3).to_rgba8())); + data.logo = logo + .and_then(|p| image::open(p).ok()) + .map(|img| into_rgba(fit_width(&img, 800))); + data +} + +fn into_rgba(img: RgbaImage) -> Rgba { + let (w, h) = img.dimensions(); + (w, h, img.into_raw()) +} + +/// Scale down to at most `max_w` wide, keeping the aspect. +fn fit_width(img: &image::DynamicImage, max_w: u32) -> RgbaImage { + if img.width() <= max_w { + return img.to_rgba8(); + } + let h = max_w + .saturating_mul(img.height()) + .checked_div(img.width()) + .unwrap_or(1) + .max(1); + img.resize_exact(max_w, h, FilterType::Lanczos3).to_rgba8() +} + +/// A heavily blurred, dimmed copy for the backdrop wash. +fn soften(img: &image::DynamicImage) -> Rgba { + let h = SOFT_W + .saturating_mul(img.height()) + .checked_div(img.width().max(1)) + .unwrap_or(1) + .max(1); + let small = img + .resize_exact((SOFT_W / 4).max(1), (h / 4).max(1), FilterType::Triangle) + .to_rgba8(); + let blurred = imageops::blur(&small, 3.0); + let mut out = imageops::resize(&blurred, SOFT_W, h, FilterType::Triangle); + for px in out.pixels_mut() { + for c in px.0.iter_mut().take(3) { + *c = scale_byte(*c, 0.72); + } + } + into_rgba(out) +} + +#[expect( + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "the value is clamped to [0,255] before the cast" +)] +fn scale_byte(c: u8, by: f32) -> u8 { + (f32::from(c) * by).clamp(0.0, 255.0) as u8 +} + +/// Steam's local cache first, else the public CDN (mirrored once). +async fn asset(appid: i64, file: &str, dir: &Path) -> Option { + for root in modrix_core::detect::steam_roots().into_iter().take(16) { + let p = root + .join("appcache/librarycache") + .join(appid.to_string()) + .join(file); + if p.is_file() { + return Some(p); + } + } + fetch_cdn(appid, file, dir).await +} + +async fn fetch_cdn(appid: i64, file: &str, dir: &Path) -> Option { + let dest = dir.join(file); + if dest.is_file() { + return Some(dest); + } + let url = format!("https://cdn.cloudflare.steamstatic.com/steam/apps/{appid}/{file}"); + let client = modrix_download::http::HttpClient::new().ok()?; + let response = client.get(&url, &[]).await.ok()?; + if response.status != 200 { + return None; + } + let bytes = response.bytes(MAX_ART_BYTES).await.ok()?; + std::fs::write(&dest, &bytes).ok()?; + Some(dest) +} + +/// Hue buckets for swatch extraction. +const BUCKETS: usize = 24; + +/// The most representative vibrant colours: bucket saturated, mid-bright +/// pixels by hue, weight each by population, return the top three. +#[expect( + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + clippy::cast_precision_loss, + reason = "the hue bucket cast is bounded and non-negative" +)] +#[must_use] +pub fn swatches(img: &RgbaImage) -> Vec<[f32; 3]> { + let small = imageops::resize(img, 64, 64, FilterType::Triangle); + let mut weight = [0.0_f32; BUCKETS]; + let mut sum = [[0.0_f32; 3]; BUCKETS]; + for px in small.pixels() { + let rgb = [px.0[0], px.0[1], px.0[2]].map(|c| f32::from(c) / 255.0); + let (hue, sat, light) = rgb_to_hsl(rgb); + if !(0.12..=0.95).contains(&light) || sat < 0.28 { + continue; + } + let w = sat * (1.0 - (light - 0.55).abs() * 1.3).max(0.15); + let bucket = ((hue * BUCKETS as f32) as usize).min(BUCKETS - 1); + if let (Some(wref), Some(sref)) = (weight.get_mut(bucket), sum.get_mut(bucket)) { + *wref += w; + for (acc, ch) in sref.iter_mut().zip(rgb) { + *acc += ch * w; + } + } + } + let mut scored: Vec<(f32, [f32; 3])> = weight + .iter() + .zip(sum.iter()) + .filter(|(w, _)| **w > 0.0) + .map(|(&w, s)| (w, s.map(|c| c / w))) + .collect(); + scored.sort_by(|a, b| b.0.total_cmp(&a.0)); + scored.into_iter().take(3).map(|(_, c)| c).collect() +} + +/// RGB (0..1) to HSL (each 0..1). +#[must_use] +pub fn rgb_to_hsl([r, g, b]: [f32; 3]) -> (f32, f32, f32) { + let max = r.max(g).max(b); + let min = r.min(g).min(b); + let light = f32::midpoint(max, min); + let d = max - min; + if d.abs() < f32::EPSILON { + return (0.0, 0.0, light); + } + let sat = d / (1.0 - (2.0 * light - 1.0).abs()); + let hue = if (max - r).abs() < f32::EPSILON { + (((g - b) / d) % 6.0 + 6.0) % 6.0 + } else if (max - g).abs() < f32::EPSILON { + (b - r) / d + 2.0 + } else { + (r - g) / d + 4.0 + }; + (hue / 6.0, sat.clamp(0.0, 1.0), light) +} + +/// HSL (each 0..1) to RGB (0..1): the inverse, for the round-trip test. +#[cfg(test)] +#[must_use] +pub fn hsl_to_rgb(hue: f32, sat: f32, light: f32) -> [f32; 3] { + if sat.abs() < f32::EPSILON { + return [light; 3]; + } + let q = if light < 0.5 { + light * (1.0 + sat) + } else { + light + sat - light * sat + }; + let p = 2.0 * light - q; + let channel = |t: f32| { + let t = t.rem_euclid(1.0); + if t < 1.0 / 6.0 { + p + (q - p) * 6.0 * t + } else if t < 0.5 { + q + } else if t < 2.0 / 3.0 { + p + (q - p) * (2.0 / 3.0 - t) * 6.0 + } else { + p + } + }; + [ + channel(hue + 1.0 / 3.0), + channel(hue), + channel(hue - 1.0 / 3.0), + ] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hsl_round_trips() { + for rgb in [[0.2, 0.6, 0.9], [0.8, 0.1, 0.3], [0.5, 0.5, 0.5]] { + let (h, s, l) = rgb_to_hsl(rgb); + let back = hsl_to_rgb(h, s, l); + for (a, b) in back.iter().zip(rgb) { + assert!((a - b).abs() < 0.02, "{back:?} vs {rgb:?}"); + } + } + } + + #[test] + fn swatches_pick_the_vibrant_region() { + let mut img = RgbaImage::from_pixel(64, 64, image::Rgba([10, 10, 12, 255])); + for y in 0..20 { + for x in 0..64 { + img.put_pixel(x, y, image::Rgba([230, 120, 20, 255])); + } + } + let found = swatches(&img); + let top = found.first().copied().unwrap(); + assert!(top[0] > top[2], "expected a warm swatch, got {top:?}"); + } + + #[test] + fn soften_keeps_aspect() { + let img = image::DynamicImage::ImageRgba8(RgbaImage::from_pixel( + 1920, + 620, + image::Rgba([200, 100, 50, 255]), + )); + let (w, h, bytes) = soften(&img); + assert_eq!(w, SOFT_W); + assert_eq!(h, 155); + assert_eq!(bytes.len(), 480 * 155 * 4); + } +} diff --git a/crates/modrix-gui/src/artwork.rs b/crates/modrix-gui/src/artwork.rs deleted file mode 100644 index 4f1b0f6..0000000 --- a/crates/modrix-gui/src/artwork.rs +++ /dev/null @@ -1,472 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -//! Game artwork: Steam's own library images, turned into the UI's identity. -//! -//! Steam keeps every installed game's storefront art under -//! `/appcache/librarycache//` - no network, no API keys. Each -//! asset has a distinct job, and we use the right one in the right place: -//! -//! * `library_hero.jpg` - the wide, **text-free** cinematic background. We -//! bake it into the **backdrop** (sharp + bright at the top behind the -//! header, blurring and fading to nothing toward the bottom) and pull the -//! **accent palette** from it, so the UI's color harmonizes with what fills -//! the screen behind it. -//! * `library_600x900.jpg` - the **portrait cover** (key art + title). Shown -//! as the "game card" in the sidebar. -//! * `logo.png` - the **transparent themed logo** (the title as art). Shown -//! on the dashboard's active-game card. -//! -//! A missing local file is fetched once from Steam's public CDN. All decoding, -//! blurring, and color work is bounded and cached to disk, and runs off the UI -//! thread (see [`resolve`]). - -use std::path::{Path, PathBuf}; - -use iced::Color; -use image::imageops::{self, FilterType}; -use image::{GenericImageView, RgbaImage}; - -/// Everything the UI needs to dress itself in a game's identity. -#[derive(Debug, Clone, Default)] -pub struct ArtSet { - /// Baked portrait cover (2:3, top strip blurred/darkened) - the full-width - /// sidebar banner behind the wordmark. - pub cover: Option, - /// Transparent themed logo - the dashboard active-game card. - pub logo: Option, - /// The baked full-bleed backdrop (blur ramp + bottom fade), from the hero. - pub backdrop: Option, - /// A frosted-glass tile for the notification popup: the hero heavily - /// blurred, desaturated, low-contrast and translucent (so it reads as - /// frosted glass, not a screenshot), with rounded corners baked in. iced - /// cannot blur live content behind a widget, so the frost is baked. - pub glass: Option, - /// Vibrant swatches of the hero art, most representative first; the theme - /// derives the accent palette from these. - pub swatches: Vec, -} - -/// Width the backdrop is baked at (upscaled to fill at draw time - it is a -/// soft background, so a modest resolution keeps the bake fast). -const BACKDROP_W: u32 = 900; -/// Largest artwork file we will download from the CDN. -const MAX_ART_BYTES: usize = 4 * 1024 * 1024; - -/// Resolve a game's artwork: locate (or fetch once) each Steam asset, then -/// bake the backdrop and extract the accent swatches off the UI thread. -pub async fn resolve(appid: i64, cache_dir: PathBuf) -> ArtSet { - let dir = cache_dir.join("artwork").join(appid.to_string()); - let _ = std::fs::create_dir_all(&dir); - let hero = asset(appid, "library_hero.jpg", &dir).await; - let cover_raw = asset(appid, "library_600x900.jpg", &dir).await; - let logo = asset(appid, "logo.png", &dir).await; - // Decode/blur/color work is CPU-bound - never run it on the UI executor. - // The `-vN` suffix invalidates any bake made by an older recipe. - let backdrop_dest = dir.join("backdrop-v3.png"); - let cover_dest = dir.join("cover-v1.png"); - let glass_dest = dir.join("glass-v4.png"); - let (backdrop, swatches, cover, glass) = tokio::task::spawn_blocking(move || { - let backdrop = hero - .as_deref() - .and_then(|h| bake_backdrop(h, &backdrop_dest)); - let swatches = hero.as_deref().map(compute_swatches).unwrap_or_default(); - let glass = hero.as_deref().and_then(|h| bake_glass(h, &glass_dest)); - let cover = cover_raw - .as_deref() - .and_then(|c| bake_cover(c, &cover_dest)); - (backdrop, swatches, cover, glass) - }) - .await - .unwrap_or_default(); - ArtSet { - cover, - logo, - backdrop, - glass, - swatches, - } -} - -/// Locate one asset: Steam's local cache first, else the public CDN (fetched -/// once and mirrored under the cache dir). -async fn asset(appid: i64, file: &str, dir: &Path) -> Option { - for root in modrix_core::detect::steam_roots() { - let p = root - .join("appcache/librarycache") - .join(appid.to_string()) - .join(file); - if p.is_file() { - return Some(p); - } - } - fetch_cdn(appid, file, dir).await -} - -/// Bake the tab backdrop: sharp at the top, blurring downward, alpha fading to -/// nothing near the bottom, dimmed for text legibility. Cached - an existing -/// bake is reused. -#[expect( - clippy::cast_possible_truncation, - clippy::cast_sign_loss, - reason = "alpha is in [0,1] so 255*alpha is a non-negative byte" -)] -fn bake_backdrop(hero: &Path, dest: &Path) -> Option { - if dest.is_file() { - return Some(dest.to_path_buf()); - } - let img = image::open(hero).ok()?; - let (w0, h0) = img.dimensions(); - if w0 == 0 || h0 == 0 { - return None; - } - let h = BACKDROP_W - .saturating_mul(h0) - .checked_div(w0) - .unwrap_or(BACKDROP_W) - .max(1); - let sharp = img - .resize_exact(BACKDROP_W, h, FilterType::Lanczos3) - .to_rgba8(); - // A smooth Gaussian blur: blur at reduced resolution (fast) then upscale - // with Lanczos3 - no blocky downscale-upscale artifacts. - let bw = (BACKDROP_W / 3).max(1); - let bh = (h / 3).max(1); - let down = img.resize_exact(bw, bh, FilterType::Lanczos3).to_rgba8(); - let blurred_small = imageops::blur(&down, 5.0); - let blurred = imageops::resize(&blurred_small, BACKDROP_W, h, FilterType::Lanczos3); - - let mut out = RgbaImage::new(BACKDROP_W, h); - for y in 0..h { - #[expect(clippy::cast_precision_loss, reason = "row index is small")] - let t = y as f32 / h as f32; - // Sharp only in the thin top strip behind the header; fully blurred - // above where any content card begins, so a card never straddles the - // sharp→blur transition (which would look like a gradient through it). - let blur_mix = smoothstep(0.0, 0.11, t); - let alpha = 1.0 - smoothstep(0.34, 0.96, t); // fade out toward the bottom - // A vignette on the *background*: crisp top stays bright, the body dims - // down. Content cards are frosted-opaque, so this fade shows only in - // the background itself, not through the cards. - let dim = 0.82 - 0.44 * smoothstep(0.10, 0.66, t); - for x in 0..BACKDROP_W { - let s = sharp.get_pixel(x, y).0; - let b = blurred.get_pixel(x, y).0; - let px = [ - mix_u8(s[0], b[0], blur_mix, dim), - mix_u8(s[1], b[1], blur_mix, dim), - mix_u8(s[2], b[2], blur_mix, dim), - (255.0 * alpha) as u8, - ]; - out.put_pixel(x, y, image::Rgba(px)); - } - } - out.save(dest).ok().map(|()| dest.to_path_buf()) -} - -/// Bake the sidebar cover: the portrait cover at a fixed 2:3 (so it fills the -/// full-width sidebar banner with no cropping), with its top strip blurred and -/// darkened so the wordmark overlaid there stays legible while the rest stays -/// sharp. Cached - an existing bake is reused. -#[expect( - clippy::many_single_char_names, - reason = "w/h dimensions and s/b pixels are conventional short names" -)] -fn bake_cover(cover: &Path, dest: &Path) -> Option { - if dest.is_file() { - return Some(dest.to_path_buf()); - } - let img = image::open(cover).ok()?; - let (w, h) = (480_u32, 720_u32); // 2:3, matching library_600x900 - let sharp = img.resize_exact(w, h, FilterType::Lanczos3).to_rgba8(); - let down = img - .resize_exact(w / 3, h / 3, FilterType::Lanczos3) - .to_rgba8(); - let blurred_small = imageops::blur(&down, 5.0); - let blurred = imageops::resize(&blurred_small, w, h, FilterType::Lanczos3); - - let mut out = RgbaImage::new(w, h); - for y in 0..h { - #[expect(clippy::cast_precision_loss, reason = "row index is small")] - let t = y as f32 / h as f32; - // Blurred and darkened at the very top (behind the wordmark), snapping - // to a sharp, full-brightness cover below. - let blur_mix = 1.0 - smoothstep(0.08, 0.28, t); - let dim = 0.42 + 0.58 * smoothstep(0.06, 0.26, t); - for x in 0..w { - let s = sharp.get_pixel(x, y).0; - let b = blurred.get_pixel(x, y).0; - out.put_pixel( - x, - y, - image::Rgba([ - mix_u8(s[0], b[0], blur_mix, dim), - mix_u8(s[1], b[1], blur_mix, dim), - mix_u8(s[2], b[2], blur_mix, dim), - 255, - ]), - ); - } - } - out.save(dest).ok().map(|()| dest.to_path_buf()) -} - -/// Bake the notification-popup frosted glass: the hero heavily blurred, -/// desaturated and compressed to a low-contrast dark tint, then made -/// translucent with rounded corners - so it reads as frosted glass (a soft -/// milky haze carrying only a faint hint of the game's color) rather than a -/// recognizable screenshot. The tile is stretched to the content-sized panel in -/// the view, so the corner radius may go slightly oval on very short/tall -/// panels; the blur hides it. Cached. -fn bake_glass(hero: &Path, dest: &Path) -> Option { - if dest.is_file() { - return Some(dest.to_path_buf()); - } - let img = image::open(hero).ok()?; - let (w0, h0) = img.dimensions(); - if w0 == 0 || h0 == 0 { - return None; - } - let (gw, gh) = (720_u32, 480_u32); - let radius = 28.0_f32; - // Very heavy blur (tiny intermediate) so no detail survives. - let down = img.resize_exact((gw / 8).max(1), (gh / 8).max(1), FilterType::Lanczos3); - let blurred_small = imageops::blur(&down.to_rgba8(), 4.0); - let blurred = imageops::resize(&blurred_small, gw, gh, FilterType::Lanczos3); - let mut out = RgbaImage::new(gw, gh); - for (x, y, px) in blurred.enumerate_pixels() { - let [r, g, b, _] = px.0; - let (fr, fg, fb) = frost(r, g, b); - // Mostly opaque tint (a sliver of the live backdrop still bleeds - // through); the corner mask carves the rounded rectangle. - let alpha = glass_alpha(corner_alpha(x, y, gw, gh, radius)); - out.put_pixel(x, y, image::Rgba([fr, fg, fb, alpha])); - } - out.save(dest).ok().map(|()| dest.to_path_buf()) -} - -/// Scale a rounded-corner mask factor (0..1) to the glass alpha (~0.90 - a -/// strong tint that still lets a sliver of the live backdrop through). -#[expect( - clippy::cast_possible_truncation, - clippy::cast_sign_loss, - reason = "the product is in [0, 230] before the cast" -)] -fn glass_alpha(mask: f32) -> u8 { - (mask * 230.0) as u8 -} - -/// Map a blurred pixel to a desaturated, low-contrast, dark "frost" tint: -/// keep ~38% of the saturation and compress the range around a dark midpoint, -/// so the tile is a soft milky haze with a faint game hue. -#[expect( - clippy::cast_possible_truncation, - clippy::cast_sign_loss, - reason = "channel math is clamped to [0,255] before the cast" -)] -fn frost(r: u8, g: u8, b: u8) -> (u8, u8, u8) { - let (rf, gf, bf) = (f32::from(r), f32::from(g), f32::from(b)); - let lum = 0.299 * rf + 0.587 * gf + 0.114 * bf; - let shade = |c: f32| { - let desaturated = lum + (c - lum) * 0.38; - (60.0 + (desaturated - 128.0) * 0.42).clamp(0.0, 255.0) as u8 - }; - (shade(rf), shade(gf), shade(bf)) -} - -/// Rounded-rectangle mask factor in `[0, 1]`: 1 inside, a 1px anti-aliased -/// edge, 0 past the corner radius `r`. -#[expect( - clippy::cast_precision_loss, - clippy::many_single_char_names, - reason = "coordinates are small pixel indices" -)] -fn corner_alpha(x: u32, y: u32, w: u32, h: u32, r: f32) -> f32 { - let (fx, fy) = (x as f32 + 0.5, y as f32 + 0.5); - let dx = (r - fx).max(fx - (w as f32 - r)).max(0.0); - let dy = (r - fy).max(fy - (h as f32 - r)).max(0.0); - (r + 0.5 - dx.hypot(dy)).clamp(0.0, 1.0) -} - -/// Lerp two channels by `mix`, then scale by `dim`, back to a byte. -#[expect( - clippy::cast_possible_truncation, - clippy::cast_sign_loss, - reason = "the value is clamped to [0,255] before the cast" -)] -fn mix_u8(a: u8, b: u8, mix: f32, dim: f32) -> u8 { - let v = (f32::from(a) * (1.0 - mix) + f32::from(b) * mix) * dim; - v.clamp(0.0, 255.0) as u8 -} - -/// Cubic smoothstep in `[edge0, edge1]`. -fn smoothstep(edge0: f32, edge1: f32, x: f32) -> f32 { - if edge1 <= edge0 { - return f32::from(x >= edge1); - } - let t = ((x - edge0) / (edge1 - edge0)).clamp(0.0, 1.0); - t * t * (3.0 - 2.0 * t) -} - -/// Hue buckets for swatch extraction. -const BUCKETS: usize = 24; - -/// The most representative *vibrant* colors of an image: bucket saturated, -/// mid-bright pixels by hue, score each bucket by weighted population, and -/// return the top buckets' colors, brightest/most-saturated first. Empty when -/// the art has no colorful region (the theme then keeps its own accent). -#[expect( - clippy::many_single_char_names, - clippy::cast_possible_truncation, - clippy::cast_sign_loss, - clippy::cast_precision_loss, - reason = "channel names are conventional; the hue-bucket cast is bounded and non-negative" -)] -fn compute_swatches(path: &Path) -> Vec { - let Ok(img) = image::open(path) else { - return Vec::new(); - }; - let small = img.resize_exact(64, 64, FilterType::Triangle).to_rgba8(); - let mut weight = [0.0_f32; BUCKETS]; - let mut sum = [[0.0_f32; 3]; BUCKETS]; - for px in small.pixels() { - let [r, g, b] = [px.0[0], px.0[1], px.0[2]].map(|c| f32::from(c) / 255.0); - let (h, s, l) = rgb_to_hsl(r, g, b); - if !(0.12..=0.95).contains(&l) || s < 0.28 { - continue; // skip near-black, near-white, and washed-out pixels - } - // Prefer saturated colors near mid brightness (the "poster" colors). - let w = s * (1.0 - (l - 0.55).abs() * 1.3).max(0.15); - let bucket = ((h * BUCKETS as f32) as usize).min(BUCKETS - 1); - // `.get_mut` (never `[]`) keeps the Power-of-Ten no-index rule; the - // bucket is provably in range, so this always hits. - if let (Some(wref), Some(sref)) = (weight.get_mut(bucket), sum.get_mut(bucket)) { - *wref += w; - for (acc, ch) in sref.iter_mut().zip([r, g, b]) { - *acc += ch * w; - } - } - } - let mut scored: Vec<(f32, Color)> = weight - .iter() - .zip(sum.iter()) - .filter(|(w, _)| **w > 0.0) - .map(|(&w, &[sr, sg, sb])| (w, Color::from_rgb(sr / w, sg / w, sb / w))) - .collect(); - scored.sort_by(|a, b| b.0.total_cmp(&a.0)); - scored.into_iter().take(3).map(|(_, c)| c).collect() -} - -async fn fetch_cdn(appid: i64, file: &str, dir: &Path) -> Option { - let dest = dir.join(file); - if dest.is_file() { - return Some(dest); - } - let url = format!("https://cdn.cloudflare.steamstatic.com/steam/apps/{appid}/{file}"); - let client = modrix_download::http::HttpClient::new().ok()?; - let response = client.get(&url, &[]).await.ok()?; - if response.status != 200 { - return None; - } - let bytes = response.bytes(MAX_ART_BYTES).await.ok()?; - std::fs::write(&dest, &bytes).ok()?; - Some(dest) -} - -/// RGB (0..1) → HSL (h in 0..1, s in 0..1, l in 0..1). -#[expect( - clippy::many_single_char_names, - reason = "r/g/b/h/s/l are the conventional channel names" -)] -pub fn rgb_to_hsl(r: f32, g: f32, b: f32) -> (f32, f32, f32) { - let max = r.max(g).max(b); - let min = r.min(g).min(b); - let l = f32::midpoint(max, min); - let d = max - min; - if d.abs() < f32::EPSILON { - return (0.0, 0.0, l); - } - let s = d / (1.0 - (2.0 * l - 1.0).abs()); - let h = if (max - r).abs() < f32::EPSILON { - (((g - b) / d) % 6.0 + 6.0) % 6.0 - } else if (max - g).abs() < f32::EPSILON { - (b - r) / d + 2.0 - } else { - (r - g) / d + 4.0 - }; - (h / 6.0, s.clamp(0.0, 1.0), l) -} - -/// HSL (0..1) → an iced [`Color`]. -#[expect( - clippy::many_single_char_names, - reason = "h/s/l are the conventional channel names" -)] -pub fn hsl_to_rgb(h: f32, s: f32, l: f32) -> Color { - if s.abs() < f32::EPSILON { - return Color::from_rgb(l, l, l); - } - let q = if l < 0.5 { - l * (1.0 + s) - } else { - l + s - l * s - }; - let p = 2.0 * l - q; - let hue = |mut t: f32| { - if t < 0.0 { - t += 1.0; - } - if t > 1.0 { - t -= 1.0; - } - if t < 1.0 / 6.0 { - p + (q - p) * 6.0 * t - } else if t < 0.5 { - q - } else if t < 2.0 / 3.0 { - p + (q - p) * (2.0 / 3.0 - t) * 6.0 - } else { - p - } - }; - Color::from_rgb(hue(h + 1.0 / 3.0), hue(h), hue(h - 1.0 / 3.0)) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn hsl_round_trips() { - for (r, g, b) in [(0.2, 0.6, 0.9), (0.8, 0.1, 0.3), (0.5, 0.5, 0.5)] { - let (h, s, l) = rgb_to_hsl(r, g, b); - let c = hsl_to_rgb(h, s, l); - assert!((c.r - r).abs() < 0.02, "r {} vs {}", c.r, r); - assert!((c.g - g).abs() < 0.02, "g {} vs {}", c.g, g); - assert!((c.b - b).abs() < 0.02, "b {} vs {}", c.b, b); - } - } - - #[test] - fn smoothstep_is_bounded_and_monotone() { - assert!(smoothstep(0.0, 1.0, -1.0).abs() < 1e-6); - assert!((smoothstep(0.0, 1.0, 2.0) - 1.0).abs() < 1e-6); - assert!(smoothstep(0.0, 1.0, 0.25) < smoothstep(0.0, 1.0, 0.75)); - } - - #[test] - fn swatches_pick_the_vibrant_region() { - // A mostly-dark image with a saturated orange block returns orange. - let mut img = RgbaImage::from_pixel(64, 64, image::Rgba([10, 10, 12, 255])); - for y in 0..20 { - for x in 0..64 { - img.put_pixel(x, y, image::Rgba([230, 120, 20, 255])); - } - } - let tmp = tempfile::tempdir().unwrap(); - let path = tmp.path().join("t.png"); - img.save(&path).unwrap(); - let swatches = compute_swatches(&path); - assert!(!swatches.is_empty()); - let top = swatches[0]; - assert!(top.r > top.b, "expected a warm swatch, got {top:?}"); - } -} diff --git a/crates/modrix-gui/src/bake.rs b/crates/modrix-gui/src/bake.rs new file mode 100644 index 0000000..762d4f0 --- /dev/null +++ b/crates/modrix-gui/src/bake.rs @@ -0,0 +1,267 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! The backdrop, baked once per game into one image. +//! +//! The view used to stack five full-window layers: a soft wash of the hero, +//! an accent glow, the sharp hero, a fade into the base colour and a tint. +//! The renderer repaints every layer on every frame, which cost this laptop's +//! integrated GPU about 18 ms a frame at 2560x1600 (a 240 Hz frame is 4.2 ms). +//! Here the same layers are flattened on the art worker, in linear light as +//! the GPU blends them, into one band the view draws as a single image. +//! +//! Below the hero band the old stack resolved to the plain base colour, so +//! the band ends in exactly that colour and the window's own fill carries on. + +use rune::Color; +use rune::color::{srgb_decode, srgb_encode}; + +use crate::art::Rgba; +use crate::look::Look; + +/// The band's width in points at the reference window width. +const REF_W: f32 = 1600.0; +/// The band's height in points (the old hero band). +const BAND_H: f32 = 440.0; +/// The reference window height the wash and glow were laid out over. +const REF_WINDOW_H: f32 = 1000.0; +/// Device pixels per point in the bake. +const SCALE: f32 = 1.2; +/// Width over height, for the view's aspect lock. +pub const RATIO: f32 = REF_W / BAND_H; +/// The glow's radius in points and its centre as fractions of the window. +const GLOW_R: f32 = 900.0; +const GLOW_AT: (f32, f32) = (0.85, 0.05); + +/// What a band is made from. +pub struct Sources<'a> { + /// The sharp hero. + pub hero: Option<&'a Rgba>, + /// The blurred, dimmed hero. + pub soft: Option<&'a Rgba>, + /// The art's swatches, linear colour. + pub swatches: &'a [Color], +} + +/// The layer strengths for one appearance and screen kind. +#[derive(Clone, Copy)] +struct Mix { + base: [f32; 3], + accent: [f32; 3], + wash: f32, + glow: f32, + hero: f32, + fade_top: f32, +} + +impl Mix { + fn new(swatches: &[Color], dark: bool, calm: bool) -> Mix { + let look = Look::new(dark, swatches); + // Work screens keep the art quieter so tables and text stay readable. + Mix { + base: rgb(look.base), + accent: rgb(look.accent), + wash: if dark { 0.55 } else { 0.30 }, + glow: if dark { 0.14 } else { 0.08 }, + hero: match (dark, calm) { + (true, false) => 0.92, + (true, true) => 0.55, + (false, false) => 0.75, + (false, true) => 0.40, + }, + fade_top: if calm { 0.55 } else { 0.10 }, + } + } +} + +/// The four bands, keyed `(dark, calm)`. +#[must_use] +pub fn all(src: &Sources) -> Vec<((bool, bool), Rgba)> { + let decode = decode_table(); + [(true, false), (true, true), (false, false), (false, true)] + .into_iter() + .map(|(dark, calm)| { + let mix = Mix::new(src.swatches, dark, calm); + ((dark, calm), band(src, &decode, mix)) + }) + .collect() +} + +fn band(src: &Sources, decode: &[f32; 256], mix: Mix) -> Rgba { + let width = to_px(REF_W * SCALE); + let height = to_px(BAND_H * SCALE); + let mut out = Vec::with_capacity(len_of(width, height)); + let wash = src.soft.map(|img| Cover::new(img, REF_W, REF_WINDOW_H)); + let hero = src.hero.map(|img| Cover::new(img, REF_W, BAND_H)); + for py in 0..height { + let at_y = (f32::from(u16::try_from(py).unwrap_or(u16::MAX)) + 0.5) / SCALE; + // By row, so the last row is exactly the base colour (no seam). + let rows = dim(height.saturating_sub(1)); + let fade = fade_alpha( + mix.fade_top, + f32::from(u16::try_from(py).unwrap_or(u16::MAX)) / rows, + ); + for px in 0..width { + let at_x = (f32::from(u16::try_from(px).unwrap_or(u16::MAX)) + 0.5) / SCALE; + let mut color = mix.base; + if let Some(wash) = &wash { + color = lerp(color, wash.sample(decode, at_x, at_y), mix.wash); + } + color = lerp(color, mix.accent, mix.glow * glow_falloff(at_x, at_y)); + if let Some(hero) = &hero { + color = lerp(color, hero.sample(decode, at_x, at_y), mix.hero); + } + color = lerp(color, mix.base, fade); + out.extend(color.map(encode)); + out.push(255); + } + } + (width, height, out) +} + +/// The fade's alpha at `t` (0 top, 1 bottom of the band). +fn fade_alpha(top: f32, t: f32) -> f32 { + let mid = top.max(0.45); + if t <= 0.45 { + top + (mid - top) * (t / 0.45) + } else { + mid + (1.0 - mid) * ((t - 0.45) / 0.55).min(1.0) + } +} + +/// The glow's strength at a point: 1 at its centre, 0 at its radius. +fn glow_falloff(x: f32, y: f32) -> f32 { + let dx = x - GLOW_AT.0 * REF_W; + let dy = y - GLOW_AT.1 * REF_WINDOW_H; + (1.0 - (dx * dx + dy * dy).sqrt() / GLOW_R).max(0.0) +} + +/// An image scaled to cover a rect (cropping, never squishing), centred. +struct Cover<'a> { + img: &'a Rgba, + scale: f32, + ox: f32, + oy: f32, +} + +impl<'a> Cover<'a> { + fn new(img: &'a Rgba, w: f32, h: f32) -> Cover<'a> { + let (iw, ih) = (dim(img.0), dim(img.1)); + let scale = (w / iw).max(h / ih); + Cover { + img, + scale, + ox: (w - iw * scale) / 2.0, + oy: (h - ih * scale) / 2.0, + } + } + + /// Bilinear sample at point `(x, y)` of the rect, linear colour. + fn sample(&self, decode: &[f32; 256], x: f32, y: f32) -> [f32; 3] { + let fx = ((x - self.ox) / self.scale - 0.5).max(0.0); + let fy = ((y - self.oy) / self.scale - 0.5).max(0.0); + let (x0, y0) = (fx.floor(), fy.floor()); + let (tx, ty) = (fx - x0, fy - y0); + let at = |dx: f32, dy: f32| texel(self.img, decode, x0 + dx, y0 + dy); + let top = lerp(at(0.0, 0.0), at(1.0, 0.0), tx); + let bottom = lerp(at(0.0, 1.0), at(1.0, 1.0), tx); + lerp(top, bottom, ty) + } +} + +/// One texel, clamped to the image, as linear colour. +fn texel(img: &Rgba, decode: &[f32; 256], x: f32, y: f32) -> [f32; 3] { + let (w, h, bytes) = img; + let col = to_px(x).min(w.saturating_sub(1)); + let row = to_px(y).min(h.saturating_sub(1)); + let at = len_of(*w, row).saturating_add(len_of(col, 1)); + let channel = |i: usize| { + bytes + .get(at.saturating_add(i)) + .and_then(|b| decode.get(usize::from(*b))) + .copied() + .unwrap_or(0.0) + }; + [channel(0), channel(1), channel(2)] +} + +fn decode_table() -> [f32; 256] { + std::array::from_fn(|i| srgb_decode(f32::from(u8::try_from(i).unwrap_or(u8::MAX)) / 255.0)) +} + +fn lerp(a: [f32; 3], b: [f32; 3], t: f32) -> [f32; 3] { + let t = t.clamp(0.0, 1.0); + [ + a[0] + (b[0] - a[0]) * t, + a[1] + (b[1] - a[1]) * t, + a[2] + (b[2] - a[2]) * t, + ] +} + +fn rgb(c: Color) -> [f32; 3] { + [c.r, c.g, c.b] +} + +#[expect( + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "the value is clamped to [0,255] before the cast" +)] +fn encode(v: f32) -> u8 { + (srgb_encode(v.clamp(0.0, 1.0)) * 255.0) + .round() + .clamp(0.0, 255.0) as u8 +} + +#[expect( + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "the value is clamped to [0, 65535] before the cast" +)] +fn to_px(v: f32) -> u32 { + v.clamp(0.0, 65_535.0) as u32 +} + +#[expect(clippy::cast_precision_loss, reason = "image sizes are far below 2^24")] +fn dim(v: u32) -> f32 { + v.max(1) as f32 +} + +/// `w * h * 4` bytes, saturating. +fn len_of(w: u32, h: u32) -> usize { + usize::try_from(u64::from(w).saturating_mul(u64::from(h)).saturating_mul(4)).unwrap_or(0) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn flat(w: u32, h: u32, v: u8) -> Rgba { + (w, h, vec![v; len_of(w, h)]) + } + + #[test] + fn bands_keep_the_aspect_and_end_in_the_base_colour() { + let hero = flat(64, 20, 200); + let soft = flat(16, 10, 90); + let src = Sources { + hero: Some(&hero), + soft: Some(&soft), + swatches: &[], + }; + let bands = all(&src); + assert_eq!(bands.len(), 4); + for ((dark, _), (w, h, bytes)) in &bands { + assert_eq!(bytes.len(), len_of(*w, *h)); + let base = rgb(Look::new(*dark, &[]).base).map(encode); + let last = len_of(*w, h.saturating_sub(1)); + let row = bytes.get(last..last.saturating_add(3)); + assert_eq!(row, Some(&base[..]), "the band must end in the base colour"); + } + } + + #[test] + fn the_fade_runs_from_its_top_to_opaque() { + assert!((fade_alpha(0.1, 0.0) - 0.1).abs() < 1e-6); + assert!((fade_alpha(0.1, 1.0) - 1.0).abs() < 1e-6); + assert!(fade_alpha(0.55, 0.3) >= 0.55); + } +} diff --git a/crates/modrix-gui/src/boot.rs b/crates/modrix-gui/src/boot.rs new file mode 100644 index 0000000..aedbb51 --- /dev/null +++ b/crates/modrix-gui/src/boot.rs @@ -0,0 +1,269 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Starting the embedded service, game discovery, the community registry and +//! the updater. Everything slow runs on a worker thread or the async runtime. + +use std::path::Path; +use std::sync::Arc; + +use modrix_core::{Engine, GameDef, Paths}; +use modrix_service::{Binding, Service}; + +use crate::bus::{Bus, Event}; +use crate::state::{ + App, DefChoice, Detected, InstalledPlugin, Link, RegistryChoice, Tone, UpdateState, +}; + +/// Simultaneously active downloads (matches `modrix serve`). +const MAX_CONCURRENT: u8 = 4; + +/// Everything boot hands back. +pub struct Booted { + /// The running service. + pub service: Service, + /// Pairing, when this process is primary. + pub link: Option, + /// Selectable definitions. + pub defs: Vec, + /// Supported games found installed. + pub detected: Vec, + /// Resolved locations. + pub paths: Paths, +} + +/// Boot on a worker thread inside the runtime (the listener and stager +/// spawn onto it), posting [`Event::Booted`] when done. +pub fn start(rt: tokio::runtime::Handle, progress: Arc, bus: Bus) { + let spawned = std::thread::Builder::new() + .name("modrix-boot".to_owned()) + .spawn(move || { + let _guard = rt.enter(); + let result = start_service(&progress).map(Box::new); + bus.send(Event::Booted(result)); + }); + if let Err(error) = spawned { + tracing::error!(%error, "could not start the boot thread"); + } +} + +fn start_service(progress: &Arc) -> Result { + let paths = Paths::resolve().map_err(|e| e.to_string())?; + let mut engine = + Engine::open_with_progress(&paths, Arc::clone(progress)).map_err(|e| e.to_string())?; + modrix_plugin::register_lua_logic(&mut engine); + let defs = discover_defs(&paths); + let detected = detect_installs(&defs); + let service = Service::new(engine, MAX_CONCURRENT).map_err(|e| format!("{e:#}"))?; + let link = match service + .bind(&paths.instance_lock(), modrix_ipc::DEFAULT_PORT) + .map_err(|e| format!("{e:#}"))? + { + Binding::Primary { port, token, .. } => Some(Link { port, token }), + Binding::AlreadyRunning => None, + }; + Ok(Booted { + service, + link, + defs, + detected, + paths, + }) +} + +/// Every definition this installation can register a game from. +#[must_use] +pub fn discover_defs(paths: &Paths) -> Vec { + let mut defs: Vec = modrix_core::defcat::discover_defs(paths) + .into_iter() + .map(|entry| DefChoice { + id: entry.def.id, + name: entry.def.name, + toml: entry.toml, + }) + .collect(); + defs.sort_by_key(|d| d.name.to_lowercase()); + defs +} + +/// Probe each definition's install detection (best-effort Steam metadata). +#[must_use] +pub fn detect_installs(defs: &[DefChoice]) -> Vec { + defs.iter() + .filter_map(|choice| { + let def = GameDef::from_toml_str(&choice.toml, Path::new("")).ok()?; + let install = modrix_core::detect::detect_install(&def)?; + Some(Detected { + def: choice.clone(), + install, + }) + }) + .collect() +} + +impl App { + /// Rescan definitions, detection and installed plugins after a change. + pub fn rediscover(&mut self) { + let Some(paths) = self.paths.clone() else { + return; + }; + self.defs = discover_defs(&paths); + self.detected = detect_installs(&self.defs); + self.refresh_installed_plugins(); + } + + /// Re-read the plugins installed from the registry. + pub fn refresh_installed_plugins(&mut self) { + let Some(paths) = &self.paths else { + return; + }; + self.installed_plugins = modrix_registry::installed_at(paths) + .into_iter() + .map(|m| InstalledPlugin { + id: m.id, + name: m.name, + version: m.version, + }) + .collect(); + } + + /// Load the registry index in the background (offline leaves it empty). + pub fn fetch_registry(&mut self) { + let (Some(rt), Some(paths)) = (&self.rt, self.paths.clone()) else { + return; + }; + self.registry_loading = true; + let bus = self.bus.clone(); + rt.spawn(async move { + bus.send(Event::Registry(registry_index(paths).await)); + }); + } + + /// Registry entries whose support is not installed yet. + #[must_use] + pub fn available_support(&self) -> Vec<(usize, &RegistryChoice)> { + self.registry + .iter() + .enumerate() + .filter(|(_, r)| !self.defs.iter().any(|d| d.id == r.id)) + .collect() + } + + /// Install game support from the registry. + pub fn install_support(&mut self, index: usize) { + let (Some(rt), Some(paths)) = (&self.rt, self.paths.clone()) else { + return; + }; + let Some(choice) = self.registry.get(index).cloned() else { + return; + }; + self.busy = self.busy.saturating_add(1); + let bus = self.bus.clone(); + rt.spawn(async move { + let result = async { + let client = registry_client(&paths)?; + client + .install(&choice.entry) + .await + .map_err(|e| e.to_string())?; + Ok(choice.id) + } + .await; + bus.send(Event::SupportInstalled(result)); + }); + } + + /// Remove an installed registry plugin. + pub fn uninstall_plugin(&mut self, id: &str) { + let Some(paths) = self.paths.clone() else { + return; + }; + let referenced: Vec = self.lib.games.iter().map(|g| g.plugin_id.clone()).collect(); + match registry_client(&paths) + .and_then(|c| c.uninstall(id, &referenced).map_err(|e| e.to_string())) + { + Ok(()) => self.note(Tone::Ok, format!("{id} removed")), + Err(error) => self.note(Tone::Error, error), + } + self.rediscover(); + } + + /// Remove every plugin no registered game uses. + pub fn gc_plugins(&mut self) { + let Some(paths) = self.paths.clone() else { + return; + }; + let referenced: Vec = self.lib.games.iter().map(|g| g.plugin_id.clone()).collect(); + match registry_client(&paths).and_then(|c| c.gc(&referenced).map_err(|e| e.to_string())) { + Ok(removed) if removed.is_empty() => self.note(Tone::Info, "No unused plugins"), + Ok(removed) => self.note(Tone::Ok, format!("Removed unused: {}", removed.join(", "))), + Err(error) => self.note(Tone::Error, error), + } + self.rediscover(); + } + + /// Check GitHub Releases for a newer build. + pub fn check_updates(&mut self) { + let Some(rt) = &self.rt else { + return; + }; + self.update = UpdateState::Checking; + let bus = self.bus.clone(); + rt.spawn(async move { + let result = modrix_update::check(env!("CARGO_PKG_VERSION")) + .await + .map_err(|e| e.to_string()); + bus.send(Event::UpdateChecked(result)); + }); + } + + /// Download and launch the pending update's installer. + pub fn start_update(&mut self) { + let UpdateState::Available(info) = &self.update else { + return; + }; + let info = info.clone(); + if !info.can_self_install() { + self.note( + Tone::Info, + "Updates install manually on this platform: see the release page.", + ); + return; + } + let (Some(rt), Some(paths)) = (&self.rt, &self.paths) else { + return; + }; + let dir = paths.cache_dir().join("updates"); + self.update = UpdateState::Installing(info.clone()); + let bus = self.bus.clone(); + rt.spawn(async move { + let result = async { + let installer = modrix_update::download(&info, &dir) + .await + .map_err(|e| e.to_string())?; + modrix_update::apply(&installer).map_err(|e| e.to_string()) + } + .await; + bus.send(Event::UpdateApplied(result)); + }); + self.note(Tone::Info, "Downloading the update"); + } +} + +fn registry_client(paths: &Paths) -> Result { + modrix_registry::RegistryClient::new(modrix_registry::RegistrySource::resolve(), paths) + .map_err(|e| e.to_string()) +} + +async fn registry_index(paths: Paths) -> Result, String> { + let client = registry_client(&paths)?; + let index = client.index(false).await.map_err(|e| e.to_string())?; + Ok(index + .plugins + .into_iter() + .map(|entry| RegistryChoice { + id: entry.id.clone(), + name: entry.name.clone(), + version: entry.version.clone(), + entry, + }) + .collect()) +} diff --git a/crates/modrix-gui/src/bus.rs b/crates/modrix-gui/src/bus.rs new file mode 100644 index 0000000..4d78e96 --- /dev/null +++ b/crates/modrix-gui/src/bus.rs @@ -0,0 +1,240 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Background work. One engine thread runs every engine call in FIFO order +//! (quick mutations, slow deploys, and the refresh queries alike), so the UI +//! thread never waits on the engine lock or the disk. Results come back as +//! [`Event`]s through a channel, and a waker asks Rune for a frame whose +//! `poll` drains them. + +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::mpsc::{Receiver, Sender, channel}; +use std::sync::{Arc, Mutex}; + +use modrix_core::{Engine, GameId, ModId}; + +use crate::art::ArtData; +use crate::state::{DupPrompt, Library, RegistryChoice, Tone, Wizard}; + +/// What a finished engine job asks the UI to do. +#[derive(Debug)] +pub enum Reply { + /// Nothing to report. + Quiet, + /// A notification. + Note(Tone, String), + /// An archive is already installed: ask before reinstalling. + Duplicate(DupPrompt), + /// Open the options wizard. + Wizard(Box), + /// A game was registered or picked: manage it. + SelectGame(GameId, String), +} + +/// An engine call run on the engine thread. +pub type Work = Box Result + Send>; + +/// One unit of engine-thread work. +pub enum Job { + /// Re-read engine state for `game` (None: the active game). + Refresh { + /// Game to read. + game: Option, + /// Also run the expensive pass (plugins, health, conflicts, external). + heavy: bool, + }, + /// Run an engine call, then refresh. + Run { + /// Counts toward the busy indicator. + slow: bool, + /// The call. + work: Work, + /// Game to refresh afterwards. + game: Option, + }, +} + +/// Events delivered to the UI thread. +pub enum Event { + /// The service finished starting (or failed to). + Booted(Result, String>), + /// Fresh engine state, gathered after job `seq`. + Snapshot { + /// Last job sequence number processed before gathering. + seq: u64, + /// The data. + lib: Box, + /// Whether the heavy pass ran. + heavy: bool, + }, + /// A job finished. + Done { + /// Whether it was a slow job. + slow: bool, + /// Its reply. + reply: Result, + }, + /// Staged plugin counts. + PluginCounts(HashMap), + /// Archives hashed: install or prompt. + Hashed(Vec<(PathBuf, Option)>), + /// The registry index loaded. + Registry(Result, String>), + /// A registry plugin install finished. + SupportInstalled(Result), + /// The update check finished. + UpdateChecked(Result, String>), + /// The update installer launched (or failed to). + UpdateApplied(Result<(), String>), + /// A game's store catalog loaded (or failed to). + StoreCatalog( + GameId, + Result, String>, + ), + /// A store install resolved and queued (or failed to). + StoreQueued(String, Result), + /// A game's artwork resolved. + Art(GameId, Box), +} + +/// The sending half of the event channel plus the frame waker. +#[derive(Clone)] +pub struct Bus { + tx: Sender, + waker: Option, +} + +impl Bus { + /// A new channel; the receiver lives in the app state. + #[must_use] + pub fn channel() -> (Bus, Receiver) { + let (tx, rx) = channel(); + (Bus { tx, waker: None }, rx) + } + + /// Attach the waker Rune hands `setup`. + pub fn set_waker(&mut self, waker: rune::Waker) { + self.waker = Some(waker); + } + + /// Post an event and wake the UI. A closed channel means the window is + /// gone, so a failed send is simply dropped. + pub fn send(&self, event: Event) { + if self.tx.send(event).is_ok() + && let Some(wake) = &self.waker + { + wake(); + } + } +} + +/// Start the engine thread. It runs until the job sender is dropped (the +/// window closed), which ends `recv` and the thread with it. +#[must_use] +pub fn spawn_engine_thread(engine: Arc>, bus: Bus) -> Option> { + let (tx, rx) = channel::<(u64, Job)>(); + let spawned = std::thread::Builder::new() + .name("modrix-engine".to_owned()) + .spawn(move || { + let mut worker = Worker { + engine, + rx, + bus, + last_seq: 0, + }; + worker.serve(); + }); + match spawned { + Ok(_) => Some(tx), + Err(error) => { + tracing::error!(%error, "could not start the engine thread"); + None + } + } +} + +/// The engine thread's state. +struct Worker { + engine: Arc>, + rx: Receiver<(u64, Job)>, + bus: Bus, + last_seq: u64, +} + +impl Worker { + fn serve(&mut self) { + // Not a bounded loop by design: it serves jobs for the window's + // lifetime and ends when the UI drops the sender. + while let Ok((seq, job)) = self.rx.recv() { + self.last_seq = self.last_seq.max(seq); + let (game, heavy) = match job { + Job::Refresh { game, heavy } => (game, heavy), + Job::Run { slow, work, game } => { + self.run(slow, work); + (game, true) + } + }; + // Coalesce: a burst of refresh requests needs one read. + let (game, heavy) = self.coalesce(game, heavy); + self.gather_and_send(game, heavy); + } + } + + /// Drain queued work, running jobs in order and merging refreshes. + fn coalesce(&mut self, mut game: Option, mut heavy: bool) -> (Option, bool) { + for _ in 0..256 { + let Ok((seq, job)) = self.rx.try_recv() else { + break; + }; + self.last_seq = self.last_seq.max(seq); + match job { + Job::Refresh { game: g, heavy: h } => { + game = g.or(game); + heavy |= h; + } + Job::Run { + slow, + work, + game: g, + } => { + self.run(slow, work); + game = g.or(game); + heavy = true; + } + } + } + (game, heavy) + } + + fn run(&self, slow: bool, work: Work) { + let reply = match self.engine.lock() { + Ok(guard) => work(&guard), + Err(_) => Err("engine lock poisoned".to_owned()), + }; + self.bus.send(Event::Done { slow, reply }); + } + + fn gather_and_send(&self, game: Option, heavy: bool) { + let Ok(guard) = self.engine.lock() else { + return; + }; + let lib = crate::sync::gather(&guard, game, heavy); + drop(guard); + let counts_for: Vec<(ModId, PathBuf)> = if heavy { + lib.mods + .iter() + .map(|m| (m.id, m.staged_path.clone())) + .collect() + } else { + Vec::new() + }; + self.bus.send(Event::Snapshot { + seq: self.last_seq, + lib: Box::new(lib), + heavy, + }); + if !counts_for.is_empty() { + let counts = crate::sync::plugin_counts(&counts_for); + self.bus.send(Event::PluginCounts(counts)); + } + } +} diff --git a/crates/modrix-gui/src/demo.rs b/crates/modrix-gui/src/demo.rs new file mode 100644 index 0000000..7e5a29a --- /dev/null +++ b/crates/modrix-gui/src/demo.rs @@ -0,0 +1,548 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Snapshot scenes: made-up libraries that put every screen in a known +//! state, for `--snap` renders and visual review. Nothing here touches disk. + +use std::path::PathBuf; + +use modrix_core::health::Severity; +use modrix_core::plugins::GamePlugin; +use modrix_core::{ + ConflictFile, ExternalMod, Game, GameCapabilities, GameId, Issue, Mod, ModConflict, ModId, + ModRule, Profile, ProfileId, +}; +use modrix_download::{DownloadId, DownloadState, DownloadStatus}; + +use crate::prefs::Appearance; +use crate::state::{App, Link, Screen, Tone}; + +/// A scene: its `--scene` name and the state it sets up. +type Scene = (&'static str, fn(&mut App)); + +/// Named scenes for `--scene`. +pub const SCENES: &[Scene] = &[ + ("dashboard", |s| scene(s, Screen::Dashboard)), + ("mods", mods), + ("loadorder", |s| scene(s, Screen::LoadOrder)), + ("conflicts", conflicts), + ("downloads", |s| scene(s, Screen::Downloads)), + ("games", |s| scene(s, Screen::Games)), + ("store", store), + ("settings", |s| scene(s, Screen::Settings)), + ("wizard", wizard), + ("light", light), + ("empty", empty), +]; + +fn id(raw: i64) -> Option { + serde_json::from_str(&raw.to_string()).ok() +} + +#[expect( + clippy::expect_used, + reason = "an i64 always deserializes into an id newtype" +)] +fn mod_id(raw: i64) -> ModId { + id(raw).expect("an i64 always deserializes into an id newtype") +} + +#[expect( + clippy::expect_used, + reason = "an i64 always deserializes into an id newtype" +)] +fn game_id(raw: i64) -> GameId { + id(raw).expect("an i64 always deserializes into an id newtype") +} + +#[expect( + clippy::expect_used, + reason = "an i64 always deserializes into an id newtype" +)] +fn profile_id(raw: i64) -> ProfileId { + id(raw).expect("an i64 always deserializes into an id newtype") +} + +/// Mod names, versions, days ago. +const MODS: &[(&str, &str, i64)] = &[ + ("SKSE64", "2.2.6", 40), + ("SkyUI", "5.2SE", 39), + ("Unofficial Skyrim Special Edition Patch", "4.3.2", 39), + ("Address Library for SKSE Plugins", "11", 38), + ("Static Mesh Improvement Mod", "2.08", 30), + ("Noble Skyrim Texture Overhaul", "4.0", 30), + ("Immersive Armors", "8.1", 22), + ("Cutting Room Floor", "3.1.9", 21), + ("Alternate Start: Live Another Life", "4.2.4", 14), + ("Enhanced Lights and FX", "5.4", 9), + ("Obsidian Weathers and Seasons", "1.03", 4), + ("Immersive Citizens: AI Overhaul", "0.4.0", 1), +]; + +fn game(raw: i64, name: &str, appid: i64, path: &str) -> Game { + Game { + id: game_id(raw), + plugin_id: name.to_lowercase().replace(' ', ""), + name: name.to_owned(), + install_path: PathBuf::from(path), + mod_root: "Data".to_owned(), + mod_base: "install".to_owned(), + store: "steam".to_owned(), + steam_appid: Some(appid), + nexus_domain: None, + staging_root: PathBuf::from("/home/player/.local/share/modrix/staging"), + } +} + +fn games(s: &mut App) { + s.lib.games = vec![ + game( + 1, + "Skyrim Special Edition", + 489_830, + "/home/player/.steam/steam/steamapps/common/Skyrim Special Edition", + ), + game( + 2, + "Subnautica", + 264_710, + "/home/player/.steam/steam/steamapps/common/Subnautica", + ), + game( + 3, + "Stardew Valley", + 413_150, + "/home/player/.steam/steam/steamapps/common/Stardew Valley", + ), + ]; + for g in &s.lib.games { + if let Some(appid) = g.steam_appid { + s.art.insert( + g.id, + crate::art::ArtSet::from_data(crate::art::local(appid)), + ); + } + } +} + +fn library(s: &mut App) { + let skyrim = game_id(1); + games(s); + s.lib.game = Some(skyrim); + s.lib.profiles = ["Default", "Survival", "Vanilla plus"] + .iter() + .zip(1..) + .map(|(name, raw)| Profile { + id: profile_id(raw), + game_id: skyrim, + name: (*name).to_owned(), + is_active: raw == 1, + }) + .collect(); + s.lib.profile = s.lib.profiles.first().cloned(); + s.lib.capabilities = Some(GameCapabilities { + load_order: true, + external_scan: true, + health_checks: true, + launch: true, + mod_loader: false, + store: false, + }); + s.lib_gen = s.lib_gen.wrapping_add(1); + s.lib.mods = MODS + .iter() + .zip(1..) + .map(|(m, raw)| demo_mod(s.now, skyrim, raw, *m)) + .collect(); + s.lib.order = s.lib.mods.clone(); + s.lib.enabled = s + .lib + .mods + .iter() + .filter(|m| m.id.get() % 5 != 0) + .map(|m| m.id) + .collect(); + plugins(s); + findings(s); +} + +fn findings(s: &mut App) { + s.lib.health = vec![ + Issue { + severity: Severity::Warning, + message: + "Cutting Room Floor expects Unofficial Skyrim Special Edition Patch to load first" + .to_owned(), + blocking: false, + }, + Issue { + severity: Severity::Info, + message: "Two plugins could be flagged as light to save load-order slots".to_owned(), + blocking: false, + }, + ]; + s.lib.conflicts = conflict_list(); + s.lib.external = vec![ExternalMod { + name: "ENB Series".to_owned(), + label: "Found in the game folder".to_owned(), + path: PathBuf::from("d3d11.dll"), + files: 14, + }]; + s.lib.log = [ + "SKSE64 2.2.6 rel 66 (runtime 01060640 1.6.1170.0)", + "plugin directory = Data\\SKSE\\Plugins\\", + "checking plugin SkyUI_SE.dll", + "plugin SkyUI_SE.dll (00000001 SkyUI 00000005) loaded correctly", + "checking plugin AddressLibrary.dll", + "init complete", + ] + .map(str::to_owned) + .to_vec(); + s.booted = true; + s.link = Some(Link { + port: 47_761, + token: "c0ffee0ddba11f00d5ca1ab1e5eed".to_owned(), + }); + s.sort_mods(); +} + +fn demo_mod(now: f64, game: GameId, raw: i64, (name, version, days): (&str, &str, i64)) -> Mod { + #[expect(clippy::cast_possible_truncation, reason = "a demo clock fits in i64")] + let base = now as i64; + let at = 1_795_600_000_i64 + .max(base) + .saturating_sub(days.saturating_mul(86_400)); + Mod { + id: mod_id(raw), + game_id: game, + name: name.to_owned(), + version: Some(version.to_owned()), + source: "archive".to_owned(), + staged_path: PathBuf::from(format!("/staging/{raw}")), + install_state: "installed".to_owned(), + archive_path: None, + nexus_mod_id: None, + created_at: Some(at), + archive_sha256: None, + } +} + +fn plugins(s: &mut App) { + let list: &[(&str, i64, bool, bool, &[&str])] = &[ + ("Skyrim.esm", 0, true, false, &[]), + ("Update.esm", 0, true, false, &[]), + ( + "Unofficial Skyrim Special Edition Patch.esp", + 3, + true, + false, + &[], + ), + ("SkyUI_SE.esp", 2, false, false, &[]), + ("Immersive Armors.esp", 7, false, false, &[]), + ("Cutting Room Floor.esp", 8, false, false, &[]), + ( + "Alternate Start - Live Another Life.esp", + 9, + false, + false, + &[], + ), + ("EnhancedLightsandFX.esp", 10, false, true, &[]), + ("Obsidian Weathers.esp", 11, false, true, &[]), + ( + "Immersive Citizens - AI Overhaul.esp", + 12, + false, + false, + &["Dawnguard.esm"], + ), + ]; + s.lib.plugins = list + .iter() + .map(|(name, owner, master, light, missing)| GamePlugin { + name: (*name).to_owned(), + mod_id: mod_id(*owner), + mod_name: s + .lib + .mods + .iter() + .find(|m| m.id.get() == *owner) + .map_or_else(|| "Base game".to_owned(), |m| m.name.clone()), + is_master: *master, + is_light: *light, + masters: Vec::new(), + missing_masters: missing.iter().map(|m| (*m).to_owned()).collect(), + enabled: *name != "SkyUI_SE.esp", + }) + .collect(); + s.lib.plugin_counts = + s.lib + .plugins + .iter() + .fold(std::collections::HashMap::new(), |mut acc, p| { + let n: &mut usize = acc.entry(p.mod_id).or_default(); + *n = n.saturating_add(1); + acc + }); +} + +fn conflict_list() -> Vec { + let files = |winner: i64, names: &[&str]| -> Vec { + names + .iter() + .enumerate() + .map(|(i, n)| ConflictFile { + target: (*n).to_owned(), + winner: mod_id(winner), + overridden: i == 1, + }) + .collect() + }; + vec![ + ModConflict { + first: mod_id(5), + second: mod_id(6), + rule: Some(ModRule { + loser: mod_id(5), + winner: mod_id(6), + }), + files: files( + 6, + &[ + "textures/architecture/whiterun/wrwoodplank01.dds", + "textures/architecture/whiterun/wrwoodplank01_n.dds", + ], + ), + }, + ModConflict { + first: mod_id(10), + second: mod_id(11), + rule: None, + files: files( + 11, + &[ + "meshes/effects/fxambsunshafts01.nif", + "shaders/weather/skyrimclear.fx", + "textures/effects/fxsunglare.dds", + "textures/sky/skyrimcloudsupper01.dds", + ], + ), + }, + ] +} + +fn scene(s: &mut App, screen: Screen) { + library(s); + downloads(s); + notes(s); + s.screen = screen; + s.appearance = Appearance::Dark; +} + +fn downloads(s: &mut App) { + let items = [ + ( + 1, + DownloadState::Active, + 412_000_000, + Some(1_024_000_000), + 8, + "Skyrim 202X 10.0 - Architecture.7z.part", + ), + ( + 2, + DownloadState::Queued, + 0, + None, + 0, + "Ordinator - Perks of Skyrim.zip.part", + ), + ( + 3, + DownloadState::Complete, + 18_400_000, + Some(18_400_000), + 0, + "SkyUI_5_2_SE.7z", + ), + ( + 4, + DownloadState::Failed, + 2_000_000, + Some(90_000_000), + 0, + "Lux - Lighting.7z.part", + ), + ]; + s.downloads = items + .into_iter() + .map( + |(raw, state, done, total, connections, file)| DownloadStatus { + id: DownloadId::from_u64(raw), + state, + done, + total, + connections, + file: PathBuf::from(file), + }, + ) + .collect(); + s.outcomes.insert( + DownloadId::from_u64(3), + modrix_service::InstallOutcome::Installed { + name: "SkyUI".to_owned(), + configurable: false, + }, + ); +} + +fn notes(s: &mut App) { + s.note( + Tone::Ok, + "Deployed: 1,284 added, 12 removed, 40,212 unchanged", + ); + s.note(Tone::Info, "Installed SkyUI"); + s.unread = 1; + s.notes.iter_mut().for_each(|n| n.at = -60.0); +} + +fn mods(s: &mut App) { + scene(s, Screen::Mods); + s.mod_sel.only(1); + s.mod_sel.toggle(2); +} + +/// A store catalog in the store API's own shape. +const STORE_ITEMS: &str = r#"[ + {"id":1,"name":"Better Building","mod_id":"BetterBuilding","shortDescription":"Snap, rotate and copy structures with fewer clicks","type":"Mod","isApproved":true,"downloads":48210,"latestVersion":"2.4.1","user":{"name":"timber"},"dependencies":["CoreLib"]}, + {"id":2,"name":"Core Library","mod_id":"CoreLib","shortDescription":"Shared helpers other mods build on","type":"Library","isApproved":true,"downloads":91544,"latestVersion":"1.9.0","user":{"name":"forge"}}, + {"id":3,"name":"Quiet Nights","mod_id":"QuietNights","shortDescription":"Fewer night raids, longer days to explore","type":"Mod","isApproved":true,"downloads":17302,"latestVersion":"0.8.3","user":{"name":"lantern"}}, + {"id":4,"name":"Map Markers","mod_id":"MapMarkers","shortDescription":"Pin caves, caches and camps on the GPS","type":"Mod","isApproved":true,"downloads":33120,"latestVersion":"3.1.0","user":{"name":"compass"}}, + {"id":5,"name":"Stack Sizes","mod_id":"StackSizes","shortDescription":"Carry more logs, sticks and stones per slot","type":"Mod","isApproved":true,"downloads":25877,"latestVersion":"1.2.2","user":{"name":"packrat"}} +]"#; + +fn store(s: &mut App) { + scene(s, Screen::Store); + if let Some(caps) = s.lib.capabilities.as_mut() { + caps.store = true; + } + s.lib.store = Some(modrix_core::StoreDef { + kind: "sotf-mods".to_owned(), + base_url: "https://api.sotf-mods.com".to_owned(), + }); + s.store.game = s.lib.game; + s.store.items = serde_json::from_str(STORE_ITEMS).unwrap_or_default(); + s.store.installing.insert("QuietNights".to_owned()); +} + +fn conflicts(s: &mut App) { + scene(s, Screen::Conflicts); + s.expanded_conflict = Some((mod_id(10), mod_id(11))); +} + +fn light(s: &mut App) { + scene(s, Screen::Dashboard); + s.appearance = Appearance::Light; +} + +fn empty(s: &mut App) { + s.booted = true; + s.screen = Screen::Dashboard; + s.appearance = Appearance::Dark; +} + +/// Options as (name, kind, description). +type Options<'a> = &'a [(&'a str, modrix_plugin::fomod::PluginKind, &'a str)]; + +fn group( + name: &str, + kind: modrix_plugin::fomod::GroupKind, + options: Options<'_>, +) -> modrix_plugin::fomod::Group { + use modrix_plugin::fomod::{Plugin, TypeDescriptor}; + modrix_plugin::fomod::Group { + name: name.to_owned(), + kind, + plugins: options + .iter() + .map(|(name, kind, description)| Plugin { + name: (*name).to_owned(), + description: (*description).to_owned(), + image: None, + files: Vec::new(), + flags: Vec::new(), + kind: TypeDescriptor::Simple(*kind), + }) + .collect(), + } +} + +fn installer() -> modrix_plugin::fomod::Installer { + use modrix_plugin::fomod::{GroupKind, Installer, PluginKind, Step}; + let weather: Options<'_> = &[ + ( + "Balanced", + PluginKind::Recommended, + "Seasons shift every month. Storms are rarer in summer and fog settles on the coast in autumn.", + ), + ( + "Harsh", + PluginKind::Optional, + "Longer blizzards, darker nights and colder light.", + ), + ( + "Cinematic", + PluginKind::Optional, + "Brighter skies with dramatic clouds, made for screenshots.", + ), + ]; + let patches: Options<'_> = &[ + ( + "Enhanced Lights and FX", + PluginKind::Recommended, + "Matches interior light to the weather outside.", + ), + ( + "Climates of Tamriel", + PluginKind::NotUsable, + "Climates of Tamriel is not installed.", + ), + ( + "Wet and Cold", + PluginKind::Optional, + "Breath and wet skin follow the season.", + ), + ]; + Installer { + module_name: "Obsidian Weathers and Seasons".to_owned(), + info_name: Some("Obsidian Weathers and Seasons".to_owned()), + info_version: Some("1.03".to_owned()), + required: Vec::new(), + steps: vec![Step { + name: "Core files".to_owned(), + visible: None, + groups: vec![ + group("Weather set", GroupKind::ExactlyOne, weather), + group("Patches", GroupKind::Any, patches), + ], + }], + conditional: Vec::new(), + module_image: None, + } +} + +fn wizard(s: &mut App) { + scene(s, Screen::Mods); + let installer = installer(); + let present = modrix_plugin::fomod::Present::new(); + let selections = modrix_plugin::fomod::defaults(&installer, &present); + s.wizard = Some(crate::state::Wizard { + mod_id: mod_id(11), + mod_name: "Obsidian Weathers and Seasons".to_owned(), + staged_path: PathBuf::from("/staging/11"), + installer, + selections, + step: 0, + focus: Some((0, 0, 0)), + present, + }); +} diff --git a/crates/modrix-gui/src/events.rs b/crates/modrix-gui/src/events.rs new file mode 100644 index 0000000..3fca797 --- /dev/null +++ b/crates/modrix-gui/src/events.rs @@ -0,0 +1,145 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Folding background events into the UI state. + +use modrix_core::GameId; + +use crate::bus::{Event, Reply}; +use crate::state::{App, Tone, UpdateState}; + +impl App { + /// Route one background event. + pub fn handle(&mut self, event: Event, tx: &mut rune::Tx) { + match event { + Event::Booted(result) => self.on_booted(result), + Event::Snapshot { seq, lib, heavy } => self.apply_snapshot(seq, *lib, heavy), + Event::Done { slow, reply } => { + if slow { + self.busy = self.busy.saturating_sub(1); + } + self.on_reply(reply); + } + Event::PluginCounts(counts) => self.lib.plugin_counts = counts, + Event::Hashed(items) => self.on_hashed(items), + Event::Registry(result) => { + self.registry_loading = false; + match result { + Ok(choices) => self.registry = choices, + Err(error) => tracing::debug!(%error, "registry index unavailable"), + } + } + Event::SupportInstalled(result) => self.on_support_installed(result), + Event::UpdateChecked(result) => self.on_update_checked(result), + Event::UpdateApplied(result) => self.on_update_applied(result, tx), + Event::StoreCatalog(game, result) => self.on_store_catalog(game, result), + Event::StoreQueued(id, result) => self.on_store_queued(&id, result), + Event::Art(game, data) => { + self.art.insert(game, crate::art::ArtSet::from_data(*data)); + } + } + } + + fn on_booted(&mut self, result: Result, String>) { + let booted = match result { + Ok(booted) => *booted, + Err(error) => { + self.boot_error = Some(error); + return; + } + }; + self.already_running = booted.link.is_none(); + self.link = booted.link; + self.defs = booted.defs; + self.detected = booted.detected; + self.paths = Some(booted.paths); + self.jobs = crate::bus::spawn_engine_thread( + std::sync::Arc::clone(booted.service.engine()), + self.bus.clone(), + ); + self.service = Some(booted.service); + self.booted = true; + self.refresh_installed_plugins(); + self.request_refresh(true); + self.fetch_registry(); + self.check_updates(); + } + + fn on_reply(&mut self, reply: Result) { + match reply { + Ok(Reply::Quiet) => {} + Ok(Reply::Note(tone, text)) => self.note(tone, text), + Ok(Reply::Duplicate(prompt)) => self.dup_queue.push(prompt), + Ok(Reply::Wizard(wizard)) => { + if self.wizard.is_none() { + self.wizard = Some(*wizard); + } + } + Ok(Reply::SelectGame(game, text)) => { + self.note(Tone::Ok, text); + self.switch_game(game); + } + Err(error) => self.note(Tone::Error, error), + } + } + + /// Manage another game: drop per-game UI state and ask for its data. + pub fn switch_game(&mut self, game: GameId) { + self.want_game = Some(game); + self.mod_sel.clear(); + self.plugin_sel.clear(); + self.expanded_conflict = None; + self.popup = None; + self.run( + false, + Box::new(move |e| { + e.set_active_game(game) + .map(|()| Reply::Quiet) + .map_err(|e| e.to_string()) + }), + ); + } + + fn on_support_installed(&mut self, result: Result) { + self.busy = self.busy.saturating_sub(1); + let id = match result { + Ok(id) => id, + Err(error) => return self.note(Tone::Error, format!("Plugin install failed: {error}")), + }; + self.note(Tone::Ok, format!("{id} support installed")); + self.rediscover(); + let found = self + .detected + .iter() + .position(|d| d.def.id == id) + .filter(|_| !self.lib.games.iter().any(|g| g.plugin_id == id)); + if let Some(index) = found { + self.add_detected(index); + } + } + + fn on_update_checked(&mut self, result: Result, String>) { + match result { + Ok(Some(info)) => { + let version = info.version.clone(); + self.update = UpdateState::Available(info); + self.note(Tone::Info, format!("Modrix {version} is available")); + } + Ok(None) => self.update = UpdateState::Idle, + Err(error) => { + tracing::debug!(%error, "update check failed"); + self.update = UpdateState::Idle; + } + } + } + + fn on_update_applied(&mut self, result: Result<(), String>, tx: &mut rune::Tx) { + match result { + Ok(()) => tx.quit(), + Err(error) => { + if let UpdateState::Installing(info) = &self.update { + self.update = UpdateState::Available(info.clone()); + } + self.note(Tone::Error, format!("Update failed: {error}")); + } + } + } +} diff --git a/crates/modrix-gui/src/icons.rs b/crates/modrix-gui/src/icons.rs index 818dd5a..3531e5f 100644 --- a/crates/modrix-gui/src/icons.rs +++ b/crates/modrix-gui/src/icons.rs @@ -1,140 +1,171 @@ // SPDX-License-Identifier: GPL-2.0-only -//! Tiny widget-drawn icons (canvas triangles, grip bars, status dots). -//! -//! Drawn, not typed: decorative Unicode glyphs render as tofu on systems -//! whose default sans lacks them, so every icon here is real geometry. +//! The icon set: simple 24-unit stroked outlines drawn in the current colour. -use iced::widget::{canvas, column, container}; -use iced::{Color, Rectangle, Renderer, Theme, mouse}; +use rune::Icon; -use crate::theme; - -/// A small filled triangle pointing up or down. -struct Triangle { - up: bool, - color: Color, -} - -impl canvas::Program for Triangle { - type State = (); - - fn draw( - &self, - (): &Self::State, - renderer: &Renderer, - _theme: &Theme, - bounds: Rectangle, - _cursor: mouse::Cursor, - ) -> Vec { - let mut frame = canvas::Frame::new(renderer, bounds.size()); - let (w, h) = (frame.width(), frame.height()); - let path = canvas::Path::new(|b| { - if self.up { - b.move_to(iced::Point::new(0.0, h)); - b.line_to(iced::Point::new(w, h)); - b.line_to(iced::Point::new(w / 2.0, 0.0)); - } else { - b.move_to(iced::Point::new(0.0, 0.0)); - b.line_to(iced::Point::new(w, 0.0)); - b.line_to(iced::Point::new(w / 2.0, h)); - } - b.close(); - }); - frame.fill(&path, self.color); - vec![frame.into_geometry()] - } -} - -/// An up/down arrow glyph as an element (for the reorder buttons). -pub fn arrow<'a, M: 'a>(up: bool) -> iced::Element<'a, M> { - canvas(Triangle { - up, - color: theme::muted(), - }) - .width(10) - .height(8) - .into() -} - -/// Three horizontal grip bars (the drag handle). -pub fn grip<'a, M: 'a>() -> iced::Element<'a, M> { - let bar = || { - container(iced::widget::Space::new(14, 2)).style(|_: &Theme| { - iced::widget::container::Style { - background: Some(iced::Background::Color(theme::faint())), - border: iced::Border { - color: Color::TRANSPARENT, - width: 0.0, - radius: 2.0.into(), - }, - ..iced::widget::container::Style::default() - } - }) +macro_rules! stroked { + ($id:ident, $name:literal, $body:literal) => { + #[doc = concat!("The ", $name, " icon.")] + pub static $id: Icon = Icon { + name: concat!("modrix-", $name), + view: 24.0, + body: concat!( + r#""#, + $body, + "" + ), + }; }; - container(column![bar(), bar(), bar()].spacing(2)) - .padding([4, 2]) - .into() } -/// A bell glyph with a status dot on its shoulder, both drawn as geometry. -struct Bell { - body: Color, - dot: Color, -} - -impl canvas::Program for Bell { - type State = (); - - fn draw( - &self, - (): &Self::State, - renderer: &Renderer, - _theme: &Theme, - bounds: Rectangle, - _cursor: mouse::Cursor, - ) -> Vec { - let mut frame = canvas::Frame::new(renderer, bounds.size()); - let (w, h) = (frame.width(), frame.height()); - // Bell body: a rounded dome over a flared rim. - let dome = canvas::Path::new(|b| { - b.move_to(iced::Point::new(w * 0.2, h * 0.72)); - b.line_to(iced::Point::new(w * 0.8, h * 0.72)); - b.line_to(iced::Point::new(w * 0.68, h * 0.6)); - b.line_to(iced::Point::new(w * 0.68, h * 0.38)); - b.quadratic_curve_to( - iced::Point::new(w * 0.5, h * 0.12), - iced::Point::new(w * 0.32, h * 0.38), - ); - b.line_to(iced::Point::new(w * 0.32, h * 0.6)); - b.close(); - }); - frame.fill(&dome, self.body); - // Clapper. - let clapper = canvas::Path::circle(iced::Point::new(w * 0.5, h * 0.82), h * 0.07); - frame.fill(&clapper, self.body); - // Status dot. - let dot = canvas::Path::circle(iced::Point::new(w * 0.78, h * 0.28), h * 0.2); - frame.fill(&dot, self.dot); - vec![frame.into_geometry()] - } -} - -/// The notification bell with a coloured status dot. -pub fn bell<'a, M: 'a>(body: Color, dot: Color) -> iced::Element<'a, M> { - canvas(Bell { body, dot }).width(18).height(18).into() -} - -/// A small colored circle (status/notification dot). -pub fn dot<'a, M: 'a>(size: f32, color: Color) -> iced::Element<'a, M> { - container(iced::widget::Space::new(size, size)) - .style(move |_: &Theme| iced::widget::container::Style { - background: Some(iced::Background::Color(color)), - border: iced::Border { - color: Color::TRANSPARENT, - width: 0.0, - radius: 99.0.into(), - }, - ..iced::widget::container::Style::default() - }) - .into() -} +stroked!( + HOME, + "home", + r#""# +); +stroked!( + LAYERS, + "layers", + r#""# +); +stroked!( + ORDER, + "order", + r#""# +); +stroked!( + CONFLICT, + "conflict", + r#""# +); +stroked!( + DOWNLOAD, + "download", + r#""# +); +stroked!( + GAMEPAD, + "gamepad", + r#""# +); +stroked!( + SETTINGS, + "settings", + r#""# +); +stroked!( + SEARCH, + "search", + r#""# +); +stroked!(PLUS, "plus", r#""#); +stroked!( + BELL, + "bell", + r#""# +); +stroked!(PLAY, "play", r#""#); +stroked!(CHECK, "check", r#""#); +stroked!(CLOSE, "close", r#""#); +stroked!(CHEVRON_DOWN, "chevron-down", r#""#); +stroked!( + CHEVRON_RIGHT, + "chevron-right", + r#""# +); +stroked!( + CHEVRON_UP_DOWN, + "chevron-up-down", + r#""# +); +stroked!( + GRIP, + "grip", + r#""# +); +stroked!(ARROW_UP, "arrow-up", r#""#); +stroked!( + ARROW_DOWN, + "arrow-down", + r#""# +); +stroked!( + TRASH, + "trash", + r#""# +); +stroked!( + REFRESH, + "refresh", + r#""# +); +stroked!( + DEPLOY, + "deploy", + r#""# +); +stroked!( + SHIELD, + "shield", + r#""# +); +stroked!( + ERASE, + "erase", + r#""# +); +stroked!( + FOLDER, + "folder", + r#""# +); +stroked!( + COPY, + "copy", + r#""# +); +stroked!( + SPARKLES, + "sparkles", + r#""# +); +stroked!( + PUZZLE, + "puzzle", + r#""# +); +stroked!( + WARNING, + "warning", + r#""# +); +stroked!( + INFO, + "info", + r#""# +); +stroked!( + LINK, + "link", + r#""# +); +stroked!( + PACKAGE, + "package", + r#""# +); +stroked!( + SLIDERS, + "sliders", + r#""# +); +stroked!( + UPDATE, + "update", + r#""# +); +stroked!( + PIN, + "pin", + r#""# +); diff --git a/crates/modrix-gui/src/keys.rs b/crates/modrix-gui/src/keys.rs new file mode 100644 index 0000000..9471e3a --- /dev/null +++ b/crates/modrix-gui/src/keys.rs @@ -0,0 +1,86 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Window-level keyboard control for the lists. Arrows move the cursor, +//! Shift extends, Ctrl moves the selected plugins, Ctrl+A selects all, +//! Escape closes the open surface or clears the selection. + +use rune::{Key, KeyEvent, Tx}; + +use crate::state::{App, Pane, Screen}; + +/// The app-level key hook. Returns whether the key was used. +pub fn on_key(s: &mut App, event: &KeyEvent, _tx: &mut Tx) -> bool { + if matches!(event.key, Key::Escape) { + return escape(s); + } + if s.wizard.is_some() || s.popup.is_some() || !s.dup_queue.is_empty() { + return false; + } + let pane = match s.screen { + Screen::Mods => Pane::Mods, + Screen::LoadOrder => Pane::Plugins, + _ => return false, + }; + s.focus_pane = pane; + let len = match pane { + Pane::Mods => s.visible_mods().len(), + Pane::Plugins => s.lib.plugins.len(), + }; + let ctrl = event.mods.ctrl || event.mods.cmd; + let delta: i8 = match &event.key { + Key::Command('a' | 'A') => { + selection(s, pane).all(len); + return true; + } + Key::Up => -1, + Key::Down => 1, + _ => return false, + }; + if ctrl && pane == Pane::Plugins { + s.move_plugins(delta); + return true; + } + let sel = selection(s, pane); + let next = sel + .cursor + .map_or(0, |c| crate::actions::step(c, delta, len)); + if len == 0 { + return true; + } + if event.mods.shift { + sel.range_to(next); + } else { + sel.only(next); + } + true +} + +fn selection(s: &mut App, pane: Pane) -> &mut crate::state::Selection { + match pane { + Pane::Mods => &mut s.mod_sel, + Pane::Plugins => &mut s.plugin_sel, + } +} + +fn escape(s: &mut App) -> bool { + if s.popup.take().is_some() { + return true; + } + if s.confirm_delete { + s.confirm_delete = false; + return true; + } + if s.wizard.is_some() { + s.wizard_cancel(); + return true; + } + if !s.dup_queue.is_empty() { + s.dup_cancel(); + return true; + } + match s.screen { + Screen::Mods if !s.mod_sel.items.is_empty() => s.mod_sel.clear(), + Screen::LoadOrder if !s.plugin_sel.items.is_empty() => s.plugin_sel.clear(), + _ => return false, + } + true +} diff --git a/crates/modrix-gui/src/look.rs b/crates/modrix-gui/src/look.rs new file mode 100644 index 0000000..d255f77 --- /dev/null +++ b/crates/modrix-gui/src/look.rs @@ -0,0 +1,204 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! The visual language: a kit palette seeded from the game's own art, plus +//! the glass, type and spacing tokens the screens share. + +use rune::{Color, TextStyle, oklch, oklcha}; +use rune_kit::{Kit, PaletteSeed}; + +/// Hue of the default accent (a clear blue, as in the brand mark). +const DEFAULT_HUE: f32 = 256.0; + +/// Everything a screen needs to paint itself. +#[derive(Clone)] +pub struct Look { + /// The component kit. + pub k: Kit, + /// Dark appearance. + pub dark: bool, + /// The accent. + pub accent: Color, + /// A wash of the accent for selected rows and chips. + pub accent_soft: Color, + /// Text on the accent. + pub on_accent: Color, + /// Translucent panel fill over the backdrop. + pub glass: Color, + /// A stronger panel fill (popovers, sticky headers). + pub glass_strong: Color, + /// Panel edge. + pub edge: Color, + /// The window colour under everything. + pub base: Color, + /// Positive state. + pub good: Color, + /// Warning state. + pub warn: Color, + /// Error state. + pub bad: Color, +} + +/// Type scale. +pub mod ty { + use super::TextStyle; + /// The big page title. + pub const TITLE: TextStyle = TextStyle::new(26.0, 680.0).tracking(-0.4); + /// Hero name over the art. + pub const HERO: TextStyle = TextStyle::new(34.0, 720.0).tracking(-0.6); + /// A section heading. + pub const HEADING: TextStyle = TextStyle::new(15.0, 640.0).tracking(-0.1); + /// A large number on a stat tile. + pub const STAT: TextStyle = TextStyle::new(28.0, 680.0).tracking(-0.5); + /// Body text. + pub const BODY: TextStyle = TextStyle::new(13.5, 450.0); + /// Body, emphasised. + pub const BODY_STRONG: TextStyle = TextStyle::new(13.5, 580.0); + /// Secondary lines. + pub const SMALL: TextStyle = TextStyle::new(12.0, 450.0); + /// Secondary, emphasised. + pub const SMALL_STRONG: TextStyle = TextStyle::new(12.0, 600.0); + /// Uppercase labels. + pub const LABEL: TextStyle = TextStyle::new(10.5, 650.0).tracking(0.9); + /// The wordmark. + pub const MARK: TextStyle = TextStyle::new(19.0, 800.0).tracking(1.6); + /// Monospace values. + pub const MONO: TextStyle = TextStyle::new(12.0, 450.0).mono(); +} + +/// Spacing scale. +pub mod space { + /// Tight gaps. + pub const SM: f32 = 8.0; + /// Default gaps. + pub const MD: f32 = 12.0; + /// Section gaps. + pub const LG: f32 = 20.0; + /// Page padding. + pub const XL: f32 = 28.0; + /// Panel radius. + pub const PANEL: f32 = 16.0; + /// The sidebar width. + pub const SIDEBAR: f32 = 248.0; +} + +/// The dark value or the light one. +const fn pick(dark: bool, on_dark: T, on_light: T) -> T { + if dark { on_dark } else { on_light } +} + +impl Look { + /// The look for an appearance, tinted by the game's art swatches. + #[must_use] + pub fn new(dark: bool, swatches: &[Color]) -> Look { + let hue = swatches.first().map_or(DEFAULT_HUE, |c| hue_of(*c)); + let chroma = swatches + .first() + .map_or(0.16, |c| chroma_of(*c).clamp(0.09, 0.17)); + let accent = pick(dark, oklch(0.72, chroma, hue), oklch(0.56, chroma, hue)); + let base = pick(dark, oklch(0.155, 0.014, hue), oklch(0.972, 0.006, hue)); + let fg = pick(dark, oklch(0.96, 0.004, hue), oklch(0.22, 0.012, hue)); + let mut k = Kit::from_palette(PaletteSeed { + bg: base, + fg, + accent, + }); + k.c.bg_accent = accent; + k.c.border_focus = accent; + k.c.text_accent = accent; + k.c.icon_accent = accent; + Look { + k, + dark, + accent, + accent_soft: oklcha(pick(dark, 0.72, 0.56), chroma, hue, pick(dark, 0.16, 0.12)), + on_accent: pick(dark, oklch(0.17, 0.02, hue), Color::WHITE), + glass: pick( + dark, + oklcha(0.21, 0.016, hue, 0.80), + oklcha(0.995, 0.004, hue, 0.84), + ), + glass_strong: pick( + dark, + oklcha(0.20, 0.016, hue, 0.90), + oklcha(0.99, 0.004, hue, 0.94), + ), + edge: pick(dark, Color::WHITE.alpha(0.075), Color::BLACK.alpha(0.07)), + base, + good: pick(dark, oklch(0.76, 0.15, 150.0), oklch(0.55, 0.15, 150.0)), + warn: pick(dark, oklch(0.82, 0.14, 80.0), oklch(0.62, 0.15, 70.0)), + bad: pick(dark, oklch(0.70, 0.17, 25.0), oklch(0.56, 0.19, 25.0)), + } + } + + /// Primary text. + #[must_use] + pub fn text(&self) -> Color { + self.k.c.text_base + } + + /// Secondary text. + #[must_use] + pub fn muted(&self) -> Color { + self.k.c.text_muted + } + + /// Tertiary text. + #[must_use] + pub fn faint(&self) -> Color { + self.k.c.text_faint + } + + /// A hover wash. + #[must_use] + pub fn hover(&self) -> Color { + if self.dark { + Color::WHITE.alpha(0.055) + } else { + Color::BLACK.alpha(0.045) + } + } + + /// A pressed wash. + #[must_use] + pub fn pressed(&self) -> Color { + if self.dark { + Color::WHITE.alpha(0.09) + } else { + Color::BLACK.alpha(0.08) + } + } + + /// The drop shadow under floating panels. + #[must_use] + pub fn shadow(&self) -> Color { + Color::BLACK.alpha(if self.dark { 0.42 } else { 0.12 }) + } +} + +fn lch(c: Color) -> (f32, f32, f32) { + let [l, a, b, _] = c.to_oklab(); + (l, a.hypot(b), b.atan2(a).to_degrees().rem_euclid(360.0)) +} + +fn hue_of(c: Color) -> f32 { + lch(c).2 +} + +fn chroma_of(c: Color) -> f32 { + lch(c).1 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn accent_follows_the_art() { + let warm = crate::art::srgb(0.9, 0.45, 0.1); + let look = Look::new(true, &[warm]); + let (_, _, hue) = lch(look.accent); + assert!((30.0..90.0).contains(&hue), "hue {hue}"); + let plain = Look::new(false, &[]); + let (_, _, blue) = lch(plain.accent); + assert!((blue - DEFAULT_HUE).abs() < 3.0, "hue {blue}"); + } +} diff --git a/crates/modrix-gui/src/main.rs b/crates/modrix-gui/src/main.rs index d477e4f..d3efe54 100644 --- a/crates/modrix-gui/src/main.rs +++ b/crates/modrix-gui/src/main.rs @@ -1,62 +1,83 @@ // SPDX-License-Identifier: GPL-2.0-only -//! Modrix graphical frontend - a classy, modern take on the Vortex layout. +//! Modrix's graphical frontend: a native GPU UI built with Rune over +//! [`modrix_core::Engine`]. It embeds the same [`modrix_service::Service`] as +//! `modrix serve`, so browser hand-offs install mods while the window is open. //! -//! A thin Iced 0.13 face over [`modrix_core::Engine`]. It embeds the same -//! [`modrix_service::Service`] as `modrix serve`, so browser download -//! hand-offs install mods while the window is open. All state lives in -//! [`app::App`]; all styling in [`theme`]; all layout in [`view`]. +//! The engine runs on its own thread ([`bus`]); the view only reads the +//! state in [`state::App`], so frames never wait on the disk. -mod app; -mod artwork; +mod actions; +mod art; +mod bake; +mod boot; +mod bus; +mod demo; +mod events; mod fmt; mod icons; -mod theme; -mod view; +mod keys; +mod look; +mod prefs; +mod state; +mod store; +mod sync; +mod ui; +mod wizard; -fn main() -> iced::Result { +use rune::{App, AppSpec}; + +use crate::state::App as State; + +/// The window's opening size. +const SIZE: (f32, f32) = (1320.0, 860.0); + +fn main() -> anyhow::Result<()> { init_tracing(); - // Single-instance guard: if a primary is already serving the loopback port, - // do not open a second window. This is checked here, before the window is - // created, so a duplicate launch exits cleanly instead of running in a - // degraded "another instance active" mode. A crashed primary leaves a stale - // lockfile with nothing listening, which reads as not-running, so recovery - // launches through normally. - if another_instance_running() { + // One window per user: a live primary already serving the loopback port + // means a second launch exits. A crashed primary leaves a stale lock with + // nothing listening, which reads as not running. + if !rune::is_headless() && another_instance_running() { tracing::info!("Modrix is already running; not opening a second window."); return Ok(()); } - iced::application("Modrix", app::update, view::view) - // Explicit app id: the Wayland window class the desktop entry's - // StartupWMClass matches against. - .settings(iced::Settings { - id: Some("modrix-gui".to_owned()), - ..iced::Settings::default() - }) - .subscription(app::subscription) - .theme(|state| state.theme.clone()) - // The window clear color comes from the active theme: glass themes - // use alpha < 1 so the compositor shows through (transparent(true) - // below makes that possible; opaque themes simply ignore it). - .style(|_state, _theme| iced::application::Appearance { - background_color: theme::window_background(), - text_color: theme::text(), - }) - .transparent(true) - .antialiasing(true) - .window_size(iced::Size::new(1280.0, 840.0)) - .centered() - .run_with(app::boot) + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .enable_all() + .thread_name("modrix-rt") + .build()?; + let handle = runtime.handle().clone(); + rune::set_app_id("modrix-gui"); + let spec = AppSpec:: { + min_size: Some((860.0, 560.0)), + scenes: demo::SCENES, + setup: Some(setup), + poll: Some(state::App::poll), + on_key: Some(keys::on_key), + ..AppSpec::new("Modrix", SIZE, || State::new(None), ui::view) + }; + App::new(spec).init(move || State::new(Some(handle))).run(); + drop(runtime); + Ok(()) +} + +/// Attach the waker, then boot the service unless this is a headless snap. +fn setup(s: &mut State, waker: rune::Waker) { + s.bus.set_waker(waker); + if rune::is_headless() { + return; + } + if let Some(rt) = s.rt.clone() { + boot::start(rt, std::sync::Arc::clone(&s.progress), s.bus.clone()); + } } /// Whether a live primary Modrix instance already holds the loopback port. -/// A failure to resolve the data directory reads as "not running" so the real -/// error surfaces during boot rather than silently blocking launch. fn another_instance_running() -> bool { modrix_core::Paths::resolve() .is_ok_and(|paths| modrix_ipc::primary_is_live(&paths.instance_lock())) } -/// Route `RUST_LOG`-filtered tracing to stderr for terminal launches. +/// `RUST_LOG`-filtered tracing to stderr. fn init_tracing() { use tracing_subscriber::{EnvFilter, fmt}; let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); diff --git a/crates/modrix-gui/src/prefs.rs b/crates/modrix-gui/src/prefs.rs new file mode 100644 index 0000000..89a4b91 --- /dev/null +++ b/crates/modrix-gui/src/prefs.rs @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! The GUI's own preferences, in `/gui.toml`. Read once at start and +//! written only when the user changes one, never during a frame. + +use modrix_core::Paths; + +/// Light, dark, or follow the system. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Appearance { + /// Follow the desktop. + #[default] + System, + /// Always dark. + Dark, + /// Always light. + Light, +} + +impl Appearance { + /// In picker order. + pub const ALL: [Appearance; 3] = [Appearance::System, Appearance::Dark, Appearance::Light]; + + /// Picker label. + #[must_use] + pub fn label(self) -> &'static str { + match self { + Appearance::System => "System", + Appearance::Dark => "Dark", + Appearance::Light => "Light", + } + } + + fn id(self) -> &'static str { + match self { + Appearance::System => "system", + Appearance::Dark => "dark", + Appearance::Light => "light", + } + } + + /// Parse the stored file. + #[must_use] + pub fn parse(text: &str) -> Appearance { + let value = text + .lines() + .take(64) + .filter_map(|line| line.split_once('=')) + .find(|(key, _)| key.trim() == "appearance") + .map(|(_, v)| v.trim().trim_matches('"')); + match value { + Some("dark") => Appearance::Dark, + Some("light") => Appearance::Light, + _ => Appearance::System, + } + } +} + +/// The stored appearance (System when absent or unreadable). +#[must_use] +pub fn load() -> Appearance { + let Ok(paths) = Paths::resolve() else { + return Appearance::System; + }; + std::fs::read_to_string(paths.config_dir().join("gui.toml")) + .map(|t| Appearance::parse(&t)) + .unwrap_or_default() +} + +/// Store the appearance. +/// +/// # Errors +/// When the config directory cannot be written. +pub fn save(paths: &Paths, appearance: Appearance) -> std::io::Result<()> { + let dir = paths.config_dir(); + std::fs::create_dir_all(dir)?; + std::fs::write( + dir.join("gui.toml"), + format!("appearance = \"{}\"\n", appearance.id()), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_and_round_trips() { + assert_eq!( + Appearance::parse("appearance = \"dark\"\n"), + Appearance::Dark + ); + assert_eq!(Appearance::parse("theme = \"x\"\n"), Appearance::System); + let tmp = tempfile::tempdir().unwrap(); + let paths = Paths::rooted_at(tmp.path()); + save(&paths, Appearance::Light).unwrap(); + let text = std::fs::read_to_string(paths.config_dir().join("gui.toml")).unwrap(); + assert_eq!(Appearance::parse(&text), Appearance::Light); + } +} diff --git a/crates/modrix-gui/src/state.rs b/crates/modrix-gui/src/state.rs new file mode 100644 index 0000000..6f06eb8 --- /dev/null +++ b/crates/modrix-gui/src/state.rs @@ -0,0 +1,752 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! The whole GUI state. Engine-derived data arrives from the worker thread +//! as snapshots (see [`crate::bus`]); everything here is plain data the view +//! reads, so a frame never touches the disk or the engine lock. + +use std::collections::{BTreeSet, HashMap, HashSet}; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::mpsc::Receiver; + +use modrix_core::plugins::GamePlugin; +use modrix_core::{ + ExternalMod, Game, GameCapabilities, GameId, Issue, Mod, ModConflict, ModId, Paths, Profile, + ProgressSnapshot, +}; +use modrix_download::{DownloadId, DownloadStatus}; +use modrix_plugin::fomod; +use modrix_service::{InstallOutcome, Service}; +use rune::TextEdit; + +use crate::art::ArtSet; +use crate::bus::{Bus, Event, Job}; +use crate::prefs::Appearance; + +/// Notifications kept before the oldest are dropped. +pub const MAX_NOTES: usize = 200; +/// Seconds an event notification lives before it expires on its own. +pub const NOTE_TTL: f64 = 300.0; +/// Seconds a toast stays on screen. +pub const TOAST_TTL: f64 = 4.5; + +/// Which main view is showing. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Screen { + /// Overview of the selected game. + Dashboard, + /// The mod library. + Mods, + /// Plugin load order. + LoadOrder, + /// Conflict rules and per-file pins. + Conflicts, + /// Browser hand-off downloads. + Downloads, + /// The game's community mod store. + Store, + /// Registered, detected and installable games. + Games, + /// Appearance, paths, pairing, plugins, updates. + Settings, +} + +impl Screen { + /// Every screen in navigation order. + pub const ALL: [Screen; 8] = [ + Screen::Dashboard, + Screen::Mods, + Screen::LoadOrder, + Screen::Conflicts, + Screen::Downloads, + Screen::Store, + Screen::Games, + Screen::Settings, + ]; + + /// The navigation label. + #[must_use] + pub fn label(self) -> &'static str { + match self { + Screen::Dashboard => "Overview", + Screen::Mods => "Mods", + Screen::LoadOrder => "Load order", + Screen::Conflicts => "Conflicts", + Screen::Downloads => "Downloads", + Screen::Store => "Mod store", + Screen::Games => "Games", + Screen::Settings => "Settings", + } + } + + /// Parse the `MODRIX_GUI_SCREEN` development override. + #[must_use] + pub fn from_env(value: &str) -> Option { + match value { + "dashboard" => Some(Screen::Dashboard), + "mods" => Some(Screen::Mods), + "loadorder" => Some(Screen::LoadOrder), + "conflicts" => Some(Screen::Conflicts), + "downloads" => Some(Screen::Downloads), + "store" => Some(Screen::Store), + "games" => Some(Screen::Games), + "settings" => Some(Screen::Settings), + _ => None, + } + } +} + +/// A sortable column of the Mods table. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SortKey { + /// Install time, the default. + Installed, + /// Alphabetical. + Name, + /// Enabled first. + Enabled, + /// Version string. + Version, + /// Source (nexus, local). + Source, +} + +/// What a right-click menu is for. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Ctx { + /// A visible row of the Mods table. + Mod(usize), + /// A registered game's card. + Game(GameId), +} + +/// Which list owns the keyboard. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Pane { + /// The Mods table. + Mods, + /// The plugin load order. + Plugins, +} + +/// A multi-selection: selected indices, a fixed anchor for Shift ranges and +/// a moving cursor. +#[derive(Debug, Clone, Default)] +pub struct Selection { + /// Selected indices. + pub items: BTreeSet, + /// The fixed end of a Shift range. + pub anchor: Option, + /// The moving end. + pub cursor: Option, +} + +impl Selection { + /// Clear everything. + pub fn clear(&mut self) { + self.items.clear(); + self.anchor = None; + self.cursor = None; + } + + /// Select exactly `index`. + pub fn only(&mut self, index: usize) { + self.items.clear(); + self.items.insert(index); + self.anchor = Some(index); + self.cursor = Some(index); + } + + /// Toggle `index`; it becomes the new anchor. + pub fn toggle(&mut self, index: usize) { + if !self.items.remove(&index) { + self.items.insert(index); + } + self.anchor = Some(index); + self.cursor = Some(index); + } + + /// Extend from the anchor to `index`. + pub fn range_to(&mut self, index: usize) { + let anchor = self.anchor.or(self.cursor).unwrap_or(index); + let (lo, hi) = (anchor.min(index), anchor.max(index)); + self.items = (lo..=hi).collect(); + self.anchor = Some(anchor); + self.cursor = Some(index); + } + + /// Select `0..len`. + pub fn all(&mut self, len: usize) { + self.items = (0..len).collect(); + self.anchor = (len > 0).then_some(0); + self.cursor = len.checked_sub(1); + } + + /// Keep only indices below `len` (after the list shrinks). + pub fn retain_below(&mut self, len: usize) { + self.items.retain(|i| *i < len); + self.anchor = self.anchor.filter(|a| *a < len); + self.cursor = self.cursor.filter(|c| *c < len); + } +} + +/// Notification severity. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Tone { + /// Completed. + Ok, + /// Failed. + Error, + /// Informational. + Info, +} + +/// One event in the notification center. +#[derive(Debug, Clone)] +pub struct Note { + /// Stable id (drives toast keys). + pub id: u64, + /// Severity. + pub tone: Tone, + /// The message. + pub text: String, + /// Frame-clock seconds when it happened. + pub at: f64, +} + +/// A selectable game definition (built-in, user, or installed plugin). +#[derive(Debug, Clone)] +pub struct DefChoice { + /// Stable id (`skyrimse`). + pub id: String, + /// Display name. + pub name: String, + /// The raw `game.toml` text. + pub toml: String, +} + +/// A supported game found installed on disk. +#[derive(Debug, Clone)] +pub struct Detected { + /// The definition that matched. + pub def: DefChoice, + /// The install directory. + pub install: PathBuf, +} + +/// One community plugin from the registry index. +#[derive(Debug, Clone)] +pub struct RegistryChoice { + /// Plugin id (= game id). + pub id: String, + /// Display name. + pub name: String, + /// Registry version. + pub version: String, + /// The full index entry (needed to install). + pub entry: modrix_registry::IndexEntry, +} + +/// An installed registry plugin. +#[derive(Debug, Clone)] +pub struct InstalledPlugin { + /// Plugin id. + pub id: String, + /// Display name. + pub name: String, + /// Installed version. + pub version: String, +} + +/// A duplicate-install prompt. +#[derive(Debug, Clone)] +pub struct DupPrompt { + /// The archive the user tried to install. + pub path: PathBuf, + /// The installed mod with the same content. + pub existing: ModId, + /// Its display name. + pub existing_name: String, +} + +/// The loopback pairing the browser extension needs. +#[derive(Debug, Clone)] +pub struct Link { + /// Bound port. + pub port: u16, + /// Per-session token. + pub token: String, +} + +/// The in-app updater's state. +#[derive(Debug, Clone, Default)] +pub enum UpdateState { + /// Up to date, offline, or not yet checked. + #[default] + Idle, + /// A check is running. + Checking, + /// A newer release is offered. + Available(modrix_update::UpdateInfo), + /// Its installer is downloading or launching. + Installing(modrix_update::UpdateInfo), +} + +/// The FOMOD options wizard. +#[derive(Debug, Clone)] +pub struct Wizard { + /// The mod being configured. + pub mod_id: ModId, + /// Its display name. + pub mod_name: String, + /// Its staged tree. + pub staged_path: PathBuf, + /// The parsed installer. + pub installer: fomod::Installer, + /// Current selections. + pub selections: fomod::Selections, + /// Position within the visible steps. + pub step: usize, + /// The option last touched (step, group, plugin): drives the preview. + pub focus: Option<(usize, usize, usize)>, + /// Files present in the install (fileDependency conditions). + pub present: fomod::Present, +} + +impl Wizard { + /// Indices of steps visible under the current selections. + #[must_use] + pub fn visible_steps(&self) -> Vec { + let flags = fomod::flags_of(&self.installer, &self.selections, &self.present); + self.installer + .steps + .iter() + .enumerate() + .filter(|(_, s)| { + s.visible + .as_ref() + .is_none_or(|d| d.eval(&flags, &self.present)) + }) + .map(|(i, _)| i) + .collect() + } +} + +/// Text fields, kept apart from engine data so a refresh never clobbers typing. +#[derive(Debug, Default)] +pub struct Forms { + /// Mods table filter. + pub search: TextEdit, + /// Store catalog filter. + pub store_search: TextEdit, + /// Picked definition id for manual registration. + pub def_id: Option, + /// Explicit `game.toml` path (overrides the pick). + pub def_path: TextEdit, + /// Install directory for manual registration. + pub install_path: TextEdit, + /// New profile name. + pub profile_name: TextEdit, +} + +/// A load-order drag in progress. +#[derive(Debug, Clone, Copy)] +pub struct PluginDrag { + /// The row being dragged. + pub from: usize, + /// Pointer travel in points. + pub dy: f32, +} + +/// Engine-derived data for the selected game, replaced wholesale per snapshot. +#[derive(Debug, Clone, Default)] +pub struct Library { + /// Registered games. + pub games: Vec, + /// The game being managed. + pub game: Option, + /// Its profiles. + pub profiles: Vec, + /// Its active profile. + pub profile: Option, + /// Every staged mod, sorted per [`App::mod_sort`]. + pub mods: Vec, + /// Enabled mods in load order. + pub order: Vec, + /// Enabled mod ids (fast lookup). + pub enabled: HashSet, + /// What the game supports. + pub capabilities: Option, + /// Plugin load order (heavy pass). + pub plugins: Vec, + /// Setup health issues, worst first (heavy pass). + pub health: Vec, + /// Pairwise conflicts (heavy pass). + pub conflicts: Vec, + /// Mods in the game dir Modrix did not deploy (heavy pass). + pub external: Vec, + /// Plugins each mod ships (heavy pass). + pub plugin_counts: HashMap, + /// The game's mod loader, when it declares one (heavy pass). + pub loader: Option, + /// The last lines of the game's log, when it declares one. + pub log: Vec, + /// The game's community mod store, when it declares one (heavy pass). + pub store: Option, +} + +/// Which popup surface is open (at most one at a time). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Popup { + /// The sidebar game switcher. + GameMenu, + /// The toolbar profile picker. + ProfileMenu, + /// Deploy split-button menu. + DeployMenu, + /// The notification center. + Notes, + /// The manual-registration definition picker. + DefPicker, + /// A per-file pin picker in Conflicts (index into the expanded pair's files). + PinPicker(usize), +} + +/// The whole GUI state. +#[expect( + clippy::struct_excessive_bools, + reason = "independent flags of the one GUI state, not a hidden enum" +)] +pub struct App { + /// Background events (snapshots, finished jobs, art, boot). + pub inbox: Receiver, + /// Where workers post events (holds the sender half). + pub bus: Bus, + /// Engine worker queue, once booted. + pub jobs: Option>, + /// The async runtime for network work (None in headless snaps). + pub rt: Option, + /// The embedded hand-off service. + pub service: Option, + /// Extension pairing when this process is primary. + pub link: Option, + /// True when another instance holds the port. + pub already_running: bool, + /// Fatal boot failure. + pub boot_error: Option, + /// Boot finished. + pub booted: bool, + /// The engine's progress sink. + pub progress: Arc, + /// Latest progress snapshot. + pub op: Option, + /// Slow actions in flight. + pub busy: u32, + /// Current view. + pub screen: Screen, + /// Engine data. + pub lib: Library, + /// The game the user asked for (snapshots for any other game are stale). + pub want_game: Option, + /// Sequence number of the last job queued. + pub job_seq: u64, + /// A light refresh is already queued. + pub refresh_queued: bool, + /// Frame-clock time of the last refresh request. + pub last_refresh: f64, + /// Latest frame clock seen by `poll`. + pub now: f64, + /// Download snapshots, newest first. + pub downloads: Vec, + /// Install phase of finished downloads. + pub outcomes: HashMap, + /// Outcomes already notified. + pub outcome_seen: HashSet, + /// Mods table selection (indices into the filtered view). + pub mod_sel: Selection, + /// Load-order selection. + pub plugin_sel: Selection, + /// Which list owns the keyboard. + pub focus_pane: Pane, + /// Mods sort (column, ascending). + pub mod_sort: (SortKey, bool), + /// Load-order drag. + pub drag: Option, + /// Expanded conflict pair. + pub expanded_conflict: Option<(ModId, ModId)>, + /// Artwork per game. + pub art: HashMap, + /// Games whose art was requested. + pub art_requested: HashSet, + /// Notification center, newest first. + pub notes: Vec, + /// Next note id. + pub note_seq: u64, + /// Unseen notifications. + pub unread: usize, + /// Open popup, if any. + pub popup: Option, + /// The open right-click menu: what was pressed, and where. + pub ctx: Option<(Ctx, rune::PointerPress)>, + /// Updater state. + pub update: UpdateState, + /// Pending duplicate prompts (the first is shown). + pub dup_queue: Vec, + /// The open wizard. + pub wizard: Option, + /// FOMOD mods waiting for their first review. + pub wizard_queue: Vec, + /// Mods already offered a wizard. + pub prompted: HashSet, + /// Files are being dragged over the window. + pub drop_hover: bool, + /// Selectable definitions. + pub defs: Vec, + /// Supported games found on disk. + pub detected: Vec, + /// Registry plugins. + pub registry: Vec, + /// Registry index is loading. + pub registry_loading: bool, + /// Installed registry plugins. + pub installed_plugins: Vec, + /// Text fields. + pub form: Forms, + /// The Store screen's catalog. + pub store: crate::store::StoreView, + /// Mods table columns dropped for width: 0 none, 1 Source, 2 Source + /// and Installed. + pub mods_narrow: u8, + /// Resolved on-disk locations. + pub paths: Option, + /// Appearance preference. + pub appearance: Appearance, + /// Confirm before deleting the selected mods. + pub confirm_delete: bool, + /// Bumped whenever `lib.mods` is replaced or reordered. + pub lib_gen: u64, + /// The filtered row list, keyed by search text and `lib_gen`: the table + /// asks for it once per drawn row, so it must not refilter each time. + visible_cache: std::cell::RefCell>, +} + +/// One computed filter result for the Mods table. +#[derive(Debug)] +struct VisibleCache { + needle: String, + lib_gen: u64, + rows: std::rc::Rc<[usize]>, +} + +impl App { + /// Fresh state with an unbooted service. + #[must_use] + pub fn new(rt: Option) -> App { + let (bus, inbox) = Bus::channel(); + App { + inbox, + bus, + jobs: None, + rt, + service: None, + link: None, + already_running: false, + boot_error: None, + booted: false, + progress: Arc::new(modrix_core::Progress::default()), + op: None, + busy: 0, + screen: initial_screen(), + lib: Library::default(), + want_game: None, + job_seq: 0, + refresh_queued: false, + last_refresh: 0.0, + now: 0.0, + downloads: Vec::new(), + outcomes: HashMap::new(), + outcome_seen: HashSet::new(), + mod_sel: Selection::default(), + plugin_sel: Selection::default(), + focus_pane: Pane::Mods, + mod_sort: (SortKey::Installed, false), + drag: None, + expanded_conflict: None, + art: HashMap::new(), + art_requested: HashSet::new(), + notes: Vec::new(), + note_seq: 0, + unread: 0, + popup: None, + ctx: None, + update: UpdateState::Idle, + dup_queue: Vec::new(), + wizard: None, + wizard_queue: Vec::new(), + prompted: HashSet::new(), + drop_hover: false, + defs: Vec::new(), + detected: Vec::new(), + registry: Vec::new(), + registry_loading: false, + installed_plugins: Vec::new(), + form: Forms::default(), + store: crate::store::StoreView::default(), + mods_narrow: 0, + paths: None, + appearance: crate::prefs::load(), + confirm_delete: false, + lib_gen: 0, + visible_cache: std::cell::RefCell::new(None), + } + } + + /// The selected game record. + #[must_use] + pub fn game(&self) -> Option<&Game> { + let id = self.lib.game?; + self.lib.games.iter().find(|g| g.id == id) + } + + /// The selected game's artwork. + #[must_use] + pub fn game_art(&self) -> Option<&ArtSet> { + self.lib.game.and_then(|id| self.art.get(&id)) + } + + /// A mod's display name. + #[must_use] + pub fn mod_name(&self, id: ModId) -> String { + self.lib + .mods + .iter() + .find(|m| m.id == id) + .map_or_else(|| id.to_string(), |m| m.name.clone()) + } + + /// Whether a screen applies to the selected game. + #[must_use] + pub fn screen_visible(&self, screen: Screen) -> bool { + let load_order = self.lib.capabilities.is_none_or(|c| c.load_order); + match screen { + Screen::LoadOrder => load_order, + Screen::Store => self.lib.capabilities.is_some_and(|c| c.store), + Screen::Conflicts => { + load_order + || !self.lib.conflicts.is_empty() + || self.lib.health.iter().any(|i| i.blocking) + } + _ => true, + } + } + + /// Issues that block a deploy. + pub fn blockers(&self) -> impl Iterator { + self.lib.health.iter().filter(|i| i.blocking) + } + + /// Indices into `lib.mods` that pass the search filter, in display order. + #[must_use] + pub fn visible_mods(&self) -> std::rc::Rc<[usize]> { + let needle = self.form.search.text.trim(); + if let Ok(cache) = self.visible_cache.try_borrow() + && let Some(hit) = cache.as_ref() + && hit.lib_gen == self.lib_gen + && hit.needle == needle + { + return std::rc::Rc::clone(&hit.rows); + } + let lower = needle.to_lowercase(); + let rows: std::rc::Rc<[usize]> = self + .lib + .mods + .iter() + .enumerate() + .filter(|(_, m)| lower.is_empty() || m.name.to_lowercase().contains(&lower)) + .map(|(i, _)| i) + .collect(); + if let Ok(mut cache) = self.visible_cache.try_borrow_mut() { + *cache = Some(VisibleCache { + needle: needle.to_owned(), + lib_gen: self.lib_gen, + rows: std::rc::Rc::clone(&rows), + }); + } + rows + } + + /// The mod ids currently selected in the Mods table. + #[must_use] + pub fn selected_mod_ids(&self) -> Vec { + let visible = self.visible_mods(); + self.mod_sel + .items + .iter() + .filter_map(|i| visible.get(*i)) + .filter_map(|i| self.lib.mods.get(*i).map(|m| m.id)) + .collect() + } + + /// Unresolved conflict pairs. + #[must_use] + pub fn unresolved_conflicts(&self) -> usize { + self.lib.conflicts.iter().filter(|c| !c.resolved()).count() + } + + /// Downloads still transferring or queued. + #[must_use] + pub fn active_downloads(&self) -> usize { + use modrix_download::DownloadState; + self.downloads + .iter() + .filter(|d| matches!(d.state, DownloadState::Active | DownloadState::Queued)) + .count() + } +} + +/// The screen to open on (`MODRIX_GUI_SCREEN` overrides for development). +fn initial_screen() -> Screen { + std::env::var("MODRIX_GUI_SCREEN") + .ok() + .and_then(|v| Screen::from_env(&v)) + .unwrap_or(Screen::Dashboard) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn selection_range_keeps_anchor() { + let mut sel = Selection::default(); + sel.only(3); + sel.range_to(6); + assert_eq!(sel.items.len(), 4); + sel.range_to(1); + assert_eq!(sel.items.iter().copied().collect::>(), vec![1, 2, 3]); + assert_eq!(sel.anchor, Some(3)); + } + + #[test] + fn selection_toggle_and_retain() { + let mut sel = Selection::default(); + sel.toggle(2); + sel.toggle(5); + sel.toggle(2); + assert_eq!(sel.items.iter().copied().collect::>(), vec![5]); + sel.retain_below(4); + assert!(sel.items.is_empty()); + assert_eq!(sel.cursor, Some(2), "a cursor still inside the list stays"); + sel.retain_below(2); + assert_eq!(sel.cursor, None); + } + + #[test] + fn selection_all_handles_empty() { + let mut sel = Selection::default(); + sel.all(0); + assert!(sel.items.is_empty()); + assert_eq!(sel.cursor, None); + sel.all(3); + assert_eq!(sel.cursor, Some(2)); + } +} diff --git a/crates/modrix-gui/src/store.rs b/crates/modrix-gui/src/store.rs new file mode 100644 index 0000000..07d3880 --- /dev/null +++ b/crates/modrix-gui/src/store.rs @@ -0,0 +1,161 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! The community mod store a game can declare (`[store]` in its +//! definition). The catalog is fetched on the async runtime; an install +//! resolves the mod and its dependencies into hand-off jobs and queues them +//! on the service, so a store install is the same download, stage and +//! route path a browser click takes. + +use std::collections::HashSet; + +use modrix_core::GameId; +use modrix_service::store::{SOTF_MODS_KIND, StoreClient, StoreItem, installed_keys}; + +use crate::bus::Event; +use crate::state::{App, Tone}; + +/// What the Store screen shows. +#[derive(Debug, Default)] +pub struct StoreView { + /// The game the catalog belongs to. + pub game: Option, + /// A fetch is running. + pub loading: bool, + /// Installable items, most downloaded first. + pub items: Vec, + /// The last fetch's error. + pub error: Option, + /// Mod ids whose install is being resolved. + pub installing: HashSet, +} + +/// The installs a store resolve queued. +#[derive(Debug)] +pub struct Queued { + /// The requested mod's name. + pub name: String, + /// Downloads queued, dependencies included. + pub jobs: usize, + /// Dependencies the catalog lacks. + pub missing: Vec, +} + +impl App { + /// The selected game's store origin, when its client exists here. + fn store_origin(&self) -> Option { + self.lib + .store + .as_ref() + .filter(|d| d.kind == SOTF_MODS_KIND) + .map(|d| d.base_url.clone()) + } + + /// Fetch the catalog unless the selected game's is loaded or loading. + pub fn open_store(&mut self) { + let loaded = self.store.game == self.lib.game && !self.store.items.is_empty(); + if !self.store.loading && !loaded { + self.fetch_store(); + } + } + + /// Fetch the selected game's catalog in the background. + pub fn fetch_store(&mut self) { + let (Some(rt), Some(base), Some(game)) = (&self.rt, self.store_origin(), self.lib.game) + else { + return; + }; + self.store = StoreView { + game: Some(game), + loading: true, + ..StoreView::default() + }; + let bus = self.bus.clone(); + rt.spawn(async move { + let result = match StoreClient::new(&base) { + Ok(client) => client.catalog().await.map(|c| c.items), + Err(error) => Err(error), + }; + bus.send(Event::StoreCatalog( + game, + result.map_err(|e| format!("{e:#}")), + )); + }); + } + + /// Fold a fetched catalog in, if it is still the selected game's. + pub fn on_store_catalog(&mut self, game: GameId, result: Result, String>) { + if self.store.game != Some(game) { + return; + } + self.store.loading = false; + match result { + Ok(items) => self.store.items = items, + Err(error) => self.store.error = Some(error), + } + } + + /// Install `mod_id` and what it needs through the download queue. + pub fn store_install(&mut self, mod_id: String) { + let domain = self.game().and_then(|g| g.nexus_domain.clone()); + let (Some(rt), Some(base)) = (self.rt.clone(), self.store_origin()) else { + return; + }; + if !self.store.installing.insert(mod_id.clone()) { + return; + } + let installed = installed_keys(self.lib.mods.iter().map(|m| m.name.as_str())); + let service = self.service.clone(); + let bus = self.bus.clone(); + rt.spawn(async move { + let result = resolve_and_queue(&base, &mod_id, &installed, domain, service).await; + bus.send(Event::StoreQueued(mod_id, result)); + }); + } + + /// Report a finished store resolve. + pub fn on_store_queued(&mut self, mod_id: &str, result: Result) { + self.store.installing.remove(mod_id); + match result { + Ok(q) if q.missing.is_empty() => self.note( + Tone::Ok, + format!("Queued {} ({} downloads)", q.name, q.jobs), + ), + Ok(q) => self.note( + Tone::Info, + format!( + "Queued {}, but the store lacks {}: it may not load", + q.name, + q.missing.join(", ") + ), + ), + Err(error) => self.note(Tone::Error, error), + } + } +} + +async fn resolve_and_queue( + base: &str, + mod_id: &str, + installed: &HashSet, + domain: Option, + service: Option, +) -> Result { + let service = service.ok_or("the service is not running")?; + let client = StoreClient::new(base).map_err(|e| format!("{e:#}"))?; + let (jobs, plan) = client + .install_jobs(mod_id, installed, domain.as_deref()) + .await + .map_err(|e| format!("{e:#}"))?; + let name = plan + .items + .last() + .map_or_else(|| mod_id.to_owned(), |i| i.name.clone()); + let count = jobs.len(); + for job in jobs { + service.enqueue_job(job).map_err(|e| format!("{e:#}"))?; + } + Ok(Queued { + name, + jobs: count, + missing: plan.missing, + }) +} diff --git a/crates/modrix-gui/src/sync.rs b/crates/modrix-gui/src/sync.rs new file mode 100644 index 0000000..1a548f5 --- /dev/null +++ b/crates/modrix-gui/src/sync.rs @@ -0,0 +1,355 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Reading engine state (on the engine thread) and folding it, plus the +//! in-memory download list, into the UI state (on the UI thread). + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +use modrix_core::{Engine, GameId, ModId}; +use modrix_download::DownloadState; +use modrix_service::InstallOutcome; + +use crate::bus::{Event, Job, Work}; +use crate::state::{App, Library, MAX_NOTES, NOTE_TTL, Note, Screen, SortKey, TOAST_TTL, Tone}; + +/// Log lines the dashboard shows. +const LOG_LINES: usize = 12; +/// Seconds between idle refreshes. +const IDLE_PERIOD: f64 = 2.0; +/// Seconds between refreshes while something is running. +const LIVE_PERIOD: f64 = 0.15; + +/// Read everything the UI shows for `game` (engine thread). Errors read as +/// empty sections: the next refresh tries again. +#[must_use] +pub fn gather(engine: &Engine, game: Option, heavy: bool) -> Library { + let games = engine.games().unwrap_or_default(); + let game = game + .filter(|id| games.iter().any(|g| g.id == *id)) + .or_else(|| engine.active_game().ok().flatten().map(|g| g.id)) + .or_else(|| games.first().map(|g| g.id)); + let mut lib = Library { + games, + game, + ..Library::default() + }; + let Some(game) = game else { + return lib; + }; + lib.profiles = engine.profiles(game).unwrap_or_default(); + lib.profile = engine.active_profile(game).ok(); + lib.mods = engine.mods(game).unwrap_or_default(); + lib.capabilities = engine.capabilities(game).ok(); + if let Some(profile) = lib.profile.as_ref().map(|p| p.id) { + lib.order = engine.enabled_mods(profile).unwrap_or_default(); + if heavy { + lib.plugins = engine.plugins(profile).unwrap_or_default(); + lib.health = engine.health(profile).unwrap_or_default(); + lib.conflicts = engine.mod_conflicts(profile).unwrap_or_default(); + } + } + let caps = lib.capabilities; + if caps.is_some_and(|c| c.launch) { + lib.log = engine + .tail_log(game, 0, LOG_LINES) + .map(|t| t.lines) + .unwrap_or_default(); + } + if heavy { + lib.external = engine.external_mods(game).unwrap_or_default(); + if caps.is_some_and(|c| c.mod_loader) { + lib.loader = engine.loader_status(game).ok(); + } + if caps.is_some_and(|c| c.store) { + lib.store = engine.game_def(game).ok().and_then(|d| d.store); + } + } + lib.enabled = lib.order.iter().map(|m| m.id).collect(); + lib +} + +/// Plugins at the top level of each staged tree (bounded scan). +#[must_use] +pub fn plugin_counts(items: &[(ModId, PathBuf)]) -> HashMap { + items + .iter() + .take(10_000) + .map(|(id, path)| (*id, staged_plugin_count(path))) + .collect() +} + +fn staged_plugin_count(staged: &Path) -> usize { + let Ok(entries) = std::fs::read_dir(staged) else { + return 0; + }; + entries + .flatten() + .take(512) + .filter(|e| { + modrix_core::esp::is_plugin_name(&e.file_name().to_string_lossy()) && e.path().is_file() + }) + .count() +} + +impl App { + /// Queue engine work; returns false before boot. + pub fn queue(&mut self, job: Job) -> bool { + let Some(jobs) = &self.jobs else { + return false; + }; + self.job_seq = self.job_seq.saturating_add(1); + jobs.send((self.job_seq, job)).is_ok() + } + + /// Run an engine call on the engine thread, then refresh. + pub fn run(&mut self, slow: bool, work: Work) { + let game = self.want_game.or(self.lib.game); + if self.queue(Job::Run { slow, work, game }) && slow { + self.busy = self.busy.saturating_add(1); + } + } + + /// Ask for fresh engine state. + pub fn request_refresh(&mut self, heavy: bool) { + if self.refresh_queued && !heavy { + return; + } + let game = self.want_game.or(self.lib.game); + if self.queue(Job::Refresh { game, heavy }) { + self.refresh_queued = true; + self.last_refresh = self.now; + } + } + + /// Record a notification. + pub fn note(&mut self, tone: Tone, text: impl Into) { + self.note_seq = self.note_seq.saturating_add(1); + self.notes.insert( + 0, + Note { + id: self.note_seq, + tone, + text: text.into(), + at: self.now, + }, + ); + self.notes.truncate(MAX_NOTES); + if self.popup != Some(crate::state::Popup::Notes) { + self.unread = self.unread.saturating_add(1).min(self.notes.len()); + } + } + + /// The per-frame poll: drain events, tick the live sections, schedule + /// the next wake. Returns whether state changed. + pub fn poll(&mut self, now: f64, tx: &mut rune::Tx) -> bool { + self.now = now; + let mut changed = false; + for _ in 0..512 { + let Ok(event) = self.inbox.try_recv() else { + break; + }; + self.handle(event, tx); + changed = true; + } + if !self.booted { + let op = self.progress.snapshot(); + changed |= op.is_some() != self.op.is_some(); + self.op = op; + tx.wake_after(std::time::Duration::from_millis(150)); + return changed; + } + let live = self.busy > 0 || self.op.is_some() || self.active_downloads() > 0; + let period = if live { LIVE_PERIOD } else { IDLE_PERIOD }; + if now - self.last_refresh >= period { + changed |= self.tick(now); + } + tx.wake_after(std::time::Duration::from_secs_f64(period)); + changed + } + + /// Re-read the live sections. Returns whether anything on screen moved, + /// so an idle window draws nothing between snapshots. + fn tick(&mut self, now: f64) -> bool { + let before = self.last_refresh; + self.last_refresh = now; + let op = self.progress.snapshot(); + let mut changed = op != self.op; + self.op = op; + changed |= self.read_downloads(); + // A toast that timed out since the last tick has to leave the screen. + changed |= self + .notes + .iter() + .any(|n| before - n.at < TOAST_TTL && now - n.at >= TOAST_TTL); + let notes = self.notes.len(); + self.notes.retain(|n| now - n.at < NOTE_TTL); + changed |= notes != self.notes.len(); + self.unread = self.unread.min(self.notes.len()); + // The light read is SQLite-only; skip it while a slow action holds + // the engine (its own refresh follows it). + if self.busy == 0 && !self.refresh_queued { + self.request_refresh(false); + } + changed + } + + /// Pull the download list and install outcomes (in-memory, cheap). + /// Returns whether the list or the notes changed. + fn read_downloads(&mut self) -> bool { + let Some(service) = &self.service else { + return false; + }; + let mut downloads = service.manager().list(); + downloads.sort_by_key(|d| std::cmp::Reverse(d.id)); + self.outcomes = downloads + .iter() + .filter(|d| d.state == DownloadState::Complete) + .filter_map(|d| service.install_outcome(d.id).map(|o| (d.id, o))) + .collect(); + let notes = self.notes.len(); + let changed = downloads != self.downloads; + self.downloads = downloads; + self.notify_new_outcomes(); + changed || notes != self.notes.len() + } + + fn notify_new_outcomes(&mut self) { + let mut fresh: Vec<(modrix_download::DownloadId, InstallOutcome)> = self + .outcomes + .iter() + .filter(|(id, _)| !self.outcome_seen.contains(*id)) + .map(|(id, o)| (*id, o.clone())) + .collect(); + fresh.sort_by_key(|(id, _)| *id); + for (id, outcome) in fresh { + self.outcome_seen.insert(id); + match outcome { + InstallOutcome::Installed { name, configurable } => { + let text = if configurable { + format!("{name} installed, options set to defaults") + } else { + format!("{name} installed") + }; + self.note(Tone::Ok, text); + self.request_refresh(true); + } + InstallOutcome::Failed(error) => { + self.note(Tone::Error, format!("Install failed: {error}")); + } + InstallOutcome::NoGame => self.note(Tone::Info, "Download kept: no game matched"), + } + } + } + + /// Fold a snapshot in. Stale ones (gathered before a job the UI already + /// queued, or for a game the user has switched away from) are dropped so + /// optimistic edits never flicker back. + pub fn apply_snapshot(&mut self, seq: u64, lib: Library, heavy: bool) { + self.refresh_queued = false; + if seq < self.job_seq { + return; + } + if self.want_game.is_some_and(|want| lib.game != Some(want)) + && lib.games.iter().any(|g| Some(g.id) == self.want_game) + { + return; + } + let game_changed = lib.game != self.lib.game; + let old = std::mem::replace(&mut self.lib, lib); + self.lib_gen = self.lib_gen.wrapping_add(1); + if !heavy && !game_changed { + self.lib.plugins = old.plugins; + self.lib.health = old.health; + self.lib.conflicts = old.conflicts; + self.lib.external = old.external; + self.lib.loader = old.loader; + self.lib.store = old.store; + } + self.lib.plugin_counts = if game_changed { + HashMap::new() + } else { + old.plugin_counts + }; + self.want_game = None; + self.sort_mods(); + self.mod_sel.retain_below(self.visible_mods().len()); + self.plugin_sel.retain_below(self.lib.plugins.len()); + if !self.screen_visible(self.screen) { + self.screen = Screen::Dashboard; + } + self.request_art(); + if self.screen == Screen::Store { + self.open_store(); + } + self.queue_unreviewed_fomods(); + if game_changed && !heavy { + self.request_refresh(true); + } + } + + /// Sort `lib.mods` by the chosen column (stable, name tiebreak). + pub fn sort_mods(&mut self) { + let (key, ascending) = self.mod_sort; + self.lib_gen = self.lib_gen.wrapping_add(1); + let enabled = &self.lib.enabled; + let names = |a: &str, b: &str| a.to_lowercase().cmp(&b.to_lowercase()); + self.lib.mods.sort_by(|a, b| { + let ord = match key { + SortKey::Installed => (a.created_at.unwrap_or(i64::MIN), a.id) + .cmp(&(b.created_at.unwrap_or(i64::MIN), b.id)), + SortKey::Name => names(&a.name, &b.name), + SortKey::Enabled => enabled + .contains(&b.id) + .cmp(&enabled.contains(&a.id)) + .then_with(|| names(&a.name, &b.name)), + SortKey::Version => a + .version + .cmp(&b.version) + .then_with(|| names(&a.name, &b.name)), + SortKey::Source => a + .source + .cmp(&b.source) + .then_with(|| names(&a.name, &b.name)), + }; + if ascending { ord } else { ord.reverse() } + }); + } + + /// Offer the options wizard once for each FOMOD mod installed with + /// defaults applied automatically. + fn queue_unreviewed_fomods(&mut self) { + let pending: Vec = self + .lib + .mods + .iter() + .filter(|m| m.install_state == "fomod-auto" && !self.prompted.contains(&m.id)) + .map(|m| m.id) + .collect(); + for id in pending { + self.prompted.insert(id); + self.wizard_queue.push(id); + } + self.open_next_wizard(); + } + + /// Start art resolution for games that have none yet. + fn request_art(&mut self) { + let (Some(rt), Some(paths)) = (&self.rt, &self.paths) else { + return; + }; + let cache = paths.cache_dir().to_path_buf(); + for game in &self.lib.games { + let Some(appid) = game.steam_appid else { + continue; + }; + if !self.art_requested.insert(game.id) { + continue; + } + let (id, bus, cache) = (game.id, self.bus.clone(), cache.clone()); + rt.spawn(async move { + let art = crate::art::resolve(appid, cache).await; + bus.send(Event::Art(id, Box::new(art))); + }); + } + } +} diff --git a/crates/modrix-gui/src/theme.rs b/crates/modrix-gui/src/theme.rs deleted file mode 100644 index 2a3cfb2..0000000 --- a/crates/modrix-gui/src/theme.rs +++ /dev/null @@ -1,725 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -//! The visual identity: switchable theme specs behind one style API. -//! -//! Two themes ship: **Aurora** (the default - dark glass surfaces with a flat -//! blue accent, translucent window) and **Gold** (the original graphite + -//! muted-gold look, banked verbatim). The accent is a single flat color (no -//! gradient); when a game is selected it is derived from that game's artwork. -//! Every widget style -//! lives here so the views stay purely structural; views read colors through -//! accessor functions (`accent()`, `muted()`, …) and never hold a palette, -//! so switching themes restyles the whole application at once. - -use std::sync::RwLock; - -use iced::theme::Palette; -use iced::widget::{button, container, pick_list, progress_bar, text_input, toggler}; -use iced::{Background, Border, Color, Shadow, Theme}; - -/// Build a solid [`Color`] from a `0xRRGGBB` literal. -#[expect( - clippy::cast_precision_loss, - reason = "channel values are <= 255 and exactly representable in f32" -)] -const fn hex(rgb: u32) -> Color { - Color { - r: ((rgb >> 16) & 0xFF) as f32 / 255.0, - g: ((rgb >> 8) & 0xFF) as f32 / 255.0, - b: (rgb & 0xFF) as f32 / 255.0, - a: 1.0, - } -} - -/// `color` at `alpha` opacity. -const fn faded(color: Color, alpha: f32) -> Color { - Color { a: alpha, ..color } -} - -/// One complete visual identity. -pub struct ThemeSpec { - /// Stable id persisted in settings (`aurora`, `gold`). - pub id: &'static str, - /// Display name for the theme picker. - pub name: &'static str, - /// Window background. - pub bg: Color, - /// Sidebar background. - pub surface: Color, - /// Card / table background. - pub card: Color, - /// Slightly raised card (hover, inset fields). - pub card_hi: Color, - /// Hairline borders. - pub hairline: Color, - /// Primary text. - pub text: Color, - /// Secondary text. - pub muted: Color, - /// Tertiary text (labels, hints). - pub faint: Color, - /// The accent color (buttons, highlights, active nav). - pub accent: Color, - /// The accent's hover shift. - pub accent_hot: Color, - /// Text on an accent-filled control. - pub on_accent: Color, - /// Success green. - pub ok: Color, - /// Danger red. - pub danger: Color, - /// Informational blue. - pub info: Color, - /// Window-background alpha: < 1.0 = glassmorphism (the compositor shows - /// through); 1.0 = opaque. - pub glass: f32, -} - -/// Aurora: dark glass + a clean flat blue accent. The default. -pub const AURORA: ThemeSpec = ThemeSpec { - id: "aurora", - name: "Aurora (glass)", - bg: hex(0x0B_0E14), - surface: hex(0x0F_1420), - card: hex(0x13_1A28), - card_hi: hex(0x1A_2233), - hairline: hex(0x24_2C40), - text: hex(0xF0_F3F9), - muted: hex(0xAF_B7CB), - faint: hex(0x78_8098), - accent: hex(0x3B_82F6), - accent_hot: hex(0x60_A5FA), - on_accent: hex(0xF2_F7FF), - ok: hex(0x34_D399), - danger: hex(0xF0_6A5E), - info: hex(0x7D_A7E0), - glass: 0.86, -}; - -/// Gold: the original graphite + muted-gold identity, kept selectable. -pub const GOLD: ThemeSpec = ThemeSpec { - id: "gold", - name: "Gold (classic)", - bg: hex(0x11_1216), - surface: hex(0x16_171C), - card: hex(0x1C_1E24), - card_hi: hex(0x23_252D), - hairline: hex(0x2A_2D36), - text: hex(0xE8_E6E1), - muted: hex(0x8E_93A2), - faint: hex(0x5D_6373), - accent: hex(0xD9_A65A), - accent_hot: hex(0xE4_B36B), - on_accent: hex(0x1A_1408), - ok: hex(0x8F_B573), - danger: hex(0xCC_5F56), - info: hex(0x7F_A6C9), - glass: 1.0, -}; - -/// Every selectable theme, in picker order. -pub const ALL: [&ThemeSpec; 2] = [&AURORA, &GOLD]; - -/// The live theme. A lock (not a const) so Settings can switch at runtime; -/// contention is nil (writes happen on a click). -static ACTIVE: RwLock<&'static ThemeSpec> = RwLock::new(&AURORA); - -/// The active theme spec. -pub fn spec() -> &'static ThemeSpec { - ACTIVE.read().map_or(&AURORA, |guard| *guard) -} - -/// Switch the active theme by id (unknown ids keep the current theme). -pub fn set_theme(id: &str) { - if let Some(found) = ALL.iter().find(|s| s.id == id) - && let Ok(mut active) = ACTIVE.write() - { - *active = found; - } -} - -// --- per-game accent (derived from the selected game's artwork) ------------- - -/// An accent palette derived from a game's artwork. When one is set it -/// overrides the theme's own accent everywhere, so the whole UI takes on the -/// colors of the game being modded. -#[derive(Debug, Clone, Copy)] -pub struct GameAccent { - /// The primary accent (a single flat color from the art). - accent: Color, - /// Its hover shift. - accent_hot: Color, - /// Text drawn on an accent fill. - on_accent: Color, -} - -impl GameAccent { - /// Build a flat accent from an image's swatches (most representative - /// first), tuned so it always reads as a vivid accent on a dark surface. - /// `None` when the art had no usable color (the theme keeps its own - /// accent). - #[must_use] - pub fn from_swatches(swatches: &[Color]) -> Option { - let accent = fit_for_dark(*swatches.first()?); - let accent_hot = lighten(accent, 0.14); - let on_accent = if luminance(accent) > 0.55 { - Color::from_rgb(0.05, 0.06, 0.08) - } else { - Color::from_rgb(0.97, 0.98, 1.0) - }; - Some(Self { - accent, - accent_hot, - on_accent, - }) - } -} - -/// The active per-game accent, if any. -static GAME_ACCENT: RwLock> = RwLock::new(None); - -/// Set (or clear) the per-game accent. Cleared = the theme's own accent. -pub fn set_game_accent(accent: Option) { - if let Ok(mut guard) = GAME_ACCENT.write() { - *guard = accent; - } -} - -fn game_accent() -> Option { - GAME_ACCENT.read().ok().and_then(|g| *g) -} - -/// The effective accent: the game's, else the theme's. -fn eff_accent() -> Color { - game_accent().map_or_else(|| spec().accent, |g| g.accent) -} -fn eff_accent_hot() -> Color { - game_accent().map_or_else(|| spec().accent_hot, |g| g.accent_hot) -} -fn eff_on_accent() -> Color { - game_accent().map_or_else(|| spec().on_accent, |g| g.on_accent) -} - -/// Nudge a color into the vivid-but-readable range for a dark surface. -fn fit_for_dark(c: Color) -> Color { - let (h, s, l) = crate::artwork::rgb_to_hsl(c.r, c.g, c.b); - crate::artwork::hsl_to_rgb(h, s.clamp(0.45, 0.92), l.clamp(0.52, 0.68)) -} - -fn lighten(c: Color, amount: f32) -> Color { - let (h, s, l) = crate::artwork::rgb_to_hsl(c.r, c.g, c.b); - crate::artwork::hsl_to_rgb(h, s, (l + amount).min(0.92)) -} - -fn mix(a: Color, b: Color, t: f32) -> Color { - Color::from_rgb( - a.r + (b.r - a.r) * t, - a.g + (b.g - a.g) * t, - a.b + (b.b - a.b) * t, - ) -} - -fn luminance(c: Color) -> f32 { - 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b -} - -// --- color accessors (views read these, never a palette) -------------------- - -/// Primary text. -pub fn text() -> Color { - spec().text -} -/// Secondary text. -pub fn muted() -> Color { - spec().muted -} -/// Tertiary text. -pub fn faint() -> Color { - spec().faint -} -/// Hairline borders. -pub fn hairline_color() -> Color { - spec().hairline -} -/// The accent. -pub fn accent() -> Color { - eff_accent() -} -/// Success green. -pub fn ok() -> Color { - spec().ok -} -/// Danger red. -pub fn danger() -> Color { - spec().danger -} -/// Informational blue. -pub fn info() -> Color { - spec().info -} - -/// A flat accent fill (primary buttons, progress bar). No gradient - a single -/// solid accent color. -fn accent_bg() -> Background { - Background::Color(eff_accent()) -} - -/// The accent at `alpha` (selections, active nav, drop zone). -fn accent_bg_faded(alpha: f32) -> Background { - Background::Color(faded(eff_accent(), alpha)) -} - -/// The application [`Theme`] for the active spec. -pub fn app_theme() -> Theme { - let s = spec(); - Theme::custom( - format!("Modrix {}", s.name), - Palette { - background: s.bg, - text: s.text, - primary: eff_accent(), - success: s.ok, - danger: s.danger, - }, - ) -} - -/// The window clear color: translucent for glass themes (the compositor -/// shows through), opaque otherwise. -pub fn window_background() -> Color { - let s = spec(); - faded(s.bg, s.glass) -} - -fn rounded(radius: f32) -> Border { - Border { - color: Color::TRANSPARENT, - width: 0.0, - radius: radius.into(), - } -} - -/// Translucent surface tint for glass themes; opaque for solid themes, so the -/// banked Gold look is unaffected. -fn glass(color: Color, alpha: f32) -> Color { - if spec().glass < 1.0 { - faded(color, alpha) - } else { - color - } -} - -/// The one recessed "well" tint used by every inset, text input, and dropdown: -/// a single step below the raised card, in the *same* hue, never pure black. -/// This keeps those surfaces consistent instead of some reading as black. -fn well() -> Color { - mix(spec().bg, spec().card, 0.55) -} - -/// The rest-state edge for a surface: the light glass rim on glass themes, a -/// dark hairline on solid themes. Shared so cards, wells, inputs, and pickers -/// all draw the same edge. -fn rim() -> Color { - let s = spec(); - if s.glass < 1.0 { - faded(s.text, 0.16) - } else { - s.hairline - } -} - -/// A frosted-glass rim: a light top-edge highlight for glass themes (the -/// specular line on a pane of glass), a dark hairline for solid themes. -fn glass_border(radius: f32) -> Border { - let s = spec(); - let color = if s.glass < 1.0 { - faded(s.text, 0.20) - } else { - s.hairline - }; - Border { - color, - width: 1.0, - radius: radius.into(), - } -} - -/// The left navigation column - a solid-ish glass so the nav stays legible -/// against the (transparent) window edge. -pub fn sidebar(_: &Theme) -> container::Style { - container::Style { - background: Some(Background::Color(glass(spec().surface, 0.80))), - border: Border { - color: spec().hairline, - width: 1.0, - radius: 0.0.into(), - }, - ..container::Style::default() - } -} - -/// A raised content card - a **frosted** panel: a single flat tint (only -/// lightly translucent, so the background's top-to-bottom fade does NOT bleed -/// through and appear as a gradient on the card), a bright glass rim, and a -/// soft shadow for depth. -pub fn card(_: &Theme) -> container::Style { - container::Style { - background: Some(Background::Color(glass(spec().card, 0.90))), - border: glass_border(14.0), - shadow: Shadow { - color: faded(Color::BLACK, 0.40), - offset: iced::Vector::new(0.0, 6.0), - blur_radius: 22.0, - }, - ..container::Style::default() - } -} - -/// An inset well inside a card (image frames, token boxes, empty states) - the -/// shared recessed [`well`] tint, so it matches inputs and dropdowns. -pub fn inset(_: &Theme) -> container::Style { - container::Style { - background: Some(Background::Color(glass(well(), 0.85))), - border: glass_border(10.0), - ..container::Style::default() - } -} - -/// A table row; `even` rows get a faint stripe. Rows are near-transparent so -/// the card's own glass shows through as one continuous surface. -pub fn table_row(even: bool) -> impl Fn(&Theme) -> container::Style { - move |_| container::Style { - background: even.then(|| Background::Color(glass(spec().card_hi, 0.35))), - border: rounded(8.0), - ..container::Style::default() - } -} - -/// A selected (highlighted) table row. -pub fn table_row_selected(_: &Theme) -> container::Style { - container::Style { - background: Some(accent_bg_faded(0.24)), - border: Border { - color: faded(eff_accent(), 0.6), - width: 1.0, - radius: 8.0.into(), - }, - ..container::Style::default() - } -} - -/// The row currently being dragged in the load order. -pub fn table_row_dragging(_: &Theme) -> container::Style { - container::Style { - background: Some(accent_bg_faded(0.22)), - border: Border { - color: eff_accent(), - width: 1.0, - radius: 8.0.into(), - }, - ..container::Style::default() - } -} - -/// The click/drop target for adding mod archives. -pub fn drop_zone(_: &Theme) -> container::Style { - container::Style { - background: Some(accent_bg_faded(0.05)), - border: Border { - color: faded(eff_accent(), 0.35), - width: 1.0, - radius: 12.0.into(), - }, - ..container::Style::default() - } -} - -/// The dimmed backdrop behind modal overlays. -pub fn backdrop(_: &Theme) -> container::Style { - container::Style { - background: Some(Background::Color(faded(Color::BLACK, 0.6))), - ..container::Style::default() - } -} - -/// The notification popup's fallback style, used when the game art has not -/// resolved: a translucent tint (so the blurred backdrop still shows through), a -/// bright glass rim, a deep shadow, and bright text. When art IS present the -/// view uses [`panel_frame`] over the baked frosted-glass tile instead. -/// (iced 0.13 cannot blur live content behind a widget, so the frost is baked.) -pub fn panel(_: &Theme) -> container::Style { - container::Style { - // Translucent so the already-blurred backdrop behind the popup shows - // through and reads as frosted glass, while staying dark enough for - // legible white text. Solid (Gold) themes ignore the alpha. - background: Some(Background::Color(glass(spec().card_hi, 0.72))), - text_color: Some(spec().text), - border: glass_border(14.0), - shadow: Shadow { - color: faded(Color::BLACK, 0.55), - offset: iced::Vector::new(0.0, 8.0), - blur_radius: 30.0, - }, - } -} - -/// The notification popup frame when the frosted-glass tile IS present: rim and -/// shadow only, no fill (the translucent tile is the surface - a fill here would -/// double up and kill the see-through). The rounded rim matches the tile's baked -/// corner radius so the corner triangles read as a clean glass edge. -pub fn panel_frame(_: &Theme) -> container::Style { - container::Style { - background: None, - text_color: Some(spec().text), - border: glass_border(14.0), - shadow: Shadow { - color: faded(Color::BLACK, 0.55), - offset: iced::Vector::new(0.0, 8.0), - blur_radius: 30.0, - }, - } -} - -/// A small tinted status chip. -pub fn chip(color: Color) -> impl Fn(&Theme) -> container::Style { - move |_| container::Style { - text_color: Some(color), - background: Some(Background::Color(faded(color, 0.12))), - border: Border { - color: faded(color, 0.35), - width: 1.0, - radius: 99.0.into(), - }, - ..container::Style::default() - } -} - -/// A sidebar navigation entry; the active one carries the accent gradient. -pub fn nav(active: bool) -> impl Fn(&Theme, button::Status) -> button::Style { - move |_, status| { - let s = spec(); - let hovered = matches!(status, button::Status::Hovered | button::Status::Pressed); - button::Style { - background: if active { - Some(accent_bg_faded(0.16)) - } else if hovered { - Some(Background::Color(faded(s.text, 0.05))) - } else { - None - }, - text_color: if active { eff_accent() } else { s.muted }, - border: rounded(8.0), - ..button::Style::default() - } - } -} - -/// A selectable list card that stands on its own over the backdrop (the game -/// rows on the Games screen) - a frosted-opaque panel so the background never -/// bleeds through, marked when selected by an accent rim and tint. -pub fn list_card(selected: bool) -> impl Fn(&Theme, button::Status) -> button::Style { - move |_, status| { - let s = spec(); - let hovered = matches!(status, button::Status::Hovered | button::Status::Pressed); - let base = if selected { - mix(s.card, eff_accent(), 0.12) - } else if hovered { - s.card_hi - } else { - s.card - }; - button::Style { - background: Some(Background::Color(glass(base, 0.92))), - text_color: s.text, - border: if selected { - Border { - color: faded(eff_accent(), 0.6), - width: 1.0, - radius: 12.0.into(), - } - } else { - glass_border(12.0) - }, - ..button::Style::default() - } - } -} - -/// The filled accent button for the primary action - a flat accent fill. -pub fn primary(_: &Theme, status: button::Status) -> button::Style { - let background = match status { - button::Status::Hovered | button::Status::Pressed => { - Some(Background::Color(eff_accent_hot())) - } - button::Status::Disabled => Some(accent_bg_faded(0.3)), - button::Status::Active => Some(accent_bg()), - }; - button::Style { - background, - text_color: eff_on_accent(), - border: rounded(8.0), - ..button::Style::default() - } -} - -/// A quiet, bordered secondary button. -pub fn ghost(_: &Theme, status: button::Status) -> button::Style { - outlined(spec().text, spec().muted, status) -} - -/// A quiet, bordered destructive button. -pub fn danger_ghost(_: &Theme, status: button::Status) -> button::Style { - outlined(spec().danger, faded(spec().danger, 0.8), status) -} - -fn outlined(hot: Color, idle: Color, status: button::Status) -> button::Style { - let s = spec(); - let glassy = s.glass < 1.0; - let hovered = matches!(status, button::Status::Hovered | button::Status::Pressed); - let disabled = matches!(status, button::Status::Disabled); - // On glass themes, secondary buttons are the SAME frosted well chip as - // inputs/insets (solid, not a faint tint over the backdrop), so Verify, - // Purge, and the notification button all read as one consistent material; - // hover tints toward the button's own color. Solid themes keep the classic - // bare outline. - let background = if disabled { - None - } else if !glassy { - hovered.then_some(Background::Color(faded(hot, 0.10))) - } else if hovered { - Some(Background::Color(glass(mix(well(), hot, 0.18), 0.92))) - } else { - Some(Background::Color(glass(well(), 0.85))) - }; - button::Style { - background, - text_color: if disabled { - s.faint - } else if hovered { - hot - } else { - idle - }, - border: Border { - color: if hovered { - faded(hot, 0.6) - } else if glassy { - rim() - } else { - s.hairline - }, - width: 1.0, - radius: 8.0.into(), - }, - ..button::Style::default() - } -} - -/// A tiny square icon button (reorder arrows, cancel). -pub fn icon(_: &Theme, status: button::Status) -> button::Style { - let s = spec(); - let hovered = matches!(status, button::Status::Hovered | button::Status::Pressed); - button::Style { - background: hovered.then_some(Background::Color(faded(s.text, 0.08))), - text_color: match status { - button::Status::Disabled => faded(s.faint, 0.4), - _ if hovered => s.text, - _ => s.muted, - }, - border: rounded(6.0), - ..button::Style::default() - } -} - -/// The slim progress bar - a flat accent fill. -pub fn progress(_: &Theme) -> progress_bar::Style { - progress_bar::Style { - background: Background::Color(spec().bg), - bar: accent_bg(), - border: rounded(99.0), - } -} - -/// Dark dropdown pickers (game/profile selectors). When open, the field's -/// bottom corners square off so it reads as connected to its menu. -pub fn picker(_: &Theme, status: pick_list::Status) -> pick_list::Style { - let s = spec(); - let opened = matches!(status, pick_list::Status::Opened); - let hot = opened || matches!(status, pick_list::Status::Hovered); - let radius = if opened { - iced::border::Radius::default().top_left(8).top_right(8) - } else { - 8.0.into() - }; - pick_list::Style { - text_color: s.text, - placeholder_color: s.faint, - handle_color: if hot { eff_accent() } else { s.muted }, - background: Background::Color(glass(well(), 0.92)), - border: Border { - color: if hot { faded(eff_accent(), 0.5) } else { rim() }, - width: 1.0, - radius, - }, - } -} - -/// The dropdown menu under an open picker: squared top corners so it visually -/// continues the field above it. -pub fn picker_menu(_: &Theme) -> iced::overlay::menu::Style { - let s = spec(); - iced::overlay::menu::Style { - background: Background::Color(s.card_hi), - border: Border { - color: faded(eff_accent(), 0.5), - width: 1.0, - radius: iced::border::Radius::default() - .bottom_left(8) - .bottom_right(8), - }, - text_color: s.text, - selected_text_color: eff_accent(), - selected_background: Background::Color(faded(eff_accent(), 0.12)), - } -} - -/// The enable/disable switch on each mod row. -pub fn toggle(_: &Theme, status: toggler::Status) -> toggler::Style { - let s = spec(); - let on = match status { - toggler::Status::Active { is_toggled } | toggler::Status::Hovered { is_toggled } => { - is_toggled - } - toggler::Status::Disabled => false, - }; - toggler::Style { - background: if on { eff_accent() } else { s.hairline }, - background_border_width: 0.0, - background_border_color: Color::TRANSPARENT, - foreground: if on { s.bg } else { s.muted }, - foreground_border_width: 0.0, - foreground_border_color: Color::TRANSPARENT, - } -} - -/// Text inputs - the same recessed [`well`] tint and rim as insets and -/// dropdowns, so every field reads as one material. -pub fn input(_: &Theme, status: text_input::Status) -> text_input::Style { - let s = spec(); - let focused = matches!(status, text_input::Status::Focused); - text_input::Style { - background: Background::Color(glass(well(), 0.92)), - border: Border { - color: if focused { - faded(eff_accent(), 0.6) - } else { - rim() - }, - width: 1.0, - radius: 8.0.into(), - }, - icon: s.muted, - placeholder: s.faint, - value: s.text, - selection: faded(eff_accent(), 0.35), - } -} diff --git a/crates/modrix-gui/src/ui/conflicts.rs b/crates/modrix-gui/src/ui/conflicts.rs new file mode 100644 index 0000000..2ec11e8 --- /dev/null +++ b/crates/modrix-gui/src/ui/conflicts.rs @@ -0,0 +1,322 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Conflicts: what blocks a deploy, then each pair of mods that ship the +//! same files, with a rule picker and per-file pins. + +use modrix_core::{ConflictFile, ModConflict, ModId}; +use rune::{El, col, row, text}; +use rune_kit::{Button, ButtonVariant, SegmentedControl, Select}; + +use crate::icons; +use crate::look::{Look, space, ty}; +use crate::state::{App, Popup}; +use crate::ui::parts::{self, glyph}; + +/// The pin choice that defers to the rule. +const FOLLOW: &str = "Follow the rule"; +/// Files listed under an expanded pair. +const MAX_FILES: usize = 200; + +/// The Conflicts screen. +pub fn view(s: &App, look: &Look, layer: &mut Vec) -> El { + let blockers: Vec<&modrix_core::Issue> = s.blockers().collect(); + let mut page = col().w_full().gap(space::LG); + if !blockers.is_empty() { + let rows = blockers.iter().enumerate().map(|(i, issue)| { + row() + .key(format!("blocker-{i}")) + .w_full() + .px(18.0) + .py(9.0) + .gap(12.0) + .child(glyph(&icons::WARNING, 16.0, look.bad)) + .child( + text(issue.message.clone()) + .font(ty::BODY) + .color(look.text()) + .wrap() + .grow(1.0), + ) + }); + page = page.child(parts::section( + look, + "blockers", + "Blocking deploy", + Some(parts::chip(format!("{}", blockers.len()), look.bad)), + col().w_full().pb(10.0).children(rows), + )); + } + if s.lib.conflicts.is_empty() { + return page.child(parts::panel(look, "no-conflicts").child(parts::empty( + look, + &icons::SHIELD, + "No file conflicts", + "No two enabled mods ship the same file.", + None, + ))); + } + let pairs = s.lib.conflicts.iter().map(|c| pair(s, look, c, layer)); + page.child(summary(s, look)) + .child(col().w_full().gap(space::SM).children(pairs)) +} + +fn summary(s: &App, look: &Look) -> El { + let open = s.unresolved_conflicts(); + let total = s.lib.conflicts.len(); + let files: usize = s.lib.conflicts.iter().map(|c| c.files.len()).sum(); + row() + .w_full() + .gap(space::MD) + .flex_wrap() + .child(parts::stat( + look, + "c-pairs", + (&icons::CONFLICT, look.accent), + total.to_string(), + "Conflicting pairs", + )) + .child(parts::stat( + look, + "c-open", + ( + &icons::WARNING, + if open > 0 { look.warn } else { look.good }, + ), + open.to_string(), + "Without a rule", + )) + .child(parts::stat( + look, + "c-files", + (&icons::PACKAGE, look.faint()), + files.to_string(), + "Contested files", + )) +} + +fn pair(s: &App, look: &Look, c: &ModConflict, layer: &mut Vec) -> El { + let (a, b) = (c.first, c.second); + let open = s.expanded_conflict == Some((a, b)); + let resolved = c.resolved(); + let status = if let Some(rule) = &c.rule { + parts::chip(format!("{} wins", s.mod_name(rule.winner)), look.good) + } else if resolved { + parts::chip("Pinned per file", look.good) + } else { + parts::chip("Load order decides", look.warn) + }; + let head = pair_head(s, look, c, open).child(status); + let mut card = parts::panel(look, &format!("pair-{a}-{b}")).child(head); + if open { + card = card + .child(parts::hair(look)) + .child(rules(s, look, c)) + .child(files(s, look, c, layer)); + } + card +} + +fn pair_head(s: &App, look: &Look, c: &ModConflict, open: bool) -> El { + let (a, b) = (c.first, c.second); + row() + .key(format!("pair-head-{a}-{b}")) + .w_full() + .h(56.0) + .px(16.0) + .gap(space::MD) + .center_y() + .hover_fill(look.hover()) + .role("button") + .label("Show files") + .on_press(move |s: &mut App| { + s.expanded_conflict = if s.expanded_conflict == Some((a, b)) { + None + } else { + Some((a, b)) + }; + }) + .child(glyph( + if open { + &icons::CHEVRON_DOWN + } else { + &icons::CHEVRON_RIGHT + }, + 16.0, + look.faint(), + )) + .child( + row() + .grow(1.0) + .min_w(0.0) + .gap(8.0) + .center_y() + .child( + text(s.mod_name(a)) + .font(ty::BODY_STRONG) + .color(look.text()) + .truncate(), + ) + .child(text("and").font(ty::SMALL).color(look.faint())) + .child( + text(s.mod_name(b)) + .font(ty::BODY_STRONG) + .color(look.text()) + .truncate(), + ), + ) + .child( + text(format!("{} files", c.files.len())) + .font(ty::SMALL) + .color(look.muted()), + ) +} + +fn rules(s: &App, look: &Look, conflict: &ModConflict) -> El { + let (first, second) = (conflict.first, conflict.second); + let labels = [ + "Load order".to_owned(), + format!("{} wins", short(&s.mod_name(first))), + format!("{} wins", short(&s.mod_name(second))), + ]; + let current = match &conflict.rule { + None => 0, + Some(r) if r.winner == first => 1, + Some(_) => 2, + }; + row() + .w_full() + .px(18.0) + .py(12.0) + .gap(space::MD) + .center_y() + .child(text("Rule").font(ty::SMALL_STRONG).color(look.muted())) + .child( + SegmentedControl::new(&labels, Some(current)) + .on_pick(move |s: &mut App, i, _| match i { + 1 => s.set_rule(second, first), + 2 => s.set_rule(first, second), + _ => s.clear_rule(first, second), + }) + .width(None) + .build(&look.k) + .grow(1.0) + .w(0.0) + .max_w(560.0), + ) +} + +fn short(name: &str) -> String { + let mut out: String = name.chars().take(22).collect(); + if name.chars().count() > 22 { + out.push_str("..."); + } + out +} + +fn files(s: &App, look: &Look, conflict: &ModConflict, layer: &mut Vec) -> El { + let pair = (conflict.first, conflict.second); + let rows = conflict + .files + .iter() + .take(MAX_FILES) + .enumerate() + .map(|entry| file_row(s, look, pair, entry, layer)) + .collect::>(); + let more = conflict.files.len().saturating_sub(MAX_FILES); + col() + .w_full() + .pb(10.0) + .children(rows) + .children((more > 0).then(|| { + row().px(18.0).py(8.0).child( + text(format!("and {more} more files")) + .font(ty::SMALL) + .color(look.faint()), + ) + })) + .child( + row().w_full().px(18.0).pt(6.0).justify_end().child( + Button::new("Close") + .variant(ButtonVariant::GhostMuted) + .on_press(|s: &mut App| s.expanded_conflict = None) + .build(&look.k), + ), + ) +} + +fn pin_picker( + s: &App, + look: &Look, + pair: (ModId, ModId), + entry: (usize, &ConflictFile), + layer: &mut Vec, +) -> El { + let (first, second) = pair; + let (index, file) = entry; + let names = [FOLLOW.to_owned(), s.mod_name(first), s.mod_name(second)]; + let current = if file.overridden { + s.mod_name(file.winner) + } else { + FOLLOW.to_owned() + }; + let target = file.target.clone(); + let popup = Popup::PinPicker(index); + Select::new(format!("pin-{first}-{second}-{index}"), &names) + .current(Some(current.as_str())) + .open(s.popup == Some(popup)) + .on_toggle(move |s: &mut App| { + s.popup = if s.popup == Some(popup) { + None + } else { + Some(popup) + }; + }) + .on_close(|s: &mut App| s.popup = None) + .on_choose(move |s: &mut App, choice: &str, _| { + let provider = pin_choice(s, choice, first, second); + s.pin_file(target.clone(), provider); + }) + .width(220.0) + .build(&look.k, layer) +} + +fn file_row( + s: &App, + look: &Look, + pair: (ModId, ModId), + entry: (usize, &ConflictFile), + layer: &mut Vec, +) -> El { + let (index, file) = entry; + let (icon, tint) = if file.overridden { + (&icons::PIN, look.accent) + } else { + (&icons::PACKAGE, look.faint()) + }; + row() + .key(format!("file-{index}")) + .w_full() + .min_h(40.0) + .px(18.0) + .gap(space::MD) + .center_y() + .child(glyph(icon, 14.0, tint)) + .child( + text(file.target.clone()) + .font(ty::MONO) + .color(look.text()) + .truncate_head() + .grow(1.0) + .w(0.0), + ) + .child(pin_picker(s, look, pair, entry, layer)) +} + +fn pin_choice(s: &App, choice: &str, a: ModId, b: ModId) -> Option { + if choice == s.mod_name(a) { + Some(a) + } else if choice == s.mod_name(b) { + Some(b) + } else { + None + } +} diff --git a/crates/modrix-gui/src/ui/dashboard.rs b/crates/modrix-gui/src/ui/dashboard.rs new file mode 100644 index 0000000..d63cac9 --- /dev/null +++ b/crates/modrix-gui/src/ui/dashboard.rs @@ -0,0 +1,379 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! The overview: the game's logo over its art, the numbers that matter, +//! setup health and what happened lately. + +use modrix_core::health::Severity; +use rune::{El, SurfaceFit, col, el, row, text}; +use rune_kit::{Button, ButtonVariant}; + +use crate::icons; +use crate::look::{Look, space, ty}; +use crate::state::{App, Screen}; +use crate::ui::parts::{self, glyph}; + +/// The overview screen. +pub fn view(s: &App, look: &Look, _layer: &mut Vec) -> El { + let Some(game) = s.game() else { + return welcome(s, look); + }; + col() + .w_full() + .gap(space::LG) + .child(hero( + s, + look, + &game.name, + &game.install_path.display().to_string(), + )) + .child(stats(s, look)) + .child( + row() + .w_full() + .gap(space::LG) + .child(health(s, look).grow(1.0).w(0.0)) + .child(recent(s, look).grow(1.0).w(0.0)), + ) + .children(game_status(s, look)) + .children((!s.lib.external.is_empty()).then(|| external(s, look))) +} + +fn hero(s: &App, look: &Look, name: &str, path: &str) -> El { + let logo = s.game_art().and_then(|a| a.logo.as_ref()); + let title = match logo { + Some(px) => el() + .h(110.0) + .w(360.0) + .pixels_fit(px, SurfaceFit::Fit) + .shadow(0.0, 30.0, look.shadow()), + None => text(name.to_owned()).font(ty::HERO).color(look.text()), + }; + col() + .key("hero-block") + .w_full() + .min_h(210.0) + .pt(26.0) + .gap(14.0) + .justify_end() + .child(title) + .child( + row() + .gap(space::SM) + .center_y() + .child(glyph(&icons::FOLDER, 14.0, look.muted())) + .child( + text(path.to_owned()) + .font(ty::SMALL) + .color(look.muted()) + .truncate(), + ), + ) + .child(hero_actions(s, look)) +} + +fn hero_actions(s: &App, look: &Look) -> El { + let blocked = s.blockers().next().is_some(); + row() + .gap(space::SM) + .child( + Button::new("Deploy") + .icon(&icons::DEPLOY) + .variant(ButtonVariant::Submit) + .disabled(blocked || s.busy > 0) + .on_press(|s: &mut App| s.deploy()) + .build(&look.k), + ) + .children(s.lib.capabilities.is_some_and(|c| c.launch).then(|| { + Button::new("Launch") + .icon(&icons::PLAY) + .variant(ButtonVariant::Neutral) + .on_press(|s: &mut App| s.launch()) + .build(&look.k) + })) + .child( + Button::new("Add mods") + .icon(&icons::PLUS) + .variant(ButtonVariant::Neutral) + .on_press_tx(|_: &mut App, tx| crate::ui::mods::pick_archives(tx)) + .build(&look.k), + ) + .child( + Button::new("Verify") + .icon(&icons::SHIELD) + .variant(ButtonVariant::Ghost) + .on_press(|s: &mut App| s.verify()) + .build(&look.k), + ) +} + +fn stats(s: &App, look: &Look) -> El { + let conflicts = s.unresolved_conflicts(); + row() + .w_full() + .gap(space::MD) + .flex_wrap() + .child(parts::stat( + look, + "stat-mods", + (&icons::LAYERS, look.accent), + s.lib.mods.len().to_string(), + "Mods installed", + )) + .child(parts::stat( + look, + "stat-enabled", + (&icons::CHECK, look.good), + s.lib.enabled.len().to_string(), + "Enabled", + )) + .children(s.screen_visible(Screen::LoadOrder).then(|| { + parts::stat( + look, + "stat-plugins", + (&icons::PUZZLE, look.warn), + s.lib.plugins.len().to_string(), + "Plugins", + ) + })) + .child(parts::stat( + look, + "stat-conflicts", + ( + &icons::CONFLICT, + if conflicts > 0 { look.bad } else { look.good }, + ), + conflicts.to_string(), + "Unresolved conflicts", + )) +} + +fn health(s: &App, look: &Look) -> El { + let body = if s.lib.health.is_empty() { + row() + .w_full() + .px(18.0) + .pb(18.0) + .gap(12.0) + .center_y() + .child(parts::icon_tile(&icons::SHIELD, look.good, 36.0)) + .child( + col() + .gap(2.0) + .child(text("All clear").font(ty::BODY_STRONG).color(look.text())) + .child( + text("Setup checks found nothing to fix") + .font(ty::SMALL) + .color(look.muted()), + ), + ) + } else { + let rows = s.lib.health.iter().take(8).enumerate().map(|(i, issue)| { + let (tint, i_icon) = match issue.severity { + Severity::Error => (look.bad, &icons::WARNING), + Severity::Warning => (look.warn, &icons::WARNING), + Severity::Info => (look.accent, &icons::INFO), + }; + row() + .key(format!("issue-{i}")) + .w_full() + .px(18.0) + .py(9.0) + .gap(12.0) + .child(glyph(i_icon, 16.0, tint)) + .child( + text(issue.message.clone()) + .font(ty::BODY) + .color(look.text()) + .wrap() + .grow(1.0), + ) + .children( + issue + .blocking + .then(|| parts::chip("Blocks deploy", look.bad)), + ) + }); + col().w_full().pb(10.0).children(rows) + }; + parts::section(look, "health", "Setup health", None, body) +} + +fn recent(s: &App, look: &Look) -> El { + let body = if s.notes.is_empty() { + col().w_full().px(18.0).pb(18.0).child( + text("Installs, deploys and checks show up here") + .font(ty::BODY) + .color(look.muted()), + ) + } else { + let rows = s.notes.iter().take(6).map(|n| { + row() + .key(format!("recent-{}", n.id)) + .w_full() + .px(18.0) + .py(8.0) + .gap(12.0) + .center_y() + .child( + el().size(7.0, 7.0) + .radius(4.0) + .fill(parts::tone_color(look, n.tone)), + ) + .child( + text(n.text.clone()) + .font(ty::BODY) + .color(look.text()) + .truncate() + .grow(1.0), + ) + .child( + text(crate::ui::shell::ago(s.now - n.at)) + .font(ty::SMALL) + .color(look.faint()), + ) + }); + col().w_full().pb(10.0).children(rows) + }; + parts::section(look, "recent", "Recent activity", None, body) +} + +/// The mod loader's state and the tail of the game's log, when the game +/// declares either. +fn game_status(s: &App, look: &Look) -> Option { + let loader = s.lib.loader.as_ref().map(|l| loader_row(look, l)); + let log = (!s.lib.log.is_empty()).then(|| log_tail(look, &s.lib.log)); + if loader.is_none() && log.is_none() { + return None; + } + let body = col() + .w_full() + .pb(14.0) + .gap(10.0) + .children(loader) + .children(log); + let title = if s.lib.loader.is_some() { + "Game" + } else { + "Game log" + }; + Some(parts::section(look, "game-status", title, None, body)) +} + +fn loader_row(look: &Look, l: &modrix_core::LoaderStatus) -> El { + let (tone, state) = match (&l.conflict, l.installed) { + (Some(rival), _) => (look.bad, format!("Blocked by {rival}")), + (None, true) => ( + look.good, + l.version + .as_ref() + .map_or_else(|| "Installed".to_owned(), |v| format!("Installed, {v}")), + ), + (None, false) => (look.warn, "Not installed".to_owned()), + }; + row() + .key("loader") + .w_full() + .px(18.0) + .gap(12.0) + .center_y() + .child(el().size(7.0, 7.0).radius(4.0).fill(tone)) + .child( + text(format!("Mod loader: {}", l.kind)) + .font(ty::BODY) + .color(look.text()) + .grow(1.0) + .truncate(), + ) + .child(text(state).font(ty::SMALL).color(look.muted())) + .children(l.installed.then(|| { + parts::tag( + look, + if l.interop_ready { + "Interop ready" + } else { + "Interop missing" + }, + ) + })) +} + +fn log_tail(look: &Look, lines: &[String]) -> El { + let rows = lines.iter().enumerate().map(|(i, line)| { + text(line.clone()) + .key(format!("log-{i}")) + .font(ty::MONO) + .color(look.muted()) + .truncate() + }); + col() + .key("log-tail") + .mx(18.0) + .padding(12.0) + .gap(3.0) + .radius(10.0) + .fill(look.base.alpha(0.55)) + .border(1.0, look.edge) + .children(rows) +} + +fn external(s: &App, look: &Look) -> El { + let rows = s.lib.external.iter().take(12).enumerate().map(|(i, m)| { + row() + .key(format!("ext-{i}")) + .w_full() + .px(18.0) + .py(8.0) + .gap(12.0) + .center_y() + .child(glyph(&icons::PACKAGE, 16.0, look.faint())) + .child( + text(m.name.clone()) + .font(ty::BODY) + .color(look.text()) + .grow(1.0) + .truncate(), + ) + .child(parts::tag(look, m.label.clone())) + .child( + text(format!("{} files", m.files)) + .font(ty::SMALL) + .color(look.faint()), + ) + }); + parts::section( + look, + "external", + "Found in the game folder", + Some( + text("Not managed by Modrix") + .font(ty::SMALL) + .color(look.faint()), + ), + col().w_full().pb(10.0).children(rows), + ) +} + +fn welcome(s: &App, look: &Look) -> El { + let found = s.unregistered_detected().len(); + let body = if found > 0 { + format!( + "Modrix found {found} supported games on this computer. Add one to start managing its mods." + ) + } else { + "Point Modrix at a game folder to start managing its mods.".to_owned() + }; + col().w_full().pt(60.0).child( + parts::panel(look, "welcome").child(parts::empty( + look, + &icons::GAMEPAD, + "Welcome to Modrix", + &body, + Some( + Button::new("Set up a game") + .icon(&icons::PLUS) + .variant(ButtonVariant::Submit) + .on_press(|s: &mut App| s.screen = Screen::Games) + .build(&look.k), + ), + )), + ) +} diff --git a/crates/modrix-gui/src/ui/dialogs.rs b/crates/modrix-gui/src/ui/dialogs.rs new file mode 100644 index 0000000..7e2c4dd --- /dev/null +++ b/crates/modrix-gui/src/ui/dialogs.rs @@ -0,0 +1,100 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Modal surfaces: the FOMOD wizard, the duplicate-archive prompt and the +//! delete confirmation. At most one shows; the wizard waits behind the others. + +use rune::{El, row, text}; +use rune_kit::{Button, ButtonVariant, Dialog}; + +use crate::look::{Look, space, ty}; +use crate::state::App; + +/// Push whichever dialog is open onto the overlay layer. +pub fn build(s: &App, look: &Look, layer: &mut Vec) { + if let Some(dup) = s.dup_queue.first() { + duplicate(look, dup, layer); + } else if s.confirm_delete { + delete(s, look, layer); + } else if let Some(wizard) = &s.wizard { + super::wizard::build(s, look, wizard, layer); + } +} + +fn actions(look: &Look, cancel: &str, confirm: El, on_cancel: fn(&mut App)) -> El { + row() + .w_full() + .px(20.0) + .pt(8.0) + .pb(18.0) + .gap(space::SM) + .justify_end() + .child( + Button::new(cancel) + .variant(ButtonVariant::GhostMuted) + .on_press(on_cancel) + .build(&look.k), + ) + .child(confirm) +} + +fn duplicate(look: &Look, dup: &crate::state::DupPrompt, layer: &mut Vec) { + let file = dup.path.file_name().map_or_else( + || dup.path.display().to_string(), + |n| n.to_string_lossy().into_owned(), + ); + Dialog::new("duplicate", "Already installed") + .open(true) + .fit() + .width(460.0) + .description(format!( + "{file} is the same archive as {}.", + dup.existing_name + )) + .child( + row().w_full().px(20.0).pb(6.0).child( + text("Install it again as a separate mod, or skip it.") + .font(ty::BODY) + .color(look.muted()) + .wrap(), + ), + ) + .child(actions( + look, + "Skip", + Button::new("Install anyway") + .variant(ButtonVariant::Submit) + .on_press(|s: &mut App| s.dup_confirm()) + .build(&look.k), + App::dup_cancel, + )) + .on_close(|s: &mut App| s.dup_cancel()) + .build(&look.k, layer); +} + +fn delete(s: &App, look: &Look, layer: &mut Vec) { + let ids = s.selected_mod_ids(); + let title = match ids.as_slice() { + [one] => format!("Delete {}?", s.mod_name(*one)), + many => format!("Delete {} mods?", many.len()), + }; + Dialog::new("confirm-delete", title) + .open(true) + .fit() + .width(440.0) + .description( + "Their staged files are removed. Deploy afterwards to take them out of the game.", + ) + .child(actions( + look, + "Keep", + Button::new("Delete") + .variant(ButtonVariant::Danger) + .on_press(|s: &mut App| { + s.confirm_delete = false; + s.delete_selected(); + }) + .build(&look.k), + |s| s.confirm_delete = false, + )) + .on_close(|s: &mut App| s.confirm_delete = false) + .build(&look.k, layer); +} diff --git a/crates/modrix-gui/src/ui/downloads.rs b/crates/modrix-gui/src/ui/downloads.rs new file mode 100644 index 0000000..a609982 --- /dev/null +++ b/crates/modrix-gui/src/ui/downloads.rs @@ -0,0 +1,197 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Browser hand-off downloads: live progress, install results, and how to +//! pair the extension. + +use modrix_download::{DownloadState, DownloadStatus}; +use modrix_service::InstallOutcome; +use rune::{El, col, el, row, text}; +use rune_kit::{IconButton, IconButtonVariant, Progress}; + +use crate::icons; +use crate::look::{Look, space, ty}; +use crate::state::App; +use crate::ui::parts::{self, glyph}; + +/// The Downloads screen. +pub fn view(s: &App, look: &Look) -> El { + let list = if s.downloads.is_empty() { + parts::panel(look, "downloads-empty").child(parts::empty( + look, + &icons::DOWNLOAD, + "No downloads yet", + "With the Modrix browser extension installed, click Mod Manager Download on a Nexus mod page and it lands here, then installs itself.", + None, + )) + } else { + let rows = s + .downloads + .iter() + .take(200) + .map(|d| download_row(s, look, d)); + parts::section( + look, + "downloads", + "Transfers", + None, + col().w_full().pb(8.0).children(rows), + ) + }; + col() + .w_full() + .gap(space::LG) + .child(list) + .child(pairing(s, look)) +} + +fn download_row(s: &App, look: &Look, d: &DownloadStatus) -> El { + let name = d.file.file_name().map_or_else( + || d.file.display().to_string(), + |n| n.to_string_lossy().trim_end_matches(".part").to_owned(), + ); + let (_, tint) = status(s, look, d); + let live = matches!(d.state, DownloadState::Active | DownloadState::Queued); + let id = d.id; + row() + .key(format!("dl-{id:?}")) + .w_full() + .px(18.0) + .py(12.0) + .gap(space::MD) + .center_y() + .child(parts::icon_tile(&icons::PACKAGE, tint, 36.0)) + .child(download_body(s, look, d, name)) + .children(live.then(|| { + IconButton::new(&icons::CLOSE) + .variant(IconButtonVariant::GhostMuted) + .label("Cancel download") + .on_press(move |s: &mut App| s.cancel_download(id)) + .build(&look.k) + })) +} + +fn download_body(s: &App, look: &Look, d: &DownloadStatus, name: String) -> El { + let (label, tint) = status(s, look, d); + let size = match d.total { + Some(t) => format!("{} of {}", crate::fmt::bytes(d.done), crate::fmt::bytes(t)), + None => crate::fmt::bytes(d.done), + }; + let live = matches!(d.state, DownloadState::Active | DownloadState::Queued); + let fraction = match d.state { + DownloadState::Complete => Some(1.0), + DownloadState::Queued => None, + _ => Some(crate::fmt::fraction(d.done, d.total)), + }; + col() + .grow(1.0) + .min_w(0.0) + .gap(6.0) + .child( + row() + .w_full() + .gap(space::SM) + .center_y() + .child( + text(name) + .font(ty::BODY_STRONG) + .color(look.text()) + .truncate() + .grow(1.0), + ) + .child(text(size).font(ty::MONO).color(look.muted())), + ) + .children(live.then(|| Progress::new(fraction).build(&look.k))) + .child( + row() + .gap(space::SM) + .center_y() + .child(el().size(6.0, 6.0).radius(3.0).fill(tint)) + .child(text(label).font(ty::SMALL).color(look.muted())) + .children((d.state == DownloadState::Active).then(|| { + text(format!( + "{} connections, {}", + d.connections, + crate::fmt::percent(d.done, d.total) + )) + .font(ty::SMALL) + .color(look.faint()) + })), + ) +} + +fn status(s: &App, look: &Look, d: &DownloadStatus) -> (String, rune::Color) { + match d.state { + DownloadState::Queued => ("Queued".to_owned(), look.faint()), + DownloadState::Active => ("Downloading".to_owned(), look.accent), + DownloadState::Paused => ("Paused".to_owned(), look.warn), + DownloadState::Failed => ("Failed".to_owned(), look.bad), + DownloadState::Complete => match s.outcomes.get(&d.id) { + Some(InstallOutcome::Installed { name, .. }) => { + (format!("Installed as {name}"), look.good) + } + Some(InstallOutcome::Failed(error)) => (format!("Install failed: {error}"), look.bad), + Some(InstallOutcome::NoGame) => ("Kept: no game matched".to_owned(), look.warn), + None => ("Installing".to_owned(), look.accent), + }, + } +} + +fn pairing(s: &App, look: &Look) -> El { + let body = if let Some(link) = &s.link { + let token = link.token.clone(); + col() + .w_full() + .pb(10.0) + .child(parts::kv( + look, + "Port", + text(link.port.to_string()) + .font(ty::MONO) + .color(look.text()), + )) + .child(parts::kv( + look, + "Token", + row() + .gap(space::SM) + .center_y() + .child(text(mask(&link.token)).font(ty::MONO).color(look.text())) + .child( + IconButton::new(&icons::COPY) + .variant(IconButtonVariant::GhostMuted) + .label("Copy token") + .on_press_tx(move |_: &mut App, tx| tx.copy(token.clone())) + .build(&look.k), + ), + )) + } else { + col().w_full().px(18.0).pb(16.0).child( + text(if s.already_running { + "Another Modrix window is receiving browser downloads. Close it to receive them here." + } else { + "The browser link starts with the engine." + }) + .font(ty::BODY) + .color(look.muted()) + .wrap(), + ) + }; + parts::section( + look, + "pairing", + "Browser extension", + Some(glyph(&icons::LINK, 16.0, look.faint())), + body, + ) +} + +fn mask(token: &str) -> String { + let tail: String = token + .chars() + .rev() + .take(4) + .collect::>() + .into_iter() + .rev() + .collect(); + format!("........{tail}") +} diff --git a/crates/modrix-gui/src/ui/games.rs b/crates/modrix-gui/src/ui/games.rs new file mode 100644 index 0000000..ec48258 --- /dev/null +++ b/crates/modrix-gui/src/ui/games.rs @@ -0,0 +1,343 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Games: the registered ones as art cards, supported games found on this +//! computer, support from the community registry, and manual setup. + +use rune::{El, FileDialogOptions, SurfaceFit, col, el, row, text}; +use rune_kit::{Button, ButtonVariant, Select, TextInput}; + +use crate::icons; +use crate::look::{Look, space, ty}; +use crate::state::{App, Popup, Screen}; +use crate::ui::parts::{self, glyph}; + +/// Cards per row. +const PER_ROW: usize = 3; + +/// The Games screen. +pub fn view(s: &App, look: &Look, layer: &mut Vec) -> El { + let mut page = col().w_full().gap(space::LG); + if !s.lib.games.is_empty() { + page = page.child(registered(s, look, layer)); + } + let found = s.unregistered_detected(); + if !found.is_empty() { + page = page.child(detected(s, look, &found)); + } + let support = s.available_support(); + if !support.is_empty() || s.registry_loading { + page = page.child(registry(s, look, &support)); + } + page.child(manual(s, look, layer)) +} + +fn registered(s: &App, look: &Look, layer: &mut Vec) -> El { + let cards: Vec = s.lib.games.iter().map(|g| game_card(s, look, g)).collect(); + let grid = super::menus::games(s, look, grid(cards), layer); + parts::section(look, "registered", "Your games", None, grid) +} + +fn grid(cards: Vec) -> El { + let mut rows = Vec::new(); + let mut current = Vec::new(); + for card in cards.into_iter().take(300) { + current.push(card); + if current.len() == PER_ROW { + rows.push( + row() + .w_full() + .gap(space::MD) + .children(std::mem::take(&mut current)), + ); + } + } + if !current.is_empty() { + let pad = PER_ROW.saturating_sub(current.len()); + let fillers = (0..pad).map(|_| el().grow(1.0).w(0.0)); + rows.push( + row() + .w_full() + .gap(space::MD) + .children(current) + .children(fillers), + ); + } + col() + .w_full() + .px(18.0) + .pb(18.0) + .gap(space::MD) + .children(rows) +} + +fn game_card(s: &App, look: &Look, g: &modrix_core::Game) -> El { + let id = g.id; + let on = s.lib.game == Some(id); + col() + .key(format!("game-{id}")) + .grow(1.0) + .w(0.0) + .radius(14.0) + .clip_rounded(14.0) + .fill(look.glass_strong) + .border( + if on { 2.0 } else { 1.0 }, + if on { look.accent } else { look.edge }, + ) + .hover_fill(look.glass_strong.mix(look.accent, 0.06)) + .role("button") + .label(format!("Manage {}", g.name)) + .on_press(move |s: &mut App| { + s.switch_game(id); + s.screen = Screen::Dashboard; + }) + .on_secondary_press(move |s: &mut App, p, _| s.open_game_menu(id, p)) + .child(banner(look, s.art.get(&id), &g.name)) + .child(caption(look, g, on)) +} + +/// The card's art strip: the hero with the logo over it, or the name on a +/// tinted gradient when the game has no art. +fn banner(look: &Look, art: Option<&crate::art::ArtSet>, name: &str) -> El { + let strip = el().w_full().h(120.0); + let Some(hero) = art.and_then(|a| a.hero.as_ref()) else { + return strip + .linear_gradient( + 2.4, + [ + (0.0, look.accent.alpha(0.40)), + (1.0, look.accent.alpha(0.06)), + ], + ) + .padding(16.0) + .child(glyph(&icons::GAMEPAD, 22.0, look.text().alpha(0.7))) + .child( + text(name.to_owned()) + .font(ty::HEADING) + .color(look.text()) + .absolute(16.0, 82.0), + ); + }; + let logo = art.and_then(|a| a.logo.as_ref()).map(|px| { + el().absolute(14.0, 66.0) + .w(150.0) + .h(44.0) + .pixels_fit(px, SurfaceFit::Fit) + }); + strip + .pixels_fit(hero, SurfaceFit::Fill) + .child( + el().absolute(0.0, 60.0) + .w_full() + .h(60.0) + .gradient(look.base.alpha(0.0), look.base.alpha(0.6)), + ) + .children(logo) +} + +fn caption(look: &Look, g: &modrix_core::Game, on: bool) -> El { + col() + .padding(14.0) + .gap(3.0) + .child( + row() + .gap(8.0) + .center_y() + .child( + text(g.name.clone()) + .font(ty::BODY_STRONG) + .color(look.text()) + .truncate() + .grow(1.0), + ) + .children(on.then(|| parts::chip("Active", look.accent))), + ) + .child( + text(g.install_path.display().to_string()) + .font(ty::SMALL) + .color(look.faint()) + .truncate_head(), + ) +} + +fn detected(s: &App, look: &Look, found: &[(usize, &crate::state::Detected)]) -> El { + let rows = found.iter().map(|(index, d)| { + let index = *index; + row() + .key(format!("found-{}", d.def.id)) + .w_full() + .px(18.0) + .py(10.0) + .gap(space::MD) + .center_y() + .child(parts::icon_tile(&icons::GAMEPAD, look.accent, 34.0)) + .child( + col() + .grow(1.0) + .min_w(0.0) + .gap(2.0) + .child( + text(d.def.name.clone()) + .font(ty::BODY_STRONG) + .color(look.text()), + ) + .child( + text(d.install.display().to_string()) + .font(ty::SMALL) + .color(look.faint()) + .truncate_head(), + ), + ) + .child( + Button::new("Add") + .icon(&icons::PLUS) + .variant(ButtonVariant::Submit) + .on_press(move |s: &mut App| s.add_detected(index)) + .build(&look.k), + ) + }); + let _ = s; + parts::section( + look, + "detected", + "Found on this computer", + Some(parts::chip(found.len().to_string(), look.accent)), + col().w_full().pb(8.0).children(rows), + ) +} + +fn registry(s: &App, look: &Look, support: &[(usize, &crate::state::RegistryChoice)]) -> El { + let body = if s.registry_loading && support.is_empty() { + row().px(18.0).pb(16.0).child( + text("Loading the community registry") + .font(ty::BODY) + .color(look.muted()), + ) + } else { + let rows = support.iter().take(200).map(|(index, r)| { + let index = *index; + row() + .key(format!("reg-{}", r.id)) + .w_full() + .px(18.0) + .py(9.0) + .gap(space::MD) + .center_y() + .child(glyph(&icons::PUZZLE, 16.0, look.faint())) + .child( + text(r.name.clone()) + .font(ty::BODY) + .color(look.text()) + .grow(1.0) + .truncate(), + ) + .child(parts::tag(look, r.version.clone())) + .child( + Button::new("Install") + .variant(ButtonVariant::Ghost) + .on_press(move |s: &mut App| s.install_support(index)) + .build(&look.k), + ) + }); + col().w_full().pb(8.0).children(rows) + }; + parts::section( + look, + "registry", + "More games from the community", + None, + body, + ) +} + +fn def_picker(s: &App, look: &Look, layer: &mut Vec) -> El { + let names: Vec<&str> = s.defs.iter().map(|d| d.name.as_str()).collect(); + let current = s + .form + .def_id + .as_deref() + .and_then(|id| s.defs.iter().find(|d| d.id == id)) + .map(|d| d.name.as_str()); + Select::new("def-picker", &names) + .current(current) + .placeholder("Choose a game") + .open(s.popup == Some(Popup::DefPicker)) + .on_toggle(|s: &mut App| { + s.popup = if s.popup == Some(Popup::DefPicker) { + None + } else { + Some(Popup::DefPicker) + } + }) + .on_close(|s: &mut App| s.popup = None) + .on_choose(|s: &mut App, name: &str, _| { + s.popup = None; + s.form.def_id = s.defs.iter().find(|d| d.name == name).map(|d| d.id.clone()); + }) + .width(300.0) + .build(&look.k, layer) +} + +/// The widest a form field grows; narrower windows shrink it. +const FIELD_MAX_W: f32 = 380.0; + +fn folder_field(s: &App, look: &Look) -> El { + row() + .w_full() + .gap(space::SM) + .child( + TextInput::new(&s.form.install_path) + .placeholder("Game folder") + .leading_icon(&icons::FOLDER) + .width(None) + .on_edit(|s: &mut App| &mut s.form.install_path) + .on_submit(|s: &mut App, _| s.add_game()) + .build(&look.k) + .grow(1.0) + .w(0.0) + .max_w(FIELD_MAX_W), + ) + .child( + Button::new("Browse") + .variant(ButtonVariant::Neutral) + .on_press_tx(|_: &mut App, tx| { + let options = FileDialogOptions { + title: "Game folder".to_owned(), + ..FileDialogOptions::default() + }; + tx.open_folder(options, |s: &mut App, picked, _| { + if let Ok(Some(dir)) = picked { + s.form.install_path = rune::TextEdit::new(dir.display().to_string()); + } + }); + }) + .build(&look.k), + ) +} + +fn manual(s: &App, look: &Look, layer: &mut Vec) -> El { + let picker = def_picker(s, look, layer); + let folder = folder_field(s, look); + let custom = TextInput::new(&s.form.def_path) + .placeholder("Optional: path to a game.toml") + .width(None) + .on_edit(|s: &mut App| &mut s.form.def_path) + .build(&look.k) + .w_full() + .max_w(FIELD_MAX_W); + let body = col() + .w_full() + .pb(14.0) + .child(parts::kv(look, "Game", picker)) + .child(parts::kv(look, "Install folder", folder)) + .child(parts::kv(look, "Definition", custom)) + .child( + row().w_full().px(18.0).pt(6.0).justify_end().child( + Button::new("Add game") + .icon(&icons::PLUS) + .variant(ButtonVariant::Submit) + .on_press(|s: &mut App| s.add_game()) + .build(&look.k), + ), + ); + parts::section(look, "manual", "Set up a game by hand", None, body) +} diff --git a/crates/modrix-gui/src/ui/load_order.rs b/crates/modrix-gui/src/ui/load_order.rs new file mode 100644 index 0000000..a605b2e --- /dev/null +++ b/crates/modrix-gui/src/ui/load_order.rs @@ -0,0 +1,271 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Plugin load order: drag rows by the grip (or Ctrl+arrows), toggle them, +//! auto-sort. Later plugins win. + +use rune::{Drag, El, Phase, Tx, col, el, row, text}; +use rune_kit::{Button, ButtonVariant, Checkbox, IconButton, IconButtonVariant}; + +use crate::icons; +use crate::look::{Look, space, ty}; +use crate::state::{App, Pane, PluginDrag}; +use crate::ui::parts::{self, glyph}; +use modrix_core::plugins::GamePlugin; + +/// Row height, fixed so a drag maps to a slot. +const ROW_H: f32 = 50.0; + +/// The Load order screen. +pub fn view(s: &App, look: &Look) -> El { + if s.lib.plugins.is_empty() { + return parts::panel(look, "order-empty").child(parts::empty( + look, + &icons::ORDER, + "No plugins", + "Enable mods that ship plugins and they appear here in load order.", + None, + )); + } + let rows = s + .lib + .plugins + .iter() + .enumerate() + .map(|(i, _)| plugin_row(s, look, i)); + let list = col() + .key("order-scroll") + .w_full() + .grow(1.0) + .min_h(0.0) + .scroll(rune::ScrollSpec::default()) + .child( + col() + .key("order-rows") + .w_full() + .children(rows) + .children(drop_line(s, look)), + ); + col() + .w_full() + .grow(1.0) + .min_h(0.0) + .gap(space::MD) + .child(toolbar(s, look)) + .child( + parts::panel(look, "order-table") + .grow(1.0) + .min_h(0.0) + .child(list), + ) +} + +fn toolbar(s: &App, look: &Look) -> El { + let any = !s.plugin_sel.items.is_empty(); + let missing = s + .lib + .plugins + .iter() + .filter(|p| !p.missing_masters.is_empty()) + .count(); + row() + .w_full() + .gap(space::SM) + .center_y() + .child( + text("Drag the grip or use Ctrl and the arrow keys to move plugins.") + .font(ty::SMALL) + .color(look.muted()), + ) + .children((missing > 0).then(|| { + parts::chip( + if missing == 1 { + "1 plugin missing masters".to_owned() + } else { + format!("{missing} plugins missing masters") + }, + look.bad, + ) + })) + .child(el().grow(1.0)) + .child( + IconButton::new(&icons::ARROW_UP) + .variant(IconButtonVariant::Ghost) + .label("Move up") + .disabled(!any) + .on_press(|s: &mut App| s.move_plugins(-1)) + .build(&look.k), + ) + .child( + IconButton::new(&icons::ARROW_DOWN) + .variant(IconButtonVariant::Ghost) + .label("Move down") + .disabled(!any) + .on_press(|s: &mut App| s.move_plugins(1)) + .build(&look.k), + ) + .child( + Button::new("Auto-sort") + .icon(&icons::SPARKLES) + .variant(ButtonVariant::Submit) + .on_press(|s: &mut App| s.auto_sort()) + .build(&look.k), + ) +} + +/// Slot a drag lands in. +#[must_use] +pub fn target(from: usize, dy: f32, len: usize) -> usize { + #[expect(clippy::cast_possible_truncation, reason = "a row count fits in i64")] + let steps = (dy / ROW_H).round() as i64; + let from = i64::try_from(from).unwrap_or(0); + let last = i64::try_from(len.saturating_sub(1)).unwrap_or(0); + usize::try_from(from.saturating_add(steps).clamp(0, last)).unwrap_or(0) +} + +fn drop_line(s: &App, look: &Look) -> Option { + let drag = s.drag?; + let to = target(drag.from, drag.dy, s.lib.plugins.len()); + if to == drag.from { + return None; + } + let below = usize::from(to > drag.from); + #[expect(clippy::cast_precision_loss, reason = "row indices are small")] + let y = to.saturating_add(below) as f32 * ROW_H - 1.0; + Some( + el().key("drop-line") + .absolute(14.0, y) + .w_full() + .mr(28.0) + .h(2.0) + .radius(1.0) + .fill(look.accent) + .shadow(0.0, 8.0, look.accent), + ) +} + +fn on_grip(s: &mut App, i: usize, d: &mut Drag, _tx: &mut Tx) { + match d.phase { + Phase::Down => s.drag = Some(PluginDrag { from: i, dy: 0.0 }), + Phase::Move => { + if let Some(drag) = &mut s.drag { + drag.dy = d.dy; + } + } + Phase::Up => { + if let Some(drag) = s.drag.take() { + let to = target(drag.from, drag.dy, s.lib.plugins.len()); + s.move_plugin_to(drag.from, to); + } + } + } +} + +fn plugin_row(s: &App, look: &Look, i: usize) -> El { + let Some(p) = s.lib.plugins.get(i) else { + return el(); + }; + let selected = s.plugin_sel.items.contains(&i); + let dragging = s.drag.filter(|d| d.from == i); + let mut line = row() + .key(format!("plugin-{}", p.name)) + .w_full() + .h(ROW_H) + .px(14.0) + .gap(space::MD) + .center_y() + .fill(if selected || dragging.is_some() { + look.accent_soft + } else { + rune::Color::TRANSPARENT + }) + .hover_fill(if selected { + look.accent_soft + } else { + look.hover() + }) + .border_sides([0.0, 0.0, 1.0, 0.0], look.edge) + .role("row") + .checked(selected) + .label(p.name.clone()) + .on_press_tx(move |s: &mut App, tx| s.row_click(Pane::Plugins, i, tx.mods())) + .children(plugin_cells(look, i, p)); + if let Some(d) = dragging { + line = line + .offset(0.0, d.dy) + .shadow(12.0, 28.0, look.shadow()) + .fill(look.glass_strong) + .radius(10.0); + } + line +} + +fn badges(look: &Look, p: &GamePlugin) -> El { + let mut badges = row().gap(6.0); + if p.is_master { + badges = badges.child(parts::chip("Master", look.warn)); + } + if p.is_light { + badges = badges.child(parts::chip("Light", look.accent)); + } + if !p.missing_masters.is_empty() { + badges = badges.child(parts::chip( + format!("Missing {}", p.missing_masters.join(", ")), + look.bad, + )); + } + badges +} + +fn plugin_cells(look: &Look, i: usize, p: &GamePlugin) -> [El; 5] { + let grip = el() + .key(format!("grip-{i}")) + .size(26.0, 34.0) + .center() + .radius(6.0) + .hover_fill(look.hover()) + .cursor(rune::Cursor::Grab) + .label("Drag to reorder") + .on_drag(move |s: &mut App, d: &mut Drag, tx: &mut Tx| on_grip(s, i, d, tx)) + .child(glyph(&icons::GRIP, 16.0, look.faint())); + [ + grip, + text(format!("{i:02}")) + .font(ty::MONO) + .color(look.faint()) + .w(28.0), + Checkbox::new(p.enabled) + .hide_label() + .label(format!("Activate {}", p.name)) + .on_toggle(move |s: &mut App| s.toggle_plugin(i)) + .build(&look.k), + col() + .grow(1.0) + .min_w(0.0) + .gap(2.0) + .child( + text(p.name.clone()) + .font(ty::BODY_STRONG) + .color(if p.enabled { look.text() } else { look.muted() }) + .truncate(), + ) + .child( + text(p.mod_name.clone()) + .font(ty::SMALL) + .color(look.faint()) + .truncate(), + ), + badges(look, p), + ] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn drag_targets_clamp() { + assert_eq!(target(2, 0.0, 5), 2); + assert_eq!(target(2, ROW_H * 1.4, 5), 3); + assert_eq!(target(2, -ROW_H * 9.0, 5), 0); + assert_eq!(target(2, ROW_H * 9.0, 5), 4); + } +} diff --git a/crates/modrix-gui/src/ui/menus.rs b/crates/modrix-gui/src/ui/menus.rs new file mode 100644 index 0000000..718c544 --- /dev/null +++ b/crates/modrix-gui/src/ui/menus.rs @@ -0,0 +1,164 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! The app's own right-click menus: on mod rows and on game cards. +//! +//! A secondary press stores what was pressed and where in `App::ctx`; the +//! menu is anchored at that point over the list it belongs to. A mod menu +//! acts on the selection when the pressed row is part of it, otherwise on +//! that row alone (the press selects it). + +use rune::{El, PointerPress}; +use rune_kit::{Menu, MenuItem, context_menu}; + +use crate::icons; +use crate::look::Look; +use crate::state::{App, Ctx, Pane, Screen}; + +impl App { + /// Open the mod menu for visible row `index`. + pub fn open_mod_menu(&mut self, index: usize, at: PointerPress) { + self.focus_pane = Pane::Mods; + if !self.mod_sel.items.contains(&index) { + self.mod_sel.only(index); + } + self.ctx = Some((Ctx::Mod(index), at)); + } + + /// Open the game menu for a game card. + pub fn open_game_menu(&mut self, game: modrix_core::GameId, at: PointerPress) { + self.ctx = Some((Ctx::Game(game), at)); + } +} + +/// The Mods table with its right-click menu. The menu's anchor wraps the +/// table in a row, so the wrapper takes over the table's growth. +pub fn mods(s: &App, look: &Look, table: El, layer: &mut Vec) -> El { + mod_menu(s, look, table.h_full(), layer) + .w_full() + .grow(1.0) + .min_h(0.0) +} + +fn mod_menu(s: &App, look: &Look, table: El, layer: &mut Vec) -> El { + let point = match s.ctx { + Some((Ctx::Mod(_), at)) => Some(at), + _ => None, + }; + let menu = context_menu("mod-menu", table, point) + .min_width(220.0) + .on_close(|s: &mut App| s.ctx = None); + let Some((Ctx::Mod(index), _)) = s.ctx else { + return menu.build(&look.k, layer); + }; + let Some(m) = s.visible_mods().get(index).and_then(|i| s.lib.mods.get(*i)) else { + return menu.build(&look.k, layer); + }; + let ids = s.selected_mod_ids(); + let many = ids.len() > 1; + let id = m.id; + let staged = m.staged_path.display().to_string(); + let head = if many { + format!("{} mods", ids.len()) + } else { + m.name.clone() + }; + let menu = edit_items(s, menu.group_label(head), m, ids); + let menu = if !many && m.install_state.starts_with("fomod") { + menu.item( + MenuItem::new("Installer options") + .icon(&icons::SLIDERS) + .on_select(move |s: &mut App| { + s.ctx = None; + s.configure(id); + }), + ) + } else { + menu + }; + menu.separator() + .item(copy_item("Copy staged path", staged).disabled(many)) + .separator() + .item( + MenuItem::new(if many { "Delete selected" } else { "Delete" }) + .icon(&icons::TRASH) + .danger(true) + .on_select(|s: &mut App| { + s.ctx = None; + s.confirm_delete = true; + }), + ) + .build(&look.k, layer) +} + +/// Enable or Disable (from the pressed mod's state) and Reinstall. +fn edit_items(s: &App, menu: Menu, m: &modrix_core::Mod, ids: Vec) -> Menu { + let on = s.lib.enabled.contains(&m.id); + menu.item( + MenuItem::new(if on { "Disable" } else { "Enable" }) + .icon(if on { &icons::CLOSE } else { &icons::CHECK }) + .disabled(s.lib.profile.is_none()) + .on_select(move |s: &mut App| { + s.ctx = None; + s.set_many_enabled(ids.clone(), !on); + }), + ) + .item( + MenuItem::new("Reinstall") + .icon(&icons::REFRESH) + .on_select(|s: &mut App| { + s.ctx = None; + s.reinstall_selected(); + }), + ) +} + +/// The game cards with their right-click menu. +pub fn games(s: &App, look: &Look, cards: El, layer: &mut Vec) -> El { + game_menu(s, look, cards, layer).w_full() +} + +fn game_menu(s: &App, look: &Look, cards: El, layer: &mut Vec) -> El { + let (point, game) = match s.ctx { + Some((Ctx::Game(id), at)) => (Some(at), s.lib.games.iter().find(|g| g.id == id)), + _ => (None, None), + }; + let menu = context_menu("game-menu-ctx", cards, point) + .min_width(220.0) + .on_close(|s: &mut App| s.ctx = None); + let Some(g) = game else { + return menu.build(&look.k, layer); + }; + let id = g.id; + let path = g.install_path.display().to_string(); + menu.group_label(g.name.clone()) + .item( + MenuItem::new("Set active") + .icon(&icons::CHECK) + .disabled(s.lib.game == Some(id)) + .on_select(move |s: &mut App| { + s.ctx = None; + s.switch_game(id); + }), + ) + .item( + MenuItem::new("Manage mods") + .icon(&icons::LAYERS) + .on_select(move |s: &mut App| { + s.ctx = None; + s.switch_game(id); + s.screen = Screen::Mods; + }), + ) + .separator() + .item(copy_item("Copy install path", path)) + .build(&look.k, layer) +} + +/// An item that copies `text` to the clipboard. +fn copy_item(label: &str, text: String) -> MenuItem { + MenuItem::new(label) + .icon(&icons::COPY) + .on_select_tx(move |s: &mut App, tx| { + s.ctx = None; + tx.copy(text.clone()); + }) +} diff --git a/crates/modrix-gui/src/ui/mod.rs b/crates/modrix-gui/src/ui/mod.rs new file mode 100644 index 0000000..47190c1 --- /dev/null +++ b/crates/modrix-gui/src/ui/mod.rs @@ -0,0 +1,128 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! The view: the game's art as a baked backdrop, a sidebar, a top bar, and +//! one screen at a time in glass panels over it. + +mod conflicts; +mod dashboard; +mod dialogs; +mod downloads; +mod games; +mod load_order; +mod menus; +mod mods; +pub mod parts; +mod settings; +mod shell; +mod store; +mod wizard; + +use rune::{Cx, El, ScrollSpec, SurfaceFit, col, el, row}; + +use crate::look::{Look, space}; +use crate::state::{App, Screen}; + +/// The whole window. +pub fn view(s: &App, cx: &mut Cx) -> El { + let dark = parts::is_dark(s, cx.system_dark()); + let swatches = s + .game_art() + .map(|a| a.swatches.as_slice()) + .unwrap_or_default(); + let look = Look::new(dark, swatches); + let mut layer: Vec = Vec::new(); + let body = row() + .key("body") + .w_full() + .h_full() + .child(shell::sidebar(s, &look, &mut layer)) + .child(main_column(s, &look, &mut layer)); + let window = el() + .key("window") + .w_full() + .h_full() + .fill(look.base) + .children(backdrop(s, &look)) + .child(body) + .children(shell::drop_overlay(s, &look)) + .on_drop_hover(|s: &mut App, on, _| s.drop_hover = on) + .on_drop_files(|s: &mut App, paths, _| { + s.drop_hover = false; + s.install_files(paths.to_vec()); + }); + dialogs::build(s, &look, &mut layer); + layer.push(shell::toasts(s, &look)); + rune_kit::root(window, layer) +} + +/// The art behind the top of the window: one image baked from the hero, +/// its soft wash, the accent glow and the fade (see `bake`). It keeps the +/// bake's aspect, so it scales with the window and is never squished, and it +/// ends in the base colour the window is filled with. +fn backdrop(s: &App, look: &Look) -> Option { + // Work screens keep the art quieter so tables and text stay readable. + let calm = s.screen != Screen::Dashboard; + let band = s.game_art()?.band(look.dark, calm)?; + Some( + el().key("backdrop") + .absolute(0.0, 0.0) + .w_full() + .aspect_ratio(crate::bake::RATIO) + .a11y_hidden() + .pixels_fit(band, SurfaceFit::Fill), + ) +} + +fn main_column(s: &App, look: &Look, layer: &mut Vec) -> El { + let content = match s.screen { + Screen::Dashboard => dashboard::view(s, look, layer), + Screen::Mods => mods::view(s, look, layer), + Screen::LoadOrder => load_order::view(s, look), + Screen::Conflicts => conflicts::view(s, look, layer), + Screen::Downloads => downloads::view(s, look), + Screen::Store => store::view(s, look), + Screen::Games => games::view(s, look, layer), + Screen::Settings => settings::view(s, look), + }; + // The Mods and Load order screens scroll their own lists. + let scrolls_itself = matches!(s.screen, Screen::Mods | Screen::LoadOrder); + let page = col() + .key(screen_key(s.screen)) + .w_full() + .px(space::XL) + .pt(6.0) + .pb(space::XL) + .gap(space::LG) + .child(content); + let page = if scrolls_itself { + page.grow(1.0).min_h(0.0) + } else { + col() + .key("page-scroll") + .w_full() + .grow(1.0) + .min_h(0.0) + .scroll(ScrollSpec::default()) + .clip_fade(0.0, 12.0, 0.0, 24.0) + .child(page) + }; + col() + .key("main") + .grow(1.0) + .h_full() + .min_w(0.0) + .child(shell::topbar(s, look, layer)) + .child(page) +} + +fn screen_key(screen: Screen) -> &'static str { + match screen { + Screen::Dashboard => "screen-overview", + Screen::Mods => "screen-mods", + Screen::LoadOrder => "screen-order", + Screen::Conflicts => "screen-conflicts", + Screen::Downloads => "screen-downloads", + Screen::Store => "screen-store", + Screen::Games => "screen-games", + Screen::Settings => "screen-settings", + } +} diff --git a/crates/modrix-gui/src/ui/mods.rs b/crates/modrix-gui/src/ui/mods.rs new file mode 100644 index 0000000..338c081 --- /dev/null +++ b/crates/modrix-gui/src/ui/mods.rs @@ -0,0 +1,421 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! The mod library: search, add, a sortable table with switches, and an +//! action bar for the selection. + +use rune::{El, FileDialogOptions, Tx, col, el, row, text}; +use rune_kit::{Button, ButtonVariant, Switch, TextInput}; + +use crate::icons; +use crate::look::{Look, space, ty}; +use crate::state::{App, Pane, SortKey}; +use crate::ui::parts::{self, glyph}; + +/// Row height in the table. +const ROW_H: f32 = 52.0; + +/// Ask for archives to install. +pub fn pick_archives(tx: &mut Tx) { + let options = FileDialogOptions { + title: "Install mods".to_owned(), + ..FileDialogOptions::default() + } + .filter("Mod archives", &["zip", "7z", "rar", "tar", "gz", "xz"]); + tx.open_files(options, |s: &mut App, picked, _| match picked { + Ok(Some(paths)) => s.install_files(paths), + Ok(None) => {} + Err(error) => s.note(crate::state::Tone::Error, error.to_string()), + }); +} + +/// The Mods screen. +pub fn view(s: &App, look: &Look, layer: &mut Vec) -> El { + if s.lib.mods.is_empty() { + return parts::panel(look, "mods-empty").child(parts::empty( + look, + &icons::LAYERS, + "No mods yet", + "Drop archives anywhere on this window, use Add mods, or click a mod manager download on Nexus with the browser extension.", + Some(add_button(look)), + )); + } + let selected = s.mod_sel.items.len(); + col() + .w_full() + .grow(1.0) + .min_h(0.0) + .gap(space::MD) + .child(toolbar(s, look)) + .children((selected > 0).then(|| action_bar(s, look, selected))) + .child(table(s, look, layer)) +} + +fn add_button(look: &Look) -> El { + Button::new("Add mods") + .icon(&icons::PLUS) + .variant(ButtonVariant::Submit) + .on_press_tx(|_: &mut App, tx| pick_archives(tx)) + .build(&look.k) +} + +fn toolbar(s: &App, look: &Look) -> El { + let disabled = s.lib.mods.iter().any(|m| !s.lib.enabled.contains(&m.id)); + row() + .w_full() + .gap(space::SM) + .center_y() + .child( + TextInput::new(&s.form.search) + .placeholder("Search mods") + .leading_icon(&icons::SEARCH) + .clear_button() + .width(Some(320.0)) + .on_edit(|s: &mut App| &mut s.form.search) + .on_change(|s: &mut App, _| s.mod_sel.clear()) + .build(&look.k), + ) + .child(el().grow(1.0)) + .children(disabled.then(|| { + Button::new("Enable all") + .icon(&icons::CHECK) + .variant(ButtonVariant::Ghost) + .on_press(|s: &mut App| s.enable_all()) + .build(&look.k) + })) + .child(add_button(look)) +} + +fn action_bar(s: &App, look: &Look, selected: usize) -> El { + let one = s + .selected_mod_ids() + .first() + .copied() + .filter(|_| selected == 1); + let configurable = one + .and_then(|id| s.lib.mods.iter().find(|m| m.id == id)) + .is_some_and(|m| m.install_state.starts_with("fomod")); + row() + .key("action-bar") + .w_full() + .h(50.0) + .px(16.0) + .gap(space::SM) + .center_y() + .radius(14.0) + .fill(look.accent_soft) + .border(1.0, look.accent.alpha(0.3)) + .transition(rune::Transition::opacity()) + .child( + text(format!("{selected} selected")) + .font(ty::BODY_STRONG) + .color(look.text()), + ) + .child(el().grow(1.0)) + .child(ghost(look, "Enable", &icons::CHECK, |s| { + let ids = s.selected_mod_ids(); + s.set_many_enabled(ids, true); + })) + .child(ghost(look, "Disable", &icons::CLOSE, |s| { + let ids = s.selected_mod_ids(); + s.set_many_enabled(ids, false); + })) + .children(configurable.then(|| { + ghost(look, "Options", &icons::SLIDERS, move |s| { + if let Some(id) = one { + s.configure(id); + } + }) + })) + .child(ghost( + look, + "Reinstall", + &icons::REFRESH, + App::reinstall_selected, + )) + .child( + Button::new("Delete") + .icon(&icons::TRASH) + .variant(ButtonVariant::Danger) + .on_press(|s: &mut App| s.confirm_delete = true) + .build(&look.k), + ) +} + +fn ghost(look: &Look, label: &str, i: &'static rune::Icon, f: impl Fn(&mut App) + 'static) -> El { + Button::new(label) + .icon(i) + .variant(ButtonVariant::Ghost) + .on_press(f) + .build(&look.k) +} + +fn table(s: &App, look: &Look, layer: &mut Vec) -> El { + let visible = s.visible_mods().len(); + let body_look = look.clone(); + let rows = col() + .key("mod-rows") + .w_full() + .virtual_rows( + visible, + ROW_H, + |s: &App, i| { + let id = s + .visible_mods() + .get(i) + .and_then(|m| s.lib.mods.get(*m)) + .map_or(0, |m| m.id.get()); + format!("mod-{id}").into() + }, + move |s: &App, i| mod_row(s, &body_look, i), + ) + .growth(rune::GrowthSpec::default()) + .virtual_rows_version(( + s.mod_sort.0 as u8, + s.mod_sort.1, + s.form.search.text.as_str(), + s.mods_narrow, + )); + let list = col() + .key("mod-scroll") + .w_full() + .grow(1.0) + .min_h(0.0) + .scroll(rune::ScrollSpec::default()) + .child(rows) + .child(el().h(10.0)); + let footer = (visible == 0).then(|| { + col().w_full().py(30.0).center().child( + text("No mods match the search") + .font(ty::BODY) + .color(look.muted()), + ) + }); + let panel = parts::panel(look, "mods-table") + .grow(1.0) + .min_h(0.0) + .on_layout(|s: &mut App, [_, _, w, _]| s.mods_narrow = narrow_level(w)) + .child(header(s, look)) + .child(parts::hair(look)) + .children(footer) + .child(list) + .child(parts::hair(look)) + .child(summary(s, look)); + super::menus::mods(s, look, panel, layer) +} + +/// The line under the table: what the library holds. +fn summary(s: &App, look: &Look) -> El { + let mods = s.lib.mods.len(); + let enabled = s + .lib + .mods + .iter() + .filter(|m| s.lib.enabled.contains(&m.id)) + .count(); + let plugins: usize = s + .lib + .plugin_counts + .values() + .copied() + .fold(0, usize::saturating_add); + let assets = s + .lib + .mods + .iter() + .filter(|m| s.lib.plugin_counts.get(&m.id).copied().unwrap_or(0) == 0) + .count(); + let mut parts = vec![ + count(mods, "mod", "mods"), + format!("{enabled} enabled"), + count(plugins, "plugin", "plugins"), + format!("{assets} asset-only"), + ]; + if !s.lib.external.is_empty() { + parts.push(format!("{} external (not managed)", s.lib.external.len())); + } + row() + .key("mods-summary") + .w_full() + .px(18.0) + .py(10.0) + .child(text(parts.join(", ")).font(ty::SMALL).color(look.muted())) +} + +fn count(n: usize, one: &str, many: &str) -> String { + format!("{n} {}", if n == 1 { one } else { many }) +} + +/// Table widths below which a column is dropped, Source first. +const SOURCE_MIN_W: f32 = 820.0; +const INSTALLED_MIN_W: f32 = 680.0; + +/// How many columns a table `w` points wide drops. +fn narrow_level(w: f32) -> u8 { + u8::from(w < INSTALLED_MIN_W).saturating_add(u8::from(w < SOURCE_MIN_W)) +} + +fn header(s: &App, look: &Look) -> El { + let narrow = s.mods_narrow; + row() + .key("mods-head") + .w_full() + .h(40.0) + .px(18.0) + .gap(space::MD) + .center_y() + .child(sort_cell(s, look, "Name", SortKey::Name).grow(1.0)) + .child(sort_cell(s, look, "Version", SortKey::Version).w(110.0)) + .children((narrow < 1).then(|| sort_cell(s, look, "Source", SortKey::Source).w(90.0))) + .children( + (narrow < 2).then(|| sort_cell(s, look, "Installed", SortKey::Installed).w(110.0)), + ) + .child(sort_cell(s, look, "On", SortKey::Enabled).w(54.0)) +} + +fn sort_cell(s: &App, look: &Look, label: &str, key: SortKey) -> El { + let (current, ascending) = s.mod_sort; + let on = current == key; + let arrow = on.then(|| { + glyph( + if ascending { + &icons::ARROW_UP + } else { + &icons::ARROW_DOWN + }, + 12.0, + look.accent, + ) + }); + row() + .key(format!("sort-{label}")) + .gap(5.0) + .center_y() + .role("button") + .label(format!("Sort by {label}")) + .on_press(move |s: &mut App| s.sort_by(key)) + .child(text(label.to_uppercase()).font(ty::LABEL).color(if on { + look.text() + } else { + look.faint() + })) + .children(arrow) +} + +fn mod_row(s: &App, look: &Look, i: usize) -> El { + let Some(m) = s.visible_mods().get(i).and_then(|m| s.lib.mods.get(*m)) else { + return el(); + }; + let id = m.id; + let on = s.lib.enabled.contains(&id); + let selected = s.mod_sel.items.contains(&i); + let plugins = s.lib.plugin_counts.get(&id).copied().unwrap_or(0); + let mut name = row().gap(8.0).center_y().min_w(0.0).child( + text(m.name.clone()) + .font(ty::BODY_STRONG) + .color(if on { look.text() } else { look.muted() }) + .truncate(), + ); + if m.install_state.starts_with("fomod") { + name = name.child(parts::chip("Options", look.accent)); + } + if plugins > 0 { + name = name.child(parts::tag( + look, + if plugins == 1 { + "1 plugin".to_owned() + } else { + format!("{plugins} plugins") + }, + )); + } + row() + .key(format!("mod-row-{}", id.get())) + .w_full() + .h(ROW_H) + .px(18.0) + .gap(space::MD) + .center_y() + .fill(if selected { + look.accent_soft + } else { + rune::Color::TRANSPARENT + }) + .hover_fill(if selected { + look.accent_soft + } else { + look.hover() + }) + .border_sides([0.0, 0.0, 1.0, 0.0], look.edge) + .role("row") + .checked(selected) + .label(m.name.clone()) + .on_press_tx(move |s: &mut App, tx| s.row_click(Pane::Mods, i, tx.mods())) + .on_double_press(move |s: &mut App| s.configure(id)) + .on_secondary_press(move |s: &mut App, p, _| s.open_mod_menu(i, p)) + .children(mod_cells(look, m, name, on, s.mods_narrow)) +} + +fn mod_cells(look: &Look, m: &modrix_core::Mod, name: El, on: bool, narrow: u8) -> Vec { + let id = m.id; + let installed = m.created_at.map_or_else(|| "-".to_owned(), date); + let source = (narrow < 1).then(|| el().w(90.0).child(parts::tag(look, m.source.clone()))); + let installed = + (narrow < 2).then(|| text(installed).font(ty::SMALL).color(look.faint()).w(110.0)); + let mut cells = vec![ + name.grow(1.0).w(0.0), + text(m.version.clone().unwrap_or_else(|| "-".to_owned())) + .font(ty::MONO) + .color(look.muted()) + .truncate() + .w(110.0), + ]; + cells.extend(source); + cells.extend(installed); + cells.push( + el().w(54.0).child( + Switch::new(on) + .hide_label() + .label(format!("Enable {}", m.name)) + .on_toggle(move |s: &mut App| s.set_mod_enabled(id, !on)) + .build(&look.k), + ), + ); + cells +} + +/// A unix time as `2026-11-25`. +#[must_use] +pub fn date(unix: i64) -> String { + let days = unix.div_euclid(86_400); + let (y, m, d) = civil(days); + format!("{y:04}-{m:02}-{d:02}") +} + +/// Days since 1970-01-01 to a civil date (Howard Hinnant's algorithm). +#[expect( + clippy::arithmetic_side_effects, + reason = "the day count is clamped to +-100 million years, far inside i64" +)] +fn civil(days: i64) -> (i64, i64, i64) { + let z = days.clamp(-36_500_000_000, 36_500_000_000) + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = yoe + era * 400 + i64::from(m <= 2); + (y, m, d) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn formats_dates() { + assert_eq!(date(0), "1970-01-01"); + assert_eq!(date(1_764_028_800), "2025-11-25"); + assert_eq!(date(951_782_400), "2000-02-29"); + } +} diff --git a/crates/modrix-gui/src/ui/parts.rs b/crates/modrix-gui/src/ui/parts.rs new file mode 100644 index 0000000..d58b8b9 --- /dev/null +++ b/crates/modrix-gui/src/ui/parts.rs @@ -0,0 +1,193 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Small building blocks the screens share: glass panels, headings, stat +//! tiles, chips, empty states. + +use rune::{Color, El, Icon, col, el, icon, row, text}; + +use crate::look::{Look, space, ty}; +use crate::state::App; + +/// A translucent panel over the backdrop. No live blur: a backdrop blur +/// copies and blurs the window behind every panel on every frame, which is +/// what made the window lag. The glass is dense enough to read without it. +#[must_use] +pub fn panel(look: &Look, key: &str) -> El { + col() + .key(key) + .w_full() + .radius(space::PANEL) + .fill(look.glass) + .border(1.0, look.edge) + .clip_rounded(space::PANEL) +} + +/// A panel with a heading row (title, optional trailing control). +#[must_use] +pub fn section(look: &Look, key: &str, title: &str, trailing: Option, body: El) -> El { + let head = row() + .w_full() + .px(18.0) + .pt(16.0) + .pb(10.0) + .gap(space::SM) + .center_y() + .child(text(title).font(ty::HEADING).color(look.text())) + .child(el().grow(1.0)) + .children(trailing); + panel(look, key).child(head).child(body) +} + +/// The page title block. +#[must_use] +pub fn page_title(look: &Look, title: &str, subtitle: &str) -> El { + col() + .gap(3.0) + .child(text(title).font(ty::TITLE).color(look.text())) + .child(text(subtitle).font(ty::BODY).color(look.muted()).truncate()) +} + +/// An icon tinted with a colour. +#[must_use] +pub fn glyph(i: &'static Icon, size: f32, color: Color) -> El { + icon(i, size).color(color) +} + +/// A rounded square holding an icon (stat tiles, list leads). +#[must_use] +pub fn icon_tile(i: &'static Icon, tint: Color, size: f32) -> El { + el().size(size, size) + .radius(size * 0.3) + .fill(tint.alpha(0.16)) + .center() + .child(glyph(i, size * 0.5, tint)) +} + +/// A stat card's narrowest width; a row of them wraps below this. +const STAT_MIN_W: f32 = 210.0; + +/// A number with its caption, as a card. Put cards in a `flex_wrap` row. +#[must_use] +pub fn stat( + look: &Look, + key: &str, + (i, tint): (&'static Icon, Color), + value: String, + caption: &str, +) -> El { + panel(look, key).grow(1.0).w(0.0).min_w(STAT_MIN_W).child( + row() + .padding(16.0) + .gap(14.0) + .center_y() + .child(icon_tile(i, tint, 40.0)) + .child( + col() + .gap(1.0) + .child(text(value).font(ty::STAT).color(look.text())) + .child(text(caption).font(ty::SMALL).color(look.muted())), + ), + ) +} + +/// A small coloured pill. +#[must_use] +pub fn chip(label: impl Into, color: Color) -> El { + row() + .h(20.0) + .px(8.0) + .radius(10.0) + .fill(color.alpha(0.15)) + .center() + .child(text(label).font(ty::SMALL_STRONG).color(color)) +} + +/// A neutral pill. +#[must_use] +pub fn tag(look: &Look, label: impl Into) -> El { + row() + .h(20.0) + .px(8.0) + .radius(6.0) + .fill(look.hover()) + .border(1.0, look.edge) + .center() + .child(text(label).font(ty::SMALL).color(look.muted())) +} + +/// A count badge on the accent. +#[must_use] +pub fn count(look: &Look, n: usize, color: Color) -> El { + row() + .h(18.0) + .min_w(18.0) + .px(5.0) + .radius(9.0) + .fill(color) + .center() + .child( + text(n.to_string()) + .font(ty::SMALL_STRONG) + .color(look.on_accent), + ) +} + +/// A centred placeholder for an empty list. +#[must_use] +pub fn empty(look: &Look, i: &'static Icon, title: &str, body: &str, action: Option) -> El { + col() + .w_full() + .py(48.0) + .px(24.0) + .gap(10.0) + .center() + .child(icon_tile(i, look.accent, 52.0)) + .child(text(title).font(ty::HEADING).color(look.text())) + .child( + text(body) + .font(ty::BODY) + .color(look.muted()) + .wrap() + .max_w(420.0) + .align(rune::Align::Center), + ) + .children(action) +} + +/// A one-line key/value row (settings, details). +#[must_use] +pub fn kv(look: &Look, key: &str, value: El) -> El { + row() + .w_full() + .min_h(44.0) + .px(18.0) + .gap(space::MD) + .center_y() + .child(text(key).font(ty::BODY).color(look.muted()).w(180.0)) + .child(value.grow(1.0)) +} + +/// A divider line inside a panel. +#[must_use] +pub fn hair(look: &Look) -> El { + el().w_full().h(1.0).fill(look.edge) +} + +/// The tone colour of a note. +#[must_use] +pub fn tone_color(look: &Look, tone: crate::state::Tone) -> Color { + match tone { + crate::state::Tone::Ok => look.good, + crate::state::Tone::Error => look.bad, + crate::state::Tone::Info => look.accent, + } +} + +/// Whether the window should render dark. +#[must_use] +pub fn is_dark(s: &App, system_dark: bool) -> bool { + match s.appearance { + crate::prefs::Appearance::System => system_dark, + crate::prefs::Appearance::Dark => true, + crate::prefs::Appearance::Light => false, + } +} diff --git a/crates/modrix-gui/src/ui/settings.rs b/crates/modrix-gui/src/ui/settings.rs new file mode 100644 index 0000000..3912859 --- /dev/null +++ b/crates/modrix-gui/src/ui/settings.rs @@ -0,0 +1,287 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Settings: appearance, profiles, where things live, installed game +//! support, updates, about. + +use rune::{El, col, row, text}; +use rune_kit::{Button, ButtonVariant, IconButton, IconButtonVariant, SegmentedControl, TextInput}; + +use crate::icons; +use crate::look::{Look, space, ty}; +use crate::prefs::Appearance; +use crate::state::{App, Tone, UpdateState}; +use crate::ui::parts; + +/// The Settings screen. +pub fn view(s: &App, look: &Look) -> El { + col() + .w_full() + .gap(space::LG) + .child(appearance(s, look)) + .children(s.lib.game.is_some().then(|| profiles(s, look))) + .child(paths(s, look)) + .child(plugins(s, look)) + .child(updates(s, look)) +} + +fn appearance(s: &App, look: &Look) -> El { + let labels: Vec<&str> = Appearance::ALL.iter().map(|a| a.label()).collect(); + let current = Appearance::ALL.iter().position(|a| *a == s.appearance); + let picker = SegmentedControl::new(&labels, current) + .on_pick(|s: &mut App, i, _| { + let Some(choice) = Appearance::ALL.get(i).copied() else { + return; + }; + s.appearance = choice; + if let Some(paths) = &s.paths + && let Err(error) = crate::prefs::save(paths, choice) + { + s.note( + Tone::Error, + format!("Could not save the appearance: {error}"), + ); + } + }) + .build(&look.k); + parts::section( + look, + "appearance", + "Appearance", + None, + col() + .w_full() + .pb(10.0) + .child(parts::kv(look, "Theme", row().child(picker))) + .child(parts::kv( + look, + "Accent", + text("Taken from the selected game's artwork") + .font(ty::BODY) + .color(look.muted()), + )), + ) +} + +fn profiles(s: &App, look: &Look) -> El { + let list = s.lib.profiles.iter().map(|p| { + let active = s.lib.profile.as_ref().is_some_and(|a| a.id == p.id); + let name = p.name.clone(); + row() + .key(format!("profile-{}", p.id)) + .w_full() + .min_h(44.0) + .px(18.0) + .gap(space::MD) + .center_y() + .child( + text(p.name.clone()) + .font(ty::BODY) + .color(look.text()) + .grow(1.0), + ) + .child(if active { + parts::chip("Active", look.accent) + } else { + Button::new("Use") + .variant(ButtonVariant::Ghost) + .on_press(move |s: &mut App| s.pick_profile(&name)) + .build(&look.k) + }) + }); + let create = row() + .w_full() + .px(18.0) + .py(10.0) + .gap(space::SM) + .child( + TextInput::new(&s.form.profile_name) + .placeholder("New profile name") + .width(Some(300.0)) + .on_edit(|s: &mut App| &mut s.form.profile_name) + .on_submit(|s: &mut App, _| s.create_profile()) + .build(&look.k), + ) + .child( + Button::new("Create") + .icon(&icons::PLUS) + .variant(ButtonVariant::Neutral) + .on_press(|s: &mut App| s.create_profile()) + .build(&look.k), + ); + parts::section( + look, + "profiles", + "Profiles", + None, + col().w_full().pb(6.0).children(list).child(create), + ) +} + +fn path_row(look: &Look, label: &str, path: Option) -> El { + let shown = path + .as_ref() + .map_or_else(|| "Not set".to_owned(), |p| p.display().to_string()); + let reveal = path.map(|p| { + IconButton::new(&icons::FOLDER) + .variant(IconButtonVariant::GhostMuted) + .label("Show in file manager") + .on_press_tx(move |s: &mut App, tx| { + if let Err(error) = tx.reveal_path(&p) { + s.note(Tone::Error, error.to_string()); + } + }) + .build(&look.k) + }); + parts::kv( + look, + label, + row() + .gap(space::SM) + .center_y() + .child( + text(shown) + .font(ty::MONO) + .color(look.text()) + .truncate_head() + .grow(1.0) + .w(0.0), + ) + .children(reveal), + ) +} + +fn paths(s: &App, look: &Look) -> El { + let p = s.paths.as_ref(); + let body = col() + .w_full() + .pb(10.0) + .child(path_row( + look, + "Data", + p.map(|p| p.data_dir().to_path_buf()), + )) + .child(path_row( + look, + "Config", + p.map(|p| p.config_dir().to_path_buf()), + )) + .child(path_row( + look, + "Cache", + p.map(|p| p.cache_dir().to_path_buf()), + )) + .child(path_row( + look, + "Staging", + p.map(modrix_core::Paths::staging_root), + )); + parts::section(look, "paths", "Where things live", None, body) +} + +fn plugins(s: &App, look: &Look) -> El { + let rows = s.installed_plugins.iter().map(|p| { + let id = p.id.clone(); + row() + .key(format!("plugin-{}", p.id)) + .w_full() + .min_h(44.0) + .px(18.0) + .gap(space::MD) + .center_y() + .child( + text(p.name.clone()) + .font(ty::BODY) + .color(look.text()) + .grow(1.0), + ) + .child(parts::tag(look, p.version.clone())) + .child( + IconButton::new(&icons::TRASH) + .variant(IconButtonVariant::GhostMuted) + .label(format!("Remove {}", p.name)) + .on_press(move |s: &mut App| s.uninstall_plugin(&id)) + .build(&look.k), + ) + }); + let body = if s.installed_plugins.is_empty() { + col().w_full().px(18.0).pb(16.0).child( + text("Built-in games need nothing extra. Support installed from the community registry shows up here.") + .font(ty::BODY) + .color(look.muted()) + .wrap(), + ) + } else { + col().w_full().pb(6.0).children(rows) + }; + parts::section( + look, + "installed-plugins", + "Game support", + Some( + Button::new("Remove unused") + .variant(ButtonVariant::GhostMuted) + .on_press(|s: &mut App| s.gc_plugins()) + .build(&look.k), + ), + body, + ) +} + +fn updates(s: &App, look: &Look) -> El { + let (line, action) = match &s.update { + UpdateState::Idle => ( + "Modrix is up to date".to_owned(), + Button::new("Check now") + .icon(&icons::REFRESH) + .variant(ButtonVariant::Neutral) + .on_press(|s: &mut App| s.check_updates()) + .build(&look.k), + ), + UpdateState::Checking => ( + "Checking for updates".to_owned(), + Button::new("Checking") + .variant(ButtonVariant::Loading) + .build(&look.k), + ), + UpdateState::Available(info) => ( + format!("Modrix {} is available", info.version), + Button::new("Install") + .icon(&icons::UPDATE) + .variant(ButtonVariant::Submit) + .on_press(|s: &mut App| s.start_update()) + .build(&look.k), + ), + UpdateState::Installing(info) => ( + format!("Installing {}", info.version), + Button::new("Installing") + .variant(ButtonVariant::Loading) + .build(&look.k), + ), + }; + let body = col() + .w_full() + .pb(10.0) + .child(parts::kv( + look, + "Version", + text(env!("CARGO_PKG_VERSION")) + .font(ty::MONO) + .color(look.text()), + )) + .child(parts::kv( + look, + "Updates", + row() + .gap(space::MD) + .center_y() + .child(text(line).font(ty::BODY).color(look.text()).grow(1.0)) + .child(action), + )) + .child(parts::kv( + look, + "License", + text("GPL-2.0-only. Free software: share and change it.") + .font(ty::BODY) + .color(look.muted()), + )); + parts::section(look, "about", "About Modrix", None, body) +} diff --git a/crates/modrix-gui/src/ui/shell.rs b/crates/modrix-gui/src/ui/shell.rs new file mode 100644 index 0000000..abbcbe5 --- /dev/null +++ b/crates/modrix-gui/src/ui/shell.rs @@ -0,0 +1,730 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! The frame around every screen: the sidebar (wordmark, game switcher, +//! navigation, service status), the top bar (title, progress, profile, +//! Deploy, notifications), the toasts and the drop target. + +use rune::{El, Spring, SurfaceFit, col, el, row, text}; +use rune_kit::{ + Button, ButtonVariant, IconButton, IconButtonVariant, Menu, MenuItem, Placement, Popover, + Select, Spinner, +}; + +use crate::icons; +use crate::look::{Look, space, ty}; +use crate::state::{App, Popup, Screen, TOAST_TTL, UpdateState}; +use crate::ui::parts::{self, glyph}; + +/// Height of one navigation row, gaps included. +const NAV_STEP: f32 = 40.0; + +/// The sidebar cover banner's height: the 2:3 cover is cropped at the +/// bottom (never squished) and the banner gives way first when the window +/// is short. +const BANNER_H: f32 = 300.0; +const BANNER_MIN_H: f32 = 96.0; + +/// The left column. +pub fn sidebar(s: &App, look: &Look, layer: &mut Vec) -> El { + let cover = s.game_art().and_then(|a| a.cover.as_ref()); + let head = match cover { + Some(px) => banner(look, px), + None => row().w_full().px(20.0).pt(18.0).child(wordmark(look)), + }; + let body = col() + .w_full() + .grow(1.0) + .px(14.0) + .pt(if cover.is_some() { 4.0 } else { 18.0 }) + .pb(14.0) + .gap(18.0) + .child(game_switcher(s, look, layer)) + .child(nav(s, look)) + .child(el().grow(1.0)) + .child(footer(s, look)); + col() + .key("sidebar") + .w(space::SIDEBAR) + .h_full() + .clip_rounded(0.0) + .fill(look.glass) + .border(1.0, look.edge) + .child(head) + .child(body) +} + +/// The active game's cover across the full sidebar width, the wordmark +/// over its top. The whole banner is a drag region. +fn banner(look: &Look, px: &rune::Pixels) -> El { + let fade = el() + .pin(Some(0.0), None, Some(0.0), Some(0.0)) + .h(BANNER_H * 0.4) + .gradient(rune::Color::TRANSPARENT, look.glass); + let shade = el() + .pin(Some(0.0), Some(0.0), Some(0.0), None) + .h(72.0) + .gradient(look.base.alpha(0.62), rune::Color::TRANSPARENT); + col() + .key("sidebar-banner") + .w_full() + .h(BANNER_H) + .min_h(BANNER_MIN_H) + .shrink() + .clip_rounded(0.0) + .pixels_fit(px, SurfaceFit::Fill) + .surface_anchor(rune::Align::Center, rune::Align::Start) + .window_drag() + .a11y_hidden() + .child(shade) + .child(fade) + .child(row().w_full().px(20.0).pt(18.0).child(wordmark(look))) +} + +fn wordmark(look: &Look) -> El { + row() + .key("wordmark") + .w_full() + .h(28.0) + .center_y() + .window_drag() + .child(text("MOD").font(ty::MARK).color(look.accent)) + .child(text("RIX").font(ty::MARK).color(look.text())) + .child(el().grow(1.0)) + .child(parts::tag(look, concat!("v", env!("CARGO_PKG_VERSION")))) +} + +fn switcher_trigger(s: &App, look: &Look, open: bool) -> El { + let game = s.game(); + let cover = s.game_art().and_then(|a| a.cover.as_ref()); + let thumb = match cover { + Some(px) => el() + .size(38.0, 54.0) + .radius(7.0) + .clip_rounded(7.0) + .pixels_fit(px, SurfaceFit::Fill), + None => parts::icon_tile(&icons::GAMEPAD, look.accent, 38.0), + }; + let (name, detail) = match game { + Some(g) => ( + g.name.clone(), + s.lib + .profile + .as_ref() + .map_or_else(|| g.store.clone(), |p| format!("Profile: {}", p.name)), + ), + None => ("No game yet".to_owned(), "Add one to start".to_owned()), + }; + row() + .key("game-switcher") + .w_full() + .padding(8.0) + .gap(10.0) + .center_y() + .radius(12.0) + .fill(if open { look.pressed() } else { look.hover() }) + .border(1.0, look.edge) + .hover_fill(look.pressed()) + .role("button") + .label("Switch game") + .on_press(|s: &mut App| toggle(s, Popup::GameMenu)) + .child(thumb) + .child( + col() + .grow(1.0) + .min_w(0.0) + .gap(2.0) + .child( + text(name) + .font(ty::BODY_STRONG) + .color(look.text()) + .truncate(), + ) + .child(text(detail).font(ty::SMALL).color(look.muted()).truncate()), + ) + .child(glyph(&icons::CHEVRON_UP_DOWN, 16.0, look.faint())) +} + +fn game_switcher(s: &App, look: &Look, layer: &mut Vec) -> El { + let open = s.popup == Some(Popup::GameMenu); + let trigger = switcher_trigger(s, look, open); + let mut menu = Menu::new("game-menu").trigger(trigger).min_width(220.0); + for g in &s.lib.games { + let id = g.id; + menu = menu.item( + MenuItem::new(g.name.clone()) + .icon(&icons::GAMEPAD) + .checked(Some(id) == s.lib.game) + .on_select(move |s: &mut App| s.switch_game(id)), + ); + } + menu.separator() + .item( + MenuItem::new("Add a game") + .icon(&icons::PLUS) + .on_select(|s: &mut App| { + s.popup = None; + s.screen = Screen::Games; + }), + ) + .open(open) + .on_close(|s: &mut App| s.popup = None) + .build(&look.k, layer) +} + +fn toggle(s: &mut App, popup: Popup) { + s.popup = if s.popup == Some(popup) { + None + } else { + Some(popup) + }; + if s.popup == Some(Popup::Notes) { + s.unread = 0; + } +} + +fn nav_badge(s: &App, screen: Screen) -> Option<(usize, bool)> { + match screen { + Screen::Mods => Some((s.lib.mods.len(), false)), + Screen::LoadOrder => Some((s.lib.plugins.len(), false)), + Screen::Conflicts => Some(( + s.unresolved_conflicts() + .saturating_add(s.blockers().count()), + true, + )), + Screen::Downloads => Some((s.active_downloads(), true)), + _ => None, + } +} + +fn nav_icon(screen: Screen) -> &'static rune::Icon { + match screen { + Screen::Dashboard => &icons::HOME, + Screen::Mods => &icons::LAYERS, + Screen::LoadOrder => &icons::ORDER, + Screen::Conflicts => &icons::CONFLICT, + Screen::Downloads => &icons::DOWNLOAD, + Screen::Store => &icons::PACKAGE, + Screen::Games => &icons::GAMEPAD, + Screen::Settings => &icons::SETTINGS, + } +} + +fn nav(s: &App, look: &Look) -> El { + let screens: Vec = Screen::ALL + .into_iter() + .filter(|x| s.screen_visible(*x)) + .collect(); + let at = screens.iter().position(|x| *x == s.screen).unwrap_or(0); + #[expect(clippy::cast_precision_loss, reason = "a handful of nav rows")] + let top = at as f32 * NAV_STEP; + let pill = el() + .key("nav-pill") + .absolute(0.0, top) + .w_full() + .h(NAV_STEP - 4.0) + .radius(10.0) + .fill(look.accent_soft) + .border(1.0, look.accent.alpha(0.22)) + .motion(Spring::new(0.38, 0.18)) + .child( + el().absolute(0.0, 9.0) + .size(3.0, 18.0) + .radius(2.0) + .fill(look.accent), + ); + let rows = screens.into_iter().map(|screen| nav_row(s, look, screen)); + el().key("nav") + .w_full() + .role("navigation") + .child(pill) + .child(col().w_full().gap(4.0).children(rows)) +} + +fn nav_row(s: &App, look: &Look, screen: Screen) -> El { + let on = s.screen == screen; + let ink = if on { look.text() } else { look.muted() }; + let badge = nav_badge(s, screen) + .filter(|(n, _)| *n > 0) + .map(|(n, loud)| { + if loud { + parts::count(look, n, look.accent) + } else { + text(n.to_string()).font(ty::SMALL).color(look.faint()) + } + }); + row() + .key(screen.label()) + .w_full() + .h(NAV_STEP - 4.0) + .px(12.0) + .gap(12.0) + .center_y() + .radius(10.0) + .hover_fill(if on { + rune::Color::TRANSPARENT + } else { + look.hover() + }) + .role("tab") + .checked(on) + .label(screen.label()) + .on_press(move |s: &mut App| { + s.screen = screen; + s.popup = None; + if screen == Screen::Store { + s.open_store(); + } + }) + .child(glyph( + nav_icon(screen), + 18.0, + if on { look.accent } else { look.faint() }, + )) + .child( + text(screen.label()) + .font(if on { ty::BODY_STRONG } else { ty::BODY }) + .color(ink) + .grow(1.0), + ) + .children(badge) +} + +fn footer(s: &App, look: &Look) -> El { + let (dot, line) = if let Some(error) = &s.boot_error { + (look.bad, format!("Engine failed: {error}")) + } else if !s.booted { + (look.warn, "Starting the engine".to_owned()) + } else if s.already_running { + ( + look.warn, + "Another Modrix owns browser downloads".to_owned(), + ) + } else if let Some(link) = &s.link { + (look.good, format!("Browser link on port {}", link.port)) + } else { + (look.faint(), "Browser link off".to_owned()) + }; + let update = match &s.update { + UpdateState::Available(info) => Some( + Button::new(format!("Update to {}", info.version)) + .icon(&icons::UPDATE) + .variant(ButtonVariant::Submit) + .expanded(true) + .on_press(|s: &mut App| s.start_update()) + .build(&look.k), + ), + UpdateState::Installing(_) => Some( + Button::new("Installing update") + .variant(ButtonVariant::Loading) + .expanded(true) + .build(&look.k), + ), + _ => None, + }; + col() + .key("sidebar-footer") + .w_full() + .gap(10.0) + .children(update) + .child( + row() + .px(8.0) + .gap(8.0) + .center_y() + .child( + el().size(7.0, 7.0) + .radius(4.0) + .fill(dot) + .shadow(0.0, 6.0, dot.alpha(0.6)), + ) + .child( + text(line) + .font(ty::SMALL) + .color(look.muted()) + .truncate() + .grow(1.0), + ), + ) +} + +/// The bar over the screen. +pub fn topbar(s: &App, look: &Look, layer: &mut Vec) -> El { + let (title, subtitle) = heading(s); + row() + .key("topbar") + .w_full() + .h(76.0) + .px(space::XL) + .gap(space::MD) + .center_y() + .window_drag() + .child( + parts::page_title(look, title, &subtitle) + .grow(1.0) + .min_w(0.0), + ) + .children(activity(s, look)) + .children(profile_picker(s, look, layer)) + .children(deploy_button(s, look, layer)) + .child(bell(s, look, layer)) +} + +fn heading(s: &App) -> (&'static str, String) { + let game = s + .game() + .map_or_else(|| "No game selected".to_owned(), |g| g.name.clone()); + let enabled = s.lib.enabled.len(); + match s.screen { + Screen::Dashboard => ("Overview", game), + Screen::Mods => ( + "Mods", + format!("{} installed, {enabled} enabled", s.lib.mods.len()), + ), + Screen::LoadOrder => ( + "Load order", + format!("{} plugins, later wins", s.lib.plugins.len()), + ), + Screen::Conflicts => ( + "Conflicts", + format!( + "{} pairs, {} unresolved", + s.lib.conflicts.len(), + s.unresolved_conflicts() + ), + ), + Screen::Downloads => ("Downloads", format!("{} active", s.active_downloads())), + Screen::Store => ( + "Mod store", + s.lib + .store + .as_ref() + .map_or_else(String::new, |d| d.base_url.clone()), + ), + Screen::Games => ("Games", format!("{} registered", s.lib.games.len())), + Screen::Settings => ( + "Settings", + "Appearance, paths, pairing and updates".to_owned(), + ), + } +} + +fn activity(s: &App, look: &Look) -> Option { + let message = + s.op.as_ref() + .map(|op| op.message.clone()) + .or_else(|| (s.busy > 0).then(|| "Working".to_owned()))?; + let progress = + s.op.as_ref() + .filter(|op| op.total > 0) + .map(|op| crate::fmt::fraction(op.done, Some(op.total))); + Some( + row() + .key("activity") + .h(34.0) + .px(12.0) + .gap(10.0) + .center_y() + .radius(17.0) + .fill(look.glass_strong) + .border(1.0, look.edge) + .max_w(320.0) + .child(Spinner::new().size(14.0).color(look.accent).build(&look.k)) + .child( + text(message) + .font(ty::SMALL_STRONG) + .color(look.text()) + .truncate(), + ) + .children(progress.map(|f| { + text(format!("{:.0}%", f * 100.0)) + .font(ty::MONO) + .color(look.muted()) + })), + ) +} + +fn profile_picker(s: &App, look: &Look, layer: &mut Vec) -> Option { + if s.lib.profiles.is_empty() { + return None; + } + let names: Vec<&str> = s.lib.profiles.iter().map(|p| p.name.as_str()).collect(); + let current = s.lib.profile.as_ref().map(|p| p.name.as_str()); + Some( + Select::new("profile", &names) + .current(current) + .open(s.popup == Some(Popup::ProfileMenu)) + .on_toggle(|s: &mut App| toggle(s, Popup::ProfileMenu)) + .on_close(|s: &mut App| s.popup = None) + .on_choose(|s: &mut App, name: &str, _| { + s.popup = None; + s.pick_profile(name); + }) + .width(170.0) + .build(&look.k, layer), + ) +} + +fn deploy_main(look: &Look, blocked: bool, busy: bool) -> El { + let ink = if blocked { + look.muted() + } else { + look.on_accent + }; + row() + .key("deploy") + .h(34.0) + .pl(14.0) + .pr(12.0) + .gap(8.0) + .center_y() + .fill(if blocked { look.hover() } else { look.accent }) + .hover_fill(if blocked { + look.pressed() + } else { + look.accent.mix(rune::Color::WHITE, 0.12) + }) + .role("button") + .label("Deploy") + .help(if blocked { + "Fix the blocking issues first" + } else { + "Link enabled mods into the game" + }) + .on_press(move |s: &mut App| { + if !blocked && !busy { + s.deploy(); + } + }) + .child(glyph(&icons::DEPLOY, 16.0, ink)) + .child(text("Deploy").font(ty::BODY_STRONG).color(ink)) +} + +fn deploy_split(look: &Look, blocked: bool, busy: bool) -> El { + let ink = if blocked { + look.muted() + } else { + look.on_accent + }; + let more = row() + .key("deploy-more") + .h(34.0) + .w(30.0) + .center() + .fill(if blocked { + look.hover() + } else { + look.accent.mix(rune::Color::BLACK, 0.12) + }) + .hover_fill(look.accent.mix(rune::Color::BLACK, 0.2)) + .role("button") + .label("More deploy actions") + .on_press(|s: &mut App| toggle(s, Popup::DeployMenu)) + .child(glyph(&icons::CHEVRON_DOWN, 14.0, ink)); + row() + .key("deploy-split") + .radius(10.0) + .clip_rounded(10.0) + .shadow( + 4.0, + 14.0, + look.accent.alpha(if blocked { 0.0 } else { 0.35 }), + ) + .child(deploy_main(look, blocked, busy)) + .child(el().w(1.0).h(34.0).fill(look.on_accent.alpha(0.2))) + .child(more) +} + +fn deploy_button(s: &App, look: &Look, layer: &mut Vec) -> Option { + s.lib.profile.as_ref()?; + let split = deploy_split(look, s.blockers().next().is_some(), s.busy > 0); + Some( + Menu::new("deploy-menu") + .trigger(split) + .placement(Placement::BottomEnd) + .min_width(200.0) + .item( + MenuItem::new("Verify files") + .icon(&icons::SHIELD) + .on_select(|s: &mut App| s.verify()), + ) + .item( + MenuItem::new("Auto-sort plugins") + .icon(&icons::SPARKLES) + .on_select(|s: &mut App| { + s.popup = None; + s.auto_sort(); + }), + ) + .separator() + .item( + MenuItem::new("Purge deployment") + .icon(&icons::ERASE) + .danger(true) + .on_select(|s: &mut App| s.purge()), + ) + .open(s.popup == Some(Popup::DeployMenu)) + .on_close(|s: &mut App| s.popup = None) + .build(&look.k, layer), + ) +} + +fn bell(s: &App, look: &Look, layer: &mut Vec) -> El { + let button = IconButton::new(&icons::BELL) + .variant(IconButtonVariant::Ghost) + .label("Notifications") + .on_press(|s: &mut App| toggle(s, Popup::Notes)) + .build(&look.k); + let trigger = el() + .key("bell") + .child(button) + .children((s.unread > 0).then(|| { + el().absolute(18.0, -2.0) + .child(parts::count(look, s.unread.min(99), look.bad)) + })); + Popover::new("notes") + .trigger(trigger) + .title("Notifications") + .child(notes_list(s, look)) + .placement(Placement::BottomEnd) + .open(s.popup == Some(Popup::Notes)) + .on_close(|s: &mut App| s.popup = None) + .build(&look.k, layer) +} + +fn notes_list(s: &App, look: &Look) -> El { + if s.notes.is_empty() { + return col() + .w(340.0) + .py(18.0) + .center() + .child(text("Nothing new").font(ty::BODY).color(look.muted())); + } + let rows = s.notes.iter().take(40).map(|n| { + row() + .key(format!("note-{}", n.id)) + .w_full() + .py(8.0) + .gap(10.0) + .child( + el().mt(5.0) + .size(7.0, 7.0) + .radius(4.0) + .fill(parts::tone_color(look, n.tone)), + ) + .child( + col() + .grow(1.0) + .min_w(0.0) + .gap(2.0) + .child( + text(n.text.clone()) + .font(ty::BODY) + .color(look.text()) + .wrap(), + ) + .child(text(ago(s.now - n.at)).font(ty::SMALL).color(look.faint())), + ) + }); + col() + .w(360.0) + .max_h(420.0) + .scroll(rune::ScrollSpec::default()) + .children(rows) + .child( + row().w_full().pt(6.0).justify_end().child( + Button::new("Clear all") + .variant(ButtonVariant::GhostMuted) + .on_press(|s: &mut App| { + s.notes.clear(); + s.unread = 0; + }) + .build(&look.k), + ), + ) +} + +/// "just now", "3 min ago". +#[must_use] +pub fn ago(seconds: f64) -> String { + if seconds < 45.0 { + "Just now".to_owned() + } else { + format!("{:.0} min ago", (seconds / 60.0).max(1.0)) + } +} + +/// Recent notes as toasts in the bottom right. +pub fn toasts(s: &App, look: &Look) -> El { + let fresh = s + .notes + .iter() + .filter(|n| s.now - n.at < TOAST_TTL) + .take(3) + .map(|n| { + let tint = parts::tone_color(look, n.tone); + let id = n.id; + row() + .key(format!("toast-{id}")) + .w(360.0) + .padding(14.0) + .gap(12.0) + .center_y() + .radius(14.0) + .fill(look.glass_strong) + .border(1.0, look.edge) + .shadow(10.0, 30.0, look.shadow()) + .transition(rune::Transition::opacity().combined(rune::Transition::scale(0.96))) + .child(el().size(4.0, 28.0).radius(2.0).fill(tint)) + .child( + text(n.text.clone()) + .font(ty::BODY) + .color(look.text()) + .wrap() + .grow(1.0), + ) + .on_press(move |s: &mut App| s.notes.retain(|x| x.id != id)) + }); + col() + .key("toasts") + .absolute(0.0, 0.0) + .w_full() + .h_full() + .padding(22.0) + .gap(10.0) + .justify_end() + .items_end() + .children(fresh) +} + +/// The full-window drop target shown while files hover. +pub fn drop_overlay(s: &App, look: &Look) -> Option { + if !s.drop_hover { + return None; + } + Some( + el().key("drop") + .absolute(0.0, 0.0) + .w_full() + .h_full() + .padding(18.0) + .fill(look.base.alpha(0.55)) + .backdrop_blur(10.0) + .child( + col() + .w_full() + .h_full() + .radius(22.0) + .border(2.0, look.accent) + .border_dash(10.0, 8.0) + .fill(look.accent.alpha(0.06)) + .center() + .gap(10.0) + .child(parts::icon_tile(&icons::DOWNLOAD, look.accent, 64.0)) + .child(text("Drop to install").font(ty::TITLE).color(look.text())) + .child( + text("Archives and folders install into the current game") + .font(ty::BODY) + .color(look.muted()), + ), + ), + ) +} diff --git a/crates/modrix-gui/src/ui/store.rs b/crates/modrix-gui/src/ui/store.rs new file mode 100644 index 0000000..745f66e --- /dev/null +++ b/crates/modrix-gui/src/ui/store.rs @@ -0,0 +1,191 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! The Mod store screen: the game's community catalog, searchable, with a +//! one-click install that queues the mod and its dependencies. + +use std::collections::HashSet; + +use modrix_service::store::{StoreItem, installed_keys}; +use rune::{El, col, el, row, text}; +use rune_kit::{Button, ButtonVariant, Spinner, TextInput}; + +use crate::icons; +use crate::look::{Look, space, ty}; +use crate::state::App; +use crate::ui::parts; + +/// Rows drawn at most; the search narrows the rest. +const MAX_ROWS: usize = 200; + +/// The Mod store screen. +pub fn view(s: &App, look: &Look) -> El { + let body = if s.store.loading { + loading(look) + } else if let Some(error) = &s.store.error { + failed(look, error) + } else { + list(s, look) + }; + col() + .w_full() + .gap(space::MD) + .child(toolbar(s, look)) + .child(parts::panel(look, "store").child(body)) +} + +fn toolbar(s: &App, look: &Look) -> El { + row() + .w_full() + .gap(space::SM) + .center_y() + .child( + TextInput::new(&s.form.store_search) + .placeholder("Search the store") + .leading_icon(&icons::SEARCH) + .clear_button() + .width(Some(320.0)) + .on_edit(|s: &mut App| &mut s.form.store_search) + .build(&look.k), + ) + .child(el().grow(1.0)) + .child( + Button::new("Refresh") + .icon(&icons::REFRESH) + .variant(ButtonVariant::Ghost) + .disabled(s.store.loading) + .on_press(|s: &mut App| s.fetch_store()) + .build(&look.k), + ) +} + +fn loading(look: &Look) -> El { + row() + .w_full() + .py(40.0) + .gap(10.0) + .center() + .child(Spinner::new().size(16.0).color(look.accent).build(&look.k)) + .child( + text("Loading the catalog") + .font(ty::BODY) + .color(look.muted()), + ) +} + +fn failed(look: &Look, error: &str) -> El { + parts::empty( + look, + &icons::WARNING, + "The store did not answer", + error, + Some( + Button::new("Try again") + .icon(&icons::REFRESH) + .variant(ButtonVariant::Neutral) + .on_press(|s: &mut App| s.fetch_store()) + .build(&look.k), + ), + ) +} + +fn list(s: &App, look: &Look) -> El { + let needle = s.form.store_search.text.trim().to_lowercase(); + let installed = installed_keys(s.lib.mods.iter().map(|m| m.name.as_str())); + let rows: Vec = s + .store + .items + .iter() + .filter(|i| needle.is_empty() || matches(i, &needle)) + .take(MAX_ROWS) + .map(|i| item_row(s, look, i, &installed)) + .collect(); + if rows.is_empty() { + return col().w_full().py(30.0).center().child( + text(if s.store.items.is_empty() { + "The catalog is empty" + } else { + "Nothing in the store matches the search" + }) + .font(ty::BODY) + .color(look.muted()), + ); + } + col().w_full().children(rows) +} + +fn matches(item: &StoreItem, needle: &str) -> bool { + item.name.to_lowercase().contains(needle) + || item + .short_description + .as_deref() + .is_some_and(|d| d.to_lowercase().contains(needle)) + || item + .author() + .is_some_and(|a| a.to_lowercase().contains(needle)) +} + +fn item_row(s: &App, look: &Look, item: &StoreItem, installed: &HashSet) -> El { + let have = installed.contains(&item.name.trim().to_lowercase()) + || installed.contains(&item.mod_id.trim().to_lowercase()); + let busy = s.store.installing.contains(&item.mod_id); + let id = item.mod_id.clone(); + let action = Button::new(if have { + "Installed" + } else if busy { + "Queuing" + } else { + "Install" + }) + .icon(if have { + &icons::CHECK + } else { + &icons::DOWNLOAD + }) + .variant(if have { + ButtonVariant::Ghost + } else { + ButtonVariant::Neutral + }) + .disabled(have || busy) + .on_press(move |s: &mut App| s.store_install(id.clone())) + .build(&look.k); + row() + .key(format!("store-{}", item.mod_id)) + .w_full() + .px(18.0) + .py(12.0) + .gap(14.0) + .center_y() + .border_sides([0.0, 0.0, 1.0, 0.0], look.edge) + .child(describe(look, item).grow(1.0).min_w(0.0)) + .children(item.latest_version.clone().map(|v| parts::tag(look, v))) + .child( + text(format!("{} downloads", item.downloads)) + .font(ty::SMALL) + .color(look.faint()), + ) + .child(action) +} + +fn describe(look: &Look, item: &StoreItem) -> El { + let mut head = row().gap(8.0).center_y().child( + text(item.name.clone()) + .font(ty::BODY_STRONG) + .color(look.text()) + .truncate(), + ); + if item.is_library() { + head = head.child(parts::tag(look, "Library")); + } + if let Some(author) = item.author() { + head = head.child( + text(format!("by {author}")) + .font(ty::SMALL) + .color(look.faint()), + ); + } + col().gap(3.0).child(head).children( + item.short_description + .clone() + .map(|d| text(d).font(ty::SMALL).color(look.muted()).truncate()), + ) +} diff --git a/crates/modrix-gui/src/ui/wizard.rs b/crates/modrix-gui/src/ui/wizard.rs new file mode 100644 index 0000000..e1a6c51 --- /dev/null +++ b/crates/modrix-gui/src/ui/wizard.rs @@ -0,0 +1,342 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! The FOMOD wizard dialog: one page per visible step, each group's options +//! picked by its rule, and a preview of the option last touched. + +use modrix_plugin::fomod::{self, GroupKind, PluginKind}; +use rune::{El, col, el, row, text}; +use rune_kit::{Button, ButtonVariant, Checkbox, Dialog}; + +use crate::icons; +use crate::look::{Look, space, ty}; +use crate::state::{App, Wizard}; +use crate::ui::parts::{self, glyph}; + +/// Options listed per group. +const MAX_OPTIONS: usize = 200; + +/// Push the wizard onto the overlay layer. +pub fn build(s: &App, look: &Look, w: &Wizard, layer: &mut Vec) { + let pages = w.visible_steps(); + let total = pages.len().max(1); + let page = w.step.min(total.saturating_sub(1)); + let current = pages.get(page).copied(); + let title = w + .installer + .info_name + .clone() + .unwrap_or_else(|| w.mod_name.clone()); + let step_name = current + .and_then(|i| w.installer.steps.get(i)) + .map_or_else(String::new, |st| st.name.clone()); + let body = row() + .w_full() + .h(440.0) + .gap(0.0) + .child(groups(look, w, current)) + .child(preview(look, w)); + let _ = s; + Dialog::new("wizard", title) + .open(true) + .fit() + .width(860.0) + .description(format!( + "Step {} of {total}: {step_name}", + page.saturating_add(1) + )) + .child(parts::hair(look)) + .child(body) + .child(parts::hair(look)) + .child(footer(look, page, total)) + .on_close(|s: &mut App| s.wizard_cancel()) + .build(&look.k, layer); +} + +fn groups(look: &Look, w: &Wizard, step: Option) -> El { + let Some(st) = step.and_then(|i| w.installer.steps.get(i).map(|st| (i, st))) else { + return col().grow(1.0).padding(20.0).child( + text("Nothing to choose here.") + .font(ty::BODY) + .color(look.muted()), + ); + }; + let (index, st) = st; + let flags = fomod::flags_of(&w.installer, &w.selections, &w.present); + let list = st.groups.iter().enumerate().map(|(g, group)| { + let picked = w.selections.get(index).and_then(|s| s.get(g)); + let options = group + .plugins + .iter() + .take(MAX_OPTIONS) + .enumerate() + .map(|(p, plugin)| { + let kind = fomod::plugin_kind(&plugin.kind, &flags, &w.present); + let on = picked.is_some_and(|set| set.contains(&p)); + let focused = w.focus == Some((index, g, p)); + option( + look, + Pick { + step: index, + group: g, + plugin: p, + }, + plugin, + Shown { + kind, + on, + focused, + group: group.kind, + }, + ) + }); + col() + .key(format!("group-{index}-{g}")) + .w_full() + .gap(4.0) + .child(group_head(look, index, g, group)) + .children(options) + }); + col() + .key("wizard-groups") + .grow(1.0) + .w(0.0) + .h_full() + .scroll(rune::ScrollSpec::default()) + .child(col().w_full().padding(18.0).gap(space::LG).children(list)) +} + +fn group_head(look: &Look, step: usize, g: usize, group: &fomod::Group) -> El { + let rule = match group.kind { + GroupKind::ExactlyOne => "Pick one", + GroupKind::AtMostOne => "Pick one or none", + GroupKind::AtLeastOne => "Pick at least one", + GroupKind::Any => "Pick any", + GroupKind::All => "All included", + }; + let bulk = matches!(group.kind, GroupKind::Any | GroupKind::AtLeastOne).then(|| { + row() + .gap(4.0) + .child( + Button::new("All") + .variant(ButtonVariant::GhostMuted) + .on_press(move |s: &mut App| s.wizard_group_set(step, g, true)) + .build(&look.k), + ) + .child( + Button::new("None") + .variant(ButtonVariant::GhostMuted) + .on_press(move |s: &mut App| s.wizard_group_set(step, g, false)) + .build(&look.k), + ) + }); + row() + .w_full() + .gap(space::SM) + .center_y() + .pb(4.0) + .child( + text(group.name.clone()) + .font(ty::HEADING) + .color(look.text()), + ) + .child(parts::tag(look, rule)) + .child(el().grow(1.0)) + .children(bulk) +} + +/// Which option a press targets. +#[derive(Clone, Copy)] +struct Pick { + step: usize, + group: usize, + plugin: usize, +} + +/// How an option shows: its kind under the current flags, whether it is +/// picked or focused, and its group's rule. +#[derive(Clone, Copy)] +struct Shown { + kind: PluginKind, + on: bool, + focused: bool, + group: GroupKind, +} + +/// The radio dot or checkbox in front of an option. +fn mark(look: &Look, plugin: &fomod::Plugin, on: bool, radio: bool) -> El { + if radio { + let ring = if on { look.accent } else { look.faint() }; + el().size(18.0, 18.0) + .radius(9.0) + .border(1.5, ring) + .center() + .children(on.then(|| el().size(8.0, 8.0).radius(4.0).fill(look.accent))) + } else { + Checkbox::new(on) + .hide_label() + .label(plugin.name.clone()) + .build(&look.k) + } +} + +fn option(look: &Look, at: Pick, plugin: &fomod::Plugin, shown: Shown) -> El { + let Shown { + kind, + on, + focused, + group, + } = shown; + let locked = + matches!(kind, PluginKind::NotUsable | PluginKind::Required) || group == GroupKind::All; + let radio = matches!(group, GroupKind::ExactlyOne | GroupKind::AtMostOne); + let badge = match kind { + PluginKind::Recommended => Some(parts::chip("Recommended", look.good)), + PluginKind::Required => Some(parts::chip("Required", look.accent)), + PluginKind::NotUsable => Some(parts::chip("Not usable", look.bad)), + _ => None, + }; + let Pick { + step, + group: g, + plugin: p, + } = at; + let mut line = row() + .key(format!("opt-{step}-{g}-{p}")) + .w_full() + .min_h(40.0) + .px(12.0) + .gap(space::MD) + .center_y() + .radius(10.0) + .fill(if focused { + look.accent_soft + } else { + rune::Color::TRANSPARENT + }) + .role(if radio { "radio" } else { "checkbox" }) + .checked(on) + .label(plugin.name.clone()) + .child(mark(look, plugin, on, radio)) + .child( + text(plugin.name.clone()) + .font(ty::BODY) + .color(if kind == PluginKind::NotUsable { + look.faint() + } else { + look.text() + }) + .grow(1.0) + .truncate(), + ) + .children(badge); + if !locked { + line = line + .hover_fill(look.hover()) + .on_press(move |s: &mut App| s.wizard_pick(step, g, p)); + } + line +} + +fn focused(w: &Wizard) -> Option<&fomod::Plugin> { + let (step, group, plugin) = w.focus?; + w.installer + .steps + .get(step)? + .groups + .get(group)? + .plugins + .get(plugin) +} + +fn preview(look: &Look, w: &Wizard) -> El { + let pane = col() + .key("wizard-preview") + .w(300.0) + .h_full() + .fill(look.glass) + .scroll(rune::ScrollSpec::default()); + let Some(plugin) = focused(w) else { + return pane.child( + col() + .w_full() + .padding(22.0) + .gap(space::SM) + .items_center() + .child(glyph(&icons::SLIDERS, 26.0, look.faint())) + .child( + text("Pick an option to read about it.") + .font(ty::BODY) + .color(look.muted()) + .wrap() + .align(rune::Align::Center), + ), + ); + }; + let description = if plugin.description.trim().is_empty() { + "This option has no description.".to_owned() + } else { + plugin.description.trim().to_owned() + }; + pane.child( + col() + .w_full() + .padding(20.0) + .gap(space::SM) + .child( + text(plugin.name.clone()) + .font(ty::HEADING) + .color(look.text()) + .wrap(), + ) + .child(text(description).font(ty::BODY).color(look.muted()).wrap()) + .child( + text(format!("{} files", plugin.files.len())) + .font(ty::SMALL) + .color(look.faint()), + ), + ) +} + +fn footer(look: &Look, page: usize, total: usize) -> El { + let last = page.saturating_add(1) >= total; + let next = if last { + Button::new("Install") + .icon(&icons::CHECK) + .variant(ButtonVariant::Submit) + .on_press(|s: &mut App| s.wizard_finish()) + .build(&look.k) + } else { + Button::new("Next") + .icon(&icons::CHEVRON_RIGHT) + .variant(ButtonVariant::Submit) + .on_press(|s: &mut App| s.wizard_step(1)) + .build(&look.k) + }; + let dots = (0..total.min(24)).map(|i| { + el().size(if i == page { 18.0 } else { 6.0 }, 6.0) + .radius(3.0) + .fill(if i == page { look.accent } else { look.edge }) + .motion(rune::Spring::new(0.25, 0.1)) + }); + row() + .w_full() + .px(20.0) + .py(14.0) + .gap(space::SM) + .center_y() + .child(row().gap(5.0).center_y().children(dots)) + .child(el().grow(1.0)) + .child( + Button::new("Skip options") + .variant(ButtonVariant::GhostMuted) + .on_press(|s: &mut App| s.wizard_cancel()) + .build(&look.k), + ) + .child( + Button::new("Back") + .variant(ButtonVariant::Neutral) + .disabled(page == 0) + .on_press(|s: &mut App| s.wizard_step(-1)) + .build(&look.k), + ) + .child(next) +} diff --git a/crates/modrix-gui/src/view/conflicts.rs b/crates/modrix-gui/src/view/conflicts.rs deleted file mode 100644 index 75fbe63..0000000 --- a/crates/modrix-gui/src/view/conflicts.rs +++ /dev/null @@ -1,279 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -//! The Conflicts screen: every pair of mods contesting files, with the rule -//! that resolves them (Vortex model). -//! -//! Red dot = no rule (install order decides, unresolved - deploy is blocked). -//! Green dot = a rule or full per-file pins cover the pair. Expanding a pair -//! lists the contested files; each can be pinned to either side. - -use iced::widget::{button, column, container, row, scrollable, text}; -use iced::{Alignment, Length}; -use modrix_core::{ModConflict, ModId}; - -use super::{BOLD, El, empty_state}; -use crate::app::{App, Message}; -use crate::{icons, theme}; - -/// Most contested files listed inside an expanded pair. -const MAX_FILES_SHOWN: usize = 300; - -/// The conflicts body. -pub(super) fn body(app: &App) -> El<'_> { - let mut page = column![].spacing(14).height(Length::Fill); - if let Some(blockers) = blockers_card(app) { - page = page.push(blockers); - } - if app.conflicts.is_empty() { - return page - .push(empty_state("No file conflicts between enabled mods.")) - .into(); - } - page = page.push(summary(app)); - let mut rows = column![].spacing(6).width(Length::Fill); - for conflict in &app.conflicts { - rows = rows.push(pair_card(app, conflict)); - } - let list = scrollable(rows).height(Length::Fill); - page.push( - container(list) - .padding(12) - .width(Length::Fill) - .height(Length::Fill) - .style(theme::card), - ) - .into() -} - -/// Everything currently blocking a deploy, so the user sees why the button -/// is off and what to fix - conflicts, missing masters, rule cycles. -fn blockers_card(app: &App) -> Option> { - let blocking: Vec<&modrix_core::Issue> = app.health.iter().filter(|i| i.blocking).collect(); - if blocking.is_empty() { - return None; - } - let mut list = column![ - text("DEPLOY BLOCKED UNTIL RESOLVED") - .size(10) - .color(theme::danger()) - ] - .spacing(6); - for issue in blocking.iter().take(8) { - list = list.push( - row![ - icons::dot(6.0, theme::danger()), - text(&issue.message).size(12).color(theme::text()), - ] - .spacing(8) - .align_y(Alignment::Center), - ); - } - Some( - container(list) - .padding([10, 14]) - .width(Length::Fill) - .style(theme::inset) - .into(), - ) -} - -fn summary(app: &App) -> El<'_> { - let total = app.conflicts.len(); - let unresolved = app.conflicts.iter().filter(|c| !c.resolved()).count(); - let label = if unresolved == 0 { - format!("{total} conflicting pairs, all resolved") - } else { - format!("{total} conflicting pairs · {unresolved} need a rule") - }; - let color = if unresolved == 0 { - theme::ok() - } else { - theme::danger() - }; - row![ - icons::dot(8.0, color), - text(label).size(13).color(theme::muted()), - ] - .spacing(8) - .align_y(Alignment::Center) - .into() -} - -/// One conflicting pair: status, names, rule buttons, and the file list -/// when expanded. Clicking the row (outside its buttons) expands it. -fn pair_card<'a>(app: &'a App, conflict: &'a ModConflict) -> El<'a> { - let (a, b) = (conflict.first, conflict.second); - let (name_a, name_b) = (app.mod_name(a), app.mod_name(b)); - let expanded = app.expanded_conflict == Some((a, b)); - let mut card = column![head_row(conflict, &name_a, &name_b)].spacing(8); - if expanded { - card = card.push(file_list(conflict, &name_a, &name_b)); - } - iced::widget::mouse_area( - container(card) - .padding([8, 12]) - .width(Length::Fill) - .style(theme::inset), - ) - .on_press(Message::ExpandConflict(a, b)) - .into() -} - -fn head_row(conflict: &ModConflict, name_a: &str, name_b: &str) -> El<'static> { - let a = conflict.first; - let dot = icons::dot( - 8.0, - if conflict.resolved() { - theme::ok() - } else { - theme::danger() - }, - ); - let files = conflict.files.len(); - let (state, color) = match conflict.rule { - Some(rule) => { - let winner = if rule.winner == a { &name_a } else { &name_b }; - (format!("{files} files · rule: {winner} wins"), theme::ok()) - } - None if conflict.resolved() => (format!("{files} files · all pinned"), theme::ok()), - None => ( - format!("{files} files · no rule · install order decides"), - theme::danger(), - ), - }; - // Stacked lines, never side-by-side with the wide rule buttons: sharing - // a row squeezes the title into a sliver on narrow windows. - column![ - row![ - dot, - text(format!("{name_a} × {name_b}")) - .size(13) - .font(BOLD) - .width(Length::Fill), - ] - .spacing(10) - .align_y(Alignment::Center), - text(state).size(11).color(color), - rule_controls(conflict, name_a, name_b), - ] - .spacing(6) - .into() -} - -/// The "A wins" / "B wins" rule buttons (the active side highlighted), plus -/// "clear" when a rule exists. -fn rule_controls(conflict: &ModConflict, name_a: &str, name_b: &str) -> El<'static> { - let (a, b) = (conflict.first, conflict.second); - let choice = |label: String, loser: ModId, winner: ModId, active: bool| { - button(text(label).size(11)) - .padding([4, 10]) - .style(if active { theme::primary } else { theme::ghost }) - .on_press(Message::SetRule { loser, winner }) - }; - let mut controls = row![ - choice( - format!("{} wins", short(name_a, 20)), - b, - a, - conflict.rule.is_some_and(|r| r.winner == a), - ), - choice( - format!("{} wins", short(name_b, 20)), - a, - b, - conflict.rule.is_some_and(|r| r.winner == b), - ), - ] - .spacing(6) - .align_y(Alignment::Center); - if conflict.rule.is_some() { - controls = controls.push( - button(text("clear").size(11)) - .padding([4, 10]) - .style(theme::danger_ghost) - .on_press(Message::ClearRule(a, b)), - ); - } - controls.into() -} - -/// The first `max` characters of a name (char-safe, for button labels). -fn short(name: &str, max: usize) -> String { - name.chars().take(max).collect() -} - -/// The pin/auto controls for one contested file. -fn file_controls<'a>( - file: &'a modrix_core::ConflictFile, - pair: (ModId, ModId), - names: (&str, &str), -) -> El<'a> { - let (a, b) = pair; - let pin = |label: String, provider: ModId, active: bool| { - button(text(label).size(10)) - .padding([2, 8]) - .style(if active { theme::primary } else { theme::ghost }) - .on_press(Message::PinFile { - target: file.target.clone(), - provider: Some(provider), - }) - }; - let mut controls = row![ - pin(names.0.to_owned(), a, file.overridden && file.winner == a), - pin(names.1.to_owned(), b, file.overridden && file.winner == b), - ] - .spacing(4) - .align_y(Alignment::Center); - if file.overridden { - controls = controls.push( - button(text("auto").size(10)) - .padding([2, 8]) - .style(theme::ghost) - .on_press(Message::PinFile { - target: file.target.clone(), - provider: None, - }), - ); - } - controls.into() -} - -/// The contested files of an expanded pair, each pinnable to either side. -fn file_list<'a>(conflict: &'a ModConflict, name_a: &str, name_b: &str) -> El<'a> { - let (a, b) = (conflict.first, conflict.second); - let (short_a, short_b) = (short(name_a, 24), short(name_b, 24)); - let mut list = column![].spacing(3); - for file in conflict.files.iter().take(MAX_FILES_SHOWN) { - let winner_name = if file.winner == a { &short_a } else { &short_b }; - list = list.push( - row![ - text(&file.target) - .size(11) - .color(theme::muted()) - .width(Length::Fill), - text(format!("→ {winner_name}")) - .size(11) - .color(if file.overridden { - theme::accent() - } else { - theme::faint() - }), - file_controls(file, (a, b), (&short_a, &short_b)), - ] - .spacing(10) - .align_y(Alignment::Center), - ); - } - let extra = conflict.files.len().saturating_sub(MAX_FILES_SHOWN); - if extra > 0 { - list = list.push( - text(format!("+{extra} more")) - .size(10) - .color(theme::faint()), - ); - } - container(scrollable(list).height(Length::Shrink)) - .padding([8, 10]) - .width(Length::Fill) - .style(theme::inset) - .into() -} diff --git a/crates/modrix-gui/src/view/dashboard.rs b/crates/modrix-gui/src/view/dashboard.rs deleted file mode 100644 index b684a13..0000000 --- a/crates/modrix-gui/src/view/dashboard.rs +++ /dev/null @@ -1,182 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -//! The Dashboard: at-a-glance glass cards over the game's backdrop (rendered -//! globally behind every tab) - or onboarding when nothing is set up. The -//! ACTIVE GAME card shows the game's own header art. - -use iced::widget::{button, column, container, image, row, text}; -use iced::{ContentFit, Length}; -use modrix_download::DownloadState; - -use super::{BOLD, El, empty_state}; -use crate::app::{App, Message, Screen}; -use crate::theme; - -/// Height of each dashboard card row - fixed, so cards in a row always align. -const ROW_HEIGHT: f32 = 188.0; - -/// The dashboard body. -pub(super) fn body(app: &App) -> El<'_> { - if app.games.is_empty() { - return onboarding(app); - } - column![ - row![game_card(app), deploy_card(app)] - .spacing(16) - .height(ROW_HEIGHT), - row![downloads_card(app), handoff_card(app)] - .spacing(16) - .height(ROW_HEIGHT), - ] - .spacing(16) - .into() -} - -fn game_card(app: &App) -> El<'_> { - let Some(game) = app.games.iter().find(|g| Some(g.id) == app.selected_game) else { - return empty_state("Select a game."); - }; - let stats = format!("{} mods · {} enabled", app.mods.len(), app.order.len()); - let mut inner = column![].spacing(10); - // The game's transparent themed logo (the title as art); falls back to - // the plain name until the art resolves. - if let Some(logo) = app.art.get(&game.id).and_then(|art| art.logo.clone()) { - inner = inner.push( - container(image(logo).content_fit(ContentFit::Contain).height(56)) - .width(Length::Fill) - .height(60), - ); - } else { - inner = inner.push(text(&game.name).size(16).font(BOLD)); - } - inner = inner.push(text(stats).size(13).color(theme::muted())).push( - button(text("Manage mods").size(13)) - .padding([8, 14]) - .style(theme::ghost) - .on_press(Message::Navigate(Screen::Mods)), - ); - tall_card("ACTIVE GAME", inner.into()) -} - -fn deploy_card(app: &App) -> El<'_> { - let profile = app - .active_profile - .as_ref() - .map_or_else(|| "no profile".to_owned(), |p| p.name.clone()); - let hint = format!("{} mods will deploy · {profile}", app.order.len()); - let mut actions = row![].spacing(10); - if app.busy { - actions = actions.push(text("Working…").size(13).color(theme::accent())); - } else { - actions = actions - .push( - button(text("Deploy").size(13)) - .padding([8, 16]) - .style(theme::primary) - .on_press(Message::Deploy), - ) - .push( - button(text("Verify").size(13)) - .padding([8, 14]) - .style(theme::ghost) - .on_press(Message::Verify), - ); - } - let inner = column![text(hint).size(13), actions].spacing(14); - tall_card("DEPLOYMENT", inner.into()) -} - -fn downloads_card(app: &App) -> El<'_> { - let active = app - .downloads - .iter() - .filter(|d| matches!(d.state, DownloadState::Active | DownloadState::Queued)) - .count(); - let summary = if app.downloads.is_empty() { - "None yet".to_owned() - } else { - format!("{active} active · {} total", app.downloads.len()) - }; - let inner = column![ - text(summary).size(13), - button(text("View downloads").size(13)) - .padding([8, 14]) - .style(theme::ghost) - .on_press(Message::Navigate(Screen::Downloads)), - ] - .spacing(12); - tall_card("DOWNLOADS", inner.into()) -} - -fn handoff_card(app: &App) -> El<'_> { - let line = match (&app.link, app.already_running) { - (Some(link), _) => format!("Listening on 127.0.0.1:{}", link.port), - (None, true) => "Another instance is receiving downloads".to_owned(), - (None, false) => "Not running".to_owned(), - }; - let inner = column![ - text(line).size(13), - button(text("Pairing").size(13)) - .padding([8, 14]) - .style(theme::ghost) - .on_press(Message::Navigate(Screen::Settings)), - ] - .spacing(12); - tall_card("BROWSER HAND-OFF", inner.into()) -} - -fn onboarding(app: &App) -> El<'_> { - let port = app - .link - .as_ref() - .map_or_else(|| "-".to_owned(), |l| l.port.to_string()); - let steps = column![ - step("1", "Register your game"), - step( - "2", - "Load the browser extension and paste the token from Settings" - ), - step("3", "Click Download on nexusmods.com"), - ] - .spacing(12); - let inner = column![ - text("Welcome").size(18).font(BOLD), - text(format!("Hand-off service on port {port}. No API keys.")) - .size(13) - .color(theme::muted()), - steps, - button(text("Register a game").size(13)) - .padding([9, 18]) - .style(theme::primary) - .on_press(Message::Navigate(Screen::Games)), - ] - .spacing(18); - container(inner) - .padding(28) - .width(Length::Fill) - .style(theme::card) - .into() -} - -/// A dashboard card that fills its fixed-height row, so a row's cards -/// always align whatever their content. -fn tall_card<'a>(label: &'a str, content: El<'a>) -> El<'a> { - let inner = column![text(label).size(10).color(theme::faint()), content].spacing(12); - container(inner) - .padding(18) - .width(Length::Fill) - .height(Length::Fill) - .style(theme::card) - .into() -} - -fn step<'a>(n: &'a str, title: &'a str) -> El<'a> { - row![ - container(text(n).size(13).font(BOLD).color(theme::accent())) - .padding([4, 11]) - .style(theme::chip(theme::accent())), - text(title).size(14), - ] - .spacing(14) - .align_y(iced::Alignment::Center) - .into() -} diff --git a/crates/modrix-gui/src/view/downloads.rs b/crates/modrix-gui/src/view/downloads.rs deleted file mode 100644 index 58ac3c2..0000000 --- a/crates/modrix-gui/src/view/downloads.rs +++ /dev/null @@ -1,133 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -//! The Downloads screen: live hand-off transfers. - -use iced::widget::{button, column, container, progress_bar, row, scrollable, text}; -use iced::{Alignment, Color, Length}; -use modrix_download::{DownloadState, DownloadStatus}; -use modrix_service::InstallOutcome; - -use super::{El, copy_button, empty_state}; -use crate::app::{App, Message}; -use crate::{fmt, icons, theme}; - -/// The downloads body. -pub(super) fn body(app: &App) -> El<'_> { - let mut page = column![].spacing(14); - page = page.push(pairing_strip(app)); - if app.downloads.is_empty() { - page = page.push(empty_state("No downloads yet.")); - } else { - let mut rows = column![].spacing(8); - for status in &app.downloads { - rows = rows.push(download_row(status, app.outcomes.get(&status.id))); - } - page = page.push( - container(scrollable(rows).height(Length::Fill)) - .padding(14) - .height(Length::Fill) - .style(theme::card), - ); - } - page.into() -} - -fn pairing_strip(app: &App) -> El<'_> { - let inner: El<'_> = match (&app.link, app.already_running) { - (Some(link), _) => row![ - icons::dot(7.0, theme::ok()), - text(format!("127.0.0.1:{}", link.port)).size(13), - iced::widget::Space::with_width(Length::Fill), - copy_button(link.token.clone()), - ] - .spacing(10) - .align_y(Alignment::Center) - .into(), - (None, true) => text("Another Modrix instance is receiving downloads.") - .size(13) - .color(theme::info()) - .into(), - (None, false) => text("Hand-off listener not running.") - .size(13) - .color(theme::danger()) - .into(), - }; - container(inner) - .padding([10, 14]) - .width(Length::Fill) - .style(theme::inset) - .into() -} - -fn download_row<'a>(status: &'a DownloadStatus, outcome: Option<&'a InstallOutcome>) -> El<'a> { - let name = status.file.file_name().map_or_else( - || "download".to_owned(), - |n| n.to_string_lossy().into_owned(), - ); - let (color, label) = badge(status.state, outcome); - let head = row![ - text(name).size(13).width(Length::Fill), - container(text(label).size(10)) - .padding([2, 8]) - .style(theme::chip(color)), - cancel_slot(status), - ] - .spacing(10) - .align_y(Alignment::Center); - let meta = row![ - text(size_line(status)).size(12).color(theme::muted()), - iced::widget::Space::with_width(Length::Fill), - text(fmt::percent(status.done, status.total)) - .size(12) - .color(theme::muted()), - ]; - let mut inner = column![ - head, - progress_bar(0.0..=1.0, fmt::fraction(status.done, status.total)) - .height(5) - .style(theme::progress), - meta, - ] - .spacing(7); - if let Some(InstallOutcome::Failed(error)) = outcome { - inner = inner.push(text(error).size(12).color(theme::danger())); - } - container(inner) - .padding([10, 14]) - .style(theme::table_row(true)) - .into() -} - -fn cancel_slot(status: &DownloadStatus) -> El<'_> { - let live = matches!( - status.state, - DownloadState::Active | DownloadState::Queued | DownloadState::Paused - ); - button(text("×").size(14)) - .padding([3, 8]) - .style(theme::icon) - .on_press_maybe(live.then_some(Message::CancelDownload(status.id))) - .into() -} - -fn size_line(status: &DownloadStatus) -> String { - let done = fmt::bytes(status.done); - match status.total { - Some(total) if total > 0 => format!("{done} of {}", fmt::bytes(total)), - _ => done, - } -} - -fn badge(state: DownloadState, outcome: Option<&InstallOutcome>) -> (Color, &'static str) { - match state { - DownloadState::Queued => (theme::faint(), "QUEUED"), - DownloadState::Active => (theme::accent(), "ACTIVE"), - DownloadState::Paused => (theme::info(), "PAUSED"), - DownloadState::Failed => (theme::danger(), "FAILED"), - DownloadState::Complete => match outcome { - Some(InstallOutcome::Installed { .. }) => (theme::ok(), "INSTALLED"), - Some(InstallOutcome::Failed(_)) => (theme::danger(), "INSTALL FAILED"), - Some(InstallOutcome::NoGame) => (theme::info(), "DOWNLOADED"), - None => (theme::accent(), "FINISHING"), - }, - } -} diff --git a/crates/modrix-gui/src/view/games.rs b/crates/modrix-gui/src/view/games.rs deleted file mode 100644 index 35fdb6e..0000000 --- a/crates/modrix-gui/src/view/games.rs +++ /dev/null @@ -1,186 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -//! The Games screen: registered installs + the registration form. - -use iced::widget::{button, column, container, pick_list, row, text, text_input}; -use iced::{Alignment, Length}; -use modrix_core::Game; - -use super::{BOLD, El, empty_state, labeled_card}; -use crate::app::{App, Detected, GameChoice, Message, RegistryChoice}; -use crate::theme; - -/// The games body. -pub(super) fn body(app: &App) -> El<'_> { - let mut list = column![].spacing(10); - if app.games.is_empty() { - list = list.push(empty_state( - "No games registered yet - pick one found installed below, or add it manually. \ - Nexus downloads route to the active game automatically.", - )); - } - for game in &app.games { - list = list.push(game_card(app, game)); - } - let mut root = column![list].spacing(16); - if let Some(card) = detected_card(app) { - root = root.push(card); - } - if let Some(card) = registry_card(app) { - root = root.push(card); - } - root.push(register_card(app)).into() -} - -/// Community game-support plugins available in the registry but not -/// installed locally. Installing one auto-registers the game when its -/// install is found on disk. `None` when everything is already local (or -/// the registry is unreachable). -fn registry_card(app: &App) -> Option> { - let available = app.available_support(); - if available.is_empty() { - return None; - } - let mut rows = column![].spacing(8); - for (index, choice) in available { - rows = rows.push(registry_row(index, choice, app.busy)); - } - Some(labeled_card("MORE GAMES - community plugins", rows.into())) -} - -fn registry_row(index: usize, choice: &RegistryChoice, busy: bool) -> El<'_> { - let info = column![ - text(&choice.name).size(14).font(BOLD), - text(format!("{} · v{}", choice.id, choice.version)) - .size(12) - .color(theme::faint()), - ] - .spacing(4) - .width(Length::Fill); - let mut install = button(text("Install support").size(13)) - .padding([8, 16]) - .style(theme::primary); - if !busy { - install = install.on_press(Message::InstallSupport(index)); - } - container(row![info, install].spacing(12).align_y(Alignment::Center)) - .padding(12) - .width(Length::Fill) - .style(theme::inset) - .into() -} - -/// A one-click "add and switch" list of supported games found installed on -/// disk but not yet registered. `None` when nothing new was detected. -fn detected_card(app: &App) -> Option> { - let found = app.unregistered_detected(); - if found.is_empty() { - return None; - } - let mut rows = column![].spacing(8); - for (index, detected) in found { - rows = rows.push(detected_row(index, detected)); - } - Some(labeled_card("FOUND INSTALLED", rows.into())) -} - -fn detected_row(index: usize, detected: &Detected) -> El<'_> { - let mut meta = detected.install.display().to_string(); - if let Some(appid) = detected.appid { - meta = format!("Steam {appid} · {meta}"); - } - let info = column![ - text(&detected.def.name).size(14).font(BOLD), - text(meta).size(12).color(theme::faint()), - ] - .spacing(4) - .width(Length::Fill); - let add = button(text("Add & switch").size(13)) - .padding([8, 16]) - .style(theme::primary) - .on_press(Message::AddDetected(index)); - container(row![info, add].spacing(12).align_y(Alignment::Center)) - .padding(12) - .width(Length::Fill) - .style(theme::inset) - .into() -} - -fn game_card<'a>(app: &App, game: &'a Game) -> El<'a> { - let selected = Some(game.id) == app.selected_game; - let mut meta = format!("{} · {}", game.plugin_id, game.store); - if let Some(appid) = game.steam_appid { - use std::fmt::Write as _; - let _ = write!(meta, " · Steam {appid}"); - } - let mut head = row![text(&game.name).size(15).font(BOLD).width(Length::Fill),] - .spacing(12) - .align_y(Alignment::Center); - if selected { - head = head.push( - container(text("ACTIVE").size(10)) - .padding([2, 8]) - .style(theme::chip(theme::accent())), - ); - } - let inner = column![ - head, - text(meta).size(12).color(theme::muted()), - text(game.install_path.display().to_string()) - .size(12) - .color(theme::faint()), - ] - .spacing(6) - .width(Length::Fill); - button(inner) - .padding(16) - .width(Length::Fill) - .style(theme::list_card(selected)) - .on_press(Message::GamePicked(GameChoice { - id: game.id, - name: game.name.clone(), - })) - .into() -} - -fn register_card(app: &App) -> El<'_> { - let picker = pick_list( - app.defs.clone(), - app.form.def_choice.clone(), - Message::DefPicked, - ) - .placeholder("Choose a game definition") - .text_size(13) - .padding([8, 10]) - .width(Length::Fill) - .style(theme::picker) - .menu_style(theme::picker_menu); - let def_path = text_input("…or a path to a custom game.toml", &app.form.def_path) - .on_input(Message::DefPathChanged) - .size(13) - .padding(9) - .width(Length::Fill) - .style(theme::input); - let install = text_input( - "Game install directory (e.g. ~/.steam/…/Skyrim Special Edition)", - &app.form.install_path, - ) - .on_input(Message::InstallPathChanged) - .on_submit(Message::AddGame) - .size(13) - .padding(9) - .style(theme::input); - let submit = button(text("Register game").size(13)) - .padding([9, 18]) - .style(theme::primary) - .on_press(Message::AddGame); - let inner = column![ - picker, - def_path, - install, - container(submit) - .align_x(Alignment::End) - .width(Length::Fill), - ] - .spacing(10); - labeled_card("REGISTER A GAME", inner.into()) -} diff --git a/crates/modrix-gui/src/view/load_order.rs b/crates/modrix-gui/src/view/load_order.rs deleted file mode 100644 index 4470cfa..0000000 --- a/crates/modrix-gui/src/view/load_order.rs +++ /dev/null @@ -1,207 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -//! The Load Order screen: the game's **plugins** (.esp/.esm/.esl), the unit -//! the engine actually sorts and writes to `Plugins.txt`. -//! -//! Reorder by drag (grip handle, commit on release), by the arrow buttons, or -//! by keyboard: arrows move the cursor, Shift extends the selection, Ctrl -//! (optionally with Shift for a block) moves the selected plugin(s). - -use iced::widget::{button, column, container, mouse_area, row, scrollable, text, toggler}; -use iced::{Alignment, Length}; -use modrix_core::plugins::GamePlugin; - -use super::{BOLD, El, empty_state}; -use crate::app::{App, Message, Pane}; -use crate::{icons, theme}; - -/// The load-order body. -pub(super) fn body(app: &App) -> El<'_> { - if app.plugins.is_empty() { - return empty_state("No plugins - enable mods that provide .esp/.esm/.esl files."); - } - // Fill, not Shrink: with the default Shrink the inner Fill scrollable - // collapses and plugins past the fold are unreachable. - let mut page = column![].spacing(14).height(Length::Fill); - page = page.push(toolbar(app)); - let mut rows = column![].spacing(3).width(Length::Fill); - for (i, plugin) in app.plugins.iter().enumerate() { - let selected = app.plugin_sel.items.contains(&i) || app.plugin_sel.cursor == Some(i); - let drag_target = app.drag.map(|(_, to)| to) == Some(i); - rows = rows.push(plugin_row( - plugin, - i, - app.plugins.len(), - selected, - drag_target, - )); - } - let list = scrollable(rows) - .id(iced::widget::scrollable::Id::new("plugins-list")) - .on_scroll(|v| Message::Scrolled(Pane::Plugins, v.absolute_offset().y, v.bounds().height)) - .height(Length::Fill); - let table = container(list) - .padding(12) - .width(Length::Fill) - .height(Length::Fill) - .style(theme::card); - // Release anywhere over the list commits a drag; clicking empty space - // clears the selection. - page.push( - mouse_area(table) - .on_release(Message::DragEnd) - .on_press(Message::ClearSelection), - ) - .into() -} - -fn toolbar(app: &App) -> El<'_> { - let count = app.plugins.len(); - let active = app.plugins.iter().filter(|p| p.enabled).count(); - // Mods without plugins (textures, meshes, SKSE DLLs) never appear here - // or in the game's mods menu - say so, or the count mismatch looks - // like mods failing to load. - let asset_only = app - .order - .iter() - .filter(|m| app.plugin_counts.get(&m.id).copied().unwrap_or(0) == 0) - .count(); - let mut bar = row![ - text(format!( - "{active} of {count} plugins active · {asset_only} enabled mods are asset-only (no plugin)" - )) - .size(12) - .color(theme::muted()), - iced::widget::Space::with_width(Length::Fill), - ] - .spacing(10) - .align_y(Alignment::Center); - if !app.busy { - bar = bar.push( - button(text("Auto-sort").size(13).font(BOLD)) - .padding([8, 16]) - .style(theme::primary) - .on_press(Message::AutoSort), - ); - } - bar.into() -} - -/// The up/down move buttons for a row. -fn move_arrows(index: usize, len: usize) -> El<'static> { - row![ - arrow_button( - true, - (index > 0).then_some(Message::MoveSelection { - pane: Pane::Plugins, - delta: -1, - }) - ), - arrow_button( - false, - (index < len.saturating_sub(1)).then_some(Message::MoveSelection { - pane: Pane::Plugins, - delta: 1, - }) - ), - ] - .spacing(4) - .into() -} - -fn plugin_row(plugin: &GamePlugin, index: usize, len: usize, selected: bool, drop: bool) -> El<'_> { - let handle = mouse_area(icons::grip::()) - .interaction(iced::mouse::Interaction::Grab) - .on_press(Message::DragStart(Pane::Plugins, index)); - let position = index.saturating_add(1); - let arrows = move_arrows(index, len); - let activate = toggler(plugin.enabled) - .size(15) - .on_toggle(move |_| Message::TogglePlugin(index)) - .style(theme::toggle); - let inner = row![ - handle, - activate, - container( - text(format!("{position:>3}")) - .size(11) - .font(BOLD) - .color(theme::accent()) - ) - .padding([3, 8]) - .style(theme::chip(theme::accent())), - name_column(plugin), - container(tier_chip(plugin)).width(44), - arrows, - ] - .spacing(10) - .align_y(Alignment::Center); - let style: fn(&iced::Theme) -> iced::widget::container::Style = if drop { - theme::table_row_dragging - } else if selected { - theme::table_row_selected - } else if index.is_multiple_of(2) { - |t| theme::table_row(true)(t) - } else { - |t| theme::table_row(false)(t) - }; - let styled = container(inner) - .width(Length::Fill) - .padding([6, 12]) - .style(style); - mouse_area(styled) - .on_press(Message::RowClick { - pane: Pane::Plugins, - index, - }) - .on_enter(Message::DragOver(index)) - .into() -} - -/// The plugin's name, mod origin, and any missing-master warning. -fn name_column(plugin: &GamePlugin) -> El<'_> { - let name_color = if plugin.missing_masters.is_empty() { - if plugin.enabled { - theme::text() - } else { - theme::muted() - } - } else { - theme::danger() - }; - let mut col = column![ - text(&plugin.name).size(13).color(name_color), - text(&plugin.mod_name).size(10).color(theme::faint()), - ] - .spacing(1) - .width(Length::Fill); - if !plugin.missing_masters.is_empty() { - col = col.push( - text(format!("missing: {}", plugin.missing_masters.join(", "))) - .size(10) - .color(theme::danger()), - ); - } - col.into() -} - -fn tier_chip(plugin: &GamePlugin) -> El<'static> { - let (label, color) = if plugin.is_light { - ("ESL", theme::info()) - } else if plugin.is_master { - ("ESM", theme::accent()) - } else { - return iced::widget::Space::with_width(0).into(); - }; - container(text(label).size(9)) - .padding([1, 6]) - .style(theme::chip(color)) - .into() -} - -fn arrow_button(up: bool, message: Option) -> El<'static> { - button(icons::arrow::(up)) - .padding([6, 8]) - .style(theme::icon) - .on_press_maybe(message) - .into() -} diff --git a/crates/modrix-gui/src/view/mod.rs b/crates/modrix-gui/src/view/mod.rs deleted file mode 100644 index 8520b16..0000000 --- a/crates/modrix-gui/src/view/mod.rs +++ /dev/null @@ -1,632 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -//! The view layer: a fixed sidebar shell around one of six screens, with a -//! notification center and the FOMOD wizard overlay. - -mod conflicts; -mod dashboard; -mod downloads; -mod games; -mod load_order; -mod mods; -mod settings; -mod wizard; - -use iced::widget::{ - Space, button, column, container, mouse_area, opaque, pick_list, row, stack, text, -}; -use iced::{Alignment, Font, Length}; - -use crate::app::{App, DupPrompt, GameChoice, Message, Note, Screen, Tone}; -use crate::{icons, theme}; - -/// The message-typed element every view helper returns. -pub type El<'a> = iced::Element<'a, Message>; - -/// A heavier weight for headings. -pub const BOLD: Font = Font { - weight: iced::font::Weight::Bold, - ..Font::DEFAULT -}; - -const NAV: [(Screen, &str); 6] = [ - (Screen::Dashboard, "Dashboard"), - (Screen::Games, "Games"), - (Screen::Mods, "Mods"), - (Screen::LoadOrder, "Load Order"), - (Screen::Conflicts, "Conflicts"), - (Screen::Downloads, "Downloads"), -]; - -/// The whole window. -pub fn view(app: &App) -> El<'_> { - if let Some(error) = &app.boot_error { - return boot_error(error); - } - // Until the embedded service finishes starting (which includes recovering - // an interrupted deploy - potentially thousands of file restores), show a - // deliberate loading screen so a slow boot never looks like a hang. - if app.service.is_none() { - return starting(app); - } - let base: El<'_> = row![sidebar(app), content(app)].into(); - // Overlays stack over the base UI: the notification popup (non-blocking, - // top-right), then modal layers (duplicate prompt, FOMOD wizard). - let mut layers: Vec> = vec![base]; - if app.notes_open { - layers.push(notes_overlay(app)); - } - if let Some(prompt) = app.dup_queue.first() { - layers.push(dup_overlay(prompt)); - } - if let Some(wizard) = &app.wizard { - layers.push(wizard::overlay(app, wizard)); - } - if layers.len() == 1 { - return layers.remove(0); - } - iced::widget::Stack::with_children(layers).into() -} - -/// The boot screen: wordmark plus a live progress bar and status line while -/// the engine starts (crash recovery can take a while on big libraries). -fn starting(app: &App) -> El<'_> { - let mut body = column![row![ - text("MOD").size(24).font(BOLD).color(theme::accent()), - text("RIX").size(24).font(BOLD).color(theme::text()), - ],] - .spacing(14) - .align_x(Alignment::Center); - body = body.push(progress_line(app, 360.0, "Starting…")); - container(body) - .center_x(Length::Fill) - .center_y(Length::Fill) - .into() -} - -/// A progress bar + percentage + status line for the live operation, or a -/// quiet fallback message when nothing is running. -/// -/// Every element has a fixed width: the status message changes length each -/// tick, and if it drove the layout the centered bar would shift ("bounce") -/// with every update. -fn progress_line<'a>(app: &'a App, width: f32, idle: &'a str) -> El<'a> { - let Some(op) = &app.op else { - return text(idle).size(13).color(theme::muted()).into(); - }; - let (value, pct): (f32, String) = match op.fraction() { - Some(f) => (f, format!("{:.0}%", f64::from(f) * 100.0)), - None => (0.0, "…".to_owned()), - }; - // Bar + spacing + a fixed percentage cell = the column's constant width. - let pct_width = 42.0_f32; - let total = width + 10.0 + pct_width; - column![ - row![ - iced::widget::progress_bar(0.0..=1.0, value) - .height(6) - .width(width) - .style(theme::progress), - text(pct).size(12).color(theme::accent()).width(pct_width), - ] - .spacing(10) - .align_y(Alignment::Center), - // Clipped to one line so a long path cannot grow the layout either. - container( - text(op.message.clone()) - .size(12) - .color(theme::muted()) - .width(total) - .align_x(Alignment::Center) - ) - .height(18) - .clip(true), - ] - .spacing(6) - .width(total) - .into() -} - -fn boot_error(error: &str) -> El<'_> { - let body = column![ - text("Modrix could not start").size(20).font(BOLD), - text(error).size(14).color(theme::danger()), - ] - .spacing(12) - .align_x(Alignment::Center); - container(container(body).padding(32).style(theme::card)) - .center_x(Length::Fill) - .center_y(Length::Fill) - .into() -} - -// --- sidebar ----------------------------------------------------------------- - -/// Height of the full-width cover banner (2:3 at the 240px sidebar width, so -/// the cover fills it with no cropping). -const BANNER_H: f32 = 360.0; - -/// Notification popup width, and the height cap past which it stops growing. -const GLASS_W: f32 = 360.0; -const GLASS_MAX_H: f32 = 480.0; - -fn sidebar(app: &App) -> El<'_> { - // The banner is edge-to-edge (no sidebar padding); everything below it is - // padded normally. - let top: El<'_> = match sidebar_banner(app) { - Some(banner) => banner, - None => container(wordmark()).padding([16, 16]).into(), - }; - let lower = column![ - game_picker(app), - nav_items(app), - Space::with_height(Length::Fill), - service_dot(app), - nav_item(app, Screen::Settings, "Settings"), - ] - .spacing(10) - .padding(16); - container(column![top, lower]) - .width(240) - .height(Length::Fill) - .style(theme::sidebar) - .into() -} - -/// The selected game's cover as a full-width banner with the wordmark over its -/// blurred top. `None` until the art resolves (or when no game is selected) - -/// the plain wordmark is shown instead. -fn sidebar_banner(app: &App) -> Option> { - let id = app.selected_game?; - let cover = app.art.get(&id).and_then(|art| art.cover.clone())?; - let image = container( - iced::widget::image(cover) - .content_fit(iced::ContentFit::Cover) - .width(Length::Fill) - .height(Length::Fill), - ) - .width(Length::Fill) - .height(Length::Fixed(BANNER_H)) - .clip(true); - // The wordmark, pinned to the top-left over the blurred strip. - let mark = container(wordmark()) - .width(Length::Fill) - .height(Length::Fixed(BANNER_H)) - .padding([16, 16]) - .align_x(iced::alignment::Horizontal::Left) - .align_y(iced::alignment::Vertical::Top); - Some(stack![image, mark].into()) -} - -fn wordmark() -> El<'static> { - row![ - text("MOD").size(20).font(BOLD).color(theme::accent()), - text("RIX").size(20).font(BOLD).color(theme::text()), - ] - .into() -} - -fn game_picker(app: &App) -> El<'_> { - let choices: Vec = app - .games - .iter() - .map(|g| GameChoice { - id: g.id, - name: g.name.clone(), - }) - .collect(); - let selected = app - .selected_game - .and_then(|id| choices.iter().find(|c| c.id == id).cloned()); - pick_list(choices, selected, Message::GamePicked) - .placeholder("No game") - .text_size(13) - .padding([8, 10]) - .width(Length::Fill) - .style(theme::picker) - .menu_style(theme::picker_menu) - .into() -} - -fn nav_items(app: &App) -> El<'_> { - let mut items = column![].spacing(2); - for (screen, label) in NAV { - // The selected game decides which screens exist: a game with no - // load-order strategy shows no Load Order (or idle Conflicts) tab. - if !app.screen_visible(screen) { - continue; - } - items = items.push(nav_item(app, screen, label)); - } - items.into() -} - -fn nav_item<'a>(app: &App, screen: Screen, label: &'a str) -> El<'a> { - let active = app.screen == screen; - let inner = row![ - icons::dot( - 6.0, - if active { - theme::accent() - } else { - theme::hairline_color() - } - ), - text(label) - .size(14) - .font(if active { BOLD } else { Font::DEFAULT }), - ] - .spacing(10) - .align_y(Alignment::Center); - button(inner) - .width(Length::Fill) - .padding([9, 12]) - .style(theme::nav(active)) - .on_press(Message::Navigate(screen)) - .into() -} - -fn service_dot(app: &App) -> El<'_> { - let (color, label) = match (&app.link, app.already_running, app.service.is_some()) { - (Some(link), _, _) => (theme::ok(), format!("Hand-off · :{}", link.port)), - (None, true, _) => (theme::info(), "Another instance active".to_owned()), - (None, false, true) => (theme::danger(), "Hand-off inactive".to_owned()), - _ => (theme::faint(), "Starting…".to_owned()), - }; - let inner = row![ - icons::dot(7.0, color), - text(label).size(11).color(theme::muted()), - ] - .spacing(7) - .align_y(Alignment::Center); - container(inner).padding([6, 8]).into() -} - -// --- content shell ----------------------------------------------------------- - -fn content(app: &App) -> El<'_> { - let body: El<'_> = match app.screen { - Screen::Dashboard => dashboard::body(app), - Screen::Games => games::body(app), - Screen::Mods => mods::body(app), - Screen::LoadOrder => load_order::body(app), - Screen::Conflicts => conflicts::body(app), - Screen::Downloads => downloads::body(app), - Screen::Settings => settings::body(app), - }; - // Fill, not the default Shrink: a Fill-height list inside a Shrink - // column collapses in iced, hiding everything below the fold. - let shell = column![header(app)] - .spacing(16) - .padding(28) - .height(Length::Fill); - let foreground = container(shell.push(body)) - .width(Length::Fill) - .height(Length::Fill); - // Every tab sits over the selected game's backdrop - sharp behind the - // header, blurring and fading to nothing toward the bottom (baked into - // the image, so it costs one draw). - match backdrop_path(app) { - Some(path) => stack![tab_backdrop(path), foreground].into(), - None => foreground.into(), - } -} - -/// The selected game's baked backdrop image, when resolved. -fn backdrop_path(app: &App) -> Option { - app.selected_game - .and_then(|id| app.art.get(&id)) - .and_then(|art| art.backdrop.clone()) -} - -/// The full-bleed backdrop layer (its own top-to-bottom fade is baked in). -fn tab_backdrop(path: std::path::PathBuf) -> El<'static> { - container( - iced::widget::image(path) - .content_fit(iced::ContentFit::Cover) - .width(Length::Fill) - .height(Length::Fill), - ) - .width(Length::Fill) - .height(Length::Fill) - .clip(true) - .into() -} - -fn header(app: &App) -> El<'_> { - let (title, subtitle) = title_of(app); - let mut bar = row![ - column![ - text(title).size(22).font(BOLD), - text(subtitle).size(13).color(theme::muted()), - ] - .spacing(3), - Space::with_width(Length::Fill), - ] - .spacing(14) - .align_y(Alignment::Center); - if app.busy || app.op.is_some() { - bar = bar.push(progress_line(app, 220.0, "Working…")); - } - bar.push(bell(app)).into() -} - -/// The notification bell: a drawn bell with a status dot coloured by the most -/// severe pending notification (red errors/conflicts, yellow warnings, blue -/// info, green all-clear). -fn bell(app: &App) -> El<'_> { - let severity = notification_severity(app); - let dot_color = match severity { - Severity::Error => theme::danger(), - Severity::Warning => theme::accent(), - Severity::Info => theme::info(), - Severity::Clear => theme::ok(), - }; - let mut inner = row![icons::bell(theme::muted(), dot_color)] - .spacing(6) - .align_y(Alignment::Center); - // Unread events plus live issues: the number tracks what the panel shows. - let pending = app.unread.saturating_add(app.health.len()); - if pending > 0 { - inner = inner.push(text(pending).size(12).color(dot_color)); - } - button(inner) - .padding([6, 12]) - .style(theme::ghost) - .on_press(Message::ToggleNotes) - .into() -} - -/// Severity of the bell dot, from live health + unread notifications. -enum Severity { - Error, - Warning, - Info, - Clear, -} - -fn notification_severity(app: &App) -> Severity { - use modrix_core::Severity as S; - if app.health.iter().any(|i| i.severity == S::Error) { - return Severity::Error; - } - if app.health.iter().any(|i| i.severity == S::Warning) { - return Severity::Warning; - } - if app.unread > 0 { - let worst = app - .notes - .iter() - .take(app.unread) - .map(|n| n.tone) - .fold(Tone::Info, |acc, t| match (acc, t) { - (Tone::Error, _) | (_, Tone::Error) => Tone::Error, - _ => acc, - }); - return match worst { - Tone::Error => Severity::Error, - _ => Severity::Info, - }; - } - Severity::Clear -} - -/// The notification popup, anchored under the bell in the top-right corner. -/// A click anywhere outside the panel dismisses it; the panel itself swallows -/// clicks so interacting with it does not close it. Not `opaque`: the rest of -/// the UI stays visible and interactive-looking beneath. -fn notes_overlay(app: &App) -> El<'_> { - // Fixed width, but the height hugs the content (see notes_panel), capped so - // a very long history cannot run off the screen. - let panel = mouse_area( - container(notes_panel(app)) - .width(Length::Fixed(GLASS_W)) - .max_height(GLASS_MAX_H), - ) - .on_press(Message::NoOp); - let positioned = container(panel) - .width(Length::Fill) - .height(Length::Fill) - .align_x(iced::alignment::Horizontal::Right) - .align_y(iced::alignment::Vertical::Top) - .padding([64, 24]); - mouse_area(positioned).on_press(Message::ToggleNotes).into() -} - -/// The notification list + header, content-sized (no fixed height) - the piece -/// that dictates how large the popup is. -fn notes_body(app: &App) -> El<'_> { - let mut list = column![].spacing(6); - if app.health.is_empty() && app.notes.is_empty() { - list = list.push(text("All clear").size(12).color(theme::muted())); - } - for issue in &app.health { - list = list.push(issue_row(issue)); - } - if !app.health.is_empty() && !app.notes.is_empty() { - list = list.push(text("RECENT").size(9).color(theme::muted())); - } - for note in app.notes.iter().take(50) { - list = list.push(note_row(note)); - } - let mut head = row![ - text("Notifications") - .size(13) - .font(BOLD) - .width(Length::Fill) - ] - .align_y(Alignment::Center); - if !app.notes.is_empty() { - head = head.push( - button(text("Clear all").size(11)) - .padding([3, 10]) - .style(theme::ghost) - .on_press(Message::ClearNotes), - ); - } - container(column![head, list].spacing(10)) - .padding(14) - .width(Length::Fill) - .into() -} - -/// Panel contents: live issues first (rendered straight from `app.health`, so a -/// resolved issue vanishes on the next health pass), then recent events. -/// -/// The popup hugs its content: a `Stack` takes its size from its FIRST child, so -/// a first copy of the body sets the panel's height, the frosted-glass tile -/// fills that (an image needs a defined size - this is how it gets one without a -/// fixed height), and a second copy of the body is drawn on top, visible. iced -/// 0.13 cannot blur live content behind a widget, so the frost is baked (a -/// translucent, desaturated, rounded tile of the game art); when art has not -/// resolved we fall back to a plain translucent panel. -fn notes_panel(app: &App) -> El<'_> { - let glass = app - .selected_game - .and_then(|id| app.art.get(&id)) - .and_then(|art| art.glass.clone()); - match glass { - Some(path) => container(stack![ - notes_body(app), - container( - iced::widget::image(path) - .content_fit(iced::ContentFit::Fill) - .width(Length::Fill) - .height(Length::Fill), - ) - .width(Length::Fill) - .height(Length::Fill) - .clip(true), - notes_body(app), - ]) - .width(Length::Fill) - .style(theme::panel_frame) - .into(), - None => container(notes_body(app)) - .width(Length::Fill) - .style(theme::panel) - .into(), - } -} - -/// A live health issue: colored by severity, no timestamp (it is current -/// state, not history). -fn issue_row(issue: &modrix_core::Issue) -> El<'_> { - let color = match issue.severity { - modrix_core::Severity::Error => theme::danger(), - modrix_core::Severity::Warning => theme::accent(), - modrix_core::Severity::Info => theme::info(), - }; - row![ - icons::dot(6.0, color), - text(&issue.message).size(12).color(theme::text()), - ] - .spacing(8) - .align_y(Alignment::Center) - .into() -} - -/// The duplicate-install modal: the dropped archive's content is already -/// installed. Same modal mechanics as the FOMOD wizard (opaque + backdrop). -fn dup_overlay(prompt: &DupPrompt) -> El<'_> { - let file = prompt.path.file_name().map_or_else( - || prompt.path.display().to_string(), - |n| n.to_string_lossy().into_owned(), - ); - let body = column![ - text("Already installed").size(16).font(BOLD), - text(format!( - "{file} is the same archive as \"{}\", which is already installed.", - prompt.existing_name - )) - .size(13) - .color(theme::muted()), - row![ - Space::with_width(Length::Fill), - button(text("Cancel").size(13)) - .padding([8, 16]) - .style(theme::ghost) - .on_press(Message::DupCancel), - button(text("Reinstall").size(13)) - .padding([8, 16]) - .style(theme::primary) - .on_press(Message::DupConfirm), - ] - .spacing(10), - ] - .spacing(16); - let card = container(body).padding(24).width(440).style(theme::card); - opaque( - container(card) - .center_x(Length::Fill) - .center_y(Length::Fill) - .style(theme::backdrop), - ) -} - -fn note_row(note: &Note) -> El<'_> { - let color = match note.tone { - Tone::Ok => theme::ok(), - Tone::Error => theme::danger(), - Tone::Info => theme::info(), - }; - row![ - icons::dot(6.0, color), - text(¬e.text).size(12).color(theme::text()), - ] - .spacing(8) - .align_y(Alignment::Center) - .into() -} - -fn title_of(app: &App) -> (&'static str, String) { - let game = app - .games - .iter() - .find(|g| Some(g.id) == app.selected_game) - .map_or_else(String::new, |g| g.name.clone()); - match app.screen { - Screen::Dashboard => ("Dashboard", game), - Screen::Games => ("Games", format!("{} registered", app.games.len())), - Screen::Mods => ("Mods", game), - Screen::LoadOrder => ( - "Load Order", - "plugins load top to bottom · masters first".to_owned(), - ), - Screen::Conflicts => ( - "Conflicts", - "rules decide which mod provides each contested file".to_owned(), - ), - Screen::Downloads => ("Downloads", String::new()), - Screen::Settings => ("Settings", String::new()), - } -} - -// --- helpers shared by the screens -------------------------------------------- - -/// A raised card with a small uppercase label. -fn labeled_card<'a>(label: &'a str, content: El<'a>) -> El<'a> { - let inner = column![text(label).size(10).color(theme::faint()), content].spacing(12); - container(inner) - .padding(18) - .width(Length::Fill) - .style(theme::card) - .into() -} - -/// A quiet inset panel for empty lists. -fn empty_state(message: &str) -> El<'_> { - container(text(message).size(13).color(theme::muted())) - .padding(24) - .width(Length::Fill) - .style(theme::inset) - .into() -} - -/// A small "Copy" button placing `value` on the clipboard. -fn copy_button(value: String) -> El<'static> { - button(text("Copy").size(11)) - .padding([4, 10]) - .style(theme::ghost) - .on_press(Message::CopyText(value)) - .into() -} diff --git a/crates/modrix-gui/src/view/mods.rs b/crates/modrix-gui/src/view/mods.rs deleted file mode 100644 index c06d05b..0000000 --- a/crates/modrix-gui/src/view/mods.rs +++ /dev/null @@ -1,376 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -//! The Mods screen: the mod table, bulk actions, and the install drop zone. -//! -//! Selection: click a row (Shift+click or Shift+arrows for a range, -//! Ctrl+click to toggle); clicking empty space or pressing Escape clears. - -use std::collections::HashSet; - -use iced::widget::{ - button, column, container, mouse_area, pick_list, row, scrollable, text, toggler, -}; -use iced::{Alignment, Length}; -use modrix_core::{ExternalMod, Mod, ModId}; - -use super::{BOLD, El, empty_state}; -use crate::app::{App, Message, Pane, SortKey}; -use crate::{icons, theme}; - -/// The mods body. -pub(super) fn body(app: &App) -> El<'_> { - let enabled: HashSet = app.order.iter().map(|m| m.id).collect(); - // A click on the surrounding container (not a row) clears the selection. - let cleared = mouse_area( - column![toolbar(app, &enabled), table(app, &enabled), drop_zone()] - .spacing(14) - .height(Length::Fill), - ) - .on_press(Message::ClearSelection); - cleared.into() -} - -fn toolbar<'a>(app: &'a App, enabled: &HashSet) -> El<'a> { - if !app.mod_sel.items.is_empty() { - return selection_bar(app); - } - let names: Vec = app.profiles.iter().map(|p| p.name.clone()).collect(); - let active = app.active_profile.as_ref().map(|p| p.name.clone()); - let profile = pick_list(names, active, Message::ProfilePicked) - .placeholder("profile") - .text_size(13) - .padding([7, 10]) - .style(theme::picker) - .menu_style(theme::picker_menu); - let mut bar = row![profile, iced::widget::Space::with_width(Length::Fill)] - .spacing(10) - .align_y(Alignment::Center); - let disabled = app.mods.len().saturating_sub(enabled.len()); - if disabled > 0 { - bar = bar.push(action( - format!("Enable all ({disabled})"), - theme::ghost, - Message::EnableAll, - )); - } - if !app.busy { - bar = bar - .push(action("Verify".to_owned(), theme::ghost, Message::Verify)) - .push(action( - "Purge".to_owned(), - theme::danger_ghost, - Message::Purge, - )); - // Deploy is gated: unresolved conflicts or dependency errors send - // the user to Conflicts instead of deploying a broken setup. - let blockers = app.health.iter().filter(|i| i.blocking).count(); - bar = bar.push(if blockers > 0 { - action( - format!("Deploy blocked ({blockers})"), - theme::danger_ghost, - Message::Navigate(crate::app::Screen::Conflicts), - ) - } else { - action("Deploy".to_owned(), theme::primary, Message::Deploy) - }); - } - bar.into() -} - -/// The bar shown while rows are selected: mass enable/disable/delete/reinstall. -fn selection_bar(app: &App) -> El<'_> { - let n = app.mod_sel.items.len(); - row![ - text(format!("{n} selected")) - .size(13) - .font(BOLD) - .color(theme::accent()), - iced::widget::Space::with_width(Length::Fill), - action( - "Enable".to_owned(), - theme::ghost, - Message::SetSelectedEnabled(true) - ), - action( - "Disable".to_owned(), - theme::ghost, - Message::SetSelectedEnabled(false) - ), - action( - "Reinstall".to_owned(), - theme::ghost, - Message::ReinstallSelected - ), - action( - "Delete".to_owned(), - theme::danger_ghost, - Message::DeleteSelected - ), - button(text("×").size(14)) - .padding([4, 10]) - .style(theme::icon) - .on_press(Message::ClearSelection), - ] - .spacing(10) - .align_y(Alignment::Center) - .into() -} - -fn action( - label: String, - style: fn(&iced::Theme, button::Status) -> button::Style, - message: Message, -) -> El<'static> { - button(text(label).size(13)) - .padding([8, 16]) - .style(style) - .on_press(message) - .into() -} - -fn table<'a>(app: &'a App, enabled: &HashSet) -> El<'a> { - if app.mods.is_empty() && app.external.is_empty() { - return empty_state("No mods yet."); - } - let mut rows = column![].spacing(4).width(Length::Fill); - for (i, m) in app.mods.iter().enumerate() { - rows = rows.push(mod_row( - m, - i, - enabled.contains(&m.id), - app.mod_sel.items.contains(&i), - )); - } - // External mods live in the same scroll region, past a divider - visible - // but read-only (no toggle, not selectable), so the user sees what is in - // the game folder that Modrix did not put there. - if !app.external.is_empty() { - rows = rows.push(external_header(app.external.len())); - for m in &app.external { - rows = rows.push(external_row(m)); - } - } - let listing = column![ - header_row(app), - scrollable(rows) - .id(iced::widget::scrollable::Id::new("mods-list")) - .on_scroll(|v| { - Message::Scrolled(Pane::Mods, v.absolute_offset().y, v.bounds().height) - }) - .height(Length::Fill), - text(summary_line(app)).size(12).color(theme::faint()), - ] - .spacing(8); - container(listing) - .padding(14) - .width(Length::Fill) - .height(Length::Fill) - .style(theme::card) - .into() -} - -fn summary_line(app: &App) -> String { - let mut line = format!( - "{} mods · {} enabled · {} plugins · {} mods are asset-only", - app.mods.len(), - app.order.len(), - app.plugin_counts.values().sum::(), - app.plugin_counts.values().filter(|c| **c == 0).count(), - ); - if !app.external.is_empty() { - use std::fmt::Write as _; - let _ = write!(line, " · {} external (not managed)", app.external.len()); - } - line -} - -/// The divider that separates managed rows from the read-only external list. -fn external_header(count: usize) -> El<'static> { - let plural = if count == 1 { "" } else { "s" }; - container( - column![ - text(format!( - "EXTERNAL - {count} mod{plural} already installed, not managed by Modrix" - )) - .size(10) - .color(theme::accent()), - text( - "Shown so you know they are here. Modrix does not enable, order, or remove \ - them - manage them where you installed them." - ) - .size(10) - .color(theme::faint()), - ] - .spacing(2), - ) - .padding([12, 12]) - .width(Length::Fill) - .into() -} - -/// A read-only external-mod row: no toggle, not selectable, muted. -fn external_row(m: &ExternalMod) -> El<'_> { - let files = format!( - "{} · {} file{}", - m.label, - m.files, - if m.files == 1 { "" } else { "s" } - ); - let inner = row![ - container(text("-").size(13).color(theme::faint())).width(48), - column![ - text(&m.name).size(13).color(theme::muted()), - text(files).size(10).color(theme::faint()), - ] - .spacing(2) - .width(Length::Fill), - container(text("EXTERNAL").size(10)) - .padding([2, 8]) - .style(theme::chip(theme::faint())), - ] - .spacing(10) - .align_y(Alignment::Center); - container(inner) - .width(Length::Fill) - .padding([7, 12]) - .style(theme::inset) - .into() -} - -/// Clickable column headers: click sorts, click again flips direction. -fn header_row(app: &App) -> El<'_> { - container( - row![ - sort_cell(app, "ON", SortKey::Enabled, 48), - sort_cell(app, "MOD", SortKey::Name, 0), - sort_cell(app, "ADDED", SortKey::Installed, 90), - sort_cell(app, "VERSION", SortKey::Version, 100), - sort_cell(app, "SOURCE", SortKey::Source, 150), - ] - .spacing(10), - ) - .padding([4, 12]) - .into() -} - -/// A compact "how long ago" for the ADDED column. Rows that predate the -/// provenance migration have no timestamp and show a dash. -fn added_label(created_at: Option) -> String { - let Some(at) = created_at else { - return "-".to_owned(); - }; - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX)); - let elapsed = now.saturating_sub(at).max(0); - match elapsed { - s if s < 60 => "just now".to_owned(), - s if s < 3_600 => format!("{}m ago", s / 60), - s if s < 86_400 => format!("{}h ago", s / 3_600), - s if s < 2_592_000 => format!("{}d ago", s / 86_400), - s => format!("{}mo ago", s / 2_592_000), - } -} - -fn sort_cell<'a>(app: &App, label: &'a str, key: SortKey, width: u16) -> El<'a> { - let (active_key, ascending) = app.mod_sort; - let mut cell = row![text(label).size(10).color(if active_key == key { - theme::accent() - } else { - theme::faint() - })] - .spacing(4) - .align_y(Alignment::Center); - if active_key == key { - cell = cell.push(icons::arrow::(ascending)); - } - let clickable = mouse_area(cell) - .interaction(iced::mouse::Interaction::Pointer) - .on_press(Message::SortBy(key)); - if width == 0 { - container(clickable).width(Length::Fill).into() - } else { - container(clickable).width(width).into() - } -} - -fn mod_row(m: &Mod, index: usize, enabled: bool, selected: bool) -> El<'_> { - let switch = toggler(enabled) - .on_toggle(move |now| Message::ToggleMod(m.id, now)) - .size(18) - .style(theme::toggle); - let mut tail = row![ - container(text(&m.source).size(10)) - .padding([2, 8]) - .style(theme::chip(theme::info())), - ] - .spacing(6) - .align_y(Alignment::Center); - if m.install_state.starts_with("fomod") { - tail = tail.push( - button(text("Options").size(11)) - .padding([3, 10]) - .style(theme::ghost) - .on_press(Message::Configure(m.id)), - ); - } - let inner = row![ - container(switch).width(48), - text(&m.name) - .size(13) - .color(if enabled { - theme::text() - } else { - theme::muted() - }) - .width(Length::Fill), - text(added_label(m.created_at)) - .size(12) - .color(theme::faint()) - .width(90), - text(m.version.as_deref().unwrap_or("-")) - .size(12) - .color(theme::muted()) - .width(100), - container(tail).width(150), - ] - .spacing(10) - .align_y(Alignment::Center); - let styled = container(inner) - .width(Length::Fill) - .padding([7, 12]) - .style(if selected { - theme::table_row_selected as fn(&iced::Theme) -> iced::widget::container::Style - } else if index.is_multiple_of(2) { - |t: &iced::Theme| theme::table_row(true)(t) - } else { - |t: &iced::Theme| theme::table_row(false)(t) - }); - mouse_area(styled) - .on_press(Message::RowClick { - pane: Pane::Mods, - index, - }) - .into() -} - -/// Click to browse, or drop archives anywhere on the window. -fn drop_zone() -> El<'static> { - let inner = column![ - text("Add mods").size(13).font(BOLD).color(theme::accent()), - text("Drop archives here, or click to browse") - .size(12) - .color(theme::muted()), - ] - .spacing(4) - .align_x(Alignment::Center); - mouse_area( - container(inner) - .padding([18, 24]) - .width(Length::Fill) - .align_x(Alignment::Center) - .style(theme::drop_zone), - ) - .interaction(iced::mouse::Interaction::Pointer) - .on_press(Message::PickFiles) - .into() -} diff --git a/crates/modrix-gui/src/view/settings.rs b/crates/modrix-gui/src/view/settings.rs deleted file mode 100644 index 43aca90..0000000 --- a/crates/modrix-gui/src/view/settings.rs +++ /dev/null @@ -1,295 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -//! The Settings screen: service pairing, locations, profiles, about. - -use iced::widget::{button, column, row, scrollable, text, text_input}; -use iced::{Alignment, Length}; - -use super::{BOLD, El, copy_button, labeled_card}; -use crate::app::{App, Message, UpdateState}; -use crate::theme; - -/// The settings body. -pub(super) fn body(app: &App) -> El<'_> { - scrollable( - column![ - theme_card(), - updates_card(app), - service_card(app), - extension_card(), - plugins_card(app), - locations_card(app), - profiles_card(app), - about_card(), - ] - .spacing(16), - ) - .height(Length::Fill) - .into() -} - -/// Update status: the installed version, and - when GitHub reports a newer -/// release - its notes plus a one-click install (Windows) or a manual link. -fn updates_card(app: &App) -> El<'_> { - let current = row![ - text("Installed").size(12).color(theme::muted()).width(130), - text(concat!("v", env!("CARGO_PKG_VERSION"))) - .size(12) - .width(Length::Fill), - ] - .spacing(10) - .align_y(Alignment::Center); - let inner: El<'_> = match &app.update { - UpdateState::Available(info) => update_available(false, info), - UpdateState::Installing(info) => update_available(true, info), - UpdateState::Idle => row![ - text("You're on the latest version.") - .size(12) - .color(theme::muted()) - .width(Length::Fill), - button(text("Check for updates").size(12)) - .padding([6, 12]) - .style(theme::ghost) - .on_press(Message::CheckUpdates), - ] - .spacing(10) - .align_y(Alignment::Center) - .into(), - }; - labeled_card("UPDATES", column![current, inner].spacing(12).into()) -} - -/// The "an update is available" body: version, a notes excerpt, and the action -/// (a self-install button on Windows, else a link to the release page). -fn update_available(updating: bool, info: &modrix_update::UpdateInfo) -> El<'static> { - let mut col = column![ - text(format!("Update available: v{}", info.version)) - .size(13) - .font(BOLD) - .color(theme::accent()), - ] - .spacing(8); - if !info.notes.is_empty() { - col = col.push( - text(notes_excerpt(&info.notes)) - .size(12) - .color(theme::faint()), - ); - } - if info.can_self_install() { - let label = if updating { - "Installing…" - } else { - "Download & install" - }; - let mut install = button(text(label).size(13)) - .padding([8, 16]) - .style(theme::primary); - if !updating { - install = install.on_press(Message::StartUpdate); - } - col.push(install).into() - } else { - col.push(kv_copy("Release", info.release_url.clone())) - .into() - } -} - -/// The first line of the release notes, trimmed to one short line. -fn notes_excerpt(notes: &str) -> String { - const MAX: usize = 160; - let first = notes.lines().next().unwrap_or("").trim(); - if first.chars().count() > MAX { - let head: String = first.chars().take(MAX).collect(); - format!("{head}…") - } else { - first.to_owned() - } -} - -/// The theme picker: every shipped theme, the active one marked. -fn theme_card() -> El<'static> { - let active = theme::spec().id; - let mut choices = row![].spacing(10); - for spec in theme::ALL { - let is_active = spec.id == active; - let label = if is_active { - format!("{} (active)", spec.name) - } else { - spec.name.to_owned() - }; - let mut pick = button(text(label).size(13)) - .padding([8, 16]) - .style(if is_active { - theme::primary - } else { - theme::ghost - }); - if !is_active { - pick = pick.on_press(Message::ThemePicked(spec.id.to_owned())); - } - choices = choices.push(pick); - } - labeled_card("THEME", choices.into()) -} - -/// Installed community plugins, with removal and cleanup. -fn plugins_card(app: &App) -> El<'_> { - let mut listing = column![].spacing(8); - if app.installed_plugins.is_empty() { - listing = listing.push( - text("None installed - game support fetched from the registry appears here.") - .size(12) - .color(theme::faint()), - ); - } - for plugin in &app.installed_plugins { - let in_use = app.games.iter().any(|g| g.plugin_id == plugin.id); - let mut remove = button(text("Remove").size(11)) - .padding([4, 10]) - .style(theme::danger_ghost); - if !in_use { - remove = remove.on_press(Message::UninstallPlugin(plugin.id.clone())); - } - let label = if in_use { "in use" } else { "" }; - listing = listing.push( - row![ - text(&plugin.name).size(13).width(Length::Fill), - text(format!("v{}", plugin.version)) - .size(12) - .color(theme::muted()), - text(label).size(11).color(theme::faint()), - remove, - ] - .spacing(10) - .align_y(Alignment::Center), - ); - } - let gc = button(text("Remove unused").size(12)) - .padding([6, 12]) - .style(theme::ghost) - .on_press(Message::GcPlugins); - labeled_card("COMMUNITY PLUGINS", column![listing, gc].spacing(12).into()) -} - -fn service_card(app: &App) -> El<'_> { - let inner: El<'_> = match (&app.link, app.already_running) { - (Some(link), _) => column![ - kv_copy("Address", format!("127.0.0.1:{}", link.port)), - kv_copy("Extension token", link.token.clone()), - text("Rotates each restart.").size(12).color(theme::faint()), - ] - .spacing(10) - .into(), - (None, true) => text("Another instance holds the port. Close it and restart the GUI.") - .size(13) - .color(theme::info()) - .into(), - (None, false) => text("The hand-off listener failed to start.") - .size(13) - .color(theme::danger()) - .into(), - }; - labeled_card("HAND-OFF SERVICE", inner) -} - -fn extension_card() -> El<'static> { - let steps = column![ - bullet("Load the `extension/` folder unpacked (developer mode)."), - bullet("That's it - no token or pairing needed while Modrix runs."), - bullet("Click Download on nexusmods.com."), - bullet("The token above is an advanced fallback (extension options)."), - ] - .spacing(6); - labeled_card("BROWSER EXTENSION", steps.into()) -} - -fn locations_card(app: &App) -> El<'_> { - let inner: El<'_> = match &app.paths { - Some(paths) => column![ - kv_copy("Data", paths.data_dir().display().to_string()), - kv_copy("Config", paths.config_dir().display().to_string()), - kv_copy("Cache", paths.cache_dir().display().to_string()), - text("Extra game definitions: /games//game.toml") - .size(12) - .color(theme::faint()), - ] - .spacing(10) - .into(), - None => text("Still starting…") - .size(13) - .color(theme::muted()) - .into(), - }; - labeled_card("LOCATIONS", inner) -} - -fn profiles_card(app: &App) -> El<'_> { - let mut listing = column![].spacing(6); - for profile in &app.profiles { - listing = listing.push( - row![ - text("•").size(15).color(if profile.is_active { - theme::accent() - } else { - theme::faint() - }), - text(&profile.name).size(13), - ] - .spacing(8) - .align_y(Alignment::Center), - ); - } - let form = row![ - text_input("New profile name", &app.form.profile_name) - .on_input(Message::ProfileNameChanged) - .on_submit(Message::CreateProfile) - .size(13) - .padding(9) - .style(theme::input), - button(text("Create").size(13)) - .padding([8, 16]) - .style(theme::ghost) - .on_press(Message::CreateProfile), - ] - .spacing(10) - .align_y(Alignment::Center); - labeled_card("PROFILES", column![listing, form].spacing(12).into()) -} - -fn about_card() -> El<'static> { - let inner = column![ - row![ - text("Modrix").size(14).font(BOLD), - text(concat!("v", env!("CARGO_PKG_VERSION"))) - .size(12) - .color(theme::muted()), - ] - .spacing(8) - .align_y(Alignment::Center), - text("GPL-2.0-only · no API keys · no telemetry") - .size(12) - .color(theme::faint()), - ] - .spacing(6); - labeled_card("ABOUT", inner.into()) -} - -fn kv_copy(label: &str, value: String) -> El<'_> { - row![ - text(label).size(12).color(theme::muted()).width(130), - text(value.clone()).size(12).width(Length::Fill), - copy_button(value), - ] - .spacing(10) - .align_y(Alignment::Center) - .into() -} - -fn bullet(line: &str) -> El<'_> { - row![ - text("·").size(13).color(theme::accent()), - text(line).size(12).color(theme::text()), - ] - .spacing(8) - .into() -} diff --git a/crates/modrix-gui/src/view/wizard.rs b/crates/modrix-gui/src/view/wizard.rs deleted file mode 100644 index 315d128..0000000 --- a/crates/modrix-gui/src/view/wizard.rs +++ /dev/null @@ -1,334 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-only -//! The FOMOD wizard: a modal that walks the installer's steps and groups. - -use iced::widget::{ - button, checkbox, column, container, mouse_area, opaque, row, scrollable, text, -}; -use iced::{Alignment, Length}; -use modrix_plugin::fomod; - -use super::{BOLD, El}; -use crate::app::{App, Message, Wizard}; -use crate::theme; - -/// The dimmed backdrop + centered wizard card. -/// -/// The whole layer is `opaque` so no event leaks through to the UI below, -/// and there is deliberately **no** click-outside-to-dismiss: passive spots -/// inside the card do not capture presses, so a backdrop dismiss handler -/// would swallow ordinary clicks and close the wizard. Only `×` closes. -pub(super) fn overlay<'a>(_app: &'a App, wizard: &'a Wizard) -> El<'a> { - let card = container(card_body(wizard)) - .padding(24) - .width(680) - .max_height(720) - .style(theme::card); - opaque( - container(card) - .center_x(Length::Fill) - .center_y(Length::Fill) - .style(theme::backdrop), - ) -} - -fn card_body(wizard: &Wizard) -> El<'_> { - let visible = wizard.visible_steps(); - let page = wizard.step.min(visible.len().saturating_sub(1)); - let Some(step_index) = visible.get(page).copied() else { - return finish_only(wizard); - }; - let flags = fomod::flags_of(&wizard.installer, &wizard.selections, &wizard.present); - let step = wizard.installer.steps.get(step_index); - let step_name = step.map_or("", |s| s.name.as_str()); - let mut groups = column![].spacing(16); - if let Some(step) = step { - for (g, group) in step.groups.iter().enumerate() { - groups = groups.push(group_view(wizard, step_index, g, group, &flags)); - } - } - let panes = row![ - // Fixed viewport: a Fill scrollable inside a shrink-sized modal - // collapses to zero height in iced - never use Fill here. - scrollable(groups).height(440).width(Length::Fill), - preview(wizard, step_index), - ] - .spacing(18); - column![ - header(wizard, step_name, page, visible.len()), - panes, - footer(page, visible.len()), - ] - .spacing(16) - .into() -} - -/// The right pane: image + description of the focused option (Vortex-style). -fn preview(wizard: &Wizard, current_step: usize) -> El<'_> { - let plugin = focused_plugin(wizard, current_step); - let mut pane = column![].spacing(10).width(300); - let image_rel = plugin - .and_then(|p| p.image.as_deref()) - .or(wizard.installer.module_image.as_deref()); - if let Some(rel) = image_rel - && let Some(path) = fomod::source_path(&wizard.staged_path, rel) - { - pane = pane.push(iced::widget::image(path).width(Length::Fill)); - } - match plugin { - Some(p) => { - pane = pane.push(text(&p.name).size(13).font(BOLD)); - let description = p.description.trim(); - if !description.is_empty() { - pane = pane.push( - scrollable(text(compact(description)).size(12).color(theme::muted())) - .height(Length::Fill), - ); - } - } - None => { - pane = pane.push( - text("Hover an option to preview it") - .size(12) - .color(theme::faint()), - ); - } - } - container(pane) - .padding(12) - .height(440) - .style(theme::inset) - .into() -} - -/// The plugin the preview shows: the hovered/last-touched one, else the first -/// selected on the current page. -fn focused_plugin(wizard: &Wizard, current_step: usize) -> Option<&fomod::Plugin> { - let lookup = |(s, g, p): (usize, usize, usize)| { - wizard.installer.steps.get(s)?.groups.get(g)?.plugins.get(p) - }; - if let Some(focus) = wizard.focus - && let Some(plugin) = lookup(focus) - { - return Some(plugin); - } - let step = wizard.installer.steps.get(current_step)?; - for (g, group) in step.groups.iter().enumerate() { - if let Some(first) = wizard - .selections - .get(current_step) - .and_then(|sg| sg.get(g)) - .and_then(|sel| sel.first()) - && let Some(plugin) = group.plugins.get(*first) - { - return Some(plugin); - } - } - None -} - -fn header<'a>(wizard: &'a Wizard, step_name: &'a str, page: usize, pages: usize) -> El<'a> { - let progress = format!("{} / {pages}", page.saturating_add(1)); - column![ - row![ - text(&wizard.mod_name) - .size(17) - .font(BOLD) - .width(Length::Fill), - button(text("×").size(15)) - .padding([2, 10]) - .style(theme::icon) - .on_press(Message::WizardCancel), - ] - .align_y(Alignment::Center), - row![ - text(step_name).size(13).color(theme::accent()), - iced::widget::Space::with_width(Length::Fill), - text(progress).size(12).color(theme::faint()), - ], - ] - .spacing(6) - .into() -} - -fn footer(page: usize, pages: usize) -> El<'static> { - let last = page.saturating_add(1) >= pages; - let mut bar = row![].spacing(10).align_y(Alignment::Center); - if page > 0 { - bar = bar.push( - button(text("Back").size(13)) - .padding([8, 16]) - .style(theme::ghost) - .on_press(Message::WizardBack), - ); - } - bar = bar.push(iced::widget::Space::with_width(Length::Fill)); - bar = bar.push(if last { - button(text("Install").size(13).font(BOLD)) - .padding([8, 20]) - .style(theme::primary) - .on_press(Message::WizardFinish) - } else { - button(text("Next").size(13)) - .padding([8, 20]) - .style(theme::primary) - .on_press(Message::WizardNext) - }); - bar.into() -} - -fn finish_only(wizard: &Wizard) -> El<'_> { - column![ - text(&wizard.mod_name).size(17).font(BOLD), - text("No options to choose").size(13).color(theme::muted()), - button(text("Install").size(13)) - .padding([8, 20]) - .style(theme::primary) - .on_press(Message::WizardFinish), - ] - .spacing(14) - .into() -} - -fn group_view<'a>( - wizard: &'a Wizard, - step: usize, - g: usize, - group: &'a fomod::Group, - flags: &std::collections::HashMap, -) -> El<'a> { - let mut items = column![].spacing(6); - let selected = wizard.selections.get(step).and_then(|s| s.get(g)); - for (p, plugin) in group.plugins.iter().enumerate() { - let slot = Slot { - step, - group: g, - plugin: p, - kind: fomod::plugin_kind(&plugin.kind, flags, &wizard.present), - on: selected.is_some_and(|s| s.contains(&p)), - group_kind: group.kind, - }; - items = items.push(plugin_row(plugin, slot)); - } - let mut head = row![].spacing(8).align_y(Alignment::Center); - // A single "select all" checkbox for checkbox-style groups (a patch hub - // has hundreds); checked when every usable option is already selected. - if matches!( - group.kind, - fomod::GroupKind::Any | fomod::GroupKind::AtLeastOne - ) { - let usable: Vec = group - .plugins - .iter() - .enumerate() - .filter(|(_, p)| { - fomod::plugin_kind(&p.kind, flags, &wizard.present) != fomod::PluginKind::NotUsable - }) - .map(|(i, _)| i) - .collect(); - let all_on = !usable.is_empty() - && usable - .iter() - .all(|i| selected.is_some_and(|s| s.contains(i))); - head = - head.push( - checkbox("", all_on) - .size(15) - .on_toggle(move |_| Message::WizardGroupSet { - step, - group: g, - all: !all_on, - }), - ); - } - // The name takes the flexible space (wrapping if long); the hint keeps - // its natural width - otherwise a long name squeezes it into a one- - // character-per-line sliver. - head = head - .push(text(&group.name).size(13).font(BOLD).width(Length::Fill)) - .push(text(rule_hint(group.kind)).size(11).color(theme::faint())); - column![head, items].spacing(8).into() -} - -const fn rule_hint(kind: fomod::GroupKind) -> &'static str { - match kind { - fomod::GroupKind::ExactlyOne => "pick one", - fomod::GroupKind::AtMostOne => "pick one or none", - fomod::GroupKind::AtLeastOne => "pick at least one", - fomod::GroupKind::Any => "pick any", - fomod::GroupKind::All => "all included", - } -} - -/// Everything a plugin row needs to render and route its toggle. -#[derive(Clone, Copy)] -struct Slot { - step: usize, - group: usize, - plugin: usize, - kind: fomod::PluginKind, - on: bool, - group_kind: fomod::GroupKind, -} - -fn plugin_row(plugin: &fomod::Plugin, slot: Slot) -> El<'_> { - let locked = matches!( - slot.kind, - fomod::PluginKind::Required | fomod::PluginKind::NotUsable - ) || slot.group_kind == fomod::GroupKind::All; - let mut check = checkbox(&plugin.name, slot.on).size(16).text_size(13); - if !locked { - let (step, group, plugin) = (slot.step, slot.group, slot.plugin); - check = check.on_toggle(move |_| Message::WizardPick { - step, - group, - plugin, - }); - } - let mut head = row![check].spacing(8).align_y(Alignment::Center); - if let Some((label, color)) = kind_chip(slot.kind) { - head = head.push( - container(text(label).size(9)) - .padding([1, 6]) - .style(theme::chip(color)), - ); - } - mouse_area(head) - .on_enter(Message::WizardHover { - step: slot.step, - group: slot.group, - plugin: slot.plugin, - }) - .into() -} - -fn kind_chip(kind: fomod::PluginKind) -> Option<(&'static str, iced::Color)> { - match kind { - fomod::PluginKind::Required => Some(("REQUIRED", theme::accent())), - fomod::PluginKind::Recommended => Some(("RECOMMENDED", theme::ok())), - fomod::PluginKind::NotUsable => Some(("UNAVAILABLE", theme::danger())), - fomod::PluginKind::CouldBeUsable => Some(("CHECK NOTES", theme::info())), - fomod::PluginKind::Optional => None, - } -} - -/// Collapse installer descriptions (often whole paragraphs of whitespace) -/// into a short readable line. -fn compact(description: &str) -> String { - let mut out = String::with_capacity(description.len().min(1200)); - let mut last_space = true; - for ch in description.chars().take(1200) { - if ch.is_whitespace() { - if !last_space { - out.push(' '); - } - last_space = true; - } else { - out.push(ch); - last_space = false; - } - } - if description.chars().count() > 1200 { - out.push('…'); - } - out -} diff --git a/crates/modrix-gui/src/wizard.rs b/crates/modrix-gui/src/wizard.rs new file mode 100644 index 0000000..acccfd2 --- /dev/null +++ b/crates/modrix-gui/src/wizard.rs @@ -0,0 +1,216 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! The FOMOD options wizard: opening it (parsed on the engine thread), +//! picking options with each group's rule, paging, applying and dismissing. + +use modrix_core::{Engine, ModId}; +use modrix_plugin::fomod; + +use crate::bus::Reply; +use crate::state::{App, Tone, Wizard}; + +impl App { + /// Pop the next queued mod into the wizard, if none is open. + pub fn open_next_wizard(&mut self) { + if self.wizard.is_some() || self.wizard_queue.is_empty() { + return; + } + let id = self.wizard_queue.remove(0); + self.configure(id); + } + + /// Open the wizard for a mod (parsing runs on the engine thread). + pub fn configure(&mut self, id: ModId) { + let Some(m) = self.lib.mods.iter().find(|m| m.id == id).cloned() else { + return; + }; + self.run( + false, + Box::new(move |e| { + let present = modrix_service::present_files(e, m.game_id); + match fomod::parse(&m.staged_path) { + Ok(Some(installer)) => { + let selections = fomod::defaults(&installer, &present); + Ok(Reply::Wizard(Box::new(Wizard { + mod_id: m.id, + mod_name: m.name, + staged_path: m.staged_path, + installer, + selections, + step: 0, + focus: None, + present, + }))) + } + Ok(None) => Ok(Reply::Note( + Tone::Info, + "No installer options in this mod".to_owned(), + )), + Err(error) => Err(error.to_string()), + } + }), + ); + } + + /// Check every usable option in a group, or clear all but Required. + pub fn wizard_group_set(&mut self, step: usize, group: usize, all: bool) { + let Some(wizard) = &mut self.wizard else { + return; + }; + let flags = fomod::flags_of(&wizard.installer, &wizard.selections, &wizard.present); + let Some(g) = wizard + .installer + .steps + .get(step) + .and_then(|s| s.groups.get(group)) + else { + return; + }; + if g.kind == fomod::GroupKind::All { + return; + } + let picked: std::collections::BTreeSet = g + .plugins + .iter() + .enumerate() + .filter(|(_, p)| { + let kind = fomod::plugin_kind(&p.kind, &flags, &wizard.present); + if all { + kind != fomod::PluginKind::NotUsable + } else { + kind == fomod::PluginKind::Required + } + }) + .map(|(i, _)| i) + .collect(); + if let Some(sel) = wizard + .selections + .get_mut(step) + .and_then(|s| s.get_mut(group)) + { + *sel = picked; + } + } + + /// Toggle an option by its group's rule. + pub fn wizard_pick(&mut self, step: usize, group: usize, plugin: usize) { + let Some(wizard) = &mut self.wizard else { + return; + }; + wizard.focus = Some((step, group, plugin)); + let Some(kind) = wizard + .installer + .steps + .get(step) + .and_then(|s| s.groups.get(group)) + .map(|g| g.kind) + else { + return; + }; + if let Some(sel) = wizard + .selections + .get_mut(step) + .and_then(|s| s.get_mut(group)) + { + pick(kind, sel, plugin); + } + } + + /// Next (+1) or previous (-1) page. + pub fn wizard_step(&mut self, delta: i8) { + let Some(wizard) = &mut self.wizard else { + return; + }; + let pages = wizard.visible_steps().len().max(1); + wizard.step = crate::actions::step(wizard.step, delta, pages); + } + + /// Apply the chosen options. + pub fn wizard_finish(&mut self) { + let Some(wizard) = self.wizard.take() else { + return; + }; + self.run(true, Box::new(move |e| apply(e, &wizard))); + self.open_next_wizard(); + } + + /// Close without applying: the defaults stand and the mod counts as + /// reviewed, so it is not offered again. + pub fn wizard_cancel(&mut self) { + if let Some(wizard) = self.wizard.take() { + let id = wizard.mod_id; + self.run( + false, + Box::new(move |e| { + e.set_install_state(id, "fomod") + .map(|()| Reply::Quiet) + .map_err(|e| e.to_string()) + }), + ); + } + self.open_next_wizard(); + } +} + +/// One option press under a group rule. +pub fn pick(kind: fomod::GroupKind, sel: &mut std::collections::BTreeSet, plugin: usize) { + match kind { + fomod::GroupKind::All => {} + fomod::GroupKind::ExactlyOne => { + sel.clear(); + sel.insert(plugin); + } + fomod::GroupKind::AtMostOne => { + let had = sel.remove(&plugin); + sel.clear(); + if !had { + sel.insert(plugin); + } + } + fomod::GroupKind::Any => { + if !sel.remove(&plugin) { + sel.insert(plugin); + } + } + fomod::GroupKind::AtLeastOne => { + if !sel.contains(&plugin) { + sel.insert(plugin); + } else if sel.len() > 1 { + sel.remove(&plugin); + } + } + } +} + +fn apply(e: &Engine, wizard: &Wizard) -> Result { + let ops = fomod::resolve(&wizard.installer, &wizard.selections, &wizard.present); + let placed = fomod::apply(&wizard.staged_path, &ops).map_err(|e| e.to_string())?; + e.set_install_state(wizard.mod_id, "fomod") + .map_err(|e| e.to_string())?; + Ok(Reply::Note( + Tone::Ok, + format!( + "Options applied to {}: {placed} files, deploy to update", + wizard.mod_name + ), + )) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::BTreeSet; + + #[test] + fn group_rules() { + let mut sel = BTreeSet::from([0]); + pick(fomod::GroupKind::ExactlyOne, &mut sel, 2); + assert_eq!(sel, BTreeSet::from([2])); + pick(fomod::GroupKind::AtMostOne, &mut sel, 2); + assert!(sel.is_empty()); + pick(fomod::GroupKind::AtLeastOne, &mut sel, 1); + pick(fomod::GroupKind::AtLeastOne, &mut sel, 1); + assert_eq!(sel, BTreeSet::from([1])); + pick(fomod::GroupKind::Any, &mut sel, 3); + assert_eq!(sel, BTreeSet::from([1, 3])); + } +} diff --git a/crates/modrix-il2cpp/Cargo.toml b/crates/modrix-il2cpp/Cargo.toml new file mode 100644 index 0000000..316c18b --- /dev/null +++ b/crates/modrix-il2cpp/Cargo.toml @@ -0,0 +1,17 @@ +# SPDX-License-Identifier: GPL-2.0-only +[package] +name = "modrix-il2cpp" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +description = "Reader for Unity IL2CPP global-metadata.dat, used to generate interop assemblies." + +[dependencies] +thiserror = { workspace = true } + +[dev-dependencies] + +[lints] +workspace = true diff --git a/crates/modrix-il2cpp/src/binary.rs b/crates/modrix-il2cpp/src/binary.rs new file mode 100644 index 0000000..c70d101 --- /dev/null +++ b/crates/modrix-il2cpp/src/binary.rs @@ -0,0 +1,544 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! The IL2CPP type system, which lives in `GameAssembly.dll` rather than in +//! `global-metadata.dat`. +//! +//! This split is the single most awkward thing about reading IL2CPP. The +//! metadata file says "field 12 has type index 4007", but the *type table* it +//! indexes into is compiled into the native binary, because a type's runtime +//! representation depends on the target. So generating a managed signature for +//! anything at all requires both files. +//! +//! The table is reached through `Il2CppMetadataRegistration`, a struct of +//! count/pointer pairs that the binary does not export and does not describe. +//! We find it the way every IL2CPP tool does: by **anchoring on a value we +//! already know**. Two of its counts - `fieldOffsetsCount` and +//! `typeDefinitionsSizesCount` - are both exactly the number of type +//! definitions, which the metadata file told us, and they sit two 8-byte slots +//! apart. Scanning the data sections for that pair, then checking that every +//! pointer field lands inside the image, identifies the struct unambiguously +//! (verified: exactly one match in a 100 MB binary). + +use crate::error::{Error, Result}; +use crate::pe::PeImage; +use crate::reader::Reader; + +/// Size of a pointer/count slot in the 64-bit registration struct. +const SLOT: usize = 8; +/// Slot index of `fieldOffsetsCount` within `Il2CppMetadataRegistration`. +const FIELD_OFFSETS_COUNT_SLOT: usize = 10; +/// Slot index of `typesCount`. +const TYPES_COUNT_SLOT: usize = 6; +/// Slot index of the `types` pointer. +const TYPES_PTR_SLOT: usize = 7; +/// Total slots we read from the struct. +const REGISTRATION_SLOTS: usize = 16; +/// Every pointer slot that must resolve inside the image for a candidate to be +/// believed. `metadataUsages` (slot 15) is legitimately null on v29, so it is +/// deliberately absent. +const POINTER_SLOTS: [usize; 7] = [1, 3, 5, 7, 9, 11, 13]; +/// Upper bound on entries in the type table. +const MAX_TYPES: usize = 4_000_000; + +/// `Il2CppTypeEnum` - the same discriminants as ECMA-335's `ELEMENT_TYPE_*`, +/// which is what makes translating a signature almost mechanical. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +#[non_exhaustive] +pub enum TypeKind { + /// `void` + Void = 0x01, + /// `bool` + Boolean = 0x02, + /// `char` + Char = 0x03, + /// `sbyte` + I1 = 0x04, + /// `byte` + U1 = 0x05, + /// `short` + I2 = 0x06, + /// `ushort` + U2 = 0x07, + /// `int` + I4 = 0x08, + /// `uint` + U4 = 0x09, + /// `long` + I8 = 0x0A, + /// `ulong` + U8 = 0x0B, + /// `float` + R4 = 0x0C, + /// `double` + R8 = 0x0D, + /// `string` + String = 0x0E, + /// Unmanaged pointer. + Ptr = 0x0F, + /// Managed reference (`ref`/`out`). + ByRef = 0x10, + /// A struct. + ValueType = 0x11, + /// A reference type. + Class = 0x12, + /// A generic type parameter (`T` on a type). + Var = 0x13, + /// A multi-dimensional array. + Array = 0x14, + /// A constructed generic type. + GenericInst = 0x15, + /// `System.TypedReference` + TypedByRef = 0x16, + /// `nint` + I = 0x18, + /// `nuint` + U = 0x19, + /// A function pointer. + FnPtr = 0x1B, + /// `object` + Object = 0x1C, + /// A vector (single-dimension, zero-based array). + SzArray = 0x1D, + /// A generic method parameter (`T` on a method). + MVar = 0x1E, +} + +impl TypeKind { + /// Map a raw discriminant, rejecting values this build does not model. + #[must_use] + pub const fn from_raw(raw: u8) -> Option { + Some(match raw { + 0x01 => Self::Void, + 0x02 => Self::Boolean, + 0x03 => Self::Char, + 0x04 => Self::I1, + 0x05 => Self::U1, + 0x06 => Self::I2, + 0x07 => Self::U2, + 0x08 => Self::I4, + 0x09 => Self::U4, + 0x0A => Self::I8, + 0x0B => Self::U8, + 0x0C => Self::R4, + 0x0D => Self::R8, + 0x0E => Self::String, + 0x0F => Self::Ptr, + 0x10 => Self::ByRef, + 0x11 => Self::ValueType, + 0x12 => Self::Class, + 0x13 => Self::Var, + 0x14 => Self::Array, + 0x15 => Self::GenericInst, + 0x16 => Self::TypedByRef, + 0x18 => Self::I, + 0x19 => Self::U, + 0x1B => Self::FnPtr, + 0x1C => Self::Object, + 0x1D => Self::SzArray, + 0x1E => Self::MVar, + _ => return None, + }) + } + + /// Whether this kind's `data` field carries a type-definition index rather + /// than a pointer to another structure. + #[must_use] + pub const fn data_is_type_index(self) -> bool { + matches!( + self, + Self::Class + | Self::ValueType + | Self::Void + | Self::Boolean + | Self::Char + | Self::I1 + | Self::U1 + | Self::I2 + | Self::U2 + | Self::I4 + | Self::U4 + | Self::I8 + | Self::U8 + | Self::R4 + | Self::R8 + | Self::String + | Self::I + | Self::U + | Self::Object + | Self::TypedByRef + ) + } +} + +/// One entry of the IL2CPP type table. +#[derive(Debug, Clone, Copy)] +pub struct Il2CppType { + /// What kind of type this is. + pub kind: TypeKind, + /// Kind-dependent payload: a type-definition index for `Class`/`ValueType` + /// and the primitives, otherwise an image pointer to a further structure + /// (a generic instantiation, an array shape, the element type). + pub data: u64, + /// Type attributes (visibility, `static`, and friends). + pub attrs: u16, + /// Whether this is a by-reference type. + pub by_ref: bool, +} + +/// The located `Il2CppMetadataRegistration`. +#[derive(Debug, Clone, Copy)] +pub struct Registration { + /// File offset of the struct itself. + pub offset: usize, + /// Number of entries in the type table. + pub types_count: usize, + /// File offset of the type table (an array of pointers to `Il2CppType`). + pub types_offset: usize, +} + +/// The native half of an IL2CPP game: `GameAssembly.dll`. +#[derive(Debug)] +pub struct GameBinary { + raw: Vec, + image: PeImage, + registration: Registration, + /// Offset -> table index, built on first use by [`GameBinary::type_index_of`]. + reverse_types: std::sync::OnceLock>, +} + +impl GameBinary { + /// Read `GameAssembly.dll` and locate its type table. + /// + /// `type_definitions` is the type-definition count from the metadata file; + /// it is the anchor the search keys on, so it must come from the *same* + /// game build. + /// + /// # Errors + /// + /// [`Error::Io`] if unreadable, [`Error::NotPe`] if it is not a 64-bit PE, + /// or [`Error::RegistrationNotFound`] if the anchor does not appear exactly + /// once - which means the layout changed and guessing would be unsafe. + pub fn open(path: &std::path::Path, type_definitions: usize) -> Result { + let raw = std::fs::read(path).map_err(|source| Error::Io { + path: path.to_path_buf(), + source, + })?; + Self::parse(raw, type_definitions) + } + + /// Parse an in-memory image. See [`GameBinary::open`]. + /// + /// # Errors + /// + /// As [`GameBinary::open`], minus the I/O case. + pub fn parse(raw: Vec, type_definitions: usize) -> Result { + let image = PeImage::parse(&raw)?; + let registration = find_registration(&raw, &image, type_definitions)?; + Ok(Self { + raw, + image, + registration, + reverse_types: std::sync::OnceLock::new(), + }) + } + + /// The located registration struct. + #[must_use] + pub const fn registration(&self) -> Registration { + self.registration + } + + /// The PE image, for callers that need to resolve their own pointers. + #[must_use] + pub const fn image(&self) -> &PeImage { + &self.image + } + + /// Number of entries in the type table. + #[must_use] + pub const fn type_count(&self) -> usize { + self.registration.types_count + } + + /// File offset of an image pointer. + /// + /// # Errors + /// + /// [`Error::Truncated`] if the pointer does not land inside the image. + pub(crate) fn offset_of(&self, pointer: u64) -> Result { + self.image.va_to_offset(pointer).ok_or(Error::Truncated { + offset: 0, + need: SLOT, + have: self.raw.len(), + }) + } + + /// The type-table index of an `Il2CppType` reached by pointer. + /// + /// Payload pointers name a type structure directly rather than by index, + /// but the rest of the reader works in indices, so the pointer is mapped + /// back through the table. The table is small enough (tens of thousands) + /// that a linear scan would be wasteful per lookup, so the reverse map is + /// built once, lazily. + /// + /// # Errors + /// + /// [`Error::Truncated`] if the pointer is not a table entry. + pub(crate) fn type_index_of(&self, pointer: u64) -> Result { + let offset = self.offset_of(pointer)?; + let index = self + .reverse_types + .get_or_init(|| self.build_reverse_map()) + .get(&offset) + .copied(); + index.ok_or(Error::Truncated { + offset, + need: SLOT, + have: self.raw.len(), + }) + } + + /// Map every type structure's file offset back to its table index. + fn build_reverse_map(&self) -> std::collections::HashMap { + let reader = Reader::new(&self.raw); + let mut map = std::collections::HashMap::with_capacity(self.registration.types_count); + for index in 0..self.registration.types_count { + let slot = self + .registration + .types_offset + .saturating_add(index.saturating_mul(SLOT)); + let Ok(va) = reader.u64_at(slot) else { + continue; + }; + if let Some(offset) = self.image.va_to_offset(va) { + map.entry(offset).or_insert(index); + } + } + map + } + + /// Read a `u64` at a file offset. + /// + /// # Errors + /// + /// [`Error::Truncated`] past the end of the file. + pub(crate) fn read_u64(&self, offset: usize) -> Result { + Reader::new(&self.raw).u64_at(offset) + } + + /// Read a `u32` at a file offset. + /// + /// # Errors + /// + /// [`Error::Truncated`] past the end of the file. + pub(crate) fn read_u32(&self, offset: usize) -> Result { + Reader::new(&self.raw).u32_at(offset) + } + + /// Read a `u8` at a file offset. + /// + /// # Errors + /// + /// [`Error::Truncated`] past the end of the file. + pub(crate) fn read_u8(&self, offset: usize) -> Result { + Reader::new(&self.raw).u8_at(offset) + } + + /// Read type-table entry `index`. + /// + /// # Errors + /// + /// [`Error::Truncated`] if the entry lies outside the file, or + /// [`Error::UnknownTypeKind`] for a discriminant this build does not model. + pub fn type_at(&self, index: usize) -> Result { + if index >= self.registration.types_count { + return Err(Error::BoundExceeded { + what: "type index", + limit: self.registration.types_count, + }); + } + let reader = Reader::new(&self.raw); + let slot = self + .registration + .types_offset + .saturating_add(index.saturating_mul(SLOT)); + let entry_va = reader.u64_at(slot)?; + let entry = self.image.va_to_offset(entry_va).ok_or(Error::Truncated { + offset: slot, + need: SLOT, + have: self.raw.len(), + })?; + // Il2CppType is { void* data; uint32 bitfield; } - 16 bytes with + // padding. The bitfield packs attrs:16, type:8, then flag bits. + let data = reader.u64_at(entry)?; + let bits = reader.u32_at(entry.saturating_add(SLOT))?; + let raw_kind = u8::try_from((bits >> 16) & 0xFF).unwrap_or(0); + let kind = TypeKind::from_raw(raw_kind).ok_or(Error::UnknownTypeKind { raw: raw_kind })?; + Ok(Il2CppType { + kind, + data, + attrs: u16::try_from(bits & 0xFFFF).unwrap_or(0), + by_ref: (bits >> 29) & 1 == 1, + }) + } +} + +/// Scan the image's data sections for `Il2CppMetadataRegistration`. +fn find_registration(raw: &[u8], image: &PeImage, type_definitions: usize) -> Result { + let anchor = (type_definitions as u64).to_le_bytes(); + let reader = Reader::new(raw); + let mut found: Option = None; + + for section in image.data_sections() { + let start = usize::try_from(section.raw_offset).unwrap_or(0); + let len = usize::try_from(section.raw_size).unwrap_or(0); + let Ok(body) = reader.slice(start, len) else { + continue; + }; + for hit in anchor_pairs(body, &anchor) { + let at = start.saturating_add(hit); + let Some(candidate) = validate_candidate(&reader, image, at) else { + continue; + }; + // A second match means the anchor is not discriminating on this + // build; refusing beats picking one at random. + if found.is_some() { + return Err(Error::RegistrationNotFound { + detail: "the anchor matched more than once - layout changed".to_owned(), + }); + } + found = Some(candidate); + } + } + found.ok_or(Error::RegistrationNotFound { + detail: format!( + "no Il2CppMetadataRegistration whose field/type-definition counts equal \ + {type_definitions}" + ), + }) +} + +/// Offsets where the anchor value appears twice, two slots apart - the +/// `fieldOffsetsCount` / `typeDefinitionsSizesCount` signature. +fn anchor_pairs<'a>(body: &'a [u8], anchor: &'a [u8; SLOT]) -> impl Iterator + 'a { + let gap = SLOT.saturating_mul(2); + body.windows(SLOT) + .enumerate() + .filter(move |(index, window)| { + if *window != anchor.as_slice() { + return false; + } + let second = index.saturating_add(gap); + body.get(second..second.saturating_add(SLOT)) == Some(anchor.as_slice()) + }) + .map(|(index, _)| index) +} + +/// Check that a candidate hit really is the registration struct, by requiring +/// every pointer field to land inside the image. +fn validate_candidate( + reader: &Reader<'_>, + image: &PeImage, + anchor_at: usize, +) -> Option { + let base = anchor_at.checked_sub(FIELD_OFFSETS_COUNT_SLOT.checked_mul(SLOT)?)?; + let mut slots = [0_u64; REGISTRATION_SLOTS]; + for (index, slot) in slots.iter_mut().enumerate() { + *slot = reader + .u64_at(base.checked_add(index.checked_mul(SLOT)?)?) + .ok()?; + } + if !POINTER_SLOTS.iter().all(|&i| { + slots + .get(i) + .copied() + .is_some_and(|p| image.is_image_pointer(p)) + }) { + return None; + } + let types_count = usize::try_from(*slots.get(TYPES_COUNT_SLOT)?).ok()?; + if types_count == 0 || types_count > MAX_TYPES { + return None; + } + let types_offset = image.va_to_offset(*slots.get(TYPES_PTR_SLOT)?)?; + Some(Registration { + offset: base, + types_count, + types_offset, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn real_game() -> Option<(std::path::PathBuf, std::path::PathBuf)> { + let home = std::env::var_os("HOME")?; + let root = std::path::Path::new(&home) + .join(".local/share/Steam/steamapps/common/Sons Of The Forest"); + let binary = root.join("GameAssembly.dll"); + let metadata = root.join("SonsOfTheForest_Data/il2cpp_data/Metadata/global-metadata.dat"); + (binary.exists() && metadata.exists()).then_some((binary, metadata)) + } + + #[test] + fn type_kind_maps_known_discriminants_and_rejects_others() { + assert_eq!(TypeKind::from_raw(0x08), Some(TypeKind::I4)); + assert_eq!(TypeKind::from_raw(0x1D), Some(TypeKind::SzArray)); + assert_eq!(TypeKind::from_raw(0x17), None, "0x17 is unassigned"); + assert_eq!(TypeKind::from_raw(0x00), None); + assert!(TypeKind::Class.data_is_type_index()); + assert!(!TypeKind::GenericInst.data_is_type_index()); + } + + #[test] + fn finds_the_registration_in_the_real_game_binary() { + let Some((binary, metadata)) = real_game() else { + return; // Game not installed. + }; + let md = crate::Metadata::open(&metadata).expect("metadata parses"); + let type_definitions = md.type_count().unwrap(); + + let game = GameBinary::open(&binary, type_definitions).expect("registration located"); + let reg = game.registration(); + assert!( + reg.types_count > 10_000, + "a Unity game has tens of thousands of types, got {}", + reg.types_count + ); + + // Decode every type and confirm the table is coherent: no unknown + // discriminants, and the class/valuetype payloads are in-range type + // definition indices rather than garbage. + let mut classes = 0_usize; + for index in 0..reg.types_count { + let ty = game.type_at(index).expect("every entry decodes"); + if matches!(ty.kind, TypeKind::Class | TypeKind::ValueType) { + classes = classes.saturating_add(1); + assert!( + usize::try_from(ty.data).unwrap_or(usize::MAX) < type_definitions, + "type {index} payload {} is not a valid type-definition index", + ty.data + ); + } + } + assert!( + classes > 1000, + "expected many class/valuetype entries, got {classes}" + ); + } + + #[test] + fn refuses_a_binary_whose_anchor_does_not_appear() { + let Some((binary, _)) = real_game() else { + return; + }; + let raw = std::fs::read(&binary).unwrap(); + // A count no build has: the search must fail rather than pick a + // plausible-looking struct. + assert!(matches!( + GameBinary::parse(raw, 7), + Err(Error::RegistrationNotFound { .. }) + )); + } +} diff --git a/crates/modrix-il2cpp/src/defs.rs b/crates/modrix-il2cpp/src/defs.rs new file mode 100644 index 0000000..80a1214 --- /dev/null +++ b/crates/modrix-il2cpp/src/defs.rs @@ -0,0 +1,301 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Fixed-layout metadata records: type, field, method and parameter definitions. +//! +//! IL2CPP stores members in flat, globally-shared tables. A type does not own +//! its fields; it owns a *run* - a start index and a count into the one big +//! field table, with every type's run laid out contiguously. Reading a type's +//! members therefore means slicing the shared table, not walking a list. +//! +//! The layouts below are not described anywhere in the file. They were derived +//! by checking which record size divides each section's byte length exactly, +//! then confirmed against invariants that cannot hold by coincidence: summing +//! every type's `field_count` reproduces the field table's row count exactly +//! (124,512 on the reference game), and likewise for methods (182,725) and +//! parameters (193,667). [`crate::Metadata::validate_member_runs`] re-checks +//! those sums on every file it opens, so a build whose layout differs is +//! rejected instead of silently misread. + +/// Byte size of `Il2CppTypeDefinition` in metadata v29. +pub(crate) const TYPE_DEF: usize = 88; +/// Byte size of `Il2CppFieldDefinition`. +pub(crate) const FIELD: usize = 12; +/// Byte size of `Il2CppMethodDefinition`. +pub(crate) const METHOD: usize = 32; +/// Byte size of `Il2CppParameterDefinition`. +pub(crate) const PARAM: usize = 12; +/// Byte size of `Il2CppGenericContainer` and `Il2CppGenericParameter` alike. +pub(crate) const GENERIC: usize = 16; +/// Byte size of `Il2CppPropertyDefinition`. +pub(crate) const PROPERTY: usize = 20; +/// Byte size of `Il2CppImageDefinition`. +pub(crate) const IMAGE: usize = 40; +/// Byte size of `Il2CppAssemblyDefinition`. +pub(crate) const ASSEMBLY: usize = 64; + +/// A run of member records owned by one type: `[start, start + count)` in the +/// corresponding shared table. A negative start means the type owns none. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Run { + /// First index in the shared table, or `None` when the run is empty. + pub start: Option, + /// How many records the run covers. + pub count: usize, +} + +impl Run { + /// Build a run from the raw start/count pair, normalising IL2CPP's + /// "negative means none" convention. + pub(crate) fn new(start: i32, count: u16) -> Self { + let count = usize::from(count); + Self { + start: usize::try_from(start).ok().filter(|_| count > 0), + count, + } + } + + /// The indices this run covers. + pub fn indices(self) -> impl Iterator { + let start = self.start.unwrap_or(0); + let count = if self.start.is_some() { self.count } else { 0 }; + (0..count).filter_map(move |offset| start.checked_add(offset)) + } + + /// One past the last index, for bounds checking. + pub(crate) fn end(self) -> usize { + self.start + .map_or(0, |start| start.saturating_add(self.count)) + } +} + +/// A type definition: a class, struct, interface, enum or delegate. +#[derive(Debug, Clone)] +pub struct TypeDef { + /// The type's own name, as IL2CPP records it (``List`1``). + pub name: String, + /// Its namespace, possibly empty. + pub namespace: String, + /// Index into the *binary's* type table for this type's own `Il2CppType`. + pub byval_type: i32, + /// Index into the binary's type table for the base type, or negative for + /// `System.Object` and interfaces. + pub parent_type: i32, + /// Index of the enclosing type definition, or negative when top-level. + pub declaring_type: i32, + /// Index into the generic-container table, or negative when non-generic. + pub generic_container: i32, + /// `TypeAttributes` - visibility, `sealed`, `abstract`, `interface`. + pub flags: u32, + /// This type's fields, as a run into the shared field table. + pub fields: Run, + /// This type's methods, as a run into the shared method table. + pub methods: Run, + /// This type's properties, as a run into the shared property table. + pub properties: Run, + /// This type's nested types, as a run into the shared nested-type table. + pub nested_types: Run, + /// The interfaces it implements, as a run into the shared interface table. + pub interfaces: Run, + /// Metadata token. + pub token: u32, +} + +impl TypeDef { + /// The namespace-qualified name, as a mod author would write it. + #[must_use] + pub fn full_name(&self) -> String { + if self.namespace.is_empty() { + self.name.clone() + } else { + format!("{}.{}", self.namespace, self.name) + } + } + + /// Whether this type is nested inside another. + #[must_use] + pub const fn is_nested(&self) -> bool { + self.declaring_type >= 0 + } + + /// Whether the type is visible outside its own assembly. Only public types + /// belong in a reference assembly a mod compiles against. + #[must_use] + pub const fn is_public(&self) -> bool { + // TypeAttributes.VisibilityMask = 0x07; Public = 1, NestedPublic = 2. + matches!(self.flags & 0x07, 1 | 2) + } +} + +/// A field definition. +#[derive(Debug, Clone)] +pub struct FieldDef { + /// The field name. + pub name: String, + /// Index into the binary's type table for the field's type. + pub type_index: i32, + /// Metadata token. + pub token: u32, +} + +/// A method definition. Bodies live in native code, so only the signature is +/// recoverable - which is exactly what a reference assembly needs. +#[derive(Debug, Clone)] +pub struct MethodDef { + /// The method name (`.ctor` for constructors, `get_X` for property getters). + pub name: String, + /// Index of the declaring type definition. + pub declaring_type: i32, + /// Index into the binary's type table for the return type. + pub return_type: i32, + /// This method's parameters, as a run into the shared parameter table. + pub parameters: Run, + /// Index into the generic-container table, or negative when non-generic. + pub generic_container: i32, + /// `MethodAttributes` - visibility, `static`, `virtual`, `abstract`. + pub flags: u16, + /// `MethodImplAttributes`. + pub impl_flags: u16, + /// vtable slot. + pub slot: u16, + /// Metadata token. + pub token: u32, +} + +impl MethodDef { + /// Whether the method is callable from outside its assembly. + #[must_use] + pub const fn is_public(&self) -> bool { + // MethodAttributes.MemberAccessMask = 0x07; Public = 6. + self.flags & 0x07 == 6 + } + + /// Whether the method is static. + #[must_use] + pub const fn is_static(&self) -> bool { + // MethodAttributes.Static = 0x0010. + self.flags & 0x0010 != 0 + } +} + +/// A property definition. +/// +/// IL2CPP stores a property as a name plus the *relative* indices of its +/// accessors within the declaring type's method run - not absolute method +/// indices - so resolving one requires the owning type's `methods.start`. +#[derive(Debug, Clone)] +pub struct PropertyDef { + /// The property name (`IsInWorld`). + pub name: String, + /// Getter index relative to the declaring type's method run, or negative. + pub get: i32, + /// Setter index relative to the declaring type's method run, or negative. + pub set: i32, + /// `PropertyAttributes`. + pub attrs: u32, + /// Metadata token. + pub token: u32, +} + +/// A type's or method's generic parameter list. +/// +/// IL2CPP records arity here rather than in the name (for methods) or only in +/// the name (for types), so this is the authoritative source. Inferring a +/// method's arity from the highest `!!N` its signature mentions is wrong for +/// `T AddComponent()`, whose arity is 1 but which may mention no parameter +/// at all in an erased signature. +#[derive(Debug, Clone)] +pub struct GenericContainer { + /// The declaring type or method index. + pub owner: i32, + /// How many generic parameters. + pub arg_count: i32, + /// True when the owner is a method rather than a type. + pub is_method: bool, + /// First index into the shared generic-parameter table. + pub param_start: i32, +} + +/// A parameter definition. +#[derive(Debug, Clone)] +pub struct ParamDef { + /// The parameter name. + pub name: String, + /// Index into the binary's type table for the parameter type. + pub type_index: i32, + /// Metadata token. + pub token: u32, +} + +/// One managed assembly the game was built from. +#[derive(Debug, Clone)] +pub struct Assembly { + /// The assembly name, without extension (`Assembly-CSharp`, `Sons`). + pub name: String, + /// Version, as `major.minor.build.revision`. + pub version: String, + /// The type definitions this assembly owns, as a run. + pub types: Run, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_run_with_a_negative_start_is_empty() { + let run = Run::new(-1, 0); + assert_eq!(run.start, None); + assert_eq!(run.indices().count(), 0); + assert_eq!(run.end(), 0); + } + + #[test] + fn a_zero_count_run_is_empty_even_with_a_valid_start() { + // IL2CPP writes a plausible start with a zero count for a type that + // declares no members; treating that as a one-element run would read a + // neighbouring type's first member. + let run = Run::new(500, 0); + assert_eq!(run.indices().count(), 0); + } + + #[test] + fn a_run_covers_exactly_its_span() { + let run = Run::new(10, 3); + assert_eq!(run.indices().collect::>(), vec![10, 11, 12]); + assert_eq!(run.end(), 13); + } + + #[test] + fn visibility_masks_match_the_ecma_encoding() { + let public = TypeDef { + name: "X".to_owned(), + namespace: String::new(), + byval_type: 0, + parent_type: -1, + declaring_type: -1, + generic_container: -1, + flags: 1, + fields: Run::new(-1, 0), + methods: Run::new(-1, 0), + properties: Run::new(-1, 0), + nested_types: Run::new(-1, 0), + interfaces: Run::new(-1, 0), + token: 0, + }; + assert!(public.is_public()); + assert!(!public.is_nested()); + + let internal = TypeDef { + flags: 0, + ..public.clone() + }; + assert!(!internal.is_public(), "NotPublic must not be exported"); + + let nested_public = TypeDef { + flags: 2, + declaring_type: 4, + ..public + }; + assert!(nested_public.is_public()); + assert!(nested_public.is_nested()); + } +} diff --git a/crates/modrix-il2cpp/src/error.rs b/crates/modrix-il2cpp/src/error.rs new file mode 100644 index 0000000..d119132 --- /dev/null +++ b/crates/modrix-il2cpp/src/error.rs @@ -0,0 +1,119 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Errors from reading IL2CPP metadata. + +/// Result alias for this crate. +pub type Result = std::result::Result; + +/// Why a metadata file could not be read. +#[derive(Debug, thiserror::Error)] +#[non_exhaustive] +pub enum Error { + /// The file does not begin with IL2CPP's magic number, so it is not + /// `global-metadata.dat` at all (a common symptom of a game update + /// leaving a partial download, or of pointing at the wrong file). + #[error("not IL2CPP metadata: expected sanity 0x{expected:08X}, found 0x{found:08X}")] + BadSanity { + /// The magic number IL2CPP writes. + expected: u32, + /// What was actually there. + found: u32, + }, + + /// The metadata version is one this build does not know how to read. + /// Record layouts change between versions with no in-band description, so + /// guessing would silently produce nonsense rather than fail. + #[error("unsupported IL2CPP metadata version {found} (this build reads {supported:?})")] + UnsupportedVersion { + /// The version in the file. + found: i32, + /// The versions this build understands. + supported: &'static [i32], + }, + + /// A read ran past the end of the file. + #[error("metadata truncated: needed {need} bytes at offset {offset}, file is {have} bytes")] + Truncated { + /// Where the read started. + offset: usize, + /// How many bytes it wanted. + need: usize, + /// How large the file actually is. + have: usize, + }, + + /// A string in the string table has no NUL terminator. + #[error("metadata string at offset {offset} is not NUL-terminated")] + Unterminated { + /// Where the string started. + offset: usize, + }, + + /// A section's byte size is not a whole number of its fixed-size records, + /// which means the layout assumption is wrong for this file. + #[error( + "metadata section `{section}` is {size} bytes, not a multiple of its {record}-byte record" + )] + RaggedSection { + /// The section name. + section: &'static str, + /// Its declared byte size. + size: usize, + /// The expected record size. + record: usize, + }, + + /// A count exceeded this build's fixed ceiling. + #[error("{what} exceeded its bound of {limit}")] + BoundExceeded { + /// What was being counted. + what: &'static str, + /// The ceiling. + limit: usize, + }, + + /// The file is not a 64-bit PE image, so it cannot be `GameAssembly.dll`. + #[error("not a 64-bit PE image: {detail}")] + NotPe { + /// What was wrong. + detail: String, + }, + + /// `Il2CppMetadataRegistration` could not be located in the binary. Its + /// layout is not described anywhere in the file, so it is found by + /// anchoring on counts the metadata already told us; failing that search + /// means the layout changed and guessing would produce silent nonsense. + #[error("could not locate the IL2CPP type table: {detail}")] + RegistrationNotFound { + /// What the search saw. + detail: String, + }, + + /// A type-table entry carries a discriminant this build does not model. + #[error("unknown IL2CPP type kind 0x{raw:02X}")] + UnknownTypeKind { + /// The raw discriminant. + raw: u8, + }, + + /// A cross-check on the record layout failed: per-type member counts did + /// not sum to the shared table's row count, or a run reached past its + /// table. The offsets this build assumes are wrong for this game. + #[error("metadata layout mismatch: {what} expected {expected}, found {found}")] + LayoutMismatch { + /// Which table disagreed. + what: &'static str, + /// What the table's own row count says. + expected: usize, + /// What summing the per-type runs produced. + found: usize, + }, + + /// The file could not be read from disk. + #[error("could not read `{path}`: {source}")] + Io { + /// The path. + path: std::path::PathBuf, + /// The underlying error. + source: std::io::Error, + }, +} diff --git a/crates/modrix-il2cpp/src/lib.rs b/crates/modrix-il2cpp/src/lib.rs new file mode 100644 index 0000000..093ced4 --- /dev/null +++ b/crates/modrix-il2cpp/src/lib.rs @@ -0,0 +1,244 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Reader for Unity's IL2CPP `global-metadata.dat`. +//! +//! ## Why this exists +//! +//! An IL2CPP game has no managed assemblies. Unity compiles C# to C++ ahead of +//! time, so the shipped game is `GameAssembly.dll` (native code) plus +//! `global-metadata.dat` (every type, method, field and string name, stripped +//! of bodies). There is no `Assembly-CSharp.dll` for a mod to reference. +//! +//! To make such a game moddable at all, a loader must read that metadata and +//! **generate managed proxy assemblies** - one .NET DLL per original assembly, +//! with the same namespaces, types and method signatures, whose bodies +//! marshal into the native code. Those generated DLLs are what a mod author +//! compiles against and what Harmony patches at runtime. +//! +//! This crate is the first half of that pipeline: it turns the binary metadata +//! into a structured model. It is deliberately **pure, safe Rust with no +//! `unsafe` and no FFI** - it only ever reads a file - which is why it can +//! live inside the main Modrix workspace under the same Power of Ten lints as +//! the deploy engine. +//! +//! ## Layout discovery +//! +//! Record sizes are not described in the file; they are implied by the version. +//! Rather than trusting a transcribed C header, the sizes here were derived +//! from a real game's metadata by checking which candidate size divides each +//! section's byte length exactly, and cross-checked against invariants that +//! must hold (every assembly has exactly one image, so those two counts match). +//! [`Metadata::parse`] re-checks divisibility on every file it reads, so a +//! version whose layout differs is rejected loudly rather than misread. + +mod binary; +mod defs; +mod error; +mod metadata; +mod pe; +mod reader; +mod resolve; + +pub use binary::{GameBinary, Il2CppType, Registration, TypeKind}; +pub use defs::{ + Assembly, FieldDef, GenericContainer, MethodDef, ParamDef, PropertyDef, Run, TypeDef, +}; +pub use error::{Error, Result}; +pub use metadata::{DefaultValue, Metadata, SANITY, SUPPORTED_VERSIONS}; +pub use pe::{PeImage, Section as PeSection}; +pub use resolve::ResolvedType; + +#[cfg(test)] +mod tests { + use std::path::Path; + + use super::*; + + /// The Sons of the Forest metadata on this machine, when it is installed. + /// Tests that need a real game are skipped elsewhere rather than failing + /// CI, which has no game directory. + fn real_metadata() -> Option { + let home = std::env::var_os("HOME")?; + let path = Path::new(&home).join( + ".local/share/Steam/steamapps/common/Sons Of The Forest/\ + SonsOfTheForest_Data/il2cpp_data/Metadata/global-metadata.dat", + ); + path.exists().then_some(path) + } + + #[test] + fn rejects_a_file_that_is_not_metadata() { + let raw = b"not il2cpp metadata at all".to_vec(); + assert!(matches!(Metadata::parse(raw), Err(Error::BadSanity { .. }))); + } + + #[test] + fn rejects_an_unknown_metadata_version() { + let mut raw = Vec::new(); + raw.extend_from_slice(&SANITY.to_le_bytes()); + raw.extend_from_slice(&99_i32.to_le_bytes()); + raw.resize(512, 0); + assert!(matches!( + Metadata::parse(raw), + Err(Error::UnsupportedVersion { found: 99, .. }) + )); + } + + #[test] + fn rejects_a_truncated_header() { + let mut raw = Vec::new(); + raw.extend_from_slice(&SANITY.to_le_bytes()); + raw.extend_from_slice(&29_i32.to_le_bytes()); + // Sanity and version are present but no section table follows. + assert!(matches!(Metadata::parse(raw), Err(Error::Truncated { .. }))); + } + + #[test] + fn reads_the_real_game_metadata() { + let Some(path) = real_metadata() else { + return; // Game not installed; covered by the synthetic tests. + }; + let md = Metadata::open(&path).expect("real metadata parses"); + assert_eq!(md.version(), 29); + + // Every assembly has exactly one image. If the record sizes were + // wrong these two would not agree, so this is the layout check. + let assemblies = md.assembly_count().unwrap(); + assert_eq!( + assemblies, + md.image_count().unwrap(), + "one image per assembly - a mismatch means the record layout is wrong" + ); + assert!(assemblies > 100, "a Unity game ships many assemblies"); + assert!(md.type_count().unwrap() > 10_000); + + // The game's own code must be in there, by name. + let names: Vec = md + .assemblies() + .unwrap() + .into_iter() + .map(|a| a.name) + .collect(); + for expected in ["Assembly-CSharp", "UnityEngine.CoreModule", "Sons"] { + assert!( + names.iter().any(|n| n == expected), + "expected assembly `{expected}` among {} assemblies", + names.len() + ); + } + } + + #[test] + fn reads_real_type_names() { + let Some(path) = real_metadata() else { + return; + }; + let md = Metadata::open(&path).unwrap(); + // Walk a bounded window and confirm we get plausible identifiers + // rather than binary noise - the check that string indices resolve. + let mut named = 0_usize; + for index in 0..2000.min(md.type_count().unwrap()) { + let def = md.type_def(index).unwrap(); + if !def.name.is_empty() && def.name.is_ascii() { + named = named.saturating_add(1); + } + } + assert!( + named > 1900, + "expected nearly every type to have a readable name, got {named}" + ); + } + + #[test] + fn decodes_a_real_type_with_its_members_and_signature_types() { + let Some(path) = real_metadata() else { + return; // Game not installed. + }; + let md = Metadata::open(&path).unwrap(); + + // LocalPlayer is the type every Sons of the Forest mod reaches for, so + // it is the right end-to-end canary: if its members decode, the shared + // field/method/parameter runs are being sliced correctly. + let target = (0..md.type_count().unwrap()) + .map(|i| (i, md.type_def(i).unwrap())) + .find(|(_, t)| t.namespace == "TheForest.Utils" && t.name == "LocalPlayer") + .map(|(_, t)| t) + .expect("TheForest.Utils.LocalPlayer exists in this game"); + + assert!(target.is_public()); + assert!(!target.is_nested()); + assert!(target.fields.count > 50, "LocalPlayer has many fields"); + assert!(target.methods.count > 50, "and many methods"); + + let field_names: Vec = target + .fields + .indices() + .map(|i| md.field_def(i).unwrap().name) + .collect(); + assert!( + field_names.iter().any(|n| n == "_transform"), + "expected the _transform field among {}", + field_names.len() + ); + + let methods: Vec = target + .methods + .indices() + .map(|i| md.method_def(i).unwrap()) + .collect(); + let getter = methods + .iter() + .find(|m| m.name == "get_IsInWorld") + .expect("LocalPlayer exposes IsInWorld"); + assert!(getter.is_public()); + assert!(getter.is_static(), "IsInWorld is a static property"); + + // Every method's declaring type must point back at some real type, and + // every parameter must resolve - that is what the emitter relies on. + for method in &methods { + assert!( + usize::try_from(method.declaring_type).unwrap_or(usize::MAX) + < md.type_count().unwrap() + ); + for index in method.parameters.indices() { + let param = md.param_def(index).unwrap(); + assert!(!param.name.is_empty(), "parameters are named"); + } + } + } + + #[test] + fn every_signature_type_index_resolves_against_the_game_binary() { + let Some(metadata) = real_metadata() else { + return; + }; + let binary = metadata + .parent() + .and_then(|p| p.parent()) + .and_then(|p| p.parent()) + .map(|root| root.join("GameAssembly.dll")) + .filter(|p| p.exists()); + let Some(binary) = binary else { + return; + }; + let md = Metadata::open(&metadata).unwrap(); + let types = md.type_count().unwrap(); + let game = GameBinary::open(&binary, types).unwrap(); + + // The metadata says "this field has type index N"; N indexes a table + // that lives in the BINARY. If these two files ever disagree, every + // emitted signature would be silently wrong - so check the join. + let type_table = game.type_count(); + let mut checked = 0_usize; + for index in 0..md.field_count().unwrap().min(20_000) { + let field = md.field_def(index).unwrap(); + let slot = usize::try_from(field.type_index).unwrap_or(usize::MAX); + assert!( + slot < type_table, + "field {index} type index {slot} is outside the {type_table}-entry type table" + ); + game.type_at(slot).expect("the referenced type decodes"); + checked = checked.saturating_add(1); + } + assert!(checked > 10_000, "checked {checked} field types"); + } +} diff --git a/crates/modrix-il2cpp/src/metadata.rs b/crates/modrix-il2cpp/src/metadata.rs new file mode 100644 index 0000000..a2fe5d0 --- /dev/null +++ b/crates/modrix-il2cpp/src/metadata.rs @@ -0,0 +1,687 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Reading `global-metadata.dat`: the section table and the record decoders. + +use std::path::Path; + +use crate::defs::{ + self as size, Assembly, FieldDef, GenericContainer, MethodDef, ParamDef, PropertyDef, Run, + TypeDef, +}; +use crate::error::{Error, Result}; +use crate::reader::Reader; + +/// IL2CPP's magic number at the head of every metadata file. +pub const SANITY: u32 = 0xFAB1_1BAF; + +/// Metadata versions this build understands. +pub const SUPPORTED_VERSIONS: &[i32] = &[29]; + +/// Ceiling on records in any one section, so a corrupt size cannot make us +/// try to allocate an enormous vector. +const MAX_RECORDS: usize = 4_000_000; + +/// Positional indices of the sections we read, within the header's flat array +/// of `(offset, size)` pairs. The order is fixed by the metadata version. +mod section { + /// The `#Strings`-equivalent blob of NUL-terminated names. + pub const STRINGS: usize = 2; + /// `Il2CppGenericParameter[]`. + pub const GENERIC_PARAMS: usize = 12; + /// `Il2CppGenericContainer[]`. + pub const GENERIC_CONTAINERS: usize = 14; + /// `Il2CppPropertyDefinition[]`. + pub const PROPERTIES: usize = 4; + /// `Il2CppMethodDefinition[]`. + pub const METHODS: usize = 5; + /// `Il2CppParameterDefinition[]`. + pub const PARAMS: usize = 10; + /// `Il2CppFieldDefaultValue[]` - field index, type index, blob offset. + pub const FIELD_DEFAULTS: usize = 7; + /// The shared blob holding field and parameter constant values. + pub const DEFAULT_DATA: usize = 8; + /// `Il2CppFieldDefinition[]`. + pub const FIELDS: usize = 11; + /// `int32[]` - each entry a binary type-table index for an implemented + /// interface. Types slice it via their `interfaces` run. + pub const INTERFACES: usize = 16; + /// `Il2CppTypeDefinition[]`. + pub const TYPE_DEFS: usize = 19; + /// `Il2CppImageDefinition[]`. + pub const IMAGES: usize = 20; + /// `Il2CppAssemblyDefinition[]`. + pub const ASSEMBLIES: usize = 21; +} + +/// A (offset, byte-size) pair naming one section of the metadata file. +#[derive(Debug, Clone, Copy, Default)] +struct MetaSection { + offset: usize, + size: usize, +} + +impl MetaSection { + /// How many fixed-size records this section holds. + fn records(self, name: &'static str, record: usize) -> Result { + if record == 0 || !self.size.is_multiple_of(record) { + return Err(Error::RaggedSection { + section: name, + size: self.size, + record, + }); + } + let count = self.size.checked_div(record).unwrap_or(0); + if count > MAX_RECORDS { + return Err(Error::BoundExceeded { + what: name, + limit: MAX_RECORDS, + }); + } + Ok(count) + } + + /// Byte offset of record `index`. + fn record_at(self, index: usize, record: usize) -> usize { + self.offset.saturating_add(index.saturating_mul(record)) + } +} + +/// A parsed `global-metadata.dat`. +#[derive(Debug)] +pub struct Metadata { + raw: Vec, + version: i32, + strings: MetaSection, + methods: MetaSection, + properties: MetaSection, + generic_params: MetaSection, + generic_containers: MetaSection, + params: MetaSection, + fields: MetaSection, + field_defaults: MetaSection, + default_data: MetaSection, + interfaces: MetaSection, + type_defs: MetaSection, + images: MetaSection, + assemblies: MetaSection, +} + +impl Metadata { + /// Read and validate a metadata file from disk. + /// + /// # Errors + /// + /// [`Error::Io`] if unreadable, [`Error::BadSanity`] if it is not IL2CPP + /// metadata, [`Error::UnsupportedVersion`] for an unknown layout, or + /// [`Error::RaggedSection`] if a section's size contradicts that layout. + pub fn open(path: &Path) -> Result { + let raw = std::fs::read(path).map_err(|source| Error::Io { + path: path.to_path_buf(), + source, + })?; + Self::parse(raw) + } + + /// Validate and index an in-memory metadata blob. + /// + /// # Errors + /// + /// As [`Metadata::open`], minus the I/O case. + pub fn parse(raw: Vec) -> Result { + let reader = Reader::new(&raw); + let found = reader.u32_at(0)?; + if found != SANITY { + return Err(Error::BadSanity { + expected: SANITY, + found, + }); + } + let version = reader.i32_at(4)?; + if !SUPPORTED_VERSIONS.contains(&version) { + return Err(Error::UnsupportedVersion { + found: version, + supported: SUPPORTED_VERSIONS, + }); + } + let parsed = Self { + version, + strings: read_section(&reader, section::STRINGS)?, + methods: read_section(&reader, section::METHODS)?, + properties: read_section(&reader, section::PROPERTIES)?, + generic_params: read_section(&reader, section::GENERIC_PARAMS)?, + generic_containers: read_section(&reader, section::GENERIC_CONTAINERS)?, + params: read_section(&reader, section::PARAMS)?, + fields: read_section(&reader, section::FIELDS)?, + field_defaults: read_section(&reader, section::FIELD_DEFAULTS)?, + default_data: read_section(&reader, section::DEFAULT_DATA)?, + interfaces: read_section(&reader, section::INTERFACES)?, + type_defs: read_section(&reader, section::TYPE_DEFS)?, + images: read_section(&reader, section::IMAGES)?, + assemblies: read_section(&reader, section::ASSEMBLIES)?, + raw, + }; + parsed.validate_member_runs()?; + Ok(parsed) + } + + /// The metadata schema version. + #[must_use] + pub const fn version(&self) -> i32 { + self.version + } + + fn reader(&self) -> Reader<'_> { + Reader::new(&self.raw) + } + + /// Read a name from the shared string blob by byte offset. + fn string(&self, index: i32) -> Result { + let offset = self + .strings + .offset + .saturating_add(usize::try_from(index).unwrap_or(0)); + self.reader().cstr_at(offset) + } + + /// Number of type definitions. + /// + /// # Errors + /// + /// [`Error::RaggedSection`] if the section size contradicts the layout. + pub fn type_count(&self) -> Result { + self.type_defs.records("typeDefinitions", size::TYPE_DEF) + } + + /// Number of field definitions. + /// + /// # Errors + /// + /// As [`Metadata::type_count`]. + pub fn field_count(&self) -> Result { + self.fields.records("fields", size::FIELD) + } + + /// Number of method definitions. + /// + /// # Errors + /// + /// As [`Metadata::type_count`]. + pub fn method_count(&self) -> Result { + self.methods.records("methods", size::METHOD) + } + + /// Number of parameter definitions. + /// + /// # Errors + /// + /// As [`Metadata::type_count`]. + pub fn param_count(&self) -> Result { + self.params.records("parameters", size::PARAM) + } + + /// Number of assemblies. Every assembly has exactly one image, so this + /// equals the image count; a mismatch means the layout is wrong. + /// + /// # Errors + /// + /// As [`Metadata::type_count`]. + pub fn assembly_count(&self) -> Result { + self.assemblies.records("assemblies", size::ASSEMBLY) + } + + /// Number of images. + /// + /// # Errors + /// + /// As [`Metadata::type_count`]. + pub fn image_count(&self) -> Result { + self.images.records("images", size::IMAGE) + } + + /// Cross-check the record layouts against invariants that cannot hold by + /// coincidence: every type's member counts must sum to exactly the shared + /// tables' row counts, and every run must stay in bounds. + /// + /// This is what turns "these offsets looked right on one game" into a + /// checked assumption. A build whose layout differs fails here rather than + /// silently producing garbage signatures. + /// + /// # Errors + /// + /// [`Error::LayoutMismatch`] if a sum or a bound does not hold. + pub fn validate_member_runs(&self) -> Result<()> { + let (types, fields, methods) = ( + self.type_count()?, + self.field_count()?, + self.method_count()?, + ); + let (mut field_sum, mut method_sum) = (0_usize, 0_usize); + for index in 0..types { + let def = self.type_def(index)?; + field_sum = field_sum.saturating_add(def.fields.count); + method_sum = method_sum.saturating_add(def.methods.count); + check_bound("field", def.fields, fields)?; + check_bound("method", def.methods, methods)?; + } + expect_sum("fields", field_sum, fields)?; + expect_sum("methods", method_sum, methods)?; + + let mut param_sum = 0_usize; + for index in 0..methods { + param_sum = param_sum.saturating_add(self.method_def(index)?.parameters.count); + } + expect_sum("parameters", param_sum, self.param_count()?) + } + + /// The binary type-table index of interface entry `index`. + /// + /// Types reach these through their `interfaces` run; the table is a flat + /// array of 4-byte indices shared by every type. + /// + /// # Errors + /// + /// [`Error::Truncated`] if the entry lies outside the file. + pub fn interface_type(&self, index: usize) -> Result { + self.reader().i32_at(self.interfaces.record_at(index, 4)) + } + + /// Number of entries in the shared interface table. + /// + /// # Errors + /// + /// As [`Metadata::type_count`]. + pub fn interface_count(&self) -> Result { + self.interfaces.records("interfaces", 4) + } + + /// Read the type definition at `index`. + /// + /// # Errors + /// + /// [`Error::Truncated`] if the record or one of its names lies outside the + /// file. + pub fn type_def(&self, index: usize) -> Result { + let base = self.type_defs.record_at(index, size::TYPE_DEF); + let r = self.reader(); + let at = |offset: usize| base.saturating_add(offset); + Ok(TypeDef { + name: self.string(r.i32_at(base)?)?, + namespace: self.string(r.i32_at(at(4))?)?, + byval_type: r.i32_at(at(8))?, + declaring_type: r.i32_at(at(12))?, + parent_type: r.i32_at(at(16))?, + generic_container: r.i32_at(at(24))?, + flags: r.u32_at(at(28))?, + fields: Run::new(r.i32_at(at(32))?, r.u16_at(at(68))?), + methods: Run::new(r.i32_at(at(36))?, r.u16_at(at(64))?), + properties: Run::new(r.i32_at(at(44))?, r.u16_at(at(66))?), + nested_types: Run::new(r.i32_at(at(48))?, r.u16_at(at(72))?), + interfaces: Run::new(r.i32_at(at(52))?, r.u16_at(at(76))?), + token: r.u32_at(at(84))?, + }) + } + + /// Read the field definition at `index`. + /// + /// # Errors + /// + /// [`Error::Truncated`] if the record lies outside the file. + pub fn field_def(&self, index: usize) -> Result { + let base = self.fields.record_at(index, size::FIELD); + let r = self.reader(); + Ok(FieldDef { + name: self.string(r.i32_at(base)?)?, + type_index: r.i32_at(base.saturating_add(4))?, + token: r.u32_at(base.saturating_add(8))?, + }) + } + + /// Read the method definition at `index`. + /// + /// # Errors + /// + /// [`Error::Truncated`] if the record lies outside the file. + pub fn method_def(&self, index: usize) -> Result { + let base = self.methods.record_at(index, size::METHOD); + let r = self.reader(); + let at = |offset: usize| base.saturating_add(offset); + Ok(MethodDef { + name: self.string(r.i32_at(base)?)?, + declaring_type: r.i32_at(at(4))?, + return_type: r.i32_at(at(8))?, + parameters: Run::new(r.i32_at(at(12))?, r.u16_at(at(30))?), + generic_container: r.i32_at(at(16))?, + token: r.u32_at(at(20))?, + flags: r.u16_at(at(24))?, + impl_flags: r.u16_at(at(26))?, + slot: r.u16_at(at(28))?, + }) + } + + /// Read the generic container at `index`, when the index is valid. + /// + /// A negative index means "not generic", which every caller has to handle, + /// so it is folded into `None` here rather than pushed onto them. + /// + /// # Errors + /// + /// [`Error::Truncated`] if the record lies outside the file. + pub fn generic_container(&self, index: i32) -> Result> { + let Ok(slot) = usize::try_from(index) else { + return Ok(None); + }; + if slot + >= self + .generic_containers + .records("genericContainers", size::GENERIC)? + { + return Ok(None); + } + let base = self.generic_containers.record_at(slot, size::GENERIC); + let r = self.reader(); + Ok(Some(GenericContainer { + owner: r.i32_at(base)?, + arg_count: r.i32_at(base.saturating_add(4))?, + is_method: r.i32_at(base.saturating_add(8))? != 0, + param_start: r.i32_at(base.saturating_add(12))?, + })) + } + + /// The declared names of a container's generic parameters (`T`, `TKey`). + /// + /// Using the real names rather than synthesised ones matters: they appear + /// in compiler diagnostics and in IDE tooltips a mod author reads. + /// + /// # Errors + /// + /// [`Error::Truncated`] if a record lies outside the file. + pub fn generic_param_names(&self, container: &GenericContainer) -> Result> { + let total = self + .generic_params + .records("genericParameters", size::GENERIC)?; + let start = usize::try_from(container.param_start).unwrap_or(0); + let count = usize::try_from(container.arg_count).unwrap_or(0).min(64); + let mut names = Vec::with_capacity(count); + for offset in 0..count { + let slot = start.saturating_add(offset); + if slot >= total { + break; + } + let base = self.generic_params.record_at(slot, size::GENERIC); + // Il2CppGenericParameter: ownerIndex, nameIndex, then constraints. + names.push(self.string(self.reader().i32_at(base.saturating_add(4))?)?); + } + Ok(names) + } + + /// Read the property definition at `index`. + /// + /// # Errors + /// + /// [`Error::Truncated`] if the record lies outside the file. + pub fn property_def(&self, index: usize) -> Result { + let base = self.properties.record_at(index, size::PROPERTY); + let r = self.reader(); + let at = |offset: usize| base.saturating_add(offset); + Ok(PropertyDef { + name: self.string(r.i32_at(base)?)?, + get: r.i32_at(at(4))?, + set: r.i32_at(at(8))?, + attrs: r.u32_at(at(12))?, + token: r.u32_at(at(16))?, + }) + } + + /// Number of property definitions. + /// + /// # Errors + /// + /// As [`Metadata::type_count`]. + pub fn property_count(&self) -> Result { + self.properties.records("properties", size::PROPERTY) + } + + /// Read the parameter definition at `index`. + /// + /// # Errors + /// + /// [`Error::Truncated`] if the record lies outside the file. + pub fn param_def(&self, index: usize) -> Result { + let base = self.params.record_at(index, size::PARAM); + let r = self.reader(); + Ok(ParamDef { + name: self.string(r.i32_at(base)?)?, + token: r.u32_at(base.saturating_add(4))?, + type_index: r.i32_at(base.saturating_add(8))?, + }) + } + + /// Read the assembly at `index`, including the type run its image owns. + /// + /// # Errors + /// + /// [`Error::Truncated`] if the record or its image lies outside the file. + pub fn assembly(&self, index: usize) -> Result { + let base = self.assemblies.record_at(index, size::ASSEMBLY); + let r = self.reader(); + let image_index = r.i32_at(base)?; + // Il2CppAssemblyDefinition: imageIndex, token, referencedAssemblyStart, + // referencedAssemblyCount, then an inline Il2CppAssemblyNameDefinition + // whose name comes first and whose version quad sits at +24. + let name_base = base.saturating_add(16); + let part = |slot: usize| -> Result { + r.u16_at( + name_base + .saturating_add(24) + .saturating_add(slot.saturating_mul(4)), + ) + }; + Ok(Assembly { + name: self.string(r.i32_at(name_base)?)?, + version: format!("{}.{}.{}.{}", part(0)?, part(1)?, part(2)?, part(3)?), + types: self.image_types(image_index)?, + }) + } + + /// The run of type definitions an image owns. + fn image_types(&self, image_index: i32) -> Result { + let index = usize::try_from(image_index).unwrap_or(0); + let base = self.images.record_at(index, size::IMAGE); + let r = self.reader(); + // Il2CppImageDefinition: nameIndex, assemblyIndex, typeStart, typeCount. + let start = r.i32_at(base.saturating_add(8))?; + let count = r.u32_at(base.saturating_add(12))?; + Ok(Run { + start: usize::try_from(start).ok().filter(|_| count > 0), + count: usize::try_from(count).unwrap_or(0), + }) + } + + /// Every assembly, in metadata order. + /// + /// # Errors + /// + /// As [`Metadata::assembly`]. + pub fn assemblies(&self) -> Result> { + let count = self.assembly_count()?; + (0..count).map(|index| self.assembly(index)).collect() + } +} + +/// Read one `(offset, size)` pair from the header's flat array. +fn read_section(reader: &Reader<'_>, index: usize) -> Result { + // The array starts after the 8-byte sanity + version prologue. + let base = 8_usize.saturating_add(index.saturating_mul(8)); + Ok(MetaSection { + offset: usize::try_from(reader.i32_at(base)?).unwrap_or(0), + size: usize::try_from(reader.i32_at(base.saturating_add(4))?).unwrap_or(0), + }) +} + +/// Fail when a per-type run reaches past its shared table. +fn check_bound(what: &'static str, run: Run, rows: usize) -> Result<()> { + if run.end() > rows { + return Err(Error::LayoutMismatch { + what, + expected: rows, + found: run.end(), + }); + } + Ok(()) +} + +/// Fail when the per-type counts do not sum to the shared table's row count. +fn expect_sum(what: &'static str, sum: usize, rows: usize) -> Result<()> { + if sum != rows { + return Err(Error::LayoutMismatch { + what, + expected: rows, + found: sum, + }); + } + Ok(()) +} + +/// A field's compile-time constant, as stored in the metadata's shared +/// default-value blob. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct DefaultValue { + /// Binary type-table index describing the constant's type. + pub type_index: i32, + /// The decoded value. Every constant IL2CPP stores for an enum member or a + /// `const` field is an integer, so one signed slot covers all of them. + pub value: i64, +} + +/// Read an ECMA-style compressed unsigned integer, returning it and its width. +/// +/// IL2CPP reuses the CLI blob compression: one byte under 0x80, two bytes under +/// 0xC0, four under 0xE0, and a 0xF0 escape carrying a raw 32-bit value. +fn read_compressed(reader: &Reader<'_>, offset: usize) -> Result<(u32, usize)> { + let first = reader.u8_at(offset)?; + let byte = |extra: usize| -> Result { + Ok(u32::from(reader.u8_at(offset.saturating_add(extra))?)) + }; + if first & 0x80 == 0 { + return Ok((u32::from(first), 1)); + } + if first & 0xC0 == 0x80 { + let high = u32::from(first & 0x3F) << 8; + return Ok((high | byte(1)?, 2)); + } + if first & 0xE0 == 0xC0 { + let value = (u32::from(first & 0x1F) << 24) | (byte(1)? << 16) | (byte(2)? << 8) | byte(3)?; + return Ok((value, 4)); + } + if first == 0xF0 { + let value = byte(1)? | (byte(2)? << 8) | (byte(3)? << 16) | (byte(4)? << 24); + return Ok((value, 5)); + } + // 0xFE / 0xFF are IL2CPP's sentinels for i32::MIN and "null"; neither can + // appear as an enum member, so treat the byte as a literal small value. + Ok((u32::from(first), 1)) +} + +/// Zig-zag decode: the encoding maps 0, -1, 1, -2 onto 0, 1, 2, 3, so a small +/// negative value still compresses to a single byte. +fn zigzag(encoded: u32) -> i64 { + let magnitude = i64::from(encoded >> 1); + if encoded & 1 == 1 { + magnitude.saturating_add(1).saturating_neg() + } else { + magnitude + } +} + +impl Metadata { + /// The compile-time constant of field `field_index`, when it has one. + /// + /// Only `const` fields and enum members carry one; everything else returns + /// `None`. The lookup is a linear scan of the default-value table, which is + /// why [`Metadata::default_values`] exists for bulk use. + /// + /// # Errors + /// + /// [`Error::Truncated`] if a record or the blob lies outside the file. + pub fn field_default_value(&self, field_index: usize) -> Result> { + Ok(self.default_values()?.remove(&field_index)) + } + + /// Every field constant, keyed by field index. + /// + /// Enum members are the reason this matters: ECMA-335 requires a `Constant` + /// row for every literal field, and a reference assembly that omits one + /// makes the *consumer* fail with an opaque `CS7038` rather than a useful + /// diagnostic. + /// + /// # Errors + /// + /// [`Error::Truncated`] if a record or the blob lies outside the file. + pub fn default_values(&self) -> Result> { + let count = self.field_defaults.records("fieldDefaultValues", 12)?; + let reader = self.reader(); + let mut out = std::collections::HashMap::with_capacity(count); + for index in 0..count { + let base = self.field_defaults.record_at(index, 12); + let field = reader.i32_at(base)?; + let type_index = reader.i32_at(base.saturating_add(4))?; + let data = reader.i32_at(base.saturating_add(8))?; + let (Ok(field), Ok(data)) = (usize::try_from(field), usize::try_from(data)) else { + continue; + }; + let at = self.default_data.offset.saturating_add(data); + let (encoded, _) = read_compressed(&reader, at)?; + out.insert( + field, + DefaultValue { + type_index, + value: zigzag(encoded), + }, + ); + } + Ok(out) + } +} + +#[cfg(test)] +mod default_value_tests { + use super::*; + + #[test] + fn zigzag_round_trips_the_documented_mapping() { + assert_eq!(zigzag(0), 0); + assert_eq!(zigzag(1), -1); + assert_eq!(zigzag(2), 1); + assert_eq!(zigzag(3), -2); + // RainType { None, Light, Medium, Heavy } stores 0, 2, 4, 6. + assert_eq!(zigzag(4), 2); + assert_eq!(zigzag(6), 3); + } + + #[test] + fn compressed_reader_handles_every_width() { + // One byte under 0x80. + let one = [0x06_u8]; + assert_eq!(read_compressed(&Reader::new(&one), 0).unwrap(), (6, 1)); + // Two bytes: 0x80 | high bits, then the low byte. 0x8200 -> 0x200 = 512. + let two = [0x82_u8, 0x00]; + assert_eq!(read_compressed(&Reader::new(&two), 0).unwrap(), (0x200, 2)); + // Four bytes with the 0xC0 tag. + let four = [0xC0_u8, 0x00, 0x10, 0x00]; + assert_eq!( + read_compressed(&Reader::new(&four), 0).unwrap(), + (0x1000, 4) + ); + // The 0xF0 escape carries a little-endian u32. + let esc = [0xF0_u8, 0x78, 0x56, 0x34, 0x12]; + assert_eq!( + read_compressed(&Reader::new(&esc), 0).unwrap(), + (0x1234_5678, 5) + ); + } + + #[test] + fn refuses_to_read_a_compressed_value_past_the_end() { + let truncated = [0x82_u8]; + assert!(read_compressed(&Reader::new(&truncated), 0).is_err()); + } +} diff --git a/crates/modrix-il2cpp/src/pe.rs b/crates/modrix-il2cpp/src/pe.rs new file mode 100644 index 0000000..c5a9dcf --- /dev/null +++ b/crates/modrix-il2cpp/src/pe.rs @@ -0,0 +1,193 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! A minimal, bounded PE32+ reader. +//! +//! `GameAssembly.dll` is a 100 MB native image. We do not load or execute any +//! of it - we only need to translate the virtual addresses stored inside it +//! into file offsets so the IL2CPP registration tables can be read. That is a +//! pure parsing job, so it stays safe Rust with no `unsafe` and no FFI. +//! +//! Only the parts of the format we actually use are decoded: the DOS stub's +//! `e_lfanew`, the COFF header's section count, the optional header's image +//! base, and the section table. Everything else is skipped. + +use crate::error::{Error, Result}; +use crate::reader::Reader; + +/// `PE\0\0`. +const PE_SIGNATURE: u32 = 0x0000_4550; +/// `IMAGE_FILE_MACHINE_AMD64`. +const MACHINE_AMD64: u16 = 0x8664; +/// `IMAGE_NT_OPTIONAL_HDR64_MAGIC`. +const PE32_PLUS: u16 = 0x020B; +/// A PE may not declare more sections than this; guards the section loop. +const MAX_SECTIONS: usize = 96; + +/// One mapped section of the image. +#[derive(Debug, Clone)] +pub struct Section { + /// Section name, trimmed of its NUL padding (`.text`, `.rdata`, `il2cpp`). + pub name: String, + /// Address relative to the image base once loaded. + pub virtual_address: u32, + /// Size the section occupies in memory. + pub virtual_size: u32, + /// Offset of the section's bytes in the file. + pub raw_offset: u32, + /// Number of bytes actually present in the file. + pub raw_size: u32, +} + +impl Section { + /// The span this section covers once loaded. A section's in-memory size + /// can exceed its on-disk size (BSS-style padding), and occasionally the + /// reverse, so the larger of the two is used when testing containment. + fn span(&self) -> u32 { + self.virtual_size.max(self.raw_size) + } +} + +/// A parsed PE32+ image: enough to map virtual addresses back to file offsets. +#[derive(Debug)] +pub struct PeImage { + /// The address the image is linked to load at. + pub image_base: u64, + /// The section table. + pub sections: Vec
, +} + +impl PeImage { + /// Parse the headers of a PE32+ image. + /// + /// # Errors + /// + /// [`Error::NotPe`] if the file is not a 64-bit PE, or [`Error::Truncated`] + /// if a header runs past the end of the buffer. + pub fn parse(data: &[u8]) -> Result { + let reader = Reader::new(data); + // The DOS header stores the PE header's offset at 0x3C. + let pe_offset = usize::try_from(reader.u32_at(0x3C)?).unwrap_or(0); + if reader.u32_at(pe_offset)? != PE_SIGNATURE { + return Err(Error::NotPe { + detail: "no PE signature".to_owned(), + }); + } + let coff = pe_offset.saturating_add(4); + let machine = reader.u16_at(coff)?; + if machine != MACHINE_AMD64 { + return Err(Error::NotPe { + detail: format!("machine 0x{machine:04X} is not x86-64"), + }); + } + let section_count = usize::from(reader.u16_at(coff.saturating_add(2))?); + if section_count > MAX_SECTIONS { + return Err(Error::BoundExceeded { + what: "PE sections", + limit: MAX_SECTIONS, + }); + } + let optional_size = usize::from(reader.u16_at(coff.saturating_add(16))?); + let optional = coff.saturating_add(20); + if reader.u16_at(optional)? != PE32_PLUS { + return Err(Error::NotPe { + detail: "not PE32+ (a 32-bit game is not supported)".to_owned(), + }); + } + // PE32+ places ImageBase at optional header offset 24 as a u64. + let image_base = reader.u64_at(optional.saturating_add(24))?; + + let table = optional.saturating_add(optional_size); + let mut sections = Vec::with_capacity(section_count); + for index in 0..section_count { + let entry = table.saturating_add(index.saturating_mul(40)); + sections.push(Section { + name: reader.fixed_str(entry, 8)?, + virtual_size: reader.u32_at(entry.saturating_add(8))?, + virtual_address: reader.u32_at(entry.saturating_add(12))?, + raw_size: reader.u32_at(entry.saturating_add(16))?, + raw_offset: reader.u32_at(entry.saturating_add(20))?, + }); + } + Ok(Self { + image_base, + sections, + }) + } + + /// Translate a relative virtual address to a file offset. + #[must_use] + pub fn rva_to_offset(&self, rva: u32) -> Option { + let section = self.sections.iter().find(|s| { + rva >= s.virtual_address && rva < s.virtual_address.saturating_add(s.span()) + })?; + let delta = rva.checked_sub(section.virtual_address)?; + usize::try_from(section.raw_offset.checked_add(delta)?).ok() + } + + /// Translate an absolute virtual address (as stored in the image's own + /// pointers) to a file offset. Returns `None` for a null or out-of-image + /// pointer, which is how callers validate a candidate structure. + #[must_use] + pub fn va_to_offset(&self, va: u64) -> Option { + let rva = va.checked_sub(self.image_base)?; + self.rva_to_offset(u32::try_from(rva).ok()?) + } + + /// Whether `va` points somewhere inside this image. Used to sanity-check a + /// candidate registration struct before trusting it. + #[must_use] + pub fn is_image_pointer(&self, va: u64) -> bool { + self.va_to_offset(va).is_some() + } + + /// Sections that can hold initialised data structures. + /// + /// The registration tables are constant data, so only these are scanned - + /// searching `.text` would waste time on 5 MB of code and risk matching an + /// immediate operand that happens to equal the anchor value. + pub fn data_sections(&self) -> impl Iterator { + self.sections + .iter() + .filter(|s| matches!(s.name.as_str(), ".rdata" | ".data" | "il2cpp")) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rejects_a_non_pe_buffer() { + let data = vec![0_u8; 512]; + assert!(matches!(PeImage::parse(&data), Err(Error::NotPe { .. }))); + } + + #[test] + fn rejects_a_truncated_buffer() { + let data = [0_u8; 4]; + assert!(PeImage::parse(&data).is_err()); + } + + #[test] + fn maps_addresses_within_a_section_and_rejects_those_outside() { + let image = PeImage { + image_base: 0x1_8000_0000, + sections: vec![Section { + name: ".rdata".to_owned(), + virtual_address: 0x1000, + virtual_size: 0x2000, + raw_offset: 0x400, + raw_size: 0x2000, + }], + }; + assert_eq!(image.rva_to_offset(0x1000), Some(0x400)); + assert_eq!(image.rva_to_offset(0x1FFF), Some(0x13FF)); + assert_eq!(image.rva_to_offset(0x3000), None, "past the section end"); + assert_eq!(image.rva_to_offset(0x0FFF), None, "before the section"); + assert_eq!(image.va_to_offset(0x1_8000_1000), Some(0x400)); + assert!(!image.is_image_pointer(0), "null is never an image pointer"); + assert!( + !image.is_image_pointer(0x1_0000_0000), + "below the image base" + ); + } +} diff --git a/crates/modrix-il2cpp/src/reader.rs b/crates/modrix-il2cpp/src/reader.rs new file mode 100644 index 0000000..0b31dcc --- /dev/null +++ b/crates/modrix-il2cpp/src/reader.rs @@ -0,0 +1,213 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! A bounded little-endian reader over an in-memory metadata blob. +//! +//! Every accessor is fallible and range-checked. `global-metadata.dat` is +//! attacker-reachable in the sense that matters here - it is a 26 MB binary +//! from a game directory Modrix does not control, and a truncated or hostile +//! one must produce an error, never a panic or an out-of-bounds read. Slicing +//! is done with `get`, never `[..]`, so a malformed offset returns `None` +//! rather than aborting the process. + +use crate::error::{Error, Result}; + +/// A read-only cursor over the metadata blob. +#[derive(Debug, Clone, Copy)] +pub struct Reader<'a> { + data: &'a [u8], +} + +impl<'a> Reader<'a> { + /// Wrap a metadata blob. + #[must_use] + pub const fn new(data: &'a [u8]) -> Self { + Self { data } + } + + /// Read a little-endian `i32` at `offset`. + /// + /// # Errors + /// + /// [`Error::Truncated`] if four bytes are not available there. + pub fn i32_at(&self, offset: usize) -> Result { + let end = offset.checked_add(4).ok_or(Error::Truncated { + offset, + need: 4, + have: self.data.len(), + })?; + let bytes = self + .data + .get(offset..end) + .ok_or(Error::Truncated { + offset, + need: 4, + have: self.data.len(), + })? + .try_into() + .map_err(|_| Error::Truncated { + offset, + need: 4, + have: self.data.len(), + })?; + Ok(i32::from_le_bytes(bytes)) + } + + /// Read a little-endian `u32` at `offset`. + /// + /// # Errors + /// + /// [`Error::Truncated`] if four bytes are not available there. + pub fn u32_at(&self, offset: usize) -> Result { + self.i32_at(offset).map(i32::cast_unsigned) + } + + /// Read a little-endian `u16` at `offset`. + /// + /// # Errors + /// + /// [`Error::Truncated`] if two bytes are not available there. + pub fn u16_at(&self, offset: usize) -> Result { + let end = offset.checked_add(2).ok_or(Error::Truncated { + offset, + need: 2, + have: self.data.len(), + })?; + let bytes = self + .data + .get(offset..end) + .ok_or(Error::Truncated { + offset, + need: 2, + have: self.data.len(), + })? + .try_into() + .map_err(|_| Error::Truncated { + offset, + need: 2, + have: self.data.len(), + })?; + Ok(u16::from_le_bytes(bytes)) + } + + /// Read a single byte at `offset`. + /// + /// # Errors + /// + /// [`Error::Truncated`] if the offset is past the end. + pub fn u8_at(&self, offset: usize) -> Result { + self.data.get(offset).copied().ok_or(Error::Truncated { + offset, + need: 1, + have: self.data.len(), + }) + } + + /// Read a little-endian `u64` at `offset`. + /// + /// # Errors + /// + /// [`Error::Truncated`] if eight bytes are not available there. + pub fn u64_at(&self, offset: usize) -> Result { + let lo = u64::from(self.u32_at(offset)?); + let hi = u64::from(self.u32_at(offset.saturating_add(4))?); + Ok((hi << 32) | lo) + } + + /// Borrow the `len` bytes at `offset`. + /// + /// # Errors + /// + /// [`Error::Truncated`] if that range is not wholly inside the blob. + pub fn slice(&self, offset: usize, len: usize) -> Result<&'a [u8]> { + let end = offset.checked_add(len).ok_or(Error::Truncated { + offset, + need: len, + have: self.data.len(), + })?; + self.data.get(offset..end).ok_or(Error::Truncated { + offset, + need: len, + have: self.data.len(), + }) + } + + /// Read a fixed-width, NUL-padded field as a string (PE section names). + /// + /// # Errors + /// + /// [`Error::Truncated`] if the field lies outside the blob. + pub fn fixed_str(&self, offset: usize, len: usize) -> Result { + let raw = self.slice(offset, len)?; + let end = raw.iter().position(|&b| b == 0).unwrap_or(raw.len()); + Ok(String::from_utf8_lossy(raw.get(..end).unwrap_or(&[])).into_owned()) + } + + /// Read the NUL-terminated UTF-8 string starting at `offset`. + /// + /// IL2CPP's string table is a single blob of NUL-terminated names indexed + /// by byte offset. Names are ordinary identifiers, but a corrupt table + /// could point mid-sequence, so decoding is lossy rather than fallible - + /// a mangled name is far better than refusing to read the whole game. + /// + /// # Errors + /// + /// [`Error::Truncated`] if `offset` is past the end of the blob, or + /// [`Error::Unterminated`] if no NUL follows within the bound. + pub fn cstr_at(&self, offset: usize) -> Result { + let rest = self.data.get(offset..).ok_or(Error::Truncated { + offset, + need: 1, + have: self.data.len(), + })?; + let end = rest + .iter() + .position(|&b| b == 0) + .ok_or(Error::Unterminated { offset })?; + let bytes = rest.get(..end).unwrap_or(&[]); + Ok(String::from_utf8_lossy(bytes).into_owned()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_little_endian_scalars() { + let data = [0x01, 0x02, 0x03, 0x04, 0xFF, 0xFF]; + let r = Reader::new(&data); + assert_eq!(r.i32_at(0).unwrap(), 0x0403_0201); + assert_eq!(r.u16_at(4).unwrap(), 0xFFFF); + } + + #[test] + fn refuses_to_read_past_the_end() { + let data = [0x01, 0x02]; + let r = Reader::new(&data); + assert!(matches!(r.i32_at(0), Err(Error::Truncated { .. }))); + assert!(matches!(r.i32_at(usize::MAX), Err(Error::Truncated { .. }))); + assert!(matches!(r.u16_at(1), Err(Error::Truncated { .. }))); + } + + #[test] + fn reads_nul_terminated_strings() { + let data = b"System.Object\0Foo\0"; + let r = Reader::new(data); + assert_eq!(r.cstr_at(0).unwrap(), "System.Object"); + assert_eq!(r.cstr_at(14).unwrap(), "Foo"); + } + + #[test] + fn rejects_an_unterminated_string() { + let data = b"no terminator"; + let r = Reader::new(data); + assert!(matches!(r.cstr_at(0), Err(Error::Unterminated { .. }))); + } + + #[test] + fn decodes_invalid_utf8_lossily_rather_than_failing() { + // A corrupt name must not make the whole game unreadable. + let data = b"bad\xFFname\0"; + let r = Reader::new(data); + assert!(r.cstr_at(0).unwrap().contains("bad")); + } +} diff --git a/crates/modrix-il2cpp/src/resolve.rs b/crates/modrix-il2cpp/src/resolve.rs new file mode 100644 index 0000000..8ae90ae --- /dev/null +++ b/crates/modrix-il2cpp/src/resolve.rs @@ -0,0 +1,265 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Turning a raw `Il2CppType` into a shape a managed signature can be written +//! from. +//! +//! A type-table entry is a tagged union: the `data` word means something +//! different for every kind. `Class`/`ValueType` and the primitives store a +//! type-definition index; `SzArray`/`Ptr`/`ByRef` store a pointer to the +//! element's own `Il2CppType`; `GenericInst` stores a pointer to an +//! `Il2CppGenericClass`; `Var`/`MVar` store a generic-parameter index. This +//! module walks that union into [`ResolvedType`], which maps one-to-one onto +//! ECMA-335 signature elements. +//! +//! The walk is **bounded and non-recursive**. A hostile or corrupt binary +//! could describe a type that contains itself (`T[][][]…` forever); an +//! explicit depth cap turns that into an error rather than a stack overflow. +//! +//! Layouts here were confirmed against the reference game, not assumed: all +//! 20,464 generic instantiations resolve to an in-range type definition with +//! zero failures, and the generic type handle was shown to point at an +//! `Il2CppType` (16-byte stride) rather than at a type definition. + +use crate::binary::{GameBinary, TypeKind}; +use crate::error::{Error, Result}; + +/// How deeply a type may nest before we call it malformed. `List[]>` is depth 4; real code never approaches this. +const MAX_DEPTH: usize = 32; + +/// How many generic arguments one instantiation may carry. +const MAX_GENERIC_ARGS: usize = 64; + +/// A type in a form that maps directly onto an ECMA-335 signature. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ResolvedType { + /// A built-in type with a dedicated `ELEMENT_TYPE_*` encoding. + Primitive(TypeKind), + /// A class or struct, named by its type-definition index. + Named { + /// Index into the metadata's type-definition table. + type_def: usize, + /// Whether it is a value type (encodes as `VALUETYPE`, not `CLASS`). + value_type: bool, + }, + /// A vector: single-dimension, zero-based. + SzArray(Box), + /// A multi-dimensional array. + Array { + /// The element type. + element: Box, + /// Number of dimensions. + rank: u32, + }, + /// An unmanaged pointer. + Pointer(Box), + /// A managed reference (`ref`/`out`). + ByRef(Box), + /// A constructed generic type, e.g. `List`. + Generic { + /// The generic type definition being instantiated. + type_def: usize, + /// Whether the definition is a value type. + value_type: bool, + /// The type arguments, in order. + args: Vec, + }, + /// A generic parameter declared on the enclosing *type*. + TypeParam(u32), + /// A generic parameter declared on the enclosing *method*. + MethodParam(u32), + /// A function pointer. Its full signature is not modelled; a reference + /// assembly can encode it as `IntPtr` without losing compilability. + FnPtr, +} + +impl GameBinary { + /// Resolve type-table entry `index` into a signature-ready shape. + /// + /// # Errors + /// + /// [`Error::BoundExceeded`] if the type nests past [`MAX_DEPTH`] or names + /// more than [`MAX_GENERIC_ARGS`] arguments, or [`Error::Truncated`] if a + /// payload pointer leaves the image. + pub fn resolve(&self, index: usize) -> Result { + self.resolve_at(index, 0) + } + + /// Depth-tracking worker behind [`GameBinary::resolve`]. + fn resolve_at(&self, index: usize, depth: usize) -> Result { + if depth > MAX_DEPTH { + return Err(Error::BoundExceeded { + what: "type nesting depth", + limit: MAX_DEPTH, + }); + } + let ty = self.type_at(index)?; + // A by-ref type is a wrapper the bitfield records separately from the + // kind, so it must be peeled before dispatching on the kind itself. + if ty.by_ref { + let inner = self.resolve_payload(index, depth)?; + return Ok(ResolvedType::ByRef(Box::new(inner))); + } + self.resolve_payload(index, depth) + } + + /// Resolve an entry ignoring its by-ref flag. + fn resolve_payload(&self, index: usize, depth: usize) -> Result { + let ty = self.type_at(index)?; + let next = depth.saturating_add(1); + match ty.kind { + TypeKind::Class | TypeKind::ValueType => Ok(ResolvedType::Named { + type_def: usize::try_from(ty.data).unwrap_or(0), + value_type: ty.kind == TypeKind::ValueType, + }), + TypeKind::SzArray => Ok(ResolvedType::SzArray(Box::new( + self.resolve_element(ty.data, next)?, + ))), + TypeKind::Ptr => Ok(ResolvedType::Pointer(Box::new( + self.resolve_element(ty.data, next)?, + ))), + TypeKind::ByRef => Ok(ResolvedType::ByRef(Box::new( + self.resolve_element(ty.data, next)?, + ))), + TypeKind::Array => self.resolve_array(ty.data, next), + TypeKind::GenericInst => self.resolve_generic(ty.data, next), + TypeKind::Var => Ok(ResolvedType::TypeParam(u32::try_from(ty.data).unwrap_or(0))), + TypeKind::MVar => Ok(ResolvedType::MethodParam( + u32::try_from(ty.data).unwrap_or(0), + )), + TypeKind::FnPtr => Ok(ResolvedType::FnPtr), + other => Ok(ResolvedType::Primitive(other)), + } + } + + /// Resolve an `Il2CppType` reached by pointer rather than by table index. + fn resolve_element(&self, pointer: u64, depth: usize) -> Result { + let index = self.type_index_of(pointer)?; + self.resolve_at(index, depth) + } + + /// Decode `Il2CppArrayType { Il2CppType* etype; uint8 rank; ... }`. + fn resolve_array(&self, pointer: u64, depth: usize) -> Result { + let base = self.offset_of(pointer)?; + let element_ptr = self.read_u64(base)?; + let rank = u32::from(self.read_u8(base.saturating_add(8))?); + Ok(ResolvedType::Array { + element: Box::new(self.resolve_element(element_ptr, depth)?), + rank: rank.max(1), + }) + } + + /// Decode `Il2CppGenericClass { Il2CppType* type; Il2CppGenericInst* + /// class_inst; ... }`, where the first field points at the *open* generic + /// type's own entry rather than at a type definition. + fn resolve_generic(&self, pointer: u64, depth: usize) -> Result { + let base = self.offset_of(pointer)?; + let handle = self.read_u64(base)?; + let open = self.resolve_element(handle, depth)?; + // A generic instantiation whose definition is not a plain named type + // is not something a reference assembly can express; fall back rather + // than emit a malformed signature. + let ResolvedType::Named { + type_def, + value_type, + } = open + else { + return Ok(ResolvedType::FnPtr); + }; + let args = self.resolve_generic_args(self.read_u64(base.saturating_add(8))?, depth)?; + Ok(ResolvedType::Generic { + type_def, + value_type, + args, + }) + } + + /// Decode `Il2CppGenericInst { uint32 argc; const Il2CppType** argv; }`. + fn resolve_generic_args(&self, pointer: u64, depth: usize) -> Result> { + let base = self.offset_of(pointer)?; + let count = usize::try_from(self.read_u32(base)?).unwrap_or(0); + if count > MAX_GENERIC_ARGS { + return Err(Error::BoundExceeded { + what: "generic arguments", + limit: MAX_GENERIC_ARGS, + }); + } + // The pointer array follows an 8-byte-aligned header, so the vector + // sits at +8 even though the count is only 4 bytes wide. + let vector = self.offset_of(self.read_u64(base.saturating_add(8))?)?; + let mut resolved = Vec::with_capacity(count); + for slot in 0..count { + let at = vector.saturating_add(slot.saturating_mul(8)); + resolved.push(self.resolve_element(self.read_u64(at)?, depth)?); + } + Ok(resolved) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Metadata; + + fn real_game() -> Option<(std::path::PathBuf, std::path::PathBuf)> { + let home = std::env::var_os("HOME")?; + let root = std::path::Path::new(&home) + .join(".local/share/Steam/steamapps/common/Sons Of The Forest"); + let binary = root.join("GameAssembly.dll"); + let metadata = root.join("SonsOfTheForest_Data/il2cpp_data/Metadata/global-metadata.dat"); + (binary.exists() && metadata.exists()).then_some((binary, metadata)) + } + + #[test] + fn resolves_every_type_in_the_real_game() { + let Some((binary, metadata)) = real_game() else { + return; + }; + let md = Metadata::open(&metadata).unwrap(); + let types = md.type_count().unwrap(); + let game = GameBinary::open(&binary, types).unwrap(); + + // Every entry must resolve. Anything that does not is a layout bug + // that would surface later as a corrupt signature, which is far + // harder to diagnose than a failure here. + let (mut named, mut generic, mut arrays) = (0_usize, 0_usize, 0_usize); + for index in 0..game.type_count() { + match game.resolve(index).expect("every type resolves") { + ResolvedType::Named { type_def, .. } => { + assert!(type_def < types, "type_def {type_def} out of range"); + named = named.saturating_add(1); + } + ResolvedType::Generic { type_def, args, .. } => { + assert!(type_def < types, "generic def {type_def} out of range"); + assert!(!args.is_empty(), "a generic instantiation has arguments"); + generic = generic.saturating_add(1); + } + ResolvedType::SzArray(_) | ResolvedType::Array { .. } => { + arrays = arrays.saturating_add(1); + } + _ => {} + } + } + assert!(named > 10_000, "named types: {named}"); + assert!(generic > 10_000, "generic instantiations: {generic}"); + assert!(arrays > 1_000, "array types: {arrays}"); + } + + #[test] + fn a_generic_instantiations_arguments_all_resolve() { + let Some((binary, metadata)) = real_game() else { + return; + }; + let md = Metadata::open(&metadata).unwrap(); + let game = GameBinary::open(&binary, md.type_count().unwrap()).unwrap(); + + let found = (0..game.type_count()) + .filter_map(|i| game.resolve(i).ok()) + .filter_map(|t| match t { + ResolvedType::Generic { args, .. } if !args.is_empty() => Some(args), + _ => None, + }) + .take(500) + .count(); + assert!(found >= 500, "expected many resolvable instantiations"); + } +} diff --git a/crates/modrix-interop-gen/Cargo.toml b/crates/modrix-interop-gen/Cargo.toml new file mode 100644 index 0000000..2bb8dc8 --- /dev/null +++ b/crates/modrix-interop-gen/Cargo.toml @@ -0,0 +1,17 @@ +# SPDX-License-Identifier: GPL-2.0-only +[package] +name = "modrix-interop-gen" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +authors.workspace = true +description = "Generates managed reference assemblies from an IL2CPP game so mods can be compiled against it." + +[dependencies] +modrix-ecma335 = { path = "../modrix-ecma335" } +modrix-il2cpp = { path = "../modrix-il2cpp" } +thiserror = { workspace = true } + +[lints] +workspace = true diff --git a/crates/modrix-interop-gen/src/corlib.rs b/crates/modrix-interop-gen/src/corlib.rs new file mode 100644 index 0000000..607d0bf --- /dev/null +++ b/crates/modrix-interop-gen/src/corlib.rs @@ -0,0 +1,183 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Redirecting the game's base class library onto the real one. +//! +//! An IL2CPP game embeds its own corlib: `mscorlib`, `System`, `System.Core` +//! and friends appear in the metadata exactly like the game's own assemblies, +//! complete with `System.Object`, `System.String` and +//! `System.Collections.Generic.List`. +//! +//! Emitting those verbatim breaks compilation in the worst way. A mod already +//! references the real .NET reference pack, so `System.Object` would exist +//! twice and every use becomes ambiguous - `CS0433`, on essentially every line. +//! The alternative that `Il2CppInterop` takes is to rename the whole tree to +//! `Il2CppSystem.*`, which avoids the clash but forces mod authors to write +//! `Il2CppSystem.Collections.Generic.List` instead of the type they mean. +//! +//! Modrix takes the third route: **redirect**. Game-corlib types are not +//! emitted at all; references to them are rewritten as `TypeRef` rows scoped to +//! the real `System.Runtime`, so `string` in a game signature binds to the +//! `string` the mod already has. +//! +//! That only works for types that genuinely exist in modern .NET with the same +//! name and arity, so redirection runs off an explicit allowlist. A type not on +//! it is **declined**, and the member using it is dropped. That direction is +//! deliberate: dropping a member costs a mod author one unavailable API, while +//! emitting a reference to a type the compiler cannot find fails the whole +//! build with an error that points nowhere useful. + +/// Assemblies whose contents are the base class library rather than the game. +/// +/// Matched case-insensitively against the metadata's assembly names. These are +/// never emitted; their types redirect. +const CORLIB_ASSEMBLIES: [&str; 10] = [ + "mscorlib", + "System", + "System.Core", + "System.Runtime", + "System.Xml", + "System.Configuration", + "netstandard", + "System.Private.CoreLib", + "System.Numerics", + "System.Data", +]; + +/// Non-generic BCL types safe to redirect: present in .NET 6 under the same +/// namespace and name. +const REDIRECT_PLAIN: [&str; 46] = [ + "System.Object", + "System.ValueType", + "System.Enum", + "System.Array", + "System.Delegate", + "System.MulticastDelegate", + "System.Attribute", + "System.Exception", + "System.String", + "System.Type", + "System.Boolean", + "System.Char", + "System.SByte", + "System.Byte", + "System.Int16", + "System.UInt16", + "System.Int32", + "System.UInt32", + "System.Int64", + "System.UInt64", + "System.Single", + "System.Double", + "System.Decimal", + "System.IntPtr", + "System.UIntPtr", + "System.Void", + "System.DateTime", + "System.TimeSpan", + "System.Guid", + "System.Uri", + "System.Version", + "System.Random", + "System.EventArgs", + "System.IDisposable", + "System.IAsyncResult", + "System.AsyncCallback", + "System.IComparable", + "System.IEquatable", + "System.ICloneable", + "System.IFormattable", + "System.Collections.IEnumerable", + "System.Collections.IEnumerator", + "System.Collections.ICollection", + "System.Collections.IList", + "System.Collections.IDictionary", + "System.Text.StringBuilder", +]; + +/// Generic BCL types safe to redirect, with their exact arity suffix. +const REDIRECT_GENERIC: [&str; 20] = [ + "System.Nullable`1", + "System.Action`1", + "System.Action`2", + "System.Action`3", + "System.Func`1", + "System.Func`2", + "System.Func`3", + "System.Func`4", + "System.IComparable`1", + "System.IEquatable`1", + "System.Collections.Generic.List`1", + "System.Collections.Generic.Dictionary`2", + "System.Collections.Generic.HashSet`1", + "System.Collections.Generic.Queue`1", + "System.Collections.Generic.Stack`1", + "System.Collections.Generic.IEnumerable`1", + "System.Collections.Generic.IEnumerator`1", + "System.Collections.Generic.ICollection`1", + "System.Collections.Generic.IList`1", + "System.Collections.Generic.IDictionary`2", +]; + +/// Whether an assembly is part of the game's embedded base class library. +#[must_use] +pub fn is_corlib_assembly(name: &str) -> bool { + CORLIB_ASSEMBLIES + .iter() + .any(|candidate| candidate.eq_ignore_ascii_case(name)) +} + +/// Whether a corlib type can be redirected onto the real `System.Runtime`. +/// +/// `namespace` and `name` are the metadata's own strings, so `name` still +/// carries its `` `N `` arity suffix for generic types. +#[must_use] +pub fn is_redirectable(namespace: &str, name: &str) -> bool { + // A nested type has no usable namespace of its own here, and its enclosing + // type would need a separate scope; never redirect one. + if name.contains('/') || namespace.is_empty() { + return false; + } + let full = format!("{namespace}.{name}"); + if name.contains('`') { + return REDIRECT_GENERIC.contains(&full.as_str()); + } + REDIRECT_PLAIN.contains(&full.as_str()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn recognises_the_game_corlib_assemblies_case_insensitively() { + assert!(is_corlib_assembly("mscorlib")); + assert!(is_corlib_assembly("MSCORLIB")); + assert!(is_corlib_assembly("System.Core")); + assert!(!is_corlib_assembly("Assembly-CSharp")); + assert!(!is_corlib_assembly("Sons")); + assert!( + !is_corlib_assembly("UnityEngine.CoreModule"), + "Unity is the game's, not the BCL's" + ); + } + + #[test] + fn redirects_only_types_that_exist_in_modern_dotnet() { + assert!(is_redirectable("System", "Object")); + assert!(is_redirectable("System", "String")); + assert!(is_redirectable("System.Collections.Generic", "List`1")); + assert!(is_redirectable( + "System.Collections.Generic", + "Dictionary`2" + )); + + // Arity must match exactly: List`2 is not List`1. + assert!(!is_redirectable("System.Collections.Generic", "List`2")); + // A type that may not exist, or may differ, is declined rather than + // guessed - a dangling TypeRef fails the whole build. + assert!(!is_redirectable("System", "__Canon")); + assert!(!is_redirectable("System.Runtime.Remoting", "ObjRef")); + // No namespace, or a nested name, is never redirectable. + assert!(!is_redirectable("", "Object")); + assert!(!is_redirectable("System", "Outer/Inner")); + } +} diff --git a/crates/modrix-interop-gen/src/emit.rs b/crates/modrix-interop-gen/src/emit.rs new file mode 100644 index 0000000..9b6bbb6 --- /dev/null +++ b/crates/modrix-interop-gen/src/emit.rs @@ -0,0 +1,818 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Encoding one assembly's model as a .NET reference assembly. +//! +//! Two ordering constraints drive the shape of this module, and both come from +//! ECMA-335 rather than from taste: +//! +//! **A base type must already exist when its subclass is declared.** The +//! builder takes `extends` at construction, so types cannot be added in +//! metadata order - a class whose base sits later in the same assembly would +//! have nothing to point at. Inheritance cannot cycle, so a dependency-ordered +//! pass always terminates; [`Layout::order`] does that, and also respects the +//! stricter rule that a nested type's enclosing type must come first. +//! +//! **Signatures may reference anything.** They are encoded in a second pass, +//! once every local type has an id, so a field can mention a type declared +//! later in the file. +//! +//! Generic arity is taken from the *name*. IL2CPP keeps the CLI convention of +//! encoding it as a `` `N `` suffix (``List`1``), and Roslyn cross-checks the +//! suffix against the declared `GenericParam` rows - so the suffix is the +//! authoritative source and the rows are generated to match it. Method arity +//! has no such marker, so it is inferred from the highest method-parameter +//! reference the signature actually makes. + +use std::collections::HashMap; + +use modrix_ecma335::model::{field_attributes, method_attributes, method_impl}; +use modrix_ecma335::{ + AssemblyBuilder, AssemblyReference, Field, GenericParameter, Method, MethodSignature, + ResolutionScope, Type, TypeDefId, TypeDefOrRef, TypeDefinition, TypeRefId, Version, +}; +use modrix_il2cpp::{Metadata, ResolvedType, TypeKind}; + +use crate::error::{Error, Result}; +use crate::model::{AssemblyModel, GameModel, TypeModel}; + +/// The framework major version the emitted references target. Mods build as +/// `net6.0`, which pins the `System.Runtime` reference to 6.0.0.0. +const FRAMEWORK_MAJOR: u16 = 6; + +/// Guard on the dependency-ordering loop. +const MAX_ORDER_ROUNDS: usize = 64; + +/// Per-assembly emission state. +struct Emitter<'a> { + builder: AssemblyBuilder, + model: &'a GameModel, + metadata: &'a Metadata, + /// Which assembly is being emitted, so foreign types can be told apart. + own: usize, + corlib: modrix_ecma335::AssemblyRefId, + /// Assembly index -> its `AssemblyRef` row. + refs: HashMap, + /// Metadata type index -> local `TypeDef` row. + local: HashMap, + /// Metadata type index -> interned `TypeRef` row. + foreign: HashMap, +} + +/// Emit every assembly of a game as a reference assembly. +/// +/// Returns `(assembly name, bytes)` pairs. An assembly with no public types is +/// skipped: an empty reference is useless and only slows a build down. +/// +/// # Errors +/// +/// Propagates read failures and any encoding error from `modrix-ecma335`. +pub fn emit_all(model: &GameModel, metadata: &Metadata) -> Result)>> { + let mut out = Vec::with_capacity(model.assemblies.len()); + for (index, assembly) in model.assemblies.iter().enumerate() { + // The game's embedded corlib is never emitted; its types redirect onto + // the real System.Runtime instead. See the `corlib` module. + if assembly.types.is_empty() || crate::corlib::is_corlib_assembly(&assembly.name) { + continue; + } + out.push(( + assembly.name.clone(), + emit_assembly(model, metadata, index)?, + )); + } + Ok(out) +} + +/// Emit a single assembly by index. +/// +/// # Errors +/// +/// As [`emit_all`], plus [`Error::NoSuchAssembly`] for an out-of-range index. +pub fn emit_assembly(model: &GameModel, metadata: &Metadata, index: usize) -> Result> { + let assembly = model + .assemblies + .get(index) + .ok_or(Error::NoSuchAssembly { index })?; + let mut emitter = Emitter::new(model, metadata, index, assembly); + emitter.declare_types(assembly)?; + emitter.encode_members(assembly)?; + Ok(emitter.builder.build()?) +} + +impl<'a> Emitter<'a> { + fn new( + model: &'a GameModel, + metadata: &'a Metadata, + own: usize, + assembly: &AssemblyModel, + ) -> Self { + let version = parse_version(&assembly.version); + let mut builder = AssemblyBuilder::new(&assembly.name, version); + let corlib = builder.add_assembly_ref(AssemblyReference::core_library(FRAMEWORK_MAJOR)); + Self { + builder, + model, + metadata, + own, + corlib, + refs: HashMap::new(), + local: HashMap::new(), + foreign: HashMap::new(), + } + } + + /// Declare every type, in an order that satisfies base and nesting first. + fn declare_types(&mut self, assembly: &AssemblyModel) -> Result<()> { + for position in Layout::order(assembly, self.own, self.model) { + let Some(model) = assembly.types.get(position) else { + continue; + }; + if let Some(id) = self.declare_one(model)? { + self.local.insert(model.type_def, id); + } + } + Ok(()) + } + + /// Declare one type, resolving its base, interfaces and generic arity. + /// + /// Returns `None` when the type cannot be declared correctly and must be + /// dropped instead - see the nesting check below. + fn declare_one(&mut self, model: &TypeModel) -> Result> { + let extends = match &model.base { + Some(base) => self.token_of(base)?, + None => None, + }; + let mut definition = TypeDefinition::new( + model.namespace.clone(), + model.name.clone(), + crate::model::publicize_type(model.flags), + extends, + ); + if let Some(outer) = model + .declaring_type + .and_then(|d| self.local.get(&d).copied()) + { + definition = definition.nested_in(outer); + } + for interface in self.interfaces_of(model)? { + definition = definition.with_interface(interface); + } + // Arity comes from the metadata's generic container, which carries the + // real declared names. Roslyn cross-checks the count against the name's + // `N suffix, so a mismatch here is a hard error - but the container and + // the suffix always agree, both being written by the same compiler. + for name in &model.generic_params { + definition = definition.with_generic_parameter(GenericParameter::new(name.clone())); + } + Ok(Some(self.builder.add_type_def(definition)?)) + } + + /// The interface tokens a type implements. + fn interfaces_of(&mut self, model: &TypeModel) -> Result> { + let def = self.metadata.type_def(model.type_def)?; + let total = self.metadata.interface_count()?; + let mut out = Vec::with_capacity(def.interfaces.count); + for slot in def.interfaces.indices() { + if slot >= total { + continue; + } + let raw = self.metadata.interface_type(slot)?; + let Ok(type_slot) = usize::try_from(raw) else { + continue; + }; + // An interface reached through a constructed generic type would + // need a TypeSpec token; skip those rather than emit a malformed + // InterfaceImpl row. Mods bind against methods, not the + // interface relationship, so this is a tolerable v1 gap. + if let Some(token) = self.token_of_index(type_slot)? { + out.push(token); + } + } + Ok(out) + } + + /// Encode every type's fields and methods. + fn encode_members(&mut self, assembly: &AssemblyModel) -> Result<()> { + for model in &assembly.types { + let Some(owner) = self.local.get(&model.type_def).copied() else { + continue; + }; + self.encode_fields(owner, model)?; + let method_ids = self.encode_methods(owner, model)?; + self.encode_properties(owner, model, &method_ids)?; + } + Ok(()) + } + + fn encode_fields(&mut self, owner: TypeDefId, model: &TypeModel) -> Result<()> { + for field in &model.fields { + let Some(ty) = self.convert(&field.ty)? else { + continue; + }; + let mut flags = u16::try_from(field.flags).unwrap_or(field_attributes::PUBLIC); + let mut row = Field::new(field.name.clone(), flags, ty.clone()); + match field.constant { + Some(value) => row = row.with_constant(constant_for(&ty, value)), + // A literal with no recoverable constant cannot be emitted: + // ECMA-335 requires the pair. Demote it to a plain static + // field so the name still exists rather than dropping it. + None if flags & field_attributes::LITERAL != 0 => { + flags &= !field_attributes::LITERAL; + flags |= field_attributes::STATIC; + row = Field::new(field.name.clone(), flags, ty); + } + None => {} + } + self.builder.add_field(owner, row)?; + } + Ok(()) + } + + /// Encode a type's methods, returning the emitted id for each model + /// position so properties can link their accessors afterwards. + fn encode_methods( + &mut self, + owner: TypeDefId, + model: &TypeModel, + ) -> Result> { + let mut ids = HashMap::new(); + // `InternalCall` is how a body-less method stays loadable, but the CLR + // rejects it on a generic method or on any method of a generic class: + // "Generic method or method in generic class is internal call, PInvoke, + // or is defined in a COM Import class." Those would need a real IL body, + // which a reference assembly does not carry, so they are omitted - + // the type still loads, and only these members are absent. + let owner_is_generic = !model.generic_params.is_empty(); + for (position, method) in model.methods.iter().enumerate() { + if owner_is_generic || !method.generic_params.is_empty() { + continue; + } + // A signature we cannot express is skipped whole: emitting a + // method with a wrong signature is far worse than omitting it, + // because the compiler would bind to it and then fail at a + // confusing place. + let Some(returns) = self.convert(&method.returns)? else { + continue; + }; + let mut parameters = Vec::with_capacity(method.parameters.len()); + let mut expressible = true; + for param in &method.parameters { + if let Some(ty) = self.convert(¶m.ty)? { + parameters.push(ty); + } else { + expressible = false; + break; + } + } + if !expressible { + continue; + } + let id = self.add_method(owner, method, returns, parameters)?; + ids.insert(position, id); + } + Ok(ids) + } + + /// Encode a type's properties, linking each to its emitted accessors. + /// + /// A property whose accessors were dropped (an inexpressible signature) is + /// skipped: a `Property` row pointing at nothing is worse than no row. + fn encode_properties( + &mut self, + owner: TypeDefId, + model: &TypeModel, + ids: &HashMap, + ) -> Result<()> { + for property in &model.properties { + let Some(ty) = self.convert(&property.ty)? else { + continue; + }; + let getter = property.getter.and_then(|index| ids.get(&index).copied()); + let setter = property.setter.and_then(|index| ids.get(&index).copied()); + if getter.is_none() && setter.is_none() { + continue; + } + let mut row = modrix_ecma335::Property::new(property.name.clone(), ty); + if let Some(id) = getter { + row = row.with_getter(id); + } + if let Some(id) = setter { + row = row.with_setter(id); + } + self.builder.add_property(owner, row)?; + } + Ok(()) + } + + /// Add one method row, inferring its generic arity from the signature. + fn add_method( + &mut self, + owner: TypeDefId, + method: &crate::model::MethodModel, + returns: Type, + parameters: Vec, + ) -> Result { + // The generic container is authoritative. Inferring arity from the + // highest `!!N` a signature mentions silently gets `T AddComponent()` + // wrong, emitting it as non-generic - which is why every + // `AddComponent()` call in a real mod failed to bind. + let arity = u32::try_from(method.generic_params.len()).unwrap_or(0); + let mut signature = if method.is_static { + MethodSignature::static_method(returns, parameters) + } else { + MethodSignature::instance_method(returns, parameters) + }; + if arity > 0 { + signature = signature.with_generic_parameters(arity); + } + let flags = method.flags | method_attributes::HIDE_BY_SIG; + let mut row = Method::new(method.name.clone(), flags, signature); + // Mark every method as an internal call. + // + // These assemblies carry no IL - a reference assembly's methods all + // have RVA 0 - and the CLR refuses to *load* a type whose ordinary + // method has no body: "Could not load type 'UnityEngine.Object' + // because the method 'GetInstanceID' has no implementation (no RVA)". + // That takes down the whole assembly, so a mod cannot even name a game + // type at runtime. + // + // `InternalCall` declares "the body lives in the runtime, not here", + // which is legal with no RVA. The type then loads, and only an actual + // *call* fails - a far better failure mode, and the shape a real + // interop layer needs anyway, since it binds these to IL2CPP thunks. + row.impl_flags = method_impl::INTERNAL_CALL; + for param in &method.parameters { + row = row.with_parameter(modrix_ecma335::Parameter::new(param.name.clone())); + } + for name in &method.generic_params { + row = row.with_generic_parameter(GenericParameter::new(name.clone())); + } + Ok(self.builder.add_method(owner, row)?) + } + + /// A token for a type used in a *token* position - a base class or an + /// implemented interface - or `None` when it cannot be expressed. + /// + /// Primitives have to be handled here as well as named types. A base class + /// is a token, not a signature, so `ELEMENT_TYPE_OBJECT` cannot be written + /// inline: it must become a `TypeRef` to `System.Object`. IL2CPP records + /// `UnityEngine.Object`'s base exactly that way, and returning `None` for it + /// emitted a class with no base at all - which the runtime rejects with + /// "Could not load type ... because the parent does not exist", taking the + /// whole assembly with it. + fn token_of(&mut self, ty: &ResolvedType) -> Result> { + match ty { + ResolvedType::Named { type_def, .. } | ResolvedType::Generic { type_def, .. } => { + self.token_of_index(*type_def) + } + ResolvedType::Primitive(kind) => Ok(self.corlib_token(*kind)), + _ => Ok(None), + } + } + + /// A `TypeRef` into the real corlib for a primitive named in a token + /// position. + fn corlib_token(&mut self, kind: TypeKind) -> Option { + let name = match kind { + TypeKind::Object => "Object", + TypeKind::String => "String", + TypeKind::Void => "Void", + TypeKind::Boolean => "Boolean", + TypeKind::Char => "Char", + TypeKind::I1 => "SByte", + TypeKind::U1 => "Byte", + TypeKind::I2 => "Int16", + TypeKind::U2 => "UInt16", + TypeKind::I4 => "Int32", + TypeKind::U4 => "UInt32", + TypeKind::I8 => "Int64", + TypeKind::U8 => "UInt64", + TypeKind::R4 => "Single", + TypeKind::R8 => "Double", + TypeKind::I => "IntPtr", + TypeKind::U => "UIntPtr", + TypeKind::TypedByRef => "TypedReference", + _ => return None, + }; + let scope = ResolutionScope::AssemblyRef(self.corlib); + Some(TypeDefOrRef::Reference( + self.builder.add_type_ref(scope, "System", name), + )) + } + + /// A token for a metadata type index, defining it locally or importing it. + fn token_of_index(&mut self, type_def: usize) -> Result> { + if let Some(id) = self.local.get(&type_def) { + return Ok(Some(TypeDefOrRef::Definition(*id))); + } + if let Some(id) = self.foreign.get(&type_def) { + return Ok(Some(TypeDefOrRef::Reference(*id))); + } + let Some(owner) = self.model.owner_of.get(&type_def).copied() else { + return Ok(None); + }; + let def = self.metadata.type_def(type_def)?; + // A base-class-library type is rewritten onto the real corlib rather + // than emitted, so `string` in a game signature binds to the `string` + // the mod already references. Anything not on the allowlist is + // declined; see the `corlib` module for why that direction is right. + if self + .model + .assemblies + .get(owner) + .is_some_and(|a| crate::corlib::is_corlib_assembly(&a.name)) + { + if !crate::corlib::is_redirectable(&def.namespace, &def.name) { + return Ok(None); + } + let scope = ResolutionScope::AssemblyRef(self.corlib); + let id = self.builder.add_type_ref(scope, &def.namespace, &def.name); + self.foreign.insert(type_def, id); + return Ok(Some(TypeDefOrRef::Reference(id))); + } + // A same-assembly type with no id yet is one the ordering pass has not + // reached; that only happens for a cycle the metadata should not + // contain, so decline rather than mis-scope it to an AssemblyRef. + if owner == self.own { + return Ok(None); + } + let scope = ResolutionScope::AssemblyRef(self.assembly_ref(owner)?); + let id = self.builder.add_type_ref(scope, &def.namespace, &def.name); + self.foreign.insert(type_def, id); + Ok(Some(TypeDefOrRef::Reference(id))) + } + + /// The `AssemblyRef` row for another game assembly, added on first use. + fn assembly_ref(&mut self, owner: usize) -> Result { + if let Some(id) = self.refs.get(&owner) { + return Ok(*id); + } + let assembly = self + .model + .assemblies + .get(owner) + .ok_or(Error::NoSuchAssembly { index: owner })?; + let reference = AssemblyReference { + name: assembly.name.clone(), + version: parse_version(&assembly.version), + culture: String::new(), + public_key_or_token: Vec::new(), + flags: 0, + }; + let id = self.builder.add_assembly_ref(reference); + self.refs.insert(owner, id); + Ok(id) + } + + /// Translate a resolved IL2CPP type into a signature type. + /// + /// `None` means "cannot be expressed in a reference assembly"; the caller + /// drops the member rather than emit something wrong. + fn convert(&mut self, ty: &ResolvedType) -> Result> { + Ok(match ty { + ResolvedType::Primitive(kind) => primitive(*kind), + ResolvedType::Named { + type_def, + value_type, + } => self.named(*type_def, *value_type)?, + ResolvedType::SzArray(inner) => { + self.convert(inner)?.map(|t| Type::SzArray(Box::new(t))) + } + ResolvedType::Array { element, rank } => self.convert(element)?.map(|t| Type::Array { + element: Box::new(t), + rank: *rank, + sizes: Vec::new(), + lower_bounds: Vec::new(), + }), + ResolvedType::Pointer(inner) => self.convert(inner)?.map(|t| Type::Ptr(Box::new(t))), + ResolvedType::ByRef(inner) => self.convert(inner)?.map(|t| Type::ByRef(Box::new(t))), + ResolvedType::Generic { + type_def, + value_type, + args, + } => self.generic(*type_def, *value_type, args)?, + ResolvedType::TypeParam(index) => Some(Type::TypeParameter(*index)), + ResolvedType::MethodParam(index) => Some(Type::MethodParameter(*index)), + // A function pointer's full signature is not modelled; IntPtr is + // the right shape and keeps the member bindable. + ResolvedType::FnPtr => Some(Type::IntPtr), + }) + } + + fn named(&mut self, type_def: usize, value_type: bool) -> Result> { + Ok(self.token_of_index(type_def)?.map(|token| { + if value_type { + Type::ValueType(token) + } else { + Type::Class(token) + } + })) + } + + fn generic( + &mut self, + type_def: usize, + value_type: bool, + args: &[ResolvedType], + ) -> Result> { + let Some(definition) = self.token_of_index(type_def)? else { + return Ok(None); + }; + let mut arguments = Vec::with_capacity(args.len()); + for arg in args { + let Some(converted) = self.convert(arg)? else { + return Ok(None); + }; + arguments.push(converted); + } + Ok(Some(Type::GenericInstance { + value_type, + definition, + arguments, + })) + } +} + +/// Dependency ordering for type declarations. +struct Layout; + +impl Layout { + /// Positions within `assembly.types`, ordered so that a type's base and + /// enclosing type are always declared first. + fn order(assembly: &AssemblyModel, own: usize, model: &GameModel) -> Vec { + let mut pending: Vec = (0..assembly.types.len()).collect(); + let mut done: std::collections::HashSet = std::collections::HashSet::new(); + let mut out = Vec::with_capacity(pending.len()); + + for _ in 0..MAX_ORDER_ROUNDS { + if pending.is_empty() { + break; + } + let mut progressed = false; + let mut deferred = Vec::new(); + for position in pending { + let Some(ty) = assembly.types.get(position) else { + continue; + }; + if Self::ready(ty, own, model, &done) { + done.insert(ty.type_def); + out.push(position); + progressed = true; + } else { + deferred.push(position); + } + } + pending = deferred; + if !progressed { + // A cycle the metadata should not contain. Emit the rest in + // metadata order: a base that never resolves just becomes + // `None`, which is harmless. `declare_one` still refuses to + // promote an unresolved nested type, so this cannot reintroduce + // duplicate `<>c` names. + out.extend(pending); + break; + } + } + out + } + + /// Whether every same-assembly dependency of `ty` is already declared. + fn ready( + ty: &TypeModel, + own: usize, + model: &GameModel, + done: &std::collections::HashSet, + ) -> bool { + let local_and_missing = |index: usize| { + model.owner_of.get(&index).copied() == Some(own) && !done.contains(&index) + }; + if let Some(outer) = ty.declaring_type + && local_and_missing(outer) + { + return false; + } + if let Some(ResolvedType::Named { type_def, .. }) = &ty.base + && local_and_missing(*type_def) + { + return false; + } + true + } +} + +/// Wrap a decoded integer constant in the `Constant` variant matching the +/// field's declared type. +/// +/// IL2CPP stores every field constant as one compressed integer, so the width +/// and signedness come from the field type rather than from the blob. An enum +/// member's field type is the enum itself, which is a value type - its +/// underlying width is not recorded here, so `i32` is the safe default: it is +/// what C# uses unless an enum explicitly says otherwise. +fn constant_for(ty: &Type, value: i64) -> modrix_ecma335::Constant { + use modrix_ecma335::Constant; + match ty { + Type::Boolean => Constant::Boolean(value != 0), + Type::Char => Constant::Char(u16::try_from(value).unwrap_or(0)), + Type::I1 => Constant::I1(i8::try_from(value).unwrap_or(0)), + Type::U1 => Constant::U1(u8::try_from(value).unwrap_or(0)), + Type::I2 => Constant::I2(i16::try_from(value).unwrap_or(0)), + Type::U2 => Constant::U2(u16::try_from(value).unwrap_or(0)), + Type::U4 => Constant::U4(u32::try_from(value).unwrap_or(0)), + Type::I8 => Constant::I8(value), + Type::U8 => Constant::U8(u64::try_from(value).unwrap_or(0)), + _ => Constant::I4(i32::try_from(value).unwrap_or(0)), + } +} + +/// The `ELEMENT_TYPE_*` equivalent of an IL2CPP primitive kind. +fn primitive(kind: TypeKind) -> Option { + Some(match kind { + TypeKind::Void => Type::Void, + TypeKind::Boolean => Type::Boolean, + TypeKind::Char => Type::Char, + TypeKind::I1 => Type::I1, + TypeKind::U1 => Type::U1, + TypeKind::I2 => Type::I2, + TypeKind::U2 => Type::U2, + TypeKind::I4 => Type::I4, + TypeKind::U4 => Type::U4, + TypeKind::I8 => Type::I8, + TypeKind::U8 => Type::U8, + TypeKind::R4 => Type::R4, + TypeKind::R8 => Type::R8, + TypeKind::String => Type::String, + TypeKind::Object => Type::Object, + TypeKind::I => Type::IntPtr, + TypeKind::U => Type::UIntPtr, + TypeKind::TypedByRef => Type::TypedByRef, + _ => return None, + }) +} + +/// Parse a `major.minor.build.revision` string, defaulting missing parts to 0. +fn parse_version(text: &str) -> Version { + let mut parts = text.split('.').map(|p| p.parse::().unwrap_or(0)); + Version { + major: parts.next().unwrap_or(0), + minor: parts.next().unwrap_or(0), + build: parts.next().unwrap_or(0), + revision: parts.next().unwrap_or(0), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_a_four_part_version_and_tolerates_short_ones() { + assert_eq!( + parse_version("1.2.3.4"), + Version { + major: 1, + minor: 2, + build: 3, + revision: 4 + } + ); + assert_eq!( + parse_version("2.0"), + Version { + major: 2, + minor: 0, + build: 0, + revision: 0 + } + ); + } + + #[test] + fn every_il2cpp_primitive_maps_to_a_signature_type() { + for kind in [ + TypeKind::Void, + TypeKind::Boolean, + TypeKind::Char, + TypeKind::I1, + TypeKind::U1, + TypeKind::I2, + TypeKind::U2, + TypeKind::I4, + TypeKind::U4, + TypeKind::I8, + TypeKind::U8, + TypeKind::R4, + TypeKind::R8, + TypeKind::String, + TypeKind::Object, + TypeKind::I, + TypeKind::U, + TypeKind::TypedByRef, + ] { + assert!(primitive(kind).is_some(), "{kind:?} must map"); + } + // Structural kinds are handled by `convert`, not by `primitive`. + assert!(primitive(TypeKind::Class).is_none()); + assert!(primitive(TypeKind::GenericInst).is_none()); + } +} + +#[cfg(test)] +mod real_game_tests { + use super::*; + use crate::model::GameModel; + use modrix_il2cpp::GameBinary; + + fn real_game() -> Option<(std::path::PathBuf, std::path::PathBuf)> { + let home = std::env::var_os("HOME")?; + let root = std::path::Path::new(&home) + .join(".local/share/Steam/steamapps/common/Sons Of The Forest"); + let binary = root.join("GameAssembly.dll"); + let metadata = root.join("SonsOfTheForest_Data/il2cpp_data/Metadata/global-metadata.dat"); + (binary.exists() && metadata.exists()).then_some((binary, metadata)) + } + + /// No two types in one assembly may share a top-level (namespace, name). + /// + /// Compiler-generated closure classes are all named `<>c` and are unique + /// only by nesting; two at top level make the runtime reject the whole + /// assembly with `BadImageFormatException: Duplicate type with name`. + #[test] + fn no_assembly_declares_two_types_with_the_same_top_level_name() { + let Some((binary_path, metadata_path)) = real_game() else { + return; + }; + let metadata = Metadata::open(&metadata_path).unwrap(); + let binary = GameBinary::open(&binary_path, metadata.type_count().unwrap()).unwrap(); + let model = GameModel::build(&metadata, &binary).unwrap(); + + for (index, assembly) in model.assemblies.iter().enumerate() { + if assembly.types.is_empty() || crate::corlib::is_corlib_assembly(&assembly.name) { + continue; + } + // Reproduce exactly what the emitter declares, in the same order. + let mut emitter = Emitter::new(&model, &metadata, index, assembly); + emitter.declare_types(assembly).unwrap(); + + let mut seen: std::collections::HashSet<(String, String)> = + std::collections::HashSet::new(); + for position in Layout::order(assembly, index, &model) { + let Some(ty) = assembly.types.get(position) else { + continue; + }; + // Only top-level declarations share a namespace; a nested type + // is scoped by its enclosing type. + let declared_nested = ty + .declaring_type + .is_some_and(|d| emitter.local.contains_key(&d)); + if declared_nested || !emitter.local.contains_key(&ty.type_def) { + continue; + } + let key = (ty.namespace.clone(), ty.name.clone()); + assert!( + seen.insert(key.clone()), + "{} declares two top-level types named {}.{}", + assembly.name, + key.0, + key.1 + ); + } + } + } + + #[test] + fn emits_reference_assemblies_for_the_real_game() { + let Some((binary_path, metadata_path)) = real_game() else { + return; // Game not installed. + }; + let metadata = Metadata::open(&metadata_path).unwrap(); + let binary = GameBinary::open(&binary_path, metadata.type_count().unwrap()).unwrap(); + let model = GameModel::build(&metadata, &binary).unwrap(); + + let emitted = emit_all(&model, &metadata).unwrap(); + assert!( + emitted.len() > 50, + "expected many assemblies, got {}", + emitted.len() + ); + // The corlib must NOT be emitted - its types redirect instead. + assert!( + !emitted.iter().any(|(name, _)| name == "mscorlib"), + "the game corlib must be redirected, not emitted" + ); + // The assemblies mods actually reference must be present and non-trivial. + for wanted in ["Assembly-CSharp", "Sons", "UnityEngine.CoreModule"] { + let Some((_, body)) = emitted.iter().find(|(name, _)| name == wanted) else { + panic!("{wanted} was not emitted") + }; + let bytes = body.len(); + assert!(bytes > 2048, "{wanted} is only {bytes} bytes"); + let dir = std::env::var("MODRIX_INTEROP_OUT").ok(); + if let Some(dir) = dir { + let out = std::path::Path::new(&dir); + std::fs::create_dir_all(out).unwrap(); + for (name, bytes) in &emitted { + std::fs::write(out.join(format!("{name}.dll")), bytes).unwrap(); + } + } + } + } +} diff --git a/crates/modrix-interop-gen/src/error.rs b/crates/modrix-interop-gen/src/error.rs new file mode 100644 index 0000000..11134dd --- /dev/null +++ b/crates/modrix-interop-gen/src/error.rs @@ -0,0 +1,36 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Errors from building the interop model. + +/// Result alias for this crate. +pub type Result = std::result::Result; + +/// Why an interop model could not be built. +#[derive(Debug, thiserror::Error)] +#[non_exhaustive] +pub enum Error { + /// The game declares more of something than this build will walk. IL2CPP + /// metadata is read from a file the user supplies, so every count that + /// drives an allocation is bounded rather than trusted. + #[error("{what} exceeded the bound of {limit}")] + TooLarge { + /// What was being counted. + what: &'static str, + /// The ceiling. + limit: usize, + }, + + /// The underlying IL2CPP metadata or binary could not be read. + #[error("reading IL2CPP metadata failed: {0}")] + Il2Cpp(#[from] modrix_il2cpp::Error), + + /// The ECMA-335 writer rejected the model. + #[error("emitting the reference assembly failed: {0}")] + Ecma(#[from] modrix_ecma335::Error), + + /// An assembly index does not name an assembly of this game. + #[error("no assembly at index {index}")] + NoSuchAssembly { + /// The offending index. + index: usize, + }, +} diff --git a/crates/modrix-interop-gen/src/lib.rs b/crates/modrix-interop-gen/src/lib.rs new file mode 100644 index 0000000..1534ebb --- /dev/null +++ b/crates/modrix-interop-gen/src/lib.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Generates managed reference assemblies from an IL2CPP game. +//! +//! This crate is the bridge between `modrix-il2cpp` (which reads a game's +//! `global-metadata.dat`) and `modrix-ecma335` (which writes .NET reference +//! assemblies). It owns the part in between: deciding which types belong to +//! which assembly and which of them are worth emitting at all. + +mod corlib; +pub mod emit; +mod error; +pub mod model; + +pub use emit::{emit_all, emit_assembly}; +pub use error::{Error, Result}; +pub use model::{AssemblyModel, FieldModel, GameModel, MethodModel, ParamModel, TypeModel}; diff --git a/crates/modrix-interop-gen/src/model.rs b/crates/modrix-interop-gen/src/model.rs new file mode 100644 index 0000000..7d76c2a --- /dev/null +++ b/crates/modrix-interop-gen/src/model.rs @@ -0,0 +1,501 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! The interop model: what to emit, before deciding how to encode it. +//! +//! Reading IL2CPP gives one flat world - 24,056 types and 182,725 methods with +//! no assembly boundaries in sight. A mod, though, compiles against +//! *assemblies*: `Assembly-CSharp.dll`, `Sons.dll`, `UnityEngine.CoreModule.dll`. +//! This module performs that partition and decides what belongs in the output. +//! +//! Two decisions shape everything downstream: +//! +//! **Everything is emitted, and everything is made public.** This is the +//! "publicized assembly" convention every Unity modding toolchain uses - +//! `RedLoader` ships `UnityEngine.CoreModule-nstrip.dll` for exactly this +//! reason. A normal reference assembly exposes only the public API, but a mod +//! is not a normal consumer: Harmony patches private methods by name, and mods +//! routinely read private fields. Emitting only the public surface makes the +//! reference assembly technically correct and practically useless - the three +//! mods in the reference repo fail on `DebugConsole.CheckDebugInputs`, +//! `ItemInstance._itemID` and `WorldSimActor._state`, all non-public. +//! +//! Widening visibility is safe here because these assemblies are *reference +//! only*: they are never loaded at runtime, so nothing they claim can violate +//! the real type's encapsulation. The runtime binding is against the game's +//! actual IL2CPP types via the loader. +//! +//! **A type belongs to exactly one assembly.** Each image declares a +//! contiguous run of type definitions, so ownership is a range lookup. Types +//! referenced from another assembly become `TypeRef` rows pointing at an +//! `AssemblyRef` - which is why the owner map has to be built before any +//! signature can be encoded. + +use std::collections::HashMap; + +use modrix_il2cpp::{GameBinary, Metadata, ResolvedType}; + +use crate::error::{Error, Result}; + +/// A type that will be emitted, with its members already resolved. +#[derive(Debug, Clone)] +pub struct TypeModel { + /// Index into the metadata's type-definition table. + pub type_def: usize, + /// The type's own name, IL2CPP-style (``List`1``). + pub name: String, + /// Its namespace, empty for the global namespace. + pub namespace: String, + /// `TypeAttributes`. + pub flags: u32, + /// The base type, absent for interfaces and `System.Object`. + pub base: Option, + /// Enclosing type, when nested. + pub declaring_type: Option, + /// Public fields, in declaration order. + pub fields: Vec, + /// Public methods, in declaration order. + pub methods: Vec, + /// Public properties, in declaration order. + pub properties: Vec, + /// Declared generic parameter names, from the type's generic container. + pub generic_params: Vec, +} + +/// A field to emit. +#[derive(Debug, Clone)] +pub struct FieldModel { + /// The field name. + pub name: String, + /// Its type. + pub ty: ResolvedType, + /// `FieldAttributes`. + pub flags: u32, + /// The compile-time constant, for a `const` field or enum member. ECMA-335 + /// *requires* one on every literal field; omitting it makes the consumer + /// fail with an opaque `CS7038` rather than a useful diagnostic. + pub constant: Option, +} + +/// A method to emit. Bodies are native, so only the signature survives - which +/// is all a reference assembly needs. +#[derive(Debug, Clone)] +pub struct MethodModel { + /// The method name (`.ctor`, `get_X`, …). + pub name: String, + /// The return type. + pub returns: ResolvedType, + /// Parameters, in order. + pub parameters: Vec, + /// `MethodAttributes`. + pub flags: u16, + /// Whether the method is static (affects the signature's calling + /// convention byte, not just the attributes). + pub is_static: bool, + /// Declared generic parameter names, from the method's generic container. + /// Empty for a non-generic method. + pub generic_params: Vec, +} + +/// A property to emit. +/// +/// C# binds `x.Foo` through a `Property` row plus `MethodSemantics` links to +/// its accessors - the `get_Foo` method alone is not enough. Omitting these +/// makes every property access fail with `CS0117`, which is the single most +/// visible gap in a naive reference assembly. +#[derive(Debug, Clone)] +pub struct PropertyModel { + /// The property name. + pub name: String, + /// Its type, taken from the getter's return or the setter's value. + pub ty: ResolvedType, + /// Index into this type's `methods` of the getter, if any. + pub getter: Option, + /// Index into this type's `methods` of the setter, if any. + pub setter: Option, +} + +/// A method parameter. +#[derive(Debug, Clone)] +pub struct ParamModel { + /// The parameter name. + pub name: String, + /// Its type. + pub ty: ResolvedType, +} + +/// One assembly's worth of types. +#[derive(Debug, Clone)] +pub struct AssemblyModel { + /// Assembly name, without extension. + pub name: String, + /// Version, as `major.minor.build.revision`. + pub version: String, + /// The public types this assembly owns. + pub types: Vec, +} + +/// The whole game, partitioned into assemblies. +#[derive(Debug)] +pub struct GameModel { + /// Every assembly, in metadata order. + pub assemblies: Vec, + /// Which assembly owns each type definition, by index. Signature encoding + /// needs this to decide `TypeDef` versus `TypeRef`. + pub owner_of: HashMap, +} + +/// How many types may be walked before we call the input malformed. +const MAX_TYPES: usize = 1_000_000; + +impl GameModel { + /// Build the model from a game's metadata and binary. + /// + /// # Errors + /// + /// Propagates any read failure from the metadata or binary, or + /// [`Error::TooLarge`] if the game declares implausibly many types. + pub fn build(metadata: &Metadata, binary: &GameBinary) -> Result { + let type_count = metadata.type_count()?; + if type_count > MAX_TYPES { + return Err(Error::TooLarge { + what: "type definitions", + limit: MAX_TYPES, + }); + } + let assemblies = metadata.assemblies()?; + let mut owner_of = HashMap::with_capacity(type_count); + for (index, assembly) in assemblies.iter().enumerate() { + for type_index in assembly.types.indices() { + owner_of.insert(type_index, index); + } + } + + // Read the constant table once; per-field lookup would rescan 26k rows. + let constants = metadata.default_values()?; + + let mut built = Vec::with_capacity(assemblies.len()); + for assembly in &assemblies { + let mut types = Vec::new(); + for type_index in assembly.types.indices() { + types.push(build_type(metadata, binary, type_index, &constants)?); + } + built.push(AssemblyModel { + name: assembly.name.clone(), + version: assembly.version.clone(), + types, + }); + } + Ok(Self { + assemblies: built, + owner_of, + }) + } + + /// Total number of types across every assembly. + #[must_use] + pub fn type_count(&self) -> usize { + self.assemblies + .iter() + .map(|a| a.types.len()) + .fold(0_usize, usize::saturating_add) + } +} + +/// Resolve a *binary type-table* index to the type definition it names. +/// +/// IL2CPP stores `declaringTypeIndex` and `parentIndex` as indices into the +/// type table that lives in `GameAssembly.dll`, not into the metadata's own +/// type-definition table. Treating one as a definition index silently points at +/// an unrelated type: nested types then fail to find their enclosing type and +/// get emitted at top level, where every compiler-generated `<>c` collides and +/// the runtime rejects the assembly outright. +fn resolve_type_def(binary: &GameBinary, type_index: i32) -> Result> { + let Ok(slot) = usize::try_from(type_index) else { + return Ok(None); + }; + Ok(match binary.resolve(slot)? { + ResolvedType::Named { type_def, .. } | ResolvedType::Generic { type_def, .. } => { + Some(type_def) + } + _ => None, + }) +} + +/// Build one type's model, resolving every member signature. +fn build_type( + metadata: &Metadata, + binary: &GameBinary, + index: usize, + constants: &HashMap, +) -> Result { + let def = metadata.type_def(index)?; + let base = usize::try_from(def.parent_type) + .ok() + .map(|slot| binary.resolve(slot)) + .transpose()?; + + let mut fields = Vec::with_capacity(def.fields.count); + for slot in def.fields.indices() { + let field = metadata.field_def(slot)?; + let type_slot = usize::try_from(field.type_index).unwrap_or(0); + // IL2CPP's field record holds only name/type/token - the field's + // FieldAttributes ride on the `attrs` word of its TYPE entry. Verified + // against the reference game: LocalPlayer._transform reads Public(6) + // and _inventory reads Private(1), matching the real declarations. + let attrs = u32::from(binary.type_at(type_slot)?.attrs); + fields.push(FieldModel { + name: field.name, + ty: binary.resolve(type_slot)?, + flags: publicize_field(attrs), + constant: constants.get(&slot).map(|d| d.value), + }); + } + + let methods = build_methods(metadata, binary, &def)?; + let properties = build_properties(metadata, &def, &methods)?; + let generic_params = match metadata.generic_container(def.generic_container)? { + Some(container) => metadata.generic_param_names(&container)?, + None => Vec::new(), + }; + + Ok(TypeModel { + type_def: index, + name: def.name, + namespace: def.namespace, + flags: def.flags, + base, + declaring_type: resolve_type_def(binary, def.declaring_type)?, + fields, + methods, + properties, + generic_params, + }) +} + +/// Resolve a type's properties, mapping IL2CPP's accessor indices - which are +/// relative to the type's method run - onto positions in the emitted method +/// list. Only properties whose accessors survived the public filter are kept. +fn build_properties( + metadata: &Metadata, + def: &modrix_il2cpp::TypeDef, + methods: &[MethodModel], +) -> Result> { + // The public filter drops methods, so emitted positions no longer match + // metadata order; index by name to bridge the two. + let position: HashMap<&str, usize> = methods + .iter() + .enumerate() + .map(|(index, method)| (method.name.as_str(), index)) + .collect(); + let start = def.methods.start.unwrap_or(0); + let mut out = Vec::with_capacity(def.properties.count); + for slot in def.properties.indices() { + let property = metadata.property_def(slot)?; + let accessor = |relative: i32| -> Result> { + let Ok(offset) = usize::try_from(relative) else { + return Ok(None); + }; + let absolute = start.saturating_add(offset); + let name = metadata.method_def(absolute)?.name; + Ok(position.get(name.as_str()).copied()) + }; + let getter = accessor(property.get)?; + let setter = accessor(property.set)?; + // A property with neither accessor public is unbindable; skip it. + let Some(ty) = property_type(methods, getter, setter) else { + continue; + }; + out.push(PropertyModel { + name: property.name, + ty, + getter, + setter, + }); + } + Ok(out) +} + +/// A property's type: the getter's return, else the setter's last parameter. +fn property_type( + methods: &[MethodModel], + getter: Option, + setter: Option, +) -> Option { + if let Some(method) = getter.and_then(|index| methods.get(index)) { + return Some(method.returns.clone()); + } + setter + .and_then(|index| methods.get(index)) + .and_then(|method| method.parameters.last()) + .map(|param| param.ty.clone()) +} + +/// Resolve a type's public methods and their signatures. +/// +/// Split out of [`build_type`] to keep both inside the workspace's 60-line +/// ceiling. +fn build_methods( + metadata: &Metadata, + binary: &GameBinary, + def: &modrix_il2cpp::TypeDef, +) -> Result> { + let mut methods = Vec::with_capacity(def.methods.count); + for slot in def.methods.indices() { + let method = metadata.method_def(slot)?; + let mut parameters = Vec::with_capacity(method.parameters.count); + for param_slot in method.parameters.indices() { + let param = metadata.param_def(param_slot)?; + parameters.push(ParamModel { + name: param.name, + ty: binary.resolve(usize::try_from(param.type_index).unwrap_or(0))?, + }); + } + let generic_params = match metadata.generic_container(method.generic_container)? { + Some(container) => metadata.generic_param_names(&container)?, + None => Vec::new(), + }; + methods.push(MethodModel { + returns: binary.resolve(usize::try_from(method.return_type).unwrap_or(0))?, + is_static: method.is_static(), + generic_params, + name: method.name, + flags: publicize_method(method.flags), + parameters, + }); + } + Ok(methods) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn real_game() -> Option<(std::path::PathBuf, std::path::PathBuf)> { + let home = std::env::var_os("HOME")?; + let root = std::path::Path::new(&home) + .join(".local/share/Steam/steamapps/common/Sons Of The Forest"); + let binary = root.join("GameAssembly.dll"); + let metadata = root.join("SonsOfTheForest_Data/il2cpp_data/Metadata/global-metadata.dat"); + (binary.exists() && metadata.exists()).then_some((binary, metadata)) + } + + #[test] + fn builds_a_model_of_the_real_game() { + let Some((binary_path, metadata_path)) = real_game() else { + return; // Game not installed. + }; + let metadata = Metadata::open(&metadata_path).unwrap(); + let binary = GameBinary::open(&binary_path, metadata.type_count().unwrap()).unwrap(); + let model = GameModel::build(&metadata, &binary).unwrap(); + + assert!( + model.assemblies.len() > 100, + "a Unity game ships many assemblies, got {}", + model.assemblies.len() + ); + // Every type must be owned by exactly one assembly, or a signature + // referencing it could not decide between TypeDef and TypeRef. + assert_eq!(model.owner_of.len(), metadata.type_count().unwrap()); + + let named: Vec<&str> = model.assemblies.iter().map(|a| a.name.as_str()).collect(); + for expected in ["Assembly-CSharp", "Sons", "UnityEngine.CoreModule"] { + assert!(named.contains(&expected), "missing assembly {expected}"); + } + assert!( + model.type_count() > 5_000, + "expected thousands of public types, got {}", + model.type_count() + ); + } + + #[test] + fn the_model_exposes_a_known_public_api() { + let Some((binary_path, metadata_path)) = real_game() else { + return; + }; + let metadata = Metadata::open(&metadata_path).unwrap(); + let binary = GameBinary::open(&binary_path, metadata.type_count().unwrap()).unwrap(); + let model = GameModel::build(&metadata, &binary).unwrap(); + + // LocalPlayer is what every Sons of the Forest mod reaches for, so it + // is the canary: if it is missing or its members are wrong, mods will + // not compile against the generated reference assemblies. + let local_player = model + .assemblies + .iter() + .flat_map(|a| &a.types) + .find(|t| t.namespace == "TheForest.Utils" && t.name == "LocalPlayer") + .expect("LocalPlayer is a public type"); + + assert!( + local_player + .methods + .iter() + .any(|m| m.name == "get_IsInWorld"), + "IsInWorld is public API used by mods" + ); + assert!( + local_player.fields.iter().any(|f| f.name == "_transform"), + "_transform is a public field" + ); + // Private members ARE exported, deliberately. These assemblies are + // publicized: mods Harmony-patch private methods and read private + // fields, so a reference assembly limited to the public API is + // useless to them. `_inventory` is private in the game and must still + // be here. + assert!( + local_player.fields.iter().any(|f| f.name == "_inventory"), + "publicized output must expose private fields too" + ); + assert!( + local_player.fields.iter().all(|f| f.flags & 0x07 == 6), + "every exported field must be widened to public" + ); + } +} + +/// Widen a `TypeAttributes` visibility nibble to public. +/// +/// Nested types must use `NestedPublic` (2) rather than `Public` (1); ECMA-335 +/// treats the two as different encodings and a nested type carrying `Public` +/// is malformed. +pub(crate) fn publicize_type(flags: u32) -> u32 { + let visibility = flags & 0x07; + let widened = if visibility >= 2 { 2 } else { 1 }; + (flags & !0x07) | widened +} + +/// Widen a `FieldAttributes` access nibble to `Public` (6). +fn publicize_field(flags: u32) -> u32 { + (flags & !0x07) | 6 +} + +/// Widen a `MethodAttributes` access nibble to `Public` (6). +fn publicize_method(flags: u16) -> u16 { + (flags & !0x07) | 6 +} + +#[cfg(test)] +mod publicize_tests { + use super::*; + + #[test] + fn type_visibility_widens_without_disturbing_other_flags() { + // NotPublic -> Public, keeping Sealed(0x100) and Abstract(0x80). + assert_eq!(publicize_type(0x180), 0x181); + // Already Public stays Public. + assert_eq!(publicize_type(0x001), 0x001); + // Every nested form collapses to NestedPublic, never plain Public - + // a nested type carrying Public is malformed metadata. + for nested in 2_u32..=7 { + assert_eq!(publicize_type(nested) & 0x07, 2, "nested {nested}"); + } + } + + #[test] + fn member_access_widens_to_public() { + // Private field with Static(0x10) keeps Static. + assert_eq!(publicize_field(0x11), 0x16); + // Private method with Static|Virtual keeps both. + assert_eq!(publicize_method(0x0051), 0x0056); + } +} diff --git a/crates/modrix-mcp/src/lib.rs b/crates/modrix-mcp/src/lib.rs index c2ec4fc..900378a 100644 --- a/crates/modrix-mcp/src/lib.rs +++ b/crates/modrix-mcp/src/lib.rs @@ -212,7 +212,7 @@ mod tests { assert!(tools.len() >= 25, "expected a full tool surface"); for tool in tools { assert!(tool["name"].is_string()); - assert!(tool["inputSchema"]["type"] == "object"); + assert_eq!(tool["inputSchema"]["type"], "object"); } } diff --git a/crates/modrix-mcp/src/tools.rs b/crates/modrix-mcp/src/tools.rs index e45ea27..bd88a22 100644 --- a/crates/modrix-mcp/src/tools.rs +++ b/crates/modrix-mcp/src/tools.rs @@ -112,9 +112,109 @@ fn all() -> Vec { tools.extend(deploy_tools_b()); tools.extend(misc_tools()); tools.extend(download_tools()); + tools.extend(launch_tools()); + tools.extend(launch_tools_b()); tools } +// --- launch, loader, and logs ------------------------------------------------ + +/// Tools that start a game, check its mod loader, and read its log. +/// +/// This is the surface an agent drives to *verify* a mod actually works, as +/// opposed to merely deploying it: deploy, launch, then poll the log. Modrix +/// deliberately stops at the log - what happens inside a running game is the +/// business of a per-game bridge, not of a mod manager. +fn launch_tools() -> Vec { + vec![ + Tool { + name: "loader_status", + description: "Whether the game's mod loader is installed, its version, \ + whether interop assemblies are ready, and whether a rival \ + loader is occupying the proxy slot.", + schema: schema(&[], &game_prop()), + read_only: true, + run: |ctx, args| { + let game = game_of(ctx, args)?; + to_value(&ctx.engine().loader_status(game.id).map_err(err)?) + }, + }, + Tool { + name: "launch_game", + description: "Start the game. Returns immediately without waiting for it \ + to appear; poll read_game_log to see it boot. Warns when the \ + platform cannot deliver the loader's required environment.", + schema: schema(&[], &game_prop()), + read_only: false, + run: |ctx, args| { + let game = game_of(ctx, args)?; + to_value(&ctx.engine().launch(game.id).map_err(err)?) + }, + }, + ] +} + +fn launch_tools_b() -> Vec { + vec![ + Tool { + name: "read_game_log", + description: "Read a bounded window of the game log. Pass the returned \ + next_cursor as `since` to follow it. A `truncated` result \ + means the game restarted and the log began again.", + schema: schema(&[], &log_props()), + read_only: true, + run: |ctx, args| { + let game = game_of(ctx, args)?; + let since = args.get("since").and_then(Value::as_u64).unwrap_or(0); + let max = args + .get("max_lines") + .and_then(Value::as_u64) + .and_then(|n| usize::try_from(n).ok()) + .unwrap_or(200); + to_value(&ctx.engine().tail_log(game.id, since, max).map_err(err)?) + }, + }, + Tool { + name: "deploy_and_launch", + description: "Deploy the active profile, then start the game. The usual \ + one-shot for testing a change end to end.", + schema: schema(&[], &game_prop()), + read_only: false, + run: |ctx, args| { + let game = game_of(ctx, args)?; + let profile = active_profile(ctx, &game)?; + let report = ctx.engine().deploy(profile.id).map_err(err)?; + let outcome = ctx.engine().launch(game.id).map_err(err)?; + // `DeployReport` is not Serialize; mirror the `deploy` tool's + // shape so the two agree field for field. + Ok(json!({ + "deploy": { "added": report.added(), "removed": report.removed(), + "unchanged": report.unchanged() }, + "launch": serde_json::to_value(&outcome).map_err(err)?, + })) + }, + }, + ] +} + +/// Schema properties for `read_game_log`: the game plus a cursor and a cap. +fn log_props() -> Value { + let mut props = game_prop(); + if let Some(map) = props.as_object_mut() { + map.insert( + "since".to_owned(), + json!({ "type": "integer", "minimum": 0, "description": + "Byte offset to resume from; 0 reads the newest window" }), + ); + map.insert( + "max_lines".to_owned(), + json!({ "type": "integer", "minimum": 1, "description": + "Maximum lines to return (default 200, capped at 2000)" }), + ); + } + props +} + // --- shared resolution ------------------------------------------------------ fn err(e: T) -> String { diff --git a/crates/modrix-plugin/src/fomod.rs b/crates/modrix-plugin/src/fomod.rs index 23883d0..0d808be 100644 --- a/crates/modrix-plugin/src/fomod.rs +++ b/crates/modrix-plugin/src/fomod.rs @@ -840,10 +840,7 @@ fn decode_text(bytes: &[u8]) -> String { } fn utf16(bytes: &[u8], from_bytes: fn([u8; 2]) -> u16) -> String { - let units = bytes - .chunks_exact(2) - .filter_map(|pair| <[u8; 2]>::try_from(pair).ok()) - .map(from_bytes); + let units = bytes.as_chunks::<2>().0.iter().copied().map(from_bytes); char::decode_utf16(units) .map(|r| r.unwrap_or('\u{fffd}')) .collect() diff --git a/crates/modrix-registry/src/lib.rs b/crates/modrix-registry/src/lib.rs index 16b55fb..f438f4f 100644 --- a/crates/modrix-registry/src/lib.rs +++ b/crates/modrix-registry/src/lib.rs @@ -618,7 +618,7 @@ mod tests { c.uninstall("testgame", &refs), Err(Error::InUse(_)) )); - assert!(c.gc(&refs).unwrap().is_empty()); + assert_eq!(c.gc(&refs).unwrap(), [] as [std::string::String; 0]); assert_eq!(c.installed().len(), 1); // Unreferenced: gc sweeps it. diff --git a/crates/modrix-service/Cargo.toml b/crates/modrix-service/Cargo.toml index 43d6a68..f1b2ef5 100644 --- a/crates/modrix-service/Cargo.toml +++ b/crates/modrix-service/Cargo.toml @@ -14,6 +14,8 @@ modrix-download.workspace = true modrix-plugin.workspace = true modrix-ipc.workspace = true anyhow.workspace = true +serde.workspace = true +serde_json.workspace = true tokio.workspace = true tracing.workspace = true diff --git a/crates/modrix-service/fixtures/sotf-catalog.json b/crates/modrix-service/fixtures/sotf-catalog.json new file mode 100644 index 0000000..e10ed5c --- /dev/null +++ b/crates/modrix-service/fixtures/sotf-catalog.json @@ -0,0 +1,342 @@ +{ + "status": true, + "data": [ + { + "id": 20, + "name": "Axel's Mod Menu", + "slug": "axel's-mod-menu", + "mod_id": "AxelModMenu", + "shortDescription": "Featurefull mod menu for Sons of The Forest", + "description": "# Warning\r\nNeeds my `SonsAxLib v1.2.0+` library to work, download it here: https://sotf-mods.com/mods/imaxel/sonsaxlib\r\n\r\n###", + "dependencies": [ + "SonsAxLib" + ], + "type": "Mod", + "modSide": null, + "isNSFW": false, + "isApproved": true, + "isFeatured": false, + "isMultiplayerCompatible": false, + "requiresAllPlayers": false, + "lastWeekDownloads": 455, + "downloads": 114160, + "latestVersion": "1.3.8", + "latestVersionSize": "", + "averageRating": 0, + "reviewsCount": 0, + "favoritesCount": 6, + "commentsCount": 9, + "sourceUrl": null, + "imageUrl": "https://r2.sotf-mods.com/1767665951899_1696956193461_axel's-mod-menu_thumbnail.png", + "buildGuid": null, + "buildShareVersion": null, + "numberOfElements": null, + "lastReleasedAt": "2026-04-05T18:33:04.942Z", + "createdAt": "2023-10-10T16:43:13.458Z", + "updatedAt": "2026-08-17T19:07:07.301Z", + "userId": 4, + "categoryId": 1, + "images": [], + "user": { + "name": "ImAxel", + "slug": "imaxel", + "imageUrl": "", + "isTrusted": true + }, + "category": { + "name": "Misc", + "slug": "misc" + }, + "versions": [ + { + "version": "1.0.0", + "isLatest": false + } + ], + "_count": { + "favorites": 6 + } + }, + { + "id": 19, + "name": "SonsAxLib", + "slug": "sonsaxlib", + "mod_id": "SonsAxLib", + "shortDescription": "Small library I made which is needed for some of my mods (e.g mod menu)", + "description": "Just drag and drop the `Libs` folder which is inside the .zip into the game folder (where mods folder is located)", + "dependencies": [], + "type": "Library", + "modSide": null, + "isNSFW": false, + "isApproved": true, + "isFeatured": false, + "isMultiplayerCompatible": false, + "requiresAllPlayers": false, + "lastWeekDownloads": 322, + "downloads": 89195, + "latestVersion": "1.2.1", + "latestVersionSize": "", + "averageRating": 0, + "reviewsCount": 0, + "favoritesCount": 0, + "commentsCount": 0, + "sourceUrl": null, + "imageUrl": "https://r2.sotf-mods.com/1767665954118_1696956108715_sonsaxlib_thumbnail.png", + "buildGuid": null, + "buildShareVersion": null, + "numberOfElements": null, + "lastReleasedAt": "2023-11-22T22:25:31.566Z", + "createdAt": "2023-10-10T16:41:48.703Z", + "updatedAt": "2026-08-17T19:00:05.892Z", + "userId": 4, + "categoryId": 4, + "images": [], + "user": { + "name": "ImAxel", + "slug": "imaxel", + "imageUrl": "", + "isTrusted": true + }, + "category": { + "name": "Library", + "slug": "library" + }, + "versions": [ + { + "version": "1.0.0", + "isLatest": false + } + ], + "_count": { + "favorites": 0 + } + }, + { + "id": 230, + "name": "Shops", + "slug": "shops", + "mod_id": "Shops", + "shortDescription": "Adds an ingame shop", + "description": "More info coming soon,\r\n## Mod Requirements:\r\n- [SimpleNetworkEvents](https://sotf-mods.com/profile/smokyace)\r\n- [Banking](https://sotf-mods.com/mods/smokyace/b", + "dependencies": [ + "SimpleNetworkEvents", + "Banking" + ], + "type": "Mod", + "modSide": null, + "isNSFW": false, + "isApproved": true, + "isFeatured": false, + "isMultiplayerCompatible": false, + "requiresAllPlayers": false, + "lastWeekDownloads": 28, + "downloads": 4723, + "latestVersion": "1.0.0", + "latestVersionSize": "", + "averageRating": 0, + "reviewsCount": 0, + "favoritesCount": 1, + "commentsCount": 1, + "sourceUrl": null, + "imageUrl": "https://r2.sotf-mods.com/1767666399740_1738804683344_shops_thumbnail.png", + "buildGuid": null, + "buildShareVersion": null, + "numberOfElements": null, + "lastReleasedAt": "2025-02-06T01:18:05.050Z", + "createdAt": "2025-02-06T01:18:05.050Z", + "updatedAt": "2026-08-17T19:00:05.857Z", + "userId": 6, + "categoryId": 1, + "images": [], + "user": { + "name": "SmokyAce", + "slug": "smokyace", + "imageUrl": "", + "isTrusted": true + }, + "category": { + "name": "Misc", + "slug": "misc" + }, + "versions": [ + { + "version": "1.0.0", + "isLatest": true + } + ], + "_count": { + "favorites": 1 + } + }, + { + "id": 74, + "name": "BuildShare", + "slug": "buildshare", + "mod_id": "BuildShare", + "shortDescription": "Share your buildings with the world.", + "description": "## Introducing Build Share open alpha. Create building prefabs and import them as blueprints\r\n\r\n\r\nIn the open alpha uploading is not yet supported. For the ful", + "dependencies": [], + "type": "Mod", + "modSide": null, + "isNSFW": false, + "isApproved": true, + "isFeatured": false, + "isMultiplayerCompatible": false, + "requiresAllPlayers": false, + "lastWeekDownloads": 134, + "downloads": 22626, + "latestVersion": "1.0.10", + "latestVersionSize": "", + "averageRating": 0, + "reviewsCount": 0, + "favoritesCount": 2, + "commentsCount": 2, + "sourceUrl": null, + "imageUrl": "https://r2.sotf-mods.com/1767666383118_1702916367133_buildshare_thumbnail.png", + "buildGuid": null, + "buildShareVersion": null, + "numberOfElements": null, + "lastReleasedAt": "2025-01-29T23:36:38.853Z", + "createdAt": "2023-12-18T16:19:27.103Z", + "updatedAt": "2026-08-17T19:00:01.311Z", + "userId": 8, + "categoryId": 1, + "images": [], + "user": { + "name": "ToniMacaroni", + "slug": "tonimacaroni", + "imageUrl": "", + "isTrusted": true + }, + "category": { + "name": "Misc", + "slug": "misc" + }, + "versions": [ + { + "version": "1.0.0", + "isLatest": false + } + ], + "_count": { + "favorites": 2 + } + }, + { + "id": 276, + "name": "Don't usee22", + "slug": "regi's-modding-library", + "mod_id": "Regi_s_Modding_Library", + "shortDescription": "Don't use", + "description": "Don't use", + "dependencies": [], + "type": "Library", + "modSide": "server", + "isNSFW": false, + "isApproved": false, + "isFeatured": false, + "isMultiplayerCompatible": false, + "requiresAllPlayers": false, + "lastWeekDownloads": 0, + "downloads": 1, + "latestVersion": "1.0.0", + "latestVersionSize": "", + "averageRating": 0, + "reviewsCount": 0, + "favoritesCount": 0, + "commentsCount": 0, + "sourceUrl": null, + "imageUrl": "https://r2.sotf-mods.com/1766549872128_regi's-modding-library_thumbnail.png", + "buildGuid": null, + "buildShareVersion": null, + "numberOfElements": null, + "lastReleasedAt": "2025-12-24T04:10:33.460Z", + "createdAt": "2025-12-24T04:10:33.460Z", + "updatedAt": "2026-08-17T19:00:05.972Z", + "userId": 413, + "categoryId": 4, + "images": [], + "user": { + "name": "RegiToXic", + "slug": "regitoxic", + "imageUrl": "https://r2.sotf-mods.com/1766549148234_413_avatar.png", + "isTrusted": true + }, + "category": { + "name": "Library", + "slug": "library" + }, + "versions": [ + { + "version": "1.0.0", + "isLatest": true + } + ], + "_count": { + "favorites": 0 + } + }, + { + "id": 39, + "name": "ItemSpawner", + "slug": "itemspawner", + "mod_id": "ItemSpawner", + "shortDescription": "Lets you search and spawn items in the game (also non-spawnable ones).", + "description": "# Item Spawner\r\n\r\n\r\n**Make sure you have RedLoader 0.6.0 or above installed**\r\n\r\nLets you search and spawn items in the game. By default you can pull up the pan", + "dependencies": [], + "type": null, + "modSide": null, + "isNSFW": false, + "isApproved": true, + "isFeatured": false, + "isMultiplayerCompatible": false, + "requiresAllPlayers": false, + "lastWeekDownloads": 10, + "downloads": 15359, + "latestVersion": "1.0.1", + "latestVersionSize": "", + "averageRating": 0, + "reviewsCount": 0, + "favoritesCount": 1, + "commentsCount": 0, + "sourceUrl": null, + "imageUrl": "https://r2.sotf-mods.com/1767665954110_1700595085313_itemspawner_thumbnail.png", + "buildGuid": null, + "buildShareVersion": null, + "numberOfElements": null, + "lastReleasedAt": "2023-11-21T14:00:38.295Z", + "createdAt": "2023-11-20T21:58:27.324Z", + "updatedAt": "2026-08-17T19:00:05.685Z", + "userId": 8, + "categoryId": 1, + "images": [], + "user": { + "name": "ToniMacaroni", + "slug": "tonimacaroni", + "imageUrl": "", + "isTrusted": true + }, + "category": { + "name": "Misc", + "slug": "misc" + }, + "versions": [ + { + "version": "1.0.0", + "isLatest": false + } + ], + "_count": { + "favorites": 1 + } + } + ], + "meta": { + "total": 6, + "page": 1, + "limit": 500, + "pages": 1, + "next_page": 1, + "prev_page": 1 + } +} diff --git a/crates/modrix-service/fixtures/sotf-detail-axel.json b/crates/modrix-service/fixtures/sotf-detail-axel.json new file mode 100644 index 0000000..a2a143a --- /dev/null +++ b/crates/modrix-service/fixtures/sotf-detail-axel.json @@ -0,0 +1,109 @@ +{ + "status": true, + "data": { + "id": 20, + "name": "Axel's Mod Menu", + "slug": "axel's-mod-menu", + "mod_id": "AxelModMenu", + "shortDescription": "Featurefull mod menu for Sons of The Forest", + "description": "# Warning\r\nNeeds my `SonsAxLib v1.2.0+` library to work, download it here: https://sotf-mods.com/mods/imaxel/sonsaxlib\r\n\r\n###", + "dependencies": "SonsAxLib", + "type": "Mod", + "modSide": null, + "isNSFW": false, + "isApproved": true, + "isFeatured": false, + "isMultiplayerCompatible": false, + "requiresAllPlayers": false, + "lastWeekDownloads": 455, + "downloads": 114160, + "latestVersion": "1.3.8", + "latestVersionSize": "", + "averageRating": 0, + "reviewsCount": 0, + "favoritesCount": 6, + "commentsCount": 9, + "sourceUrl": null, + "imageUrl": "https://r2.sotf-mods.com/1767665951899_1696956193461_axel's-mod-menu_thumbnail.png", + "buildGuid": null, + "buildShareVersion": null, + "numberOfElements": null, + "lastReleasedAt": "2026-04-05T18:33:04.942Z", + "createdAt": "2023-10-10T16:43:13.458Z", + "updatedAt": "2026-08-17T19:07:07.301Z", + "userId": 4, + "categoryId": 1, + "images": [], + "user": { + "name": "ImAxel", + "slug": "imaxel", + "imageUrl": "", + "isTrusted": true + }, + "category": { + "name": "Misc", + "slug": "misc" + }, + "versions": [ + { + "id": 664, + "version": "1.3.8", + "isLatest": true, + "changelog": "Fixed noclip causing issues with riding ziplines and character physics override", + "downloadUrl": "https://r2.sotf-mods.com/1775413983720_axel's-mod-menu_1.3.8.zip", + "extension": "zip", + "filename": "1775413983720_axel's-mod-menu_1.3.8.zip", + "createdAt": "2026-04-05T18:33:04.943Z", + "updatedAt": "2026-04-05T18:33:04.943Z", + "_count": { + "downloads": 15641 + } + }, + { + "id": 365, + "version": "1.3.7", + "isLatest": false, + "changelog": "Fixed saved daytime speed not applying on game start", + "downloadUrl": "https://r2.sotf-mods.com/1767668359472_1720112606809_axel's-mod-menu_1.3.7.zip", + "extension": "zip", + "filename": "1720112606809_axel's-mod-menu_1.3.7.zip", + "createdAt": "2024-07-04T17:03:27.260Z", + "updatedAt": "2026-04-05T18:33:04.937Z", + "_count": { + "downloads": 72332 + } + }, + { + "id": 364, + "version": "1.3.6", + "isLatest": false, + "changelog": "Daytime speed will now also be saved upon game restart if \"save settings\" is enabled", + "downloadUrl": "https://r2.sotf-mods.com/1767668367048_1720112355161_axel's-mod-menu_1.3.6.zip", + "extension": "zip", + "filename": "1720112355161_axel's-mod-menu_1.3.6.zip", + "createdAt": "2024-07-04T16:59:16.740Z", + "updatedAt": "2026-04-05T18:33:04.937Z", + "_count": { + "downloads": 1 + } + }, + { + "id": 315, + "version": "1.3.5", + "isLatest": false, + "changelog": "Disabled HUD when interactive map is open to avoid overlying text", + "downloadUrl": "https://r2.sotf-mods.com/1767669001602_1715157214354_axel's-mod-menu_1.3.5.zip", + "extension": "zip", + "filename": "1715157214354_axel's-mod-menu_1.3.5.zip", + "createdAt": "2024-05-08T08:33:34.765Z", + "updatedAt": "2026-04-05T18:33:04.937Z", + "_count": { + "downloads": 4756 + } + } + ], + "_count": { + "favorites": 6 + } + } +} diff --git a/crates/modrix-service/fixtures/sotf-detail-buildshare.json b/crates/modrix-service/fixtures/sotf-detail-buildshare.json new file mode 100644 index 0000000..1bee7c7 --- /dev/null +++ b/crates/modrix-service/fixtures/sotf-detail-buildshare.json @@ -0,0 +1,179 @@ +{ + "status": true, + "data": { + "id": 74, + "name": "BuildShare", + "slug": "buildshare", + "mod_id": "BuildShare", + "shortDescription": "Share your buildings with the world.", + "description": "## Introducing Build Share open alpha. Create building prefabs and import them as blueprints\r\n\r\n\r\nIn the open alpha uploading is not yet supported. For the ful", + "dependencies": "", + "type": "Mod", + "modSide": null, + "isNSFW": false, + "isApproved": true, + "isFeatured": false, + "isMultiplayerCompatible": false, + "requiresAllPlayers": false, + "lastWeekDownloads": 134, + "downloads": 22626, + "latestVersion": "1.0.10", + "latestVersionSize": "", + "averageRating": 0, + "reviewsCount": 0, + "favoritesCount": 2, + "commentsCount": 2, + "sourceUrl": null, + "imageUrl": "https://r2.sotf-mods.com/1767666383118_1702916367133_buildshare_thumbnail.png", + "buildGuid": null, + "buildShareVersion": null, + "numberOfElements": null, + "lastReleasedAt": "2025-01-29T23:36:38.853Z", + "createdAt": "2023-12-18T16:19:27.103Z", + "updatedAt": "2026-08-17T19:00:01.311Z", + "userId": 8, + "categoryId": 1, + "images": [], + "user": { + "name": "ToniMacaroni", + "slug": "tonimacaroni", + "imageUrl": "", + "isTrusted": true + }, + "category": { + "name": "Misc", + "slug": "misc" + }, + "versions": [ + { + "id": 226, + "version": "1.0.8", + "isLatest": false, + "changelog": "Fix not being able to place buildings on new games.", + "downloadUrl": "https://r2.sotf-mods.com/1767668351060_1710694865825_buildshare_1.0.8.zip", + "extension": "zip", + "filename": "1710694865825_buildshare_1.0.8.zip", + "createdAt": "2024-03-17T17:01:05.885Z", + "updatedAt": "2026-01-06T02:59:11.519Z", + "_count": { + "downloads": 4844 + } + }, + { + "id": 225, + "version": "1.0.7", + "isLatest": false, + "changelog": "Recompile that might fix some placing issues.", + "downloadUrl": "https://r2.sotf-mods.com/1767668350750_1710693481987_buildshare_1.0.7.zip", + "extension": "zip", + "filename": "1710693481987_buildshare_1.0.7.zip", + "createdAt": "2024-03-17T16:38:02.065Z", + "updatedAt": "2026-01-06T02:59:11.206Z", + "_count": { + "downloads": 4 + } + }, + { + "id": 174, + "version": "1.0.6", + "isLatest": false, + "changelog": "Quick fix for SOTF 1.0", + "downloadUrl": "https://r2.sotf-mods.com/1767668940029_1709230978600_buildshare_1.0.6.zip", + "extension": "zip", + "filename": "1709230978600_buildshare_1.0.6.zip", + "createdAt": "2024-02-29T18:22:58.661Z", + "updatedAt": "2026-01-06T03:09:00.614Z", + "_count": { + "downloads": 1198 + } + }, + { + "id": 142, + "version": "1.0.4", + "isLatest": false, + "changelog": "Fixed duplication of original building", + "downloadUrl": "https://r2.sotf-mods.com/1767668243029_1704041784782_buildshare_1.0.4.zip", + "extension": "zip", + "filename": "1704041784782_buildshare_1.0.4.zip", + "createdAt": "2023-12-31T16:56:24.979Z", + "updatedAt": "2026-01-06T02:57:23.533Z", + "_count": { + "downloads": 1837 + } + }, + { + "id": 140, + "version": "1.0.3", + "isLatest": false, + "changelog": "Fixed places in-progress blueprints not saving correctly", + "downloadUrl": "https://r2.sotf-mods.com/1767668242952_1703109632183_buildshare_1.0.3.zip", + "extension": "zip", + "filename": "1703109632183_buildshare_1.0.3.zip", + "createdAt": "2023-12-20T22:00:32.302Z", + "updatedAt": "2026-01-06T02:57:23.412Z", + "_count": { + "downloads": 546 + } + }, + { + "id": 138, + "version": "1.0.2", + "isLatest": false, + "changelog": "Constraint RedLoader version", + "downloadUrl": "https://r2.sotf-mods.com/1767668242951_1702932624568_buildshare_1.0.2.zip", + "extension": "zip", + "filename": "1702932624568_buildshare_1.0.2.zip", + "createdAt": "2023-12-18T20:50:24.657Z", + "updatedAt": "2026-01-06T02:57:23.518Z", + "_count": { + "downloads": 371 + } + }, + { + "id": 479, + "version": "1.0.10", + "isLatest": true, + "changelog": "Fix for new game version", + "downloadUrl": "https://r2.sotf-mods.com/1767668375925_1738193798432_buildshare_1.0.10.zip", + "extension": "zip", + "filename": "1738193798432_buildshare_1.0.10.zip", + "createdAt": "2025-01-29T23:36:38.819Z", + "updatedAt": "2026-01-06T02:59:36.381Z", + "_count": { + "downloads": 13793 + } + }, + { + "id": 137, + "version": "1.0.1", + "isLatest": false, + "changelog": "Remove some debugging stuff", + "downloadUrl": "https://r2.sotf-mods.com/1767668242958_1702920087009_buildshare_1.0.1.zip", + "extension": "zip", + "filename": "1702920087009_buildshare_1.0.1.zip", + "createdAt": "2023-12-18T17:21:27.080Z", + "updatedAt": "2026-01-06T02:57:23.433Z", + "_count": { + "downloads": 13 + } + }, + { + "id": 136, + "version": "1.0.0", + "isLatest": false, + "changelog": "First release", + "downloadUrl": "https://r2.sotf-mods.com/1767668242976_1702916367664_buildshare_1.0.0.zip", + "extension": "zip", + "filename": "1702916367664_buildshare_1.0.0.zip", + "createdAt": "2023-12-18T16:19:27.103Z", + "updatedAt": "2026-01-06T02:57:23.417Z", + "_count": { + "downloads": 20 + } + } + ], + "_count": { + "favorites": 2 + } + } +} diff --git a/crates/modrix-service/src/lib.rs b/crates/modrix-service/src/lib.rs index d272ad5..aa4ce74 100644 --- a/crates/modrix-service/src/lib.rs +++ b/crates/modrix-service/src/lib.rs @@ -13,6 +13,8 @@ //! single-instance primary and serves the listener in the background; //! frontends keep the same `Service` to answer their own UI queries. +pub mod store; + use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; @@ -228,6 +230,20 @@ impl Service { fn try_enqueue(&self, body: &str) -> Result { let job = HandoffJob::from_json(body).context("parsing the hand-off")?; + self.enqueue_job(job) + } + + /// Queue an already-built hand-off job, exactly as if the browser had sent + /// it: it is routed to a game, downloaded, and auto-staged by the same + /// pipeline. This is what lets an in-app source (the mod store) install + /// with one click without duplicating any of that machinery. + /// + /// # Errors + /// + /// Returns an error if the job fails validation (bad URL, unusable + /// filename), the download cannot be queued, or the route table is + /// poisoned. + pub fn enqueue_job(&self, job: HandoffJob) -> Result { let game = self.route(&job); // Each hand-off downloads into its own subdirectory, so two downloads // that share a filename never collide on .part / .mmdl / destination. diff --git a/crates/modrix-service/src/store.rs b/crates/modrix-service/src/store.rs new file mode 100644 index 0000000..641cfed --- /dev/null +++ b/crates/modrix-service/src/store.rs @@ -0,0 +1,593 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Client for the community mod stores a game definition can declare. +//! +//! Today that means `sotf-mods.com`, the Sons of the Forest community store: a +//! public, unauthenticated JSON API. This module knows its shape so that +//! `modrix-core` does not - core only carries `[store] { kind, base_url }` and +//! exposes it as the `store` capability. +//! +//! Installing is deliberately *not* a second download pipeline. Resolution ends +//! in a [`HandoffJob`] per mod, handed to [`Service::enqueue_job`], so a store +//! install is the same segmented, resumable, auto-staged path a browser click +//! takes. +//! +//! ## What this API does that a naive client gets wrong +//! +//! Every one of these is verified against the live service and pinned by a test +//! over a captured fixture in `fixtures/`: +//! +//! 1. `type` defaults to `Mod`, which hides every `Library`. Dependencies are +//! almost always libraries, so `type=Both` is mandatory or dependency +//! resolution silently finds nothing. +//! 2. Omitting `approved` **disables** the approval filter rather than +//! defaulting it on. `approved=true` must be sent literally. +//! 3. `dependencies` is a JSON array on the list endpoint and a +//! comma-separated string on the detail endpoint. Both are accepted here. +//! 4. `versions` on the list endpoint is a single arbitrary *old* entry, and +//! even on the detail endpoint the latest is not necessarily first +//! (`BuildShare` has it at index 6). The `isLatest` flag decides; index 0 +//! never does. +//! +//! [`Service::enqueue_job`]: crate::Service::enqueue_job + +use std::collections::{BTreeMap, HashSet, VecDeque}; +use std::sync::Arc; + +use anyhow::{Context as _, Result, anyhow, bail}; +use modrix_download::http::HttpClient; +use modrix_download::{GameHint, HandoffJob}; + +/// The `store.kind` this client handles. +pub const SOTF_MODS_KIND: &str = "sotf-mods"; + +/// What Modrix identifies itself as to a store API. +const USER_AGENT: &str = concat!("Modrix/", env!("CARGO_PKG_VERSION")); + +/// Hard cap on any store response body. The whole catalog is ~300 KiB, so this +/// is orders of magnitude of headroom while still bounding what a hostile or +/// broken origin can make us allocate. +const MAX_BODY_BYTES: usize = 8 * 1024 * 1024; + +/// Catalog page size. The store has ~200 mods, so one page is the whole thing; +/// [`StoreCatalog::truncated`] reports it if that ever stops being true. +const CATALOG_LIMIT: u32 = 500; + +/// Simultaneous requests this client will make. The store asks for nothing and +/// rate-limits nothing; this is politeness, not a limit being worked around. +const MAX_IN_FLIGHT: usize = 4; + +/// How deep a dependency chain may go before it is treated as malformed. Real +/// chains are one or two links; this only exists so a pathological graph cannot +/// walk forever even with the cycle guard. +const MAX_DEPTH: usize = 8; + +/// How many mods one install may pull in. A one-click action that queues +/// hundreds of downloads is a bug, not a feature. +const MAX_PLAN_ITEMS: usize = 32; + +// --- model ------------------------------------------------------------------- + +/// One mod (or library, or build) as the store describes it. +/// +/// Only the fields Modrix acts on are modelled; unknown fields are ignored, so +/// the store adding columns never breaks parsing. +#[derive(Debug, Clone, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StoreItem { + /// The store's numeric row id. Not an addressable identifier: the detail + /// endpoint is keyed by [`mod_id`](Self::mod_id), and passing this instead + /// answers 404. + pub id: i64, + /// Display name (e.g. `Axel's Mod Menu`). + pub name: String, + /// URL slug on the website. Free-form: a real one is `axel's-mod-menu`, so + /// it is never interpolated into a URL unencoded. + #[serde(default)] + pub slug: String, + /// The stable string identifier the detail and download endpoints use, and + /// the name other mods list as a dependency. + #[serde(rename = "mod_id")] + pub mod_id: String, + /// One-line summary shown in the list. + #[serde(default)] + pub short_description: Option, + /// The [`mod_id`](Self::mod_id)s this mod needs. Array or comma-separated + /// string depending on the endpoint - see the module docs. + #[serde(default, deserialize_with = "deserialize_dependencies")] + pub dependencies: Vec, + /// `Mod`, `Library`, `Build`, or absent on older rows. + #[serde(rename = "type", default)] + pub kind: Option, + /// Whether a moderator approved it. Never assume: the API only filters on + /// this when explicitly asked to. + #[serde(default)] + pub is_approved: bool, + /// Whether it is flagged adult. + #[serde(rename = "isNSFW", default)] + pub is_nsfw: bool, + /// All-time download count (the catalog's default ordering). + #[serde(default)] + pub downloads: u64, + /// The current version string. Authoritative - unlike + /// [`versions`](Self::versions) on the list endpoint. + #[serde(default)] + pub latest_version: Option, + /// Released versions. One stale entry on the list endpoint; the full set, + /// in no particular order, on the detail endpoint. + #[serde(default)] + pub versions: Vec, + /// The author. + #[serde(default)] + pub user: Option, +} + +/// One released version of a mod. +#[derive(Debug, Clone, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StoreVersion { + /// The version string (e.g. `1.3.8`). + pub version: String, + /// Whether this is the current release. The **only** trustworthy way to + /// pick a version; ordering is not. + #[serde(default)] + pub is_latest: bool, + /// Direct CDN URL for the archive. Present on the detail endpoint only. + #[serde(default)] + pub download_url: Option, + /// The archive's original filename. + #[serde(default)] + pub filename: Option, +} + +/// A mod author. +#[derive(Debug, Clone, serde::Deserialize)] +pub struct StoreUser { + /// Display name. + #[serde(default)] + pub name: String, +} + +/// A parsed catalog page. +#[derive(Debug, Clone)] +pub struct StoreCatalog { + /// Installable items (approved, not adult), most-downloaded first. + pub items: Vec, + /// True if the store reported more pages than were fetched, so dependency + /// resolution may not see every library. + pub truncated: bool, +} + +/// What a one-click install resolved to. +#[derive(Debug, Clone)] +pub struct InstallPlan { + /// Everything to install, **dependencies first** and the requested mod + /// last, so the queue installs them in a usable order. + pub items: Vec, + /// Dependencies skipped because they are already installed. + pub satisfied: Vec, + /// Dependencies the catalog does not contain. Usually a library that is + /// unapproved or withdrawn - the mod will install but may not load, so the + /// caller is expected to say so rather than pretend success. + pub missing: Vec, +} + +impl StoreItem { + /// Whether Modrix will offer this item at all. + #[must_use] + pub fn is_installable(&self) -> bool { + self.is_approved && !self.is_nsfw + } + + /// Whether this item is a library (a dependency rather than a thing a user + /// picks). Absent `type` is treated as a plain mod, matching the store's + /// own default. + #[must_use] + pub fn is_library(&self) -> bool { + self.kind.as_deref() == Some("Library") + } + + /// The author's display name, when the store returned one. + #[must_use] + pub fn author(&self) -> Option<&str> { + self.user.as_ref().map(|u| u.name.as_str()) + } + + /// The current release's entry. + /// + /// Selection is by the `isLatest` flag, then by matching the top-level + /// `latestVersion`. It deliberately never falls back to `versions[0]`: on + /// the list endpoint that is an arbitrary old release, and on the detail + /// endpoint the entries are unordered. + #[must_use] + pub fn latest(&self) -> Option<&StoreVersion> { + self.versions + .iter() + .find(|v| v.is_latest) + .or_else(|| self.latest_version.as_deref().and_then(|w| self.find(w))) + } + + fn find(&self, version: &str) -> Option<&StoreVersion> { + self.versions.iter().find(|v| v.version == version) + } + + /// Case-insensitive identity key, used for cycle and duplicate detection. + fn key(&self) -> String { + self.mod_id.to_ascii_lowercase() + } +} + +// --- parsing ----------------------------------------------------------------- + +/// The `{ status, data }` envelope every endpoint wraps its payload in. +#[derive(serde::Deserialize)] +struct Envelope { + data: T, +} + +/// Paging counters returned beside a list. +#[derive(serde::Deserialize)] +struct Meta { + #[serde(default)] + pages: u32, +} + +#[derive(serde::Deserialize)] +struct ListEnvelope { + data: Vec, + #[serde(default)] + meta: Option, +} + +/// Accept `dependencies` as either a JSON array or a comma-separated string. +/// +/// The two endpoints genuinely disagree - the list returns `["SonsAxLib"]` and +/// the detail returns `"SimpleNetworkEvents,Banking"` - so a client that models +/// only one of them either fails to parse half the API or resolves nothing. +/// +/// # Errors +/// +/// Returns the deserializer's error if the field is neither shape. +fn deserialize_dependencies<'de, D>(deserializer: D) -> Result, D::Error> +where + D: serde::Deserializer<'de>, +{ + #[derive(serde::Deserialize)] + #[serde(untagged)] + enum Raw { + List(Vec), + Csv(String), + } + use serde::Deserialize as _; + // `Option` absorbs an explicit JSON null, which the store also sends. + let raw = Option::::deserialize(deserializer)?; + let parts: Vec = match raw { + None => Vec::new(), + Some(Raw::List(list)) => list, + Some(Raw::Csv(text)) => text.split(',').map(str::to_owned).collect(), + }; + Ok(parts + .into_iter() + .map(|p| p.trim().to_owned()) + .filter(|p| !p.is_empty()) + .collect()) +} + +/// Parse a catalog response, dropping anything not installable. +/// +/// The approval and adult filters are re-applied here even though the query +/// asks for them: they are query *parameters*, and a parameter that is dropped, +/// renamed, or ignored server-side fails open. +/// +/// # Errors +/// +/// Returns an error if the body is not the expected JSON envelope. +pub fn parse_catalog(body: &[u8]) -> Result { + let parsed: ListEnvelope = serde_json::from_slice(body).context("parsing the store catalog")?; + let truncated = parsed.meta.is_some_and(|m| m.pages > 1); + let items = parsed + .data + .into_iter() + .filter(StoreItem::is_installable) + .collect(); + Ok(StoreCatalog { items, truncated }) +} + +/// Parse a single-mod detail response. +/// +/// # Errors +/// +/// Returns an error if the body is not the expected JSON envelope. +pub fn parse_detail(body: &[u8]) -> Result { + let parsed: Envelope = + serde_json::from_slice(body).context("parsing the store mod detail")?; + Ok(parsed.data) +} + +// --- URLs -------------------------------------------------------------------- + +/// The catalog URL for a store origin. +/// +/// `type=Both` and `approved=true` are not defaults being restated: without the +/// first the API hides every library, and without the second it disables the +/// approval filter entirely. +#[must_use] +pub fn catalog_url(base_url: &str) -> String { + format!( + "{base_url}/api/mods?type=Both&approved=true&nsfw=false&limit={CATALOG_LIMIT}\ + &orderby=most_downloaded" + ) +} + +/// The detail URL for one mod id. +#[must_use] +pub fn detail_url(base_url: &str, mod_id: &str) -> String { + format!("{base_url}/api/mods/{}", percent_encode(mod_id)) +} + +/// Percent-encode one URL path segment, keeping only RFC 3986 unreserved +/// characters. Store identifiers and slugs are author-supplied free text - +/// `axel's-mod-menu` is a real slug - so nothing goes into a URL raw. +fn percent_encode(segment: &str) -> String { + use std::fmt::Write as _; + let mut out = String::with_capacity(segment.len()); + for byte in segment.bytes() { + if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') { + out.push(char::from(byte)); + } else { + // Writing to a String cannot fail, so there is no error to handle. + let _ = write!(out, "%{byte:02X}"); + } + } + out +} + +// --- dependency resolution --------------------------------------------------- + +/// Resolve everything installing `mod_id` implies, from an already-fetched +/// catalog. +/// +/// The whole graph is available in the catalog (every row carries its own +/// `dependencies`), so this needs no network and is a pure function of its +/// inputs - which is what makes it testable against a captured fixture. +/// +/// The walk is an explicit worklist rather than recursion, and every id is +/// entered into `visited` before it is expanded. That is what makes a cycle +/// (`A` needs `B`, `B` needs `A`) terminate instead of recursing forever, and +/// it also collapses a diamond to one install. `installed` (lowercased mod ids +/// and mod names already present) is consulted per node, so re-installing a mod +/// whose library is already there queues only the mod. +/// +/// # Errors +/// +/// Returns an error if `mod_id` is not in the catalog, or if the graph pulls in +/// more than [`MAX_PLAN_ITEMS`] mods. +pub fn resolve_plan( + catalog: &[StoreItem], + mod_id: &str, + installed: &HashSet, +) -> Result { + let root = find_item(catalog, mod_id) + .ok_or_else(|| anyhow!("`{mod_id}` is not in the store catalog"))?; + let mut visited: HashSet = HashSet::new(); + visited.insert(root.key()); + let mut work: VecDeque<(String, usize)> = VecDeque::new(); + for dep in &root.dependencies { + work.push_back((dep.clone(), 1)); + } + let mut plan = InstallPlan { + items: Vec::new(), + satisfied: Vec::new(), + missing: Vec::new(), + }; + while let Some((dep_id, depth)) = work.pop_front() { + if plan.items.len() >= MAX_PLAN_ITEMS { + bail!("installing `{mod_id}` would pull in more than {MAX_PLAN_ITEMS} mods"); + } + let key = dep_id.to_ascii_lowercase(); + if !visited.insert(key.clone()) { + continue; + } + if installed.contains(&key) { + plan.satisfied.push(dep_id); + continue; + } + let Some(item) = find_item(catalog, &dep_id) else { + plan.missing.push(dep_id); + continue; + }; + if let Some(next) = depth.checked_add(1).filter(|d| *d <= MAX_DEPTH) { + for dep in &item.dependencies { + work.push_back((dep.clone(), next)); + } + } + plan.items.push(item.clone()); + } + // Dependencies queue first so they are staged before the mod that needs them. + plan.items.push(root.clone()); + Ok(plan) +} + +/// Find a catalog row by mod id, case-insensitively (authors are inconsistent +/// about casing when listing a dependency). +fn find_item<'a>(catalog: &'a [StoreItem], mod_id: &str) -> Option<&'a StoreItem> { + let want = mod_id.to_ascii_lowercase(); + catalog.iter().find(|item| item.key() == want) +} + +/// Build the lookup set [`resolve_plan`] consults, from the names and ids of mods that +/// are already installed for the game. +#[must_use] +pub fn installed_keys<'a>(names: impl IntoIterator) -> HashSet { + names + .into_iter() + .map(|n| n.trim().to_ascii_lowercase()) + .filter(|n| !n.is_empty()) + .collect() +} + +// --- hand-off ---------------------------------------------------------------- + +/// Turn a **detail** item into the download hand-off that installs it. +/// +/// `domain` is the game's Nexus domain, which is what routes the finished +/// download to the right game; `None` leaves it unrouted and the archive stays +/// in the download directory. +/// +/// The direct CDN URL is strongly preferred: the store's own +/// `/api/mods/{id}/download/{version}` route answers a `Range` request with +/// `200` and the whole body (with a `Content-Range` header that contradicts +/// it), so it can only ever be a single non-resumable connection. +/// +/// # Errors +/// +/// Returns an error if the item carries no identifiable current version. +pub fn handoff_job(item: &StoreItem, base_url: &str, domain: Option<&str>) -> Result { + let version = item + .latest() + .ok_or_else(|| anyhow!("`{}` has no current version to download", item.mod_id))?; + let url = match version.download_url.as_deref() { + Some(direct) if direct.starts_with("https://") => direct.to_owned(), + _ => format!( + "{base_url}/api/mods/{}/download/{}", + percent_encode(&item.mod_id), + percent_encode(&version.version) + ), + }; + let filename = version + .filename + .clone() + .filter(|f| !f.trim().is_empty()) + .unwrap_or_else(|| format!("{}-{}.zip", item.mod_id, version.version)); + Ok(HandoffJob { + schema_version: 1, + url, + filename, + mime: Some("application/zip".to_owned()), + referrer: None, + user_agent: Some(USER_AGENT.to_owned()), + cookie: None, + headers: BTreeMap::new(), + total_bytes: None, + page_url: None, + game_hint: domain.map(|d| GameHint { + domain: Some(d.to_owned()), + numeric_id: None, + }), + }) +} + +// --- client ------------------------------------------------------------------ + +/// An HTTP client for one store origin. +#[derive(Clone)] +pub struct StoreClient { + http: HttpClient, + base_url: String, + /// Caps simultaneous requests at [`MAX_IN_FLIGHT`] even when several + /// resolutions run at once. + gate: Arc, +} + +impl std::fmt::Debug for StoreClient { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("StoreClient") + .field("base_url", &self.base_url) + .finish_non_exhaustive() + } +} + +impl StoreClient { + /// Build a client for a `[store]` table's `base_url`. + /// + /// # Errors + /// + /// Returns an error if `base_url` is not an https origin, or if the TLS + /// stack cannot be initialized. + pub fn new(base_url: &str) -> Result { + let base_url = base_url.trim_end_matches('/').to_owned(); + if !base_url.starts_with("https://") { + bail!("store base_url `{base_url}` must be an https:// origin"); + } + Ok(Self { + http: HttpClient::new().context("building the store HTTP client")?, + base_url, + gate: Arc::new(tokio::sync::Semaphore::new(MAX_IN_FLIGHT)), + }) + } + + /// Fetch the installable catalog, most-downloaded first. + /// + /// # Errors + /// + /// Returns an error on any transport failure, a non-200 status, an + /// over-cap body, or a malformed response. + pub async fn catalog(&self) -> Result { + let body = self.get(&catalog_url(&self.base_url)).await?; + parse_catalog(&body) + } + + /// Fetch one mod's detail, which is the only place a downloadable version + /// (and its CDN URL) appears. + /// + /// # Errors + /// + /// As [`Self::catalog`], plus a 404 for an unknown mod id. + pub async fn detail(&self, mod_id: &str) -> Result { + let body = self.get(&detail_url(&self.base_url, mod_id)).await?; + parse_detail(&body) + } + + /// Resolve `mod_id` and everything it needs into ready-to-queue hand-offs, + /// dependencies first. + /// + /// # Errors + /// + /// Returns an error if the catalog cannot be fetched, `mod_id` is not in + /// it, or no resolved mod has a downloadable version. + pub async fn install_jobs( + &self, + mod_id: &str, + installed: &HashSet, + domain: Option<&str>, + ) -> Result<(Vec, InstallPlan)> { + let catalog = self.catalog().await?; + let plan = resolve_plan(&catalog.items, mod_id, installed)?; + let mut jobs = Vec::with_capacity(plan.items.len()); + for item in &plan.items { + // The catalog's `versions` is a stale stub with no URL, so the + // download always comes from a detail fetch. + let detail = self + .detail(&item.mod_id) + .await + .with_context(|| format!("looking up `{}`", item.mod_id))?; + jobs.push(handoff_job(&detail, &self.base_url, domain)?); + } + Ok((jobs, plan)) + } + + /// One capped GET, identified as Modrix. + async fn get(&self, url: &str) -> Result> { + let _permit = self + .gate + .acquire() + .await + .map_err(|_| anyhow!("the store client was shut down"))?; + let headers = [("User-Agent", USER_AGENT.to_owned())]; + let response = self + .http + .get(url, &headers) + .await + .with_context(|| format!("GET {url}"))?; + if response.status != 200 { + bail!("GET {url} returned {}", response.status); + } + response + .bytes(MAX_BODY_BYTES) + .await + .with_context(|| format!("reading {url}")) + } +} + +#[cfg(test)] +#[path = "store_tests.rs"] +mod store_tests; diff --git a/crates/modrix-service/src/store_tests.rs b/crates/modrix-service/src/store_tests.rs new file mode 100644 index 0000000..02cfbb4 --- /dev/null +++ b/crates/modrix-service/src/store_tests.rs @@ -0,0 +1,412 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Tests for the store client, over JSON captured from the live API. +//! +//! Nothing here touches the network: the fixtures in `fixtures/` are verbatim +//! (only long prose fields truncated) responses from `api.sotf-mods.com`, so +//! the four ways this API misleads a client stay pinned even offline. + +use super::*; + +/// `GET /api/mods?type=Both&approved=true&nsfw=false&limit=500&orderby=most_downloaded` +const CATALOG: &str = include_str!("../fixtures/sotf-catalog.json"); +/// `GET /api/mods/AxelModMenu` - dependencies as a comma-separated string. +const DETAIL_AXEL: &str = include_str!("../fixtures/sotf-detail-axel.json"); +/// `GET /api/mods/BuildShare` - `isLatest` at index 6, not 0. +const DETAIL_BUILDSHARE: &str = include_str!("../fixtures/sotf-detail-buildshare.json"); + +const BASE: &str = "https://api.sotf-mods.com"; + +fn catalog() -> StoreCatalog { + parse_catalog(CATALOG.as_bytes()).unwrap() +} + +fn item<'a>(catalog: &'a StoreCatalog, mod_id: &str) -> &'a StoreItem { + catalog + .items + .iter() + .find(|i| i.mod_id == mod_id) + .unwrap_or_else(|| panic!("fixture has no `{mod_id}`")) +} + +// --- gotcha 1: `type` defaults to Mod and hides every Library ---------------- + +#[test] +fn gotcha_1_libraries_need_type_both_and_are_kept() { + // The default `type` is `Mod`, so a request without this parameter returns + // no libraries at all - and dependencies are almost always libraries. + assert!( + catalog_url(BASE).contains("type=Both"), + "without type=Both the catalog contains no libraries, and every \ + dependency silently fails to resolve" + ); + + let catalog = catalog(); + let lib = item(&catalog, "SonsAxLib"); + assert!(lib.is_library(), "SonsAxLib is type=Library in the capture"); + assert!( + catalog.items.iter().any(StoreItem::is_library), + "filtering libraries out of the catalog would break resolution" + ); + + // The proof it matters: the most-downloaded mod's only dependency IS that + // library, so a Mod-only catalog resolves it as missing. + let plan = resolve_plan(&catalog.items, "AxelModMenu", &HashSet::new()).unwrap(); + assert!(plan.missing.is_empty(), "{:?}", plan.missing); + assert_eq!( + plan.items.first().map(|i| i.mod_id.as_str()), + Some("SonsAxLib") + ); + + let mods_only: Vec = catalog + .items + .iter() + .filter(|i| !i.is_library()) + .cloned() + .collect(); + let degraded = resolve_plan(&mods_only, "AxelModMenu", &HashSet::new()).unwrap(); + assert_eq!(degraded.missing, vec!["SonsAxLib".to_owned()]); +} + +// --- gotcha 2: omitting `approved` DISABLES the approval filter -------------- + +#[test] +fn gotcha_2_unapproved_mods_are_filtered_out() { + assert!( + catalog_url(BASE).contains("approved=true"), + "omitting `approved` disables the filter rather than defaulting it on" + ); + assert!(catalog_url(BASE).contains("nsfw=false")); + + // The fixture carries a real unapproved library (`Regi_s_Modding_Library`, + // captured from a request WITHOUT approved=true), so the client-side guard + // is exercised even though the query already asks for approved mods. + let raw: serde_json::Value = serde_json::from_str(CATALOG).unwrap(); + let rows = raw["data"].as_array().unwrap(); + assert!( + rows.iter().any(|r| r["isApproved"] == false), + "fixture must contain an unapproved row or this test proves nothing" + ); + + let catalog = catalog(); + assert!( + catalog.items.iter().all(|i| i.is_approved && !i.is_nsfw), + "an unapproved or adult mod must never reach the install path" + ); + assert!( + !catalog + .items + .iter() + .any(|i| i.mod_id == "Regi_s_Modding_Library"), + "the unapproved library survived the filter" + ); +} + +// --- gotcha 3: `dependencies` is an array here and a CSV string there -------- + +#[test] +fn gotcha_3_dependencies_parse_as_array_or_csv() { + // List endpoint: a JSON array. + let catalog = catalog(); + assert_eq!(item(&catalog, "AxelModMenu").dependencies, ["SonsAxLib"]); + assert_eq!( + item(&catalog, "Shops").dependencies, + ["SimpleNetworkEvents", "Banking"] + ); + + // Detail endpoint: the same field, comma-separated. + let raw: serde_json::Value = serde_json::from_str(DETAIL_AXEL).unwrap(); + assert!( + raw["data"]["dependencies"].is_string(), + "the detail endpoint really does return a string" + ); + let detail = parse_detail(DETAIL_AXEL.as_bytes()).unwrap(); + assert_eq!(detail.dependencies, ["SonsAxLib"]); + + // An empty CSV string is no dependencies, not one blank dependency - which + // would resolve as a missing mod named "". + let empty = parse_detail(DETAIL_BUILDSHARE.as_bytes()).unwrap(); + assert!( + empty.dependencies.is_empty(), + "expected empty, got {:?}", + empty.dependencies + ); + + // Both shapes, plus null, whitespace, and an absent field, through the + // deserializer directly. + let cases = [ + (r#""dependencies":["A","B"],"#, vec!["A", "B"]), + (r#""dependencies":"A, B ,C","#, vec!["A", "B", "C"]), + (r#""dependencies":"","#, vec![]), + (r#""dependencies":null,"#, vec![]), + ("", vec![]), + ]; + for (field, want) in cases { + let full = format!(r#"{{{field}"id":1,"name":"n","mod_id":"m"}}"#); + let parsed: StoreItem = serde_json::from_str(&full).unwrap(); + assert_eq!(parsed.dependencies, want, "for `{field}`"); + } +} + +// --- gotcha 4: `versions` is never the way to find the latest release -------- + +#[test] +fn gotcha_4_latest_comes_from_is_latest_never_index_zero() { + // On the LIST endpoint `versions` is `take: 1` ordered ASC: one arbitrary + // old release, flagged isLatest = false. + let catalog = catalog(); + let listed = item(&catalog, "AxelModMenu"); + assert_eq!( + listed.versions.first().map(|v| v.version.as_str()), + Some("1.0.0"), + "the list endpoint returns a stale single version" + ); + assert_eq!(listed.latest_version.as_deref(), Some("1.3.8")); + assert!( + listed.versions.iter().all(|v| !v.is_latest), + "nothing on the list endpoint is flagged latest, so `latestVersion` is \ + the only usable source" + ); + + // On the DETAIL endpoint the entries are unordered: BuildShare really does + // carry its current release at index 6. + let detail = parse_detail(DETAIL_BUILDSHARE.as_bytes()).unwrap(); + assert_eq!( + detail.versions.first().map(|v| v.version.as_str()), + Some("1.0.8"), + "versions[0] is not the latest release" + ); + assert_eq!(detail.latest_version.as_deref(), Some("1.0.10")); + let latest = detail.latest().unwrap(); + assert_eq!(latest.version, "1.0.10"); + assert!(latest.is_latest); + + // And the hand-off must carry that version's archive, not index 0's. + let job = handoff_job(&detail, BASE, Some("sonsoftheforest")).unwrap(); + assert!(job.url.contains("1.0.10"), "{}", job.url); + assert!(!job.url.contains("1.0.8"), "{}", job.url); +} + +// --- URL construction -------------------------------------------------------- + +#[test] +fn catalog_url_sends_every_parameter_the_api_needs() { + assert_eq!( + catalog_url(BASE), + "https://api.sotf-mods.com/api/mods?type=Both&approved=true&nsfw=false\ + &limit=500&orderby=most_downloaded" + ); +} + +#[test] +fn identifiers_are_percent_encoded_into_the_path() { + // A real slug on this store is `axel's-mod-menu`; ids are author-supplied + // free text and never go into a URL raw. + assert_eq!( + detail_url(BASE, "axel's-mod-menu"), + "https://api.sotf-mods.com/api/mods/axel%27s-mod-menu" + ); + assert_eq!( + detail_url(BASE, "a b/../c"), + "https://api.sotf-mods.com/api/mods/a%20b%2F..%2Fc", + "a traversal attempt must not escape the path segment" + ); + assert_eq!( + detail_url(BASE, "AxelModMenu"), + format!("{BASE}/api/mods/AxelModMenu") + ); +} + +// --- dependency resolution --------------------------------------------------- + +/// A minimal item, for graphs the live store does not (yet) contain. +fn synthetic(mod_id: &str, deps: &[&str]) -> StoreItem { + let deps = deps + .iter() + .map(|d| format!("\"{d}\"")) + .collect::>() + .join(","); + let json = format!( + r#"{{"id":1,"name":"{mod_id}","mod_id":"{mod_id}","isApproved":true, + "dependencies":[{deps}],"latestVersion":"1.0.0", + "versions":[{{"version":"1.0.0","isLatest":true, + "downloadUrl":"https://cdn.example/{mod_id}.zip"}}]}}"# + ); + serde_json::from_str(&json).unwrap() +} + +#[test] +fn a_dependency_cycle_terminates_instead_of_recursing_forever() { + // A needs B, B needs C, C needs A. RedManager recurses on this until it + // dies; the visited set makes it one pass. + let catalog = [ + synthetic("A", &["B"]), + synthetic("B", &["C"]), + synthetic("C", &["A"]), + ]; + let plan = resolve_plan(&catalog, "A", &HashSet::new()).unwrap(); + let ids: Vec<&str> = plan.items.iter().map(|i| i.mod_id.as_str()).collect(); + assert_eq!(ids, ["B", "C", "A"], "deps first, root last, each once"); + assert!( + plan.missing.is_empty(), + "expected empty, got {:?}", + plan.missing + ); + + // Self-dependency is the degenerate cycle. + let selfish = [synthetic("S", &["S"])]; + let plan = resolve_plan(&selfish, "S", &HashSet::new()).unwrap(); + assert_eq!(plan.items.len(), 1); +} + +#[test] +fn a_diamond_installs_each_mod_once() { + let catalog = [ + synthetic("Top", &["Left", "Right"]), + synthetic("Left", &["Base"]), + synthetic("Right", &["Base"]), + synthetic("Base", &[]), + ]; + let plan = resolve_plan(&catalog, "Top", &HashSet::new()).unwrap(); + let ids: Vec<&str> = plan.items.iter().map(|i| i.mod_id.as_str()).collect(); + assert_eq!(ids, ["Left", "Right", "Base", "Top"]); +} + +#[test] +fn an_already_installed_dependency_is_not_queued_again() { + // RedManager has no such check and re-downloads what is already there. + let catalog = catalog(); + let installed = installed_keys(["sonsaxlib"]); + let plan = resolve_plan(&catalog.items, "AxelModMenu", &installed).unwrap(); + assert_eq!(plan.satisfied, ["SonsAxLib".to_owned()]); + let ids: Vec<&str> = plan.items.iter().map(|i| i.mod_id.as_str()).collect(); + assert_eq!(ids, ["AxelModMenu"]); +} + +#[test] +fn installed_keys_are_matched_case_insensitively() { + let keys = installed_keys([" SonsAxLib ", "", "Axel's Mod Menu"]); + assert!(keys.contains("sonsaxlib")); + assert!(keys.contains("axel's mod menu")); + assert_eq!(keys.len(), 2, "blank names must not become a key"); +} + +#[test] +fn an_unknown_mod_id_is_an_error_not_an_empty_install() { + let catalog = catalog(); + assert!(resolve_plan(&catalog.items, "NoSuchMod", &HashSet::new()).is_err()); +} + +#[test] +fn a_dependency_missing_from_the_catalog_is_reported_not_swallowed() { + let catalog = [synthetic("A", &["Withdrawn"])]; + let plan = resolve_plan(&catalog, "A", &HashSet::new()).unwrap(); + assert_eq!(plan.missing, ["Withdrawn".to_owned()]); + assert_eq!( + plan.items.len(), + 1, + "the mod still installs, with a warning" + ); +} + +// --- hand-off ---------------------------------------------------------------- + +#[test] +fn the_handoff_reuses_the_browser_download_pipeline() { + let detail = parse_detail(DETAIL_AXEL.as_bytes()).unwrap(); + let job = handoff_job(&detail, BASE, Some("sonsoftheforest")).unwrap(); + assert_eq!(job.schema_version, 1, "must match the hand-off schema"); + // The direct CDN URL, not the API download route: that route answers a + // Range request with 200 and the whole body, so it cannot be segmented. + assert!( + job.url.starts_with("https://r2.sotf-mods.com/"), + "{}", + job.url + ); + assert!(job.url.contains("1.3.8")); + assert_eq!( + job.game_hint.and_then(|h| h.domain).as_deref(), + Some("sonsoftheforest"), + "the domain hint is what routes the finished download to the game" + ); + assert!(job.user_agent.unwrap().starts_with("Modrix/")); + + // The job survives the same trust-boundary validation a browser job does, + // apostrophe in the filename and all. + let dir = std::path::Path::new("/tmp/modrix-store-test"); + let job = handoff_job(&detail, BASE, None).unwrap(); + let request = job.into_request(dir).unwrap(); + assert_eq!( + std::path::Path::new(&request.out).extension(), + Some(std::ffi::OsStr::new("zip")), + "{}", + request.out + ); + assert!(!request.out.contains('/')); +} + +#[test] +fn a_version_with_no_cdn_url_falls_back_to_the_api_download_route() { + let json = r#"{"status":"success","data":{"id":1,"name":"n","mod_id":"My Mod", + "isApproved":true,"latestVersion":"2.0","dependencies":null, + "versions":[{"version":"2.0","isLatest":true}]}}"#; + let item = parse_detail(json.as_bytes()).unwrap(); + let job = handoff_job(&item, BASE, None).unwrap(); + assert_eq!(job.url, format!("{BASE}/api/mods/My%20Mod/download/2.0")); + assert_eq!(job.filename, "My Mod-2.0.zip"); +} + +#[test] +fn an_item_with_no_identifiable_release_is_an_error() { + let json = r#"{"status":"success","data":{"id":1,"name":"n","mod_id":"m", + "isApproved":true,"versions":[{"version":"0.1","isLatest":false}]}}"#; + let item = parse_detail(json.as_bytes()).unwrap(); + assert!( + handoff_job(&item, BASE, None).is_err(), + "guessing versions[0] here is exactly the bug being avoided" + ); +} + +// --- catalog shape ----------------------------------------------------------- + +#[test] +fn the_captured_catalog_still_parses_end_to_end() { + let catalog = catalog(); + assert!(!catalog.truncated, "one page holds the whole store"); + assert!(catalog.items.len() >= 5); + let axel = item(&catalog, "AxelModMenu"); + assert_eq!(axel.name, "Axel's Mod Menu"); + assert_eq!(axel.author(), Some("ImAxel")); + assert!(axel.downloads > 0); + // `type` is null on older rows; those are plain mods, not libraries. + let untyped = catalog.items.iter().find(|i| i.kind.is_none()); + assert!(untyped.is_some_and(|i| !i.is_library())); +} + +// --- live smoke check -------------------------------------------------------- + +/// Confirms the captured fixtures still describe the live service. Ignored by +/// default: `cargo test --workspace` must never depend on the network. +/// +/// Run with `cargo test -p modrix-service -- --ignored --nocapture`. +#[tokio::test] +#[ignore = "hits the live sotf-mods.com API"] +async fn live_api_still_matches_the_fixtures() { + let client = StoreClient::new(BASE).unwrap(); + let catalog = client.catalog().await.unwrap(); + assert!(catalog.items.len() > 100, "{}", catalog.items.len()); + assert!( + catalog.items.iter().any(StoreItem::is_library), + "type=Both must still surface libraries" + ); + assert!(catalog.items.iter().all(StoreItem::is_installable)); + + let plan = resolve_plan(&catalog.items, "AxelModMenu", &HashSet::new()).unwrap(); + assert_eq!(plan.missing, Vec::::new()); + let detail = client.detail("BuildShare").await.unwrap(); + assert_eq!( + detail.latest().map(|v| v.version.as_str()), + detail.latest_version.as_deref() + ); + let job = handoff_job(&detail, BASE, Some("sonsoftheforest")).unwrap(); + assert!(job.url.starts_with("https://"), "{}", job.url); +} diff --git a/deny.toml b/deny.toml index 41dedf5..e662640 100644 --- a/deny.toml +++ b/deny.toml @@ -1,141 +1,27 @@ # SPDX-License-Identifier: GPL-2.0-only -# cargo-deny: make GPLv2 compliance a mechanical CI gate. Anything not in the -# `allow` list below fails the build. Apache-2.0 is intentionally ABSENT - it is -# incompatible with GPL-2.0-only; dual `MIT OR Apache-2.0` crates still pass via -# their MIT arm. +# cargo-deny: security advisories, duplicate-version policy and registry +# sources. Dependency licenses are not gated: the project stopped constraining +# its dependency graph by license (see docs/ARCHITECTURE.md §11). [advisories] -# Each ignore is justified by our *actual* usage, not waved away. All stem from -# `rustls-rustcrypto` (the pure-Rust TLS crypto provider we use to stay -# GPLv2-clean instead of the Apache-encumbered ring/aws-lc). Re-audit if that -# provider is bumped. +# Each ignore is justified by our *actual* usage, not waved away. Re-audit an +# entry whenever the crate that pulls it in is bumped. ignore = [ - # `paste`: unmaintained, but a *build-time* proc-macro with no runtime or - # security surface, pulled transitively by RustCrypto crates. No upgrade. - "RUSTSEC-2024-0436", - # `rsa` "Marvin Attack": a timing sidechannel in RSA PKCS#1 v1.5 - # *decryption* (a private-key operation). We are a TLS *client*: - # rustls-rustcrypto uses `rsa` only to VERIFY the server's certificate - # signature (a public-key operation) - no RSA private-key decryption ever - # happens on our side - so the vulnerable path is not exercised. No fix - # exists upstream. - "RUSTSEC-2023-0071", - # `rustybuzz`: text shaping inside iced's cosmic-text - declared - # unmaintained (superseded by harfrust), not a vulnerability. It shapes - # our own UI strings, not untrusted input. Goes away when iced moves; - # re-check on the next iced upgrade. - "RUSTSEC-2026-0206", - # `rustls-webpki` 0.102.8 (CRL matching, URI/wildcard name constraints, CRL - # parse panic): our certificate chain verification runs through - # rustls-webpki 0.103.13 (patched, via rustls 0.23). We only pull 0.102.8 - # because rustls-rustcrypto imports its `alg_id` OID *constants*; the - # vulnerable CRL/name-constraint code is never invoked. - "RUSTSEC-2026-0049", - "RUSTSEC-2026-0098", - "RUSTSEC-2026-0099", - "RUSTSEC-2026-0104", - # --- GUI windowing/text stack (iced/winit), no untrusted-input path ------- - # `instant`: unmaintained; pulled by `wasm-timer` (iced_futures). Only its - # time-now shim is used, on the wasm target we do not even ship. No upgrade - # path until iced drops wasm-timer. - "RUSTSEC-2024-0384", - # `ttf-parser` 0.20/0.25: unmaintained (author archived it); pulled by - # ab_glyph/fontdb to parse *locally installed system fonts*, not - # attacker-supplied files. Re-audit when iced's text stack migrates. - "RUSTSEC-2026-0192", - # `quick-xml` (attribute-scan and namespace DoS): pulled by - # `wayland-scanner`, a BUILD-TIME code generator that parses the trusted, - # repository-pinned Wayland protocol XML shipped in the crate - it never - # parses untrusted XML and does not exist in the shipped binary. - "RUSTSEC-2026-0194", - "RUSTSEC-2026-0195", + # zbus_names, zvariant, zvariant_derive: "unmaintained" notices (folded + # into zbus 6), not vulnerabilities. They come only from Rune's + # accessibility bridge (accesskit_unix over AT-SPI on the session bus). + # Drop these once the pinned Rune rev moves to zbus 6. + "RUSTSEC-2026-0370", + "RUSTSEC-2026-0371", + "RUSTSEC-2026-0372", ] -[licenses] -# Only GPLv2-compatible licenses. Add here (with a note) if a legitimately -# compatible license shows up in the tree; never add Apache-2.0-only or GPL/LGPL-3.0. -allow = [ - "GPL-2.0-only", # our own license - "MIT", - "BSD-2-Clause", - "BSD-3-Clause", - "ISC", - "Zlib", - "Unlicense", - "LGPL-2.1-only", - "CC0-1.0", - "Unicode-DFS-2016", - "Unicode-3.0", - "MIT-0", - "BSL-1.0", - # MPL-2.0 is GPL-2.0-compatible: MPL 2.0 §1.12 names "GNU GPL Version 2.0" a - # Secondary License and §3.3 grants distribution of a Larger Work under it, - # unless a file is flagged "Incompatible With Secondary Licenses" (none here - # are). Pulled in by `option-ext` via the locked `directories` dependency. - "MPL-2.0", -] -confidence-threshold = 0.9 -# The allow list is a curated superset of acceptable licenses, so entries that -# no current dependency uses are expected - don't fail CI on them. -unused-allowed-license = "allow" - -# --- GUI linking exception (Apache-2.0 for the windowing/rendering stack only) -- -# Apache-2.0 is NOT allowed in general (it is GPLv2-incompatible). But every -# native Rust GUI is built on `winit` (Apache-2.0), and Iced needs it plus a few -# Apache-2.0 text/clipboard crates. Modrix grants a documented additional -# permission (see docs/LICENSE-EXCEPTIONS.md) to link these specific GUI libraries, so -# they are excepted BY NAME here - the engine stays 100% Apache-free; only the -# `modrix-gui` windowing layer relies on this. -[[licenses.exceptions]] -name = "winit" -allow = ["Apache-2.0"] -[[licenses.exceptions]] -name = "dpi" -allow = ["Apache-2.0"] -[[licenses.exceptions]] -name = "ab_glyph" -allow = ["Apache-2.0"] -[[licenses.exceptions]] -name = "ab_glyph_rasterizer" -allow = ["Apache-2.0"] -[[licenses.exceptions]] -name = "owned_ttf_parser" -allow = ["Apache-2.0"] -[[licenses.exceptions]] -name = "unicode-linebreak" -allow = ["Apache-2.0"] -[[licenses.exceptions]] -name = "clipboard_macos" -allow = ["Apache-2.0"] -[[licenses.exceptions]] -name = "clipboard_wayland" -allow = ["Apache-2.0"] -[[licenses.exceptions]] -name = "approx" -allow = ["Apache-2.0"] -[[licenses.exceptions]] -name = "gethostname" -allow = ["Apache-2.0"] -# The GPU renderer (wgpu/naga) additions - same GUI-only linking exception. -[[licenses.exceptions]] -name = "codespan-reporting" -allow = ["Apache-2.0"] -[[licenses.exceptions]] -name = "spirv" -allow = ["Apache-2.0"] -[[licenses.exceptions]] -name = "gl_generator" -allow = ["Apache-2.0"] -[[licenses.exceptions]] -name = "khronos_api" -allow = ["Apache-2.0"] -[[licenses.exceptions]] -name = "glutin_wgl_sys" -allow = ["Apache-2.0"] - [bans] multiple-versions = "allow" [sources] unknown-registry = "deny" unknown-git = "deny" +# Rune (the GUI toolkit) is not on crates.io yet; it is pinned to a commit in +# Cargo.toml, so the git source cannot move under us. +allow-git = ["https://github.com/anomalyco/rune"] diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index da517d6..371a171 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -34,19 +34,19 @@ engine that touches users' files. | Area | Choice | Rationale | |---|---|---| | Language | **Rust** | Safety where it matters most: the file-deployment engine touches users' game installs. Cargo + the crate ecosystem make 3 frontends cheap. | -| GUI | **Iced** (MIT, pure-Rust) | GPLv2-compatible; one renderer → identical on all 3 OSes; tiny self-contained binary; themed toward a clean macOS-like look. | -| GUI - ruled out | Slint | Was the first pick, but its free build is **GPLv3-only**, incompatible with our GPLv2 goal (see §11). Only `modrix-gui` links a toolkit, so this stayed a cheap swap. | +| GUI | **Rune** (pure Rust) | Its own GPU renderer, text and layout, so it looks identical on all 3 OSes with no web view; springs and gradients for a polished look; headless `--snap` renders for visual review. Replaced a Tauri web UI: a native renderer resizes without the web process's lag. | +| GUI - superseded | Slint, Iced 0.13, then a Tauri 2 webview | Slint was dropped under the (since removed) license gate; Iced hit its ceiling on effects and animation; the web UI got the look but resized and scrolled through a separate web process. Only `modrix-gui` links a toolkit, so each swap was one crate. | | TUI | **ratatui** | Mature, the standard. | | CLI | **clap** (derive) | Standard, scriptable. | | Plugins | **Two-tier: `game.toml` + `game.lua` (`mlua`, vendored Lua 5.4)** | Most games are just data; Lua only when logic is needed. | | Deployment | **Link → symlink → copy, transactional manifest** | Cross-platform, reversible, ships sooner. VFS deferred. | -| Async/net | **tokio + hyper + rustls** (RustCrypto provider) | Concurrent, resumable downloads; Nexus API. *Not reqwest:* it transitively pulls Apache-2.0-only crates (`ring`, `sync_wrapper`), which are GPLv2-incompatible. We assemble a pure-Rust, all-MIT/ISC HTTPS stack instead (see §11). | +| Async/net | **tokio + hyper + rustls** (ring provider) | Concurrent, resumable downloads; browser hand-off. Assembled from parts rather than `reqwest`; originally for licensing reasons, kept because it is small, pure Rust and already audited against our usage. | | Storage | **SQLite via `rusqlite`** | mods × profiles × files × conflicts is relational + transactional. | | Reliability | **Power of Ten for Rust** | forbid `unsafe`, panic-free, bounded loops, lint-enforced in CI - the deploy engine is safety-critical (§9.3). | | Steam | **`steamlocate`** | Parses `libraryfolders.vdf` / `appmanifest_*.acf`. | | Paths | **`directories`** | XDG / Known Folders / Application Support. | | Errors | **`thiserror`** (libs) / **`anyhow`** (binary edges) | Typed errors in the engine; ergonomic context at the top. | -| License | **GPL-2.0-only** | Free/open-source; preference of v2 over v3. It's what drives the GUI choice (see §11). | +| License | **GPL-2.0-only** (project); dependencies not gated | Free/open-source; preference of v2 over v3 for our own code. Dependency licenses are not policed (see §11). | --- @@ -83,15 +83,13 @@ modrix/ (cargo workspace) │ # URL to the running instance (or starts a headless one). ├── modrix-cli # thin: clap over core. The scriptable surface. ├── modrix-tui # thin: ratatui over core. -├── modrix-gui # thin: Iced over core. The only crate that links a GUI toolkit. +├── modrix-gui # thin: Rune over core. The only crate that links a GUI toolkit. └── extension/ # userscript (v1) + WebExtension (later). JS - unavoidable # in a browser. ``` -**Licensing:** the project ships **GPL-2.0-only** (free/open-source; preference of -v2 over v3). Every dependency is MIT/BSD/LGPL-2.1 or dual-licensed with an MIT arm, -all GPLv2-compatible, enforced by `cargo-deny` in CI. See §11 for why the GUI is -Iced and not Slint. +**Licensing:** the project ships **GPL-2.0-only**. Dependency licenses are not +gated; `cargo-deny` runs for advisories, bans and sources only (§11). --- @@ -252,7 +250,7 @@ loads under the sandbox). Modrix is, at its core, a clean-room Rust reimplementation of the aria2/Motrix download *engine* (segmented, multi-connection, resumable) with no UI and **no -aria2 code or binary** - a GPLv2-clean rebuild on our hyper + rustls stack. A thin +aria2 code or binary** - a clean-room rebuild on our hyper + rustls stack. A thin **WebExtension** captures the browser's real, already-authenticated download and hands it to the engine over loopback; the engine downloads and installs. @@ -321,16 +319,18 @@ logic in a frontend. engine headless. Everything is reachable here, and `--json` wraps every command in a stable `{"ok":true,"data":…}` envelope for agents and scripts. - **TUI (`ratatui`)**: mod list, load-order reorder, conflict view, download queue. -- **GUI (`Iced`, MIT)**: the same, themed (switchable specs: Aurora glass / - Gold classic, Steam library artwork); the install wizard (FOMOD) renders here. +- **GUI (`Rune`)**: the same, over the game's Steam library artwork, with + switchable themes (Aurora glass and Gold classic), the accent colour taken + from the art and light, dark or system appearance; the install wizard (FOMOD) + and, for games that declare one, the mod store render here. - **MCP (`modrix mcp`)**: the fourth frontend is an AI agent: a hand-rolled stdio JSON-RPC MCP server (`modrix-mcp`) exposing the full action surface as tools plus observability (downloads, progress, health) and `modrix://skill/*` resources - built-in usage/plugin-authoring guides and each installed game plugin's skill files - so agents learn per-game modding practice on install. -Because frontends are thin, the GUI toolkit is a localized, swappable choice - which -is exactly why the GPLv2 requirement (§11) only cost us a one-crate change. +Because frontends are thin, the GUI toolkit is a localized, swappable choice - the +GUI has already changed toolkit twice with no engine change. --- @@ -404,7 +404,7 @@ loses saves and installs. It is mechanized so it holds from commit #1: semantics (ranges, invariants), not just shape. - **Short functions (~60 lines), immutable by default** (minimize `let mut`). - **Enforced mechanically:** pedantic clippy + cherry-picked `restriction` lints, - `-D warnings`, `cargo-deny` (incl. the GPLv2 license gate), cross-OS CI. The exact + `-D warnings`, `cargo-deny` (advisories, bans, sources), cross-OS CI. The exact `[workspace.lints]` / `clippy.toml` / `deny.toml` live at the repository root and are wired in Phase 0. @@ -422,46 +422,25 @@ loses saves and installs. It is mechanized so it holds from commit #1: --- -## 11. Licensing - why GPL-2.0, and why that picks the GUI - -**GPL-2.0-only**, because you prefer v2 over v3 and want the manager free and open -source. Both are FSF/OSI free-software licenses; the difference is v3's added terms -(anti-tivoization, explicit patent grant, anti-DRM). Preferring v2 is a legitimate -choice - it's the Linux-kernel license. - -**The one hard constraint:** GPLv2 and GPLv3 are *mutually incompatible* - you cannot -legally combine GPLv2-only code with GPLv3 code and redistribute it. That part is -genuinely unavoidable. It bit us only because **Slint's free build is GPLv3-only**, so -choosing Slint would force the whole app to v3. That was the *sole* thing pushing v3. - -**The fix is just the GUI.** Slint → **Iced** (MIT). MIT is GPLv2-compatible, so the app -is GPL-2.0 cleanly. We give up Slint's free "Cupertino" theme and instead theme Iced -toward the macOS-like look - a little more styling, no blocker. Iced is also arguably -*more* suckless: pure Rust, one language, no DSL, no external framework. - -**Rest of the tree is clean:** tokio, rusqlite, ratatui, clap, mlua, serde, -directories, steamlocate, zip, sevenz-rust are all MIT or dual-licensed with an MIT -arm → GPLv2-compatible. Rule: take the MIT arm on dual-licensed crates, and avoid any -**Apache-2.0-only** dependency (Apache-2.0 is incompatible with GPLv2). `unrar` is -excluded for a related reason (§8). All of this is a mechanical `cargo-deny` gate. - -**The HTTP client is where this bit hardest.** The obvious choice, `reqwest`, -transitively pulls **`ring`** (its rustls crypto backend, `Apache-2.0 AND ISC`) -and **`sync_wrapper`** (`Apache-2.0`-only, via `tower-http`). Apache-2.0 is -one-way-incompatible with GPLv2, so `cargo-deny` rejects both. We therefore do -**not** use reqwest. Instead we assemble the client from **hyper + rustls**, with -rustls's crypto provided by **`rustls-rustcrypto`** (pure-Rust RustCrypto -primitives - aes-gcm, chacha20poly1305, p256/p384, rsa, sha2) and roots from the -OS trust store via **`rustls-native-certs`** (avoiding the `CDLA-Permissive-2.0` -`webpki-roots`). Every crate in that stack is MIT/ISC. The TLS state machine is -still audited rustls; only the primitives change. Trade-off accepted with the -maintainer: `rustls-rustcrypto` is young (0.0.x), in exchange for a 100% -GPLv2-clean tree with no license exception. `zip` likewise uses the pure-Rust -`flate2` backend, never `zopfli` (Apache-2.0-only). - -**v2-only vs "v2 or later":** we ship **GPL-2.0-only**, which most faithfully honors -"v2 over v3." "GPL-2.0-or-later" would be the flexible alternative, but it lets v3 back -in as a possibility - so we don't use it. - -**Escape hatch:** if you later decide Slint's free macOS look is worth more than v2, the -alternative is GPLv3 + Slint. It's a one-crate change. +## 11. Licensing + +Modrix's own code is **GPL-2.0-only** (v2 preferred over v3; the Linux-kernel +license). Every source file carries an SPDX header and `LICENSE` holds the full text. + +**Dependency licenses are not gated.** Earlier revisions enforced GPLv2-compatibility +across the whole dependency graph with a `cargo-deny` license allow-list, which is +what excluded `reqwest` (via `ring`/`sync_wrapper`), forced a RustCrypto TLS +provider (since replaced by `ring`, whose alpha RustCrypto rival lagged on +security fixes), ruled out Slint and later required a documented linking +exception for Iced's windowing stack. That rule has been removed: `deny.toml` now +checks security advisories, duplicate-version policy and registry sources only, and +nothing in the build rejects a crate by license. + +What remains of the old constraint is a set of working choices, kept on their +merits rather than by rule: the hyper + rustls client is small, pure Rust and +already audited against how Modrix uses it, and `zip` decompresses with `flate2` +because Modrix never compresses. Any of these may be replaced when something +better is available. + +Redistributors of binaries should still review `cargo tree` and each crate's own +license terms; the build no longer does that for them. diff --git a/docs/LICENSE-EXCEPTIONS.md b/docs/LICENSE-EXCEPTIONS.md deleted file mode 100644 index 9142aa4..0000000 --- a/docs/LICENSE-EXCEPTIONS.md +++ /dev/null @@ -1,51 +0,0 @@ -# License Exceptions: GUI Linking Exception - -Modrix is licensed under **GPL-2.0-only** (see [LICENSE](../LICENSE)). - -## Additional permission for GUI windowing/rendering libraries - -As an additional permission under section 10 of the GNU General Public -License version 2, the copyright holders of Modrix grant you permission -to combine the `modrix-gui` program with the following Apache-2.0-licensed -libraries (or modified versions of them, under the same license), and to -convey the resulting work: - -| Crate | Role | -| --------------------- | ------------------------------------------- | -| `winit` | Cross-platform window creation and events | -| `dpi` | DPI/scale-factor types (winit companion) | -| `ab_glyph` | Font loading and glyph outlines | -| `ab_glyph_rasterizer` | Glyph rasterization | -| `owned_ttf_parser` | TTF font parsing (ab_glyph dependency) | -| `unicode-linebreak` | Unicode line-breaking for text layout | -| `clipboard_macos` | macOS clipboard backend | -| `clipboard_wayland` | Wayland clipboard backend | -| `approx` | Float comparisons (glyph layout dependency) | -| `gethostname` | Hostname lookup (X11 windowing dependency) | -| `codespan-reporting` | Shader-compiler diagnostics (naga/wgpu) | -| `spirv` | SPIR-V type definitions (naga/wgpu) | -| `gl_generator` | Build-time OpenGL binding codegen (wgpu) | -| `khronos_api` | Khronos XML registry data (build-time) | -| `glutin_wgl_sys` | Windows WGL bindings (wgpu GL fallback) | - -You must comply with the Apache License 2.0 in all respects for those -libraries themselves. If you modify Modrix, you may extend this -exception to your version, but you are not obligated to do so; if you do -not wish to, delete this exception statement from your version. - -## Scope: what it deliberately does *not* cover - -- This exception exists **only** because every viable native Rust - windowing/GPU stack is built on `winit` and `wgpu`, which are - Apache-2.0 licensed (or depend on Apache-2.0-only crates) and have no - GPLv2-compatible substitute. -- It applies **only** to the `modrix-gui` binary. The engine - (`modrix-core`), the download manager (`modrix-download`), the IPC - layer (`modrix-ipc`), the protocol handler, the CLI, and the TUI link - **zero** Apache-2.0 code - this is enforced mechanically by - [`deny.toml`](../deny.toml), which forbids Apache-2.0 globally and excepts - precisely the fifteen crates named above, by name. -- It is **not** a general grant to add Apache-2.0 dependencies. Any new - Apache-2.0 crate fails `cargo deny check` unless it is a - windowing/rendering requirement of the GUI and is added both here and - in `deny.toml` with justification. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index ab91e98..0ea75b8 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -16,12 +16,12 @@ Workspace + plumbing. No features yet. - Cargo workspace, the crate skeletons from `ARCHITECTURE.md §3`. - **Power of Ten enforcement from commit #1:** workspace `[lints]` (forbid `unsafe`, panic-free, indexing/arithmetic guards), `clippy.toml` (≤60-line - functions), `deny.toml` (GPLv2 license gate + advisories). Full configs live + functions), `deny.toml` (advisories + bans + sources). Full configs live at the repository root. - `directories`-based config/data/cache paths; structured logging (`tracing`). - SQLite schema + migrations (`rusqlite`); open/create the DB. - GPL-2.0 `LICENSE` (full text) + SPDX headers on every source file; `README`. -- CI = fmt + clippy `-D warnings` + test + `cargo deny` on Linux/Windows/macOS. +- CI = fmt + clippy `-D warnings` + test + `cargo deny` (advisories) on Linux/Windows/macOS. **Done when:** CI green on all 3 OSes with **zero clippy warnings under `-D warnings`**; `cargo deny` passes; the app creates its data dir and an empty DB. @@ -52,7 +52,7 @@ Make "click in browser → installed" real - **with no site API and no API key** (corrected from the original API-based plan; see `ARCHITECTURE.md §6`). - `modrix-download`: a segmented, multi-connection, **resumable, checksum-verified** download engine (a clean-room aria2/Motrix-style engine, no aria2 code), on the - GPLv2-clean hyper + rustls stack. FIFO queue + concurrency cap + progress events. + hyper + rustls stack. FIFO queue + concurrency cap + progress events. Retains an `nxm://` identity parser (not a download mechanism). - `modrix-ipc`: loopback listener + single-instance guard + session token; a JSON `POST /download` hand-off endpoint (+ `GET /download/`, `/downloads`). @@ -96,7 +96,7 @@ install / update / gc from the GUI, CLI, and MCP). --- ## Phase 5 - GUI -- `modrix-gui` (**Iced**, MIT): the same feature set, themed classy/macOS-like; +- `modrix-gui` (**Rune**): the same feature set, a native GPU UI tinted by each game's artwork; drag-to-reorder load order; the install wizard; settings. - Optional system-tray / headless-background so browser clicks work while "closed." diff --git a/docs/SONS-LOADER.md b/docs/SONS-LOADER.md new file mode 100644 index 0000000..ce1daca --- /dev/null +++ b/docs/SONS-LOADER.md @@ -0,0 +1,370 @@ +# The native Sons of the Forest loader + +Status: **mods compile against the game with no third-party loader; the +injection chain is built but has never been run.** This document records the design, what is verified, and what remains, so +the next person picking it up does not have to re-derive any of it. + +Milestone M0 (proxy → CoreCLR → managed entrypoint) exists in +[`loaders/`](../loaders/README.md) and builds. It has **never been executed**: +see [Milestone M0](#milestone-m0--proving-injection) for exactly what that means +and for the acceptance procedure someone with the game installed has to run. + +## Why Modrix needs a loader at all + +Every other game Modrix supports is modded by *placing files*. Sons of the +Forest is not. It is an **IL2CPP** build: Unity compiled its C# ahead of time to +native code, so the shipped game is `GameAssembly.dll` (100 MB of machine code) +plus `global-metadata.dat` (26 MB of names and layouts, no method bodies). There +is no `Assembly-CSharp.dll`. A mod cannot reference the game, and there is +nothing for Harmony to patch. + +Making such a game moddable requires four things that a file-copying mod manager +does not have: + +1. **Injection**: get our code running inside the game process. +2. **A managed runtime**: host .NET 6 in that process. +3. **Interop assemblies**: generate one managed proxy DLL per original + assembly, so mods have something to compile against and patch. +4. **A mod host**: discover `Mods/*.dll`, resolve order, call lifecycle hooks. + +Third-party loaders (RedLoader, MelonLoader, BepInEx 6 IL2CPP) each do all four. +Modrix doing it natively means users need one tool, not two, and Modrix can +manage the loader's lifecycle instead of treating it as an opaque prerequisite. + +## Verified facts + +Measured on a real install, not inferred: + +| Fact | Value | +| --- | --- | +| Steam AppID | `1326470` | +| Unity | `2022.2.16f1` | +| Metadata version | **29** (`sanity = 0xFAB11BAF`) | +| `global-metadata.dat` | 26,505,936 bytes | +| Assemblies / images | 210 each (they must match: this is the layout check) | +| Type definitions | 24,056 | +| Method definitions | 182,725 | +| Field definitions | 124,512 | +| Proxy DLL slot | `version.dll` (shared with MelonLoader and RedLoader) | + +Record sizes for v29, derived by finding which candidate size divides each +section's byte length exactly, then cross-checked against the +one-image-per-assembly invariant: + +| Record | Bytes | +| --- | --- | +| `Il2CppImageDefinition` | 40 | +| `Il2CppAssemblyDefinition` | 64 | +| `Il2CppTypeDefinition` | 88 | +| `Il2CppMethodDefinition` | 32 | +| `Il2CppFieldDefinition` | 12 | + +`crates/modrix-il2cpp` re-checks divisibility on every file it opens, so a game +update that changes the layout fails loudly instead of being misread. + +## Architecture + +The split is chosen so that **everything that can be safe Rust is safe Rust**, +and the unavoidable `unsafe` is quarantined in one crate outside the main +workspace. Modrix forbids `unsafe` workspace-wide because the deploy engine +touches users' game files; a runtime injector is a different risk class and does +not get to erode that guarantee. + +``` + OUT OF PROCESS (safe Rust, main workspace) + global-metadata.dat ──> modrix-il2cpp ──────> metadata model [DONE] + │ + v + modrix-interop-gen ──> managed .dll set [DONE] + + modrix-ecma335 (197 ref assemblies) + ────────────────────────────────-│──────────────────────────────────────── + v IN PROCESS (unsafe, separate workspace) + version.dll (Rust cdylib proxy) [M0 BUILT] + │ forwards the 17 real version.dll exports, + │ waits for il2cpp, then hosts CoreCLR via + │ coreclr_initialize + coreclr_create_delegate + v + Modrix.Loader.dll (C#) [M0 BUILT] + │ M0: proves managed code ran. + │ M2: discovers Mods/*.dll, reads + │ manifest.json, calls lifecycle hooks + v + Modrix.Sons.Sdk.dll (C#) [TODO] + the API mods are written against +``` + +### Why CoreCLR directly and not hostfxr + +Two routes exist and the reference loaders take one each. MelonLoader uses +`nethost` → `hostfxr_initialize_for_runtime_config` → +`hostfxr_get_runtime_delegate`, which resolves frameworks properly and can use a +system .NET, but needs `hostfxr.dll`, a `*.runtimeconfig.json`, and a correct +`DOTNET_ROOT` inside a Proton prefix. Unity Doorstop (and therefore RedLoader) +resolves exactly two symbols from a vendored `coreclr.dll` and calls them. + +Modrix takes Doorstop's route. It is two symbols, no config file, no framework +resolution and no `DOTNET_ROOT`, and it is the route already proven to work in +this game under this Proton prefix. It is also the only route the runtime we ship +supports: BepInEx's `mini-coreclr` 6.0.7 `win-x64` contains `coreclr.dll`, +`clrjit.dll` and `System.Private.CoreLib.dll` but deliberately **no +`hostfxr.dll`**: verified against the real archive, whose `coreclr.dll` exports +nine symbols including both hosting entry points. + +### Why the generator is Rust but the SDK is C# + +The generator's *output* must be .NET, but the generator itself is just a binary +reader and an ECMA-335 writer: both plainly expressible in safe Rust, and doing +it in Rust means interop generation can run from the CLI with no .NET installed. +The mod host and SDK cannot be anything but C#, because mods are C#. + +### Component status + +| Component | Crate / project | Status | +| --- | --- | --- | +| Metadata reader | `crates/modrix-il2cpp` | **Done.** Parses the real 26 MB file; 10 tests, two against the live install. | +| Loader lifecycle | `crates/modrix-core/src/launch.rs` | **Done.** Status, conflict detection, launch, log tail. | +| Game definition | `games/sonsoftheforest/game.toml` | **Done.** `api_version = 3`. | +| Interop generator | `crates/modrix-interop-gen` + `crates/modrix-ecma335` | **Done.** Emits 197 reference assemblies (39 MB) from the reference game; a real mod project compiles against them. `modrix interop generate` drives it. | +| Proxy DLL | `loaders/sons-proxy` (separate workspace) | **M0 built.** Cross-compiles to a Windows PE with all 17 exports; 18 host-side tests. Never executed. | +| CoreCLR host | same crate, `src/coreclr.rs` | **M0 built.** Compiles; the hosting calls have never run. | +| Mod host + SDK | `loaders/sons-managed/Modrix.Loader` | **M0 built.** `dotnet build` against `net6.0` is green; entry point contract verified in the emitted metadata. Discovery/SDK not started. | + +`install_loader` is deliberately **not implemented yet**: it would have nothing +to install. `loader_status` already reports the truth (not installed, interop +not generated), which is more useful than an action that half-works. + + +## Interop generation: what actually works today + +`modrix interop generate --game sonsoftheforest` reads the two files already in +the game directory and writes 197 managed reference assemblies into +`_Modrix/interop/`. Nothing is downloaded, and no third-party loader has to be +installed. Verified end to end on the reference machine: a C# project using +`LocalPlayer`, `GameObject`, `Vector3`, `VailActor` and the `LocalPlayer.IsInWorld` +*property* compiles clean against the output. + +Three decisions inside it are worth knowing before changing anything: + +**Only the public surface is emitted.** A reference assembly exists so a +compiler can bind names, and private members are unbindable by definition. + +**The game's own corlib is redirected, not emitted.** IL2CPP embeds `mscorlib`, +`System` and friends. Emitting them would make `System.Object` exist twice and +every use ambiguous (`CS0433`). Il2CppInterop solves this by renaming the tree to +`Il2CppSystem.*`; Modrix instead rewrites references to a curated allowlist of +BCL types onto the real `System.Runtime`, so `string` means `string`. A corlib +type not on the allowlist is declined and the member using it is dropped - +deliberately, because a dangling `TypeRef` fails the whole build with a +diagnostic that points nowhere, while a missing member costs one API. + +**A member whose signature cannot be expressed is skipped, never approximated.** +Emitting a method with a subtly wrong signature is worse than omitting it: the +compiler binds to it and fails somewhere confusing. + +### Known gaps in the generated output + +- **Interfaces reached through a constructed generic type** are skipped; they + would need a `TypeSpec` token. +- **Method generic arity is inferred** from the highest `!!N` the signature + mentions, because IL2CPP records no arity marker for methods. A generic method + that never references its own parameter is emitted as non-generic. +- **Enum literals with an unrecoverable constant** are demoted to plain static + fields rather than dropped, so the name still resolves. + +### Staleness + +`_Modrix/interop/generated-from.txt` records the metadata version and type count. +A game update changes both, and the assemblies must be regenerated - otherwise +mods compile against yesterday's game and fail at runtime in ways that look like +mod bugs. + +## Constraints that shape the design + +**One proxy slot, and it is already taken.** A game has exactly one +`version.dll`. On the reference machine MelonLoader currently owns it. Two +loaders cannot coexist: whichever loads second never runs, and the user gets a +game with half its mods missing and no diagnostic. This is why +`[mod_loader] conflicts` exists and why `install_loader` must refuse rather than +guess. `modrix loader status` already reports this correctly. + +**Proton makes the proxy inert by default.** Wine resolves `version.dll` to its +own builtin unless `WINEDLLOVERRIDES="version=n,b"` is set. Without it the game +starts perfectly and *no mods load*, with no error anywhere. Modrix surfaces this +as `LaunchReadiness.warning` rather than letting users discover it. Note Modrix +cannot inject the variable by spawning, because Steam owns the game process, +only the user's Steam launch options can carry it. + +**Interop regenerates on every game update.** The metadata hash changes, so the +generated assemblies must be rebuilt, and obfuscated type names can shift, +breaking mods at compile time. Modrix should hash `GameAssembly.dll` and compare +against a stamp beside the interop output, so this is reported as "the game +updated, mods need rebuilding" rather than experienced as a mystery. + +**Mods split across two paths.** The loader enumerates `Mods/*.dll` +non-recursively for payloads but reads `Mods//manifest.json` for metadata. A +mod legitimately owns both a bare top-level DLL and a folder. This is why +`park_root_binaries = false` is mandatory in the game definition: without it +Modrix's Bethesda-shaped heuristic parks every payload DLL to the install root, +deploy reports success, and nothing loads. + +**`manifest.json` version must parse as `System.Version`.** `1.0.0-beta.1` is +schema-valid but throws at load, and the mod is silently dropped. + +## Milestone M0: proving injection + +M0 answers one question with evidence and nothing else: **can managed .NET code +run inside this IL2CPP game, under Proton, without breaking it?** Everything +downstream (interop assemblies, detours, mod discovery, the SDK) is worthless +if the answer is no, and expensive to debug if it is discovered later from inside +a Proton-hosted CoreCLR process. + +### The chain + +1. **`DLL_PROCESS_ATTACH`.** Derive our own file name, resolve the real DLL + (`_original.dll` / `_alt.dll` in the game folder, else + `%SystemDirectory%\.dll`), point all 17 export thunks at it, truncate + `_Modrix/Latest.log`, and `SetCurrentDirectory` to the game folder (under + Steam the working directory is Steam's, which is Doorstop's `fix_cwd`). +2. **A spawned thread** polls `GetModuleHandleW("GameAssembly.dll")` and then + `il2cpp_domain_get()` until it returns non-null. Nothing is hooked. +3. **CoreCLR** is loaded from `_Modrix/dotnet/coreclr.dll` and initialized with a + single `APP_PATHS` property = `_Modrix/dotnet;_Modrix/net6`. +4. **`Modrix.Loader.Entrypoint.Start()`** (zero parameters, void return) writes + the final log line. + +`coreclr.dll` is loaded on the spawned thread, never under the loader lock. + +### The export forwarding, and the one documented deviation from PLAN.md + +`PLAN.md` D6 chose MelonLoader's model: export the names, then overwrite our own +stubs at runtime with `VirtualProtect(PAGE_EXECUTE_READWRITE)` + `mov r11, addr; +jmp r11`. What shipped instead is a `#[unsafe(naked)]` function per export that +loads a pointer from a table and tail-jumps: + +```asm +mov rax, qword ptr [rip + SLOTS + N*8] +test rax, rax +je .null +jmp rax +``` + +Both are unconditionally correct for exports whose arguments spill to the stack +(the reason D6 rejected Doorstop's zero-argument C thunk, which is correct only +because the compiler happens to tail-call at `-Os`). The naked thunk additionally +needs no RWX memory, and `injection.md` names it "the only strictly correct +implementation". Verified by disassembling the cross-compiled release DLL. + +### Why the poll trigger and not the IAT hook + +`PLAN.md` §3 lists the IAT hook on `UnityPlayer.dll`'s +`kernel32!GetProcAddress` (returning our own `il2cpp_init`) and then names the +poll as the *lower-risk path to implement first*, with the hook as M0b. That is +what happened. Whether IAT patching survives this Proton build is an open +question (`injection.md`, Unknowns), and M0's claim does not need it. + +Polling proves the runtime is **up**. Interception would additionally prove we +are **ahead of it**, which is what M1's `il2cpp_runtime_invoke` detour will +require. The log line says which mechanism produced it, because the two prove +different things: + +``` +[modrix] il2cpp runtime ready (poll trigger), domain = 0x00007ff... +``` + +### Acceptance + +Full procedure (install, launch options, the four required log lines, failure +triage, and how to revert) is in +[`loaders/sons-proxy/README.md`](../loaders/sons-proxy/README.md). In short: park +MelonLoader's `version.dll`, copy the staged tree in, set +`WINEDLLOVERRIDES="version=n,b" %command%`, reach the main menu, and read +`_Modrix/Latest.log`. **The game must still play**: a log with a broken game is +a failed M0. + +### What is verified today, and what is not + +Verified on a Linux host, without the game: + +- The proxy cross-compiles to an x86-64 Windows PE exporting all 17 + `version.dll` names (checked with `pefile`), importing only system DLLs. +- The PE entry point `DllMainCRTStartup` calls our `DllMain` (checked with + `objdump`). +- Each export thunk reads its own table slot at the right offset (checked with + `objdump`; also a unit test on the declaration table). +- 18 unit tests over path derivation, the `MODRIX_*` environment block, log + formatting and the `mini-coreclr` `.version` parse (CRLF, real bytes). +- `Modrix.Loader.dll` builds against `net6.0`, and its emitted metadata says + `.NETCoreApp,Version=v6.0` with `Modrix.Loader.Entrypoint` non-public and + `Start` public/static/void/zero-parameter. +- `mini-coreclr` 6.0.7 `win-x64` `coreclr.dll` exports both hosting symbols and + ships no `hostfxr.dll`. + +**Not verified: this has never run:** + +- Whether Wine loads our `version.dll` at all with the override set. +- Whether `coreclr_initialize` succeeds under this Proton build. This is the + single largest unknown in the whole design; the loader logs + `host = wine ` immediately before trying, so a failure report carries + the one fact needed to diagnose it. +- Whether `il2cpp_domain_get` returns non-null within the 120 s budget. +- Whether the game still plays with the proxy in place. +- Whether Rust's `windows-gnu` UCRT imports (`api-ms-win-crt-*`) resolve in the + Proton prefix. Proton ships `ucrtbase.dll`, so they should. + +None of these can be answered from Linux without the game running, and the +reference machine's `version.dll` belongs to MelonLoader, which was left +untouched. + +## Suggested order of work + +1. **`modrix-interop-gen`**: emit one managed assembly per IL2CPP assembly: + types, fields, method signatures, no bodies. Even a signatures-only output + unblocks *compiling* mods, which is the current hard blocker (`dotnet build` + in SOTFMods fails with `CS0246` because no interop assemblies exist). +2. **Proxy + CoreCLR host**: *built (M0), not yet run.* The next action is not + more code: it is running the acceptance test on the real install. Until that + passes, everything after it is speculative. +3. **M0b: the IAT hook**: replace the poll with interception of `il2cpp_init`, + which M1's detour work needs. Only worth attempting once M0 has passed, so a + failure is attributable to the hook and not to the whole chain. +4. **Mod host + SDK**: discovery, manifest parsing, lifecycle hooks, `RLog` + equivalent. Aim for source compatibility with `SonsSdk` where it is free, so + existing mods port with an import change rather than a rewrite. +5. **`install_loader`**: now that M0 defines a payload: `version.dll`, + `_Modrix/net6/Modrix.Loader.dll`, `_Modrix/dotnet/*`. It must still refuse + when a rival loader owns the slot, and it must park rather than overwrite. + +Step 1 is independently valuable and has no `unsafe` in it. Steps 2 to 5 are where +the real risk lives. + +## The unsafe boundary + +`loaders/sons-proxy` is a **separate Cargo workspace**, not a member of +`crates/*`. The root manifest's `members = ["crates/*"]` never sees it, so +`unsafe_code = "forbid"` remains true for all thirteen workspace crates and root +`cargo build` / `clippy` / `test` are unaffected: verified with +`cargo metadata`, which lists 15 packages and no `modrix-sons-proxy`. + +In exchange, the loader workspace is *stricter* where it counts: +`undocumented_unsafe_blocks` and `multiple_unsafe_ops_per_block` are **deny**, so +every unsafe block does one thing and says why it is sound; all FFI is confined +to `src/win.rs`; `panic = "abort"` in every profile, because unwinding across the +FFI boundary into Unity's stack is undefined behaviour. The rest (`unwrap_used`, +`panic`, `indexing_slicing`, `missing_docs`, the 60-line function cap) matches +the main workspace exactly. + +## Honest scope note + +Steps 2 to 5 are a substantial native-runtime project, not an afternoon. The +metadata reader is deliberately the first piece because it is the hard +dependency for everything else, is verifiable today against a real game, and +carries none of the injection risk. Until step 1 lands, Sons of the Forest mods +in this repo cannot be compiled at all without a third-party loader installed, +which the shared props supports, and which `SotfLoader=redloader` selects. + +M0 shifts the loader from "not started" to "written and compiling", which is a +smaller step than it looks: every genuinely uncertain thing about injection is +uncertain *at runtime*, on a Windows PE, inside a Proton prefix. The code being +correct on a Linux host is a precondition, not evidence. Treat M0 as unproven +until someone has read those four lines out of a real `_Modrix/Latest.log` and +then played the game. diff --git a/games/sonsoftheforest/game.toml b/games/sonsoftheforest/game.toml new file mode 100644 index 0000000..08d2bfc --- /dev/null +++ b/games/sonsoftheforest/game.toml @@ -0,0 +1,102 @@ +# SPDX-License-Identifier: GPL-2.0-only +# Sons of the Forest - Unity 2022.2.16f1, IL2CPP-compiled, Windows-only binary +# (it runs under Proton/Wine on Linux and macOS). Endnight / Steam appid 1326470. +# +# Because the game is IL2CPP there is no Assembly-CSharp.dll to patch: a mod +# loader must inject through a proxy DLL, host a .NET runtime in-process, and +# generate managed interop assemblies from GameAssembly.dll + global-metadata.dat +# before any mod can even be compiled. Modrix ships that loader natively - see +# the [mod_loader] table and `crates/modrix-loader-*`. +# +# `mod_root = "Mods"` is the loader's mod directory, mirroring what a manual +# install does. Note the layout is SPLIT: the loader enumerates `Mods/*.dll` +# NON-RECURSIVELY for payloads, but reads metadata from `Mods//manifest.json`. +# A mod therefore legitimately owns both a bare top-level DLL and a folder. +api_version = 3 +id = "sonsoftheforest" +name = "Sons of the Forest" +steam_appid = 1326470 +nexus_domain = "sonsoftheforest" # routes nxm://sonsoftheforest/... here +mod_root = "Mods" +deploy = "link" +install_probe = ["steam"] +required_files = ["SonsOfTheForest.exe", "SonsOfTheForest_Data/il2cpp_data/Metadata/global-metadata.dat"] + +# CRITICAL, and the reason this definition needs api_version 3. +# +# Without this, `Mods` (a single-component mod root) triggers the loader-parking +# heuristic in store::normalize_staged: every top-level .exe/.dll is moved to +# `.root/` and deployed to the game INSTALL ROOT. For Bethesda that is correct - +# `Data/` sits beside the binary, so a loose DLL is SKSE. Here it is exactly +# backwards: the bare top-level DLL IS the mod payload, and parking it would +# deploy every Sons of the Forest mod to a directory the loader never reads. +# +# The failure is silent - deploy reports success and the game loads nothing. +park_root_binaries = false + +# A `Mods/` tree at an archive root is content, not a packaging wrapper - +# hoisting it would strip the container. `_modrix`/`_redloader` appear in +# archives that bundle a loader alongside the mod. +content_dirs = ["mods", "_modrix", "_redloader", "userdata", "fomod"] + +# Hand-installed mods are BOTH loose DLLs and folders in Mods/ (the split layout +# above), so both kinds are scanned. The base game ships no Mods/ directory at +# all, so anything unowned there is genuinely an external mod. +[[external_scan]] +kind = "file" +label = "mod" +dir = "" +exts = ["dll"] + +[[external_scan]] +kind = "folder" +label = "mod data" +dir = "" + +# ── Launch ─────────────────────────────────────────────────────────────────── +# Steam-launched even on Windows: the game is a Steam DRM title, and going +# through steam:// keeps overlay and entitlement init correct. +# +# `env` is what makes modding work off-Windows at all. Under Proton the loader's +# version.dll proxy is inert unless WINEDLLOVERRIDES names it as a native +# override; Modrix applies this through Steam's launch options. It is ignored on +# Windows, where the proxy is picked up by the normal DLL search order. +[launch] +mode = "steam" +log = "_Modrix/Latest.log" +process = "SonsOfTheForest.exe" + +[launch.env] +WINEDLLOVERRIDES = "version=n,b" + +# ── Loader ─────────────────────────────────────────────────────────────────── +# `modrix-sons` is Modrix's own native loader: there is no third-party project +# to download, no [loader.source], and no version drift to track. The sentinel +# is the managed host assembly, which only exists after a successful install. +# +# `conflicts` lists the rival loaders that claim the same single proxy slot. +# Installing over one of them bricks both, so install_loader refuses rather than +# guessing which the user wanted. MelonLoader and RedLoader both take +# version.dll; BepInEx 6 IL2CPP takes winhttp.dll. +[mod_loader] +kind = "modrix-sons" +install_root = "_Modrix" +sentinel = "_Modrix/net6/Modrix.Loader.dll" +proxy = "version.dll" +interop_dir = "_Modrix/interop" +version_file = "_Modrix/version.txt" +conflicts = ["MelonLoader", "_Redloader", "_RedLoader", "BepInEx", "winhttp.dll", "dxgi.dll"] + +# ── Mod store ──────────────────────────────────────────────────────────────── +# sotf-mods.com is where this community actually publishes: the game has no +# Nexus presence to speak of, so without this the browser hand-off is the only +# way to install anything. The API is public and unauthenticated, which is why +# Modrix can browse and one-click install from it directly. +# +# `kind` selects the client in modrix-service that knows this site's JSON shape +# (its quirks are real: dependencies come back as an array from the list +# endpoint and a comma-separated string from the detail endpoint, and the list +# endpoint's `versions` array is a stale single entry, never the latest). +[store] +kind = "sotf-mods" +base_url = "https://api.sotf-mods.com" diff --git a/loaders/README.md b/loaders/README.md new file mode 100644 index 0000000..16683e3 --- /dev/null +++ b/loaders/README.md @@ -0,0 +1,30 @@ + + +# `loaders/`: code that runs inside a game process + +Everything under this directory executes **in another program's address space**. +That is a different risk class from the rest of Modrix, and it is kept out of the +main Cargo workspace for exactly that reason: the root manifest declares +`members = ["crates/*"]`, so `cargo build` / `cargo clippy` / `cargo test` at the +repository root never build anything here, and `unsafe_code = "forbid"` stays +true for all thirteen workspace crates. + +| Directory | What it is | Language | Workspace | +| --- | --- | --- | --- | +| `sons-proxy/` | Sons of the Forest `version.dll` proxy + CoreCLR host | Rust `cdylib`, Windows x86-64 | its own | +| `sons-managed/Modrix.Loader/` | the managed entry point CoreCLR calls | C# `net6.0` | its own | + +Read [`sons-proxy/README.md`](sons-proxy/README.md) first: it carries the unsafe +policy, the build commands, the install procedure and the M0 acceptance test. +The architecture and status live in +[`../docs/SONS-LOADER.md`](../docs/SONS-LOADER.md). + +## The one-line summary + +```sh +cd sons-proxy && ./build-windows.sh --managed --coreclr /win-x64 +``` + +produces `sons-proxy/dist/` (a `version.dll` plus a `_Modrix/` tree) and copies +it nowhere. Installing is manual and deliberate: a game has exactly one proxy +slot, and on most machines another loader already occupies it. diff --git a/loaders/sons-managed/.gitignore b/loaders/sons-managed/.gitignore new file mode 100644 index 0000000..9333b8a --- /dev/null +++ b/loaders/sons-managed/.gitignore @@ -0,0 +1,4 @@ +# SPDX-License-Identifier: GPL-2.0-only +# MSBuild intermediates. The root .gitignore does not cover .NET output. +bin/ +obj/ diff --git a/loaders/sons-managed/Modrix.Loader/DetourSetup.cs b/loaders/sons-managed/Modrix.Loader/DetourSetup.cs new file mode 100644 index 0000000..cfe7b4a --- /dev/null +++ b/loaders/sons-managed/Modrix.Loader/DetourSetup.cs @@ -0,0 +1,165 @@ +// SPDX-License-Identifier: GPL-2.0-only + +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.CompilerServices; + +using MonoMod.Utils; + +namespace Modrix.Loader; + +/// +/// Configures MonoMod's dynamic-method backend before Harmony is used. +/// +/// +/// +/// Harmony does not rewrite a method in place. It generates a replacement and +/// points the original at it, and the generation goes through MonoMod's +/// DynamicMethodDefinition, which has two backends: +/// +/// +/// DynamicMethod - emits IL straight into the +/// running runtime via System.Reflection.Emit. Needs nothing from +/// disk. +/// Cecil - builds a whole in-memory assembly with +/// Mono.Cecil and loads it. To do that, Cecil must resolve every +/// assembly the new one references, starting with +/// System.Private.CoreLib. +/// +/// +/// The Cecil backend cannot work here. Cecil's default resolver searches the +/// process directory and the GAC; our runtime lives in _Modrix/dotnet, +/// which is on CoreCLR's APP_PATHS but is not a place Cecil looks. The +/// symptom is a HarmonyException: IL Compile Error (unknown location) +/// whose real cause, four frames down the inner chain, is +/// AssemblyResolutionException: Failed to resolve assembly +/// 'System.Private.CoreLib'. Nothing about that message points at the +/// backend choice, which is why this is worth a file of its own. +/// +/// +/// So the backend is pinned to DynamicMethod - but only after checking +/// that dynamic IL is actually available, because forcing a backend that cannot +/// run would trade a decipherable error for an opaque one. +/// +/// +internal static class DetourSetup +{ + /// + /// MonoMod's environment variable selecting the DMD backend. + /// + /// + /// Set through the environment rather than through MonoMod's own + /// Switches API, because that type exists only in MonoMod 25 and up + /// while the pinned version here is 22.x. The variable is read by both. + /// + private const string DmdTypeVariable = "MONOMOD_DMDTYPE"; + + /// The backend that needs no assembly resolution. + private const string DynamicMethodBackend = "DynamicMethod"; + + /// + /// Pin the DMD backend, reporting what was decided and why. + /// + /// + /// Must run before the first Harmony patch. It is called from interop + /// startup rather than from , because mods patch too + /// and the first patch may well be a mod's, not ours. + /// + /// Where to report the decision. + internal static void Configure(Action log) + { + var dynamicCode = RuntimeFeature.IsDynamicCodeSupported; + var dynamicIl = DynamicMethodDefinition.IsDynamicILAvailable; + log($"monomod: dynamic code = {dynamicCode}, dynamic IL = {dynamicIl}"); + + if (!dynamicIl) + { + // Cecil is the only remaining backend, and it will fail to resolve + // corlib. Say so now, with the fix, instead of letting the first + // patch produce "IL Compile Error (unknown location)". + log("monomod: WARN dynamic IL unavailable - Harmony patches will use " + + "the Cecil backend and are expected to fail to resolve " + + "System.Private.CoreLib"); + return; + } + + Environment.SetEnvironmentVariable(DmdTypeVariable, DynamicMethodBackend); + log($"monomod: DMD backend pinned to {DynamicMethodBackend}"); + + EnsureTrustedPlatformAssemblies(log); + } + + /// The AppContext key Cecil reads to find the platform assemblies. + private const string TrustedAssembliesKey = "TRUSTED_PLATFORM_ASSEMBLIES"; + + /// + /// Guarantee TRUSTED_PLATFORM_ASSEMBLIES has a value. + /// + /// + /// + /// Harmony's DelegateTypeFactory builds the delegate type for an + /// IL2CPP detour with Cecil, unconditionally - the DMD backend choice above + /// does not affect it. Writing that type means writing an + /// UnmanagedFunctionPointer attribute whose argument is a + /// CallingConvention enum, and Cecil must resolve the enum to learn + /// its underlying type. It looks for platform assemblies in exactly one + /// place: AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES"). + /// + /// + /// A normal .NET application gets that from the host. We are not a normal + /// application - the proxy calls coreclr_initialize directly, and it + /// is the proxy's job to pass it. It does. This is the belt to that + /// suspenders: the value is checked, and reconstructed here if absent, so + /// that an older proxy paired with a newer managed loader degrades into a + /// log line rather than into "IL Compile Error (unknown location)" on every + /// Harmony patch in the process. + /// + /// + private static void EnsureTrustedPlatformAssemblies(Action log) + { + var existing = AppContext.GetData(TrustedAssembliesKey) as string; + if (!string.IsNullOrEmpty(existing)) + { + var count = existing!.Split(new[] { ';', Path.PathSeparator }).Length; + log($"monomod: {TrustedAssembliesKey} supplied by host ({count} assemblies)"); + return; + } + + // Reconstruct from where the runtime and this assembly actually live, + // rather than from the environment block, so it is right even if the + // proxy published nothing at all. + var runtimeDir = Path.GetDirectoryName(typeof(object).Assembly.Location); + var hostDir = AppContext.BaseDirectory; + var loaderDir = Path.GetDirectoryName(typeof(DetourSetup).Assembly.Location); + + var assemblies = new List(); + foreach (var dir in new[] { runtimeDir, hostDir, loaderDir }) + { + if (string.IsNullOrWhiteSpace(dir) || !Directory.Exists(dir)) + { + continue; + } + foreach (var dll in Directory.GetFiles(dir!, "*.dll")) + { + if (!assemblies.Contains(dll)) + { + assemblies.Add(dll); + } + } + } + + if (assemblies.Count == 0) + { + log($"monomod: WARN {TrustedAssembliesKey} is unset and could not be " + + "reconstructed - Harmony patches of IL2CPP methods will fail"); + return; + } + + // AppDomain.SetData forwards to the AppContext data store that + // AppContext.GetData - and therefore Cecil - reads. AppContext.SetData + // itself is not on net6.0's reference assembly. + AppDomain.CurrentDomain.SetData(TrustedAssembliesKey, string.Join(';', assemblies)); + log($"monomod: {TrustedAssembliesKey} reconstructed ({assemblies.Count} assemblies)"); + } +} diff --git a/loaders/sons-managed/Modrix.Loader/Entrypoint.cs b/loaders/sons-managed/Modrix.Loader/Entrypoint.cs new file mode 100644 index 0000000..df48671 --- /dev/null +++ b/loaders/sons-managed/Modrix.Loader/Entrypoint.cs @@ -0,0 +1,324 @@ +// SPDX-License-Identifier: GPL-2.0-only + +using System; +using System.IO; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Threading; + +namespace Modrix.Loader; + +/// +/// The single managed function the native proxy calls. +/// +/// +/// +/// The shape of is dictated by the host, not chosen: +/// coreclr_create_delegate builds a reverse-P/Invoke stub from the +/// method's own signature, so it must take zero parameters and return void. +/// Adding a parameter would not fail to compile - it would corrupt the stack at +/// call time, inside the game. +/// +/// +/// The type is internal on purpose, mirroring RedLoader's +/// Doorstop.Entrypoint: CoreCLR resolves the entry point reflectively and +/// does not require it to be public, and nothing else should ever call this. +/// +/// +/// For milestone M0 the body does exactly one thing - prove that managed code +/// ran inside the IL2CPP process - and then returns. No mod discovery, no +/// interop assemblies, no Harmony. +/// +/// +internal static class Entrypoint +{ + /// Prefix shared with the native side so the log reads as one stream. + private const string Tag = "[modrix]"; + + /// Log file name inside the loader directory. + private const string LogFileName = "Latest.log"; + + /// Attempts to make when the log file is briefly locked. + private const int WriteAttempts = 5; + + /// Milliseconds between write attempts. + private const int WriteBackoffMs = 20; + + /// + /// Native entry point. Zero parameters, void return - non-negotiable. + /// + /// + /// Nothing may escape this method. An exception crossing back through the + /// reverse-P/Invoke stub tears down the process, and the user sees the game + /// close with no window, no dialog and no log - which is precisely the + /// failure mode a loader must never have. Everything is therefore caught and + /// written to a crash file. + /// + public static void Start() + { + string loaderDirectory = ResolveLoaderDirectory(); + try + { + Report(loaderDirectory); + } + catch (Exception error) + { + WriteCrashFile(loaderDirectory, error); + } + } + + /// Writes the milestone line and the diagnostics behind it. + private static void Report(string loaderDirectory) + { + string logPath = Path.Combine(loaderDirectory, LogFileName); + + // The acceptance line. Everything else in this method is context for + // when it does NOT appear. + Append(logPath, $"managed entrypoint reached: Modrix.Loader {Version()}"); + + Append(logPath, $"managed runtime = {RuntimeInformation.FrameworkDescription}"); + Append(logPath, $"managed base directory = {AppContext.BaseDirectory}"); + + // Echoed back so a mismatch between what the proxy published and what + // the runtime sees - a real risk under Wine - is visible in one place. + foreach (string name in new[] + { + "MODRIX_INITIALIZED", + "MODRIX_PROCESS_PATH", + "MODRIX_GAME_ROOT", + "MODRIX_LOADER_DIR", + "MODRIX_GAME_ASSEMBLY", + }) + { + string value = Environment.GetEnvironmentVariable(name) ?? ""; + Append(logPath, $"env {name} = {value}"); + } + + LoadMods(logPath); + } + + /// Discovers and initializes the mods in the game's Mods folder. + /// + /// Wrapped so that a failure here still leaves the milestone lines above in + /// the log: knowing the runtime started but mod loading threw is far more + /// actionable than an empty file. + /// + private static void LoadMods(string logPath) + { + string? gameRoot = Environment.GetEnvironmentVariable("MODRIX_GAME_ROOT"); + if (string.IsNullOrWhiteSpace(gameRoot)) + { + Append(logPath, "WARN MODRIX_GAME_ROOT unset - cannot locate Mods"); + return; + } + + void Log(string message) => Append(logPath, message); + + // Point the SDK's logger at our file before any mod runs, so a mod's + // own RLog.Msg output lands in the same stream as the loader's and the + // ordering between them is real. + RedLoader.RLog.Sink = Log; + + // IL2CPP interop must be up BEFORE any mod is constructed. A mod's type + // references game types, so the CLR resolves them while loading the mod + // assembly - if the interop assemblies are not generated and resolvable + // by then, every mod fails with TypeLoadException on its first game + // type. Generation is cached; only the first launch after a game update + // pays the cost. + string? loaderDir = Environment.GetEnvironmentVariable("MODRIX_LOADER_DIR"); + if (string.IsNullOrWhiteSpace(loaderDir)) + { + Append(logPath, "WARN MODRIX_LOADER_DIR unset - cannot initialize interop"); + return; + } + try + { + var interop = InteropManager.Initialize(gameRoot!, loaderDir!, Log); + InteropManager.PreloadInteropAssemblies(interop, Log); + } + catch (Exception error) + { + // Without interop, mods that touch game types cannot work - but the + // loader itself is fine, and reporting precisely why is far more + // useful than a silent absence of mods. + Append(logPath, $"ERROR interop initialization failed: {ModHost.Describe(error)}"); + return; + } + + // The gate is armed FIRST, before the pump. Both are Harmony patches made + // from this thread, but attaching the pump costs over a second, and the + // gate can only catch scene changes that happen after it is installed - + // so arming it first buys that second back as earlier main-thread access. + // + // It does NOT buy the splash. Measured on this machine: the managed + // entrypoint runs at 1.2s and the gate arms at 3.3s, while the game's + // first scene is already active before either. There is no way to reach + // the boot sequence from inside the process, and an attempt to trim its + // dwell times from the loader was removed after measuring it save + // nothing. The splash is not idle time anyway - vanilla reaches the title + // at 12.1s and the loader at 12.3s, so those seconds are the game loading, + // not waiting. What IS worth having is starting a save load the moment + // the title exists (~7s) rather than when the menu finishes building + // (~12s); SonsBridge's SONSBRIDGE_AUTOLOAD does that, and it is worth + // about twenty seconds end to end. + try + { + MainThreadGate.Open(() => StartOnMainThread(gameRoot!, Log), Log); + } + catch (Exception error) + { + Append(logPath, $"ERROR main-thread gate failed: {ModHost.Describe(error)}"); + return; + } + + try + { + UnityPump.Start(Log); + } + catch (Exception error) + { + Append(logPath, $"ERROR per-frame pump failed: {ModHost.Describe(error)}"); + return; + } + + } + + /// + /// The rest of startup, running on the Unity main thread. + /// + /// + /// Ordering is deliberate. The pump goes in first, so a mod's own per-frame + /// callback is already being driven by the time the mod exists. Mods load + /// second. The gate is torn down from the first pump tick rather than here, + /// because a detour cannot safely be undone from inside itself - and this + /// method is running inside it. + /// + private static void StartOnMainThread(string gameRoot, Action log) + { + // The pump was armed before the gate; Start is idempotent, so this is + // only a guard for the case where arming failed earlier. + try + { + UnityPump.Start(log); + } + catch (Exception error) + { + log($"ERROR per-frame pump failed: {ModHost.Describe(error)}"); + } + + try + { + var mods = ModHost.LoadAll(Path.Combine(gameRoot, "Mods"), log); + Lifecycle.Attach(mods, log); + } + catch (Exception error) + { + log($"ERROR mod loading failed: {ModHost.Describe(error)}"); + } + } + + /// + /// Where Latest.log lives. + /// + /// + /// MODRIX_LOADER_DIR is authoritative because the native side already + /// derived it from the process path; re-deriving it here would create two + /// sources of truth that can disagree. The fallbacks exist only so that a + /// missing environment block produces a log rather than silence. + /// + private static string ResolveLoaderDirectory() + { + string? configured = Environment.GetEnvironmentVariable("MODRIX_LOADER_DIR"); + if (!string.IsNullOrWhiteSpace(configured)) + { + return configured!; + } + + string? processPath = Environment.GetEnvironmentVariable("MODRIX_PROCESS_PATH"); + string? gameRoot = string.IsNullOrWhiteSpace(processPath) + ? null + : Path.GetDirectoryName(processPath); + if (!string.IsNullOrWhiteSpace(gameRoot)) + { + return Path.Combine(gameRoot!, "_Modrix"); + } + + // Last resort: this assembly lives in `/_Modrix/net6`, so the + // loader directory is its parent. + string baseDirectory = AppContext.BaseDirectory; + string? parent = Path.GetDirectoryName(baseDirectory.TrimEnd( + Path.DirectorySeparatorChar, + Path.AltDirectorySeparatorChar)); + return parent ?? baseDirectory; + } + + /// Informational version, without any build metadata suffix. + private static string Version() + { + Assembly self = typeof(Entrypoint).Assembly; + string? informational = self + .GetCustomAttribute() + ?.InformationalVersion; + if (string.IsNullOrWhiteSpace(informational)) + { + return self.GetName().Version?.ToString() ?? "0.0.0"; + } + + int plus = informational!.IndexOf('+'); + return plus < 0 ? informational : informational.Substring(0, plus); + } + + /// + /// Appends one tagged line, retrying briefly if the file is momentarily + /// locked. Best-effort: failing to log must not become the failure. + /// + private static void Append(string logPath, string message) + { + string line = $"{Tag} {message}{Environment.NewLine}"; + for (int attempt = 0; attempt < WriteAttempts; attempt++) + { + try + { + Directory.CreateDirectory(Path.GetDirectoryName(logPath) ?? "."); + File.AppendAllText(logPath, line); + return; + } + catch (IOException) + { + Thread.Sleep(WriteBackoffMs); + } + catch (UnauthorizedAccessException) + { + return; + } + } + } + + /// + /// Records a failure to its own timestamped file. + /// + /// + /// A separate file rather than a line in Latest.log: whatever broke + /// may be the log itself, and a crash report that survives a truncated log + /// is worth more than a tidy one that does not. + /// + private static void WriteCrashFile(string loaderDirectory, Exception error) + { + try + { + Directory.CreateDirectory(loaderDirectory); + string stamp = DateTime.Now.ToString("yyyyMMdd_HHmmss_fff"); + string path = Path.Combine(loaderDirectory, $"crash_{stamp}.log"); + File.WriteAllText( + path, + $"Modrix.Loader {Version()} failed in Entrypoint.Start{Environment.NewLine}" + + $"{RuntimeInformation.FrameworkDescription}{Environment.NewLine}" + + $"{Environment.NewLine}{error}{Environment.NewLine}"); + } + catch (Exception) + { + // There is nowhere left to report to. Returning quietly keeps the + // game running, which is the only remaining useful outcome. + } + } +} diff --git a/loaders/sons-managed/Modrix.Loader/Il2CppDetours.cs b/loaders/sons-managed/Modrix.Loader/Il2CppDetours.cs new file mode 100644 index 0000000..36325ca --- /dev/null +++ b/loaders/sons-managed/Modrix.Loader/Il2CppDetours.cs @@ -0,0 +1,220 @@ +// SPDX-License-Identifier: GPL-2.0-only + +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Runtime.InteropServices; + +using Il2CppInterop.Runtime.Injection; + +using MonoMod.RuntimeDetour; + +// Both libraries define an `IDetour`, and this file is the seam between them, so +// the Il2CppInterop one is aliased rather than imported plainly. Using the wrong +// one compiles in some positions and fails in others with a message about return +// types that does not mention the ambiguity at all. +using InteropDetour = Il2CppInterop.Runtime.Injection.IDetour; + +namespace Modrix.Loader; + +/// +/// Supplies Il2CppInterop with the native detours it cannot provide itself. +/// +/// +/// +/// Il2CppInterop deliberately does not ship a detour implementation. It needs +/// one - to hook IL2CPP internals when injecting a managed type, and to +/// redirect a native method when Harmony patches it - but which hooking library +/// to use is the host's decision, so it asks for an +/// and calls into that. +/// +/// +/// Leaving it unset does not fail at startup. The runtime initializes happily, +/// interop assemblies load, and then the first Harmony patch of an IL2CPP method +/// throws NullReferenceException from inside +/// Il2CppDetourMethodPatcher.DetourTo - a stack that names neither this +/// interface nor the fact that it was never populated. That is why this exists as +/// its own file with this comment on it. +/// +/// +/// BepInEx and RedLoader each hand-wrote a native detour engine for this job. +/// This one delegates to MonoMod's, which is a maintained implementation of +/// exactly that, and needs only the small adaptation below. +/// +/// +internal sealed class Il2CppDetourProvider : IDetourProvider +{ + /// + /// Keeps every hook delegate reachable for the life of the process. + /// + /// + /// This list is load-bearing, not bookkeeping. + /// does not + /// root its argument: the pointer stays valid only while the delegate is + /// alive. Once collected, the native code the detour installed jumps into + /// freed memory, and the game dies with an access violation somewhere + /// unrelated, minutes later, with nothing tying it back to here. Detours are + /// never uninstalled, so the list only grows to the number of patched + /// methods and needs no eviction. + /// + private static readonly List Roots = new(); + + private static readonly object Gate = new(); + + /// Create a detour from a native address to a managed delegate. + /// + /// Not applied here. Il2CppInterop's contract is create-then-apply, so + /// ManualApply is set and the caller decides when the redirect goes + /// live. + /// + /// The hook's signature. + /// Address of the function to redirect. + /// The managed replacement. + /// The unapplied detour. + public InteropDetour Create(nint original, TDelegate target) + where TDelegate : Delegate + { + lock (Gate) + { + Roots.Add(target); + } + + var replacement = Marshal.GetFunctionPointerForDelegate(target); + var config = new NativeDetourConfig { ManualApply = true }; + // target.GetType(), not typeof(TDelegate). Il2CppInterop calls this with + // the argument statically typed as `Delegate`, so TDelegate infers to + // `System.Delegate` - which has no Invoke and therefore describes no + // signature. The concrete delegate type is only available at runtime. + return new Il2CppDetour( + new NativeDetour(original, replacement, config), + target.GetType()); + } + + /// Root a delegate for the process lifetime. See . + internal static void Root(Delegate value) + { + lock (Gate) + { + Roots.Add(value); + } + } +} + +/// One native detour, adapted to the shape Il2CppInterop expects. +internal sealed class Il2CppDetour : InteropDetour +{ + private readonly NativeDetour _detour; + + /// + /// Concrete type of the hook delegate, which is also the signature of the + /// function being detoured. + /// + /// + /// Carried explicitly because it cannot be recovered later: the interface + /// erases it to , and a trampoline cannot be built + /// without a signature. + /// + private readonly Type _signature; + + private readonly object _gate = new(); + private IntPtr _trampoline; + + internal Il2CppDetour(NativeDetour detour, Type signature) + { + _detour = detour; + _signature = signature; + } + + /// The function being redirected. + public IntPtr Target => _detour.Data.Method; + + /// Where it is redirected to. + public IntPtr Detour => _detour.Data.Target; + + /// + /// A callable native address for the original, pre-detour code. + /// + /// + /// + /// The tempting implementation - hand back MonoMod's internal + /// _BackupNative - is wrong in a way that is very hard to diagnose. + /// That buffer holds a *copy of the overwritten bytes* and nothing else: no + /// jump back into the remainder of the original function. Executing it runs + /// the first few instructions and then falls into whatever follows in memory, + /// so the game dies on the first frame after the patch with an access + /// violation and no managed stack. Il2CppInterop reads this property on every + /// IL2CPP patch, so getting it wrong is not a corner case. + /// + /// + /// Generated once and cached, and the delegate is rooted: the returned + /// pointer is only valid while the delegate behind it is alive. + /// + /// + public IntPtr OriginalTrampoline + { + get + { + lock (_gate) + { + if (_trampoline == IntPtr.Zero) + { + var original = Trampoline(_signature); + Il2CppDetourProvider.Root(original); + _trampoline = Marshal.GetFunctionPointerForDelegate(original); + } + return _trampoline; + } + } + } + + /// Make the redirect live. + public void Apply() + { + _detour.Apply(); + } + + /// A callable delegate for the original, pre-detour code. + /// + /// The requested delegate type. When this is itself - + /// which is how Il2CppInterop calls it - the concrete signature captured at + /// construction is used instead. + /// + /// A delegate invoking the original code. + public T GenerateTrampoline() + where T : Delegate + { + var requested = typeof(T).GetMethod("Invoke") is null ? _signature : typeof(T); + return (T)Trampoline(requested); + } + + /// + /// Build a trampoline delegate, supplying the signature explicitly. + /// + /// + /// cannot be used. It + /// forwards a null signature and expects the detour to carry the managed + /// method it replaced - but a detour created from two raw addresses, which is + /// all Il2CppInterop can give us for a native IL2CPP function, has no managed + /// method. It throws ArgumentNullException: A signature must be given if + /// the NativeDetour doesn't hold a reference to a managed method. + /// + /// Concrete delegate type describing the call. + /// A delegate invoking the original code. + private Delegate Trampoline(Type delegateType) + { + // A delegate type's Invoke method IS the signature being asked for. + var signature = delegateType.GetMethod("Invoke") + ?? throw new InvalidOperationException( + $"{delegateType.FullName} has no Invoke method"); + var generated = _detour.GenerateTrampoline(signature) + ?? throw new InvalidOperationException( + $"MonoMod produced no trampoline for {delegateType.FullName}"); + return ((MethodInfo)generated).CreateDelegate(delegateType); + } + + /// Undo the redirect and release the detour. + public void Dispose() + { + _detour.Dispose(); + } +} diff --git a/loaders/sons-managed/Modrix.Loader/InteropManager.cs b/loaders/sons-managed/Modrix.Loader/InteropManager.cs new file mode 100644 index 0000000..aba8790 --- /dev/null +++ b/loaders/sons-managed/Modrix.Loader/InteropManager.cs @@ -0,0 +1,509 @@ +// SPDX-License-Identifier: GPL-2.0-only + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Net.Http; +using System.Reflection; +using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; + +using Cpp2IL.Core; +using Cpp2IL.Core.Api; +using Cpp2IL.Core.OutputFormats; +using Cpp2IL.Core.ProcessingLayers; +using Cpp2IL.Core.InstructionSets; +using Il2CppInterop.Generator; +using Il2CppInterop.Generator.Runners; +using Il2CppInterop.HarmonySupport; +using Il2CppInterop.Runtime.Startup; +using LibCpp2IL; + +namespace Modrix.Loader; + +/// +/// Builds and starts the IL2CPP interop layer. +/// +/// +/// +/// An IL2CPP game ships no managed assemblies, so a mod has nothing to call. +/// Bridging that needs two distinct artifacts, and conflating them is the +/// mistake that costs days: +/// +/// +/// Dummy assemblies - types, fields and method +/// signatures with no bodies, reconstructed from `global-metadata.dat` by +/// Cpp2IL. These are enough to compile against and nothing +/// more: the CLR refuses to load a type whose method has no +/// RVA. +/// Interop assemblies - the same shape, but with +/// real bodies that marshal through `il2cpp_runtime_invoke`. Il2CppInterop +/// generates these from the dummies, and they are what actually +/// runs. +/// +/// +/// Generation happens once per game build and is cached against a hash of the +/// inputs, because it takes minutes. It runs at first launch rather than at +/// install time for one reason: the Unity version and the metadata are read out +/// of the live process, so the output is guaranteed to match the game actually +/// running rather than whatever was installed when the user last pressed a +/// button. +/// +/// +internal static class InteropManager +{ + /// Where Unity publishes the stripped base libraries per version. + private const string UnityBaseLibrariesSource = + "https://unity.bepinex.dev/libraries/{VERSION}.zip"; + + /// Interop assemblies, relative to the loader directory. + private const string InteropDirName = "interop"; + + /// Unity base libraries, relative to the loader directory. + private const string UnityLibsDirName = "unity-libs"; + + /// Stamp recording the inputs the current output was built from. + private const string HashFileName = "interop.hash"; + + /// Resolved paths and the detected Unity version. + internal sealed class Context + { + internal Context(string gameRoot, string loaderDir, Version unityVersion) + { + GameRoot = gameRoot; + LoaderDir = loaderDir; + UnityVersion = unityVersion; + } + + internal string GameRoot { get; } + internal string LoaderDir { get; } + internal Version UnityVersion { get; } + + internal string GameAssemblyPath => Path.Combine(GameRoot, "GameAssembly.dll"); + internal string InteropDir => Path.Combine(LoaderDir, InteropDirName); + internal string UnityLibsDir => Path.Combine(LoaderDir, UnityLibsDirName); + internal string HashPath => Path.Combine(LoaderDir, HashFileName); + + /// `<Game>_Data/il2cpp_data/Metadata/global-metadata.dat`. + internal string MetadataPath + { + get + { + foreach (var dir in Directory.EnumerateDirectories(GameRoot, "*_Data")) + { + var candidate = Path.Combine( + dir, "il2cpp_data", "Metadata", "global-metadata.dat"); + if (File.Exists(candidate)) + { + return candidate; + } + } + throw new FileNotFoundException( + $"no il2cpp global-metadata.dat under any *_Data directory in {GameRoot}"); + } + } + } + + /// + /// Generate the interop assemblies if needed, then start the runtime. + /// + /// The game's install directory. + /// `<game>/_Modrix`. + /// Progress sink. + /// The context, so callers can report paths. + internal static Context Initialize(string gameRoot, string loaderDir, Action log) + { + var unityVersion = DetectUnityVersion(gameRoot); + var context = new Context(gameRoot, loaderDir, unityVersion); + log($"unity version = {unityVersion}"); + + // Before anything patches: Harmony's code generation must not fall back + // to MonoMod's Cecil backend, which cannot resolve corlib from here. + DetourSetup.Configure(log); + + EnsureInteropAssemblies(context, log); + RegisterAssemblyResolver(context, log); + StartRuntime(context, log); + return context; + } + + /// + /// Read the Unity version out of the game's own data. + /// + /// + /// `globalgamemanagers` begins with a serialized-file header whose version + /// string is plain ASCII, so this needs no Unity API and works before + /// anything is initialized. The version selects which stripped base + /// libraries to fetch, and a mismatch there produces interop assemblies + /// that reference types the game does not have. + /// + private static Version DetectUnityVersion(string gameRoot) + { + foreach (var dir in Directory.EnumerateDirectories(gameRoot, "*_Data")) + { + var path = Path.Combine(dir, "globalgamemanagers"); + if (!File.Exists(path)) + { + continue; + } + var head = new byte[4096]; + using var stream = File.OpenRead(path); + var read = stream.Read(head, 0, head.Length); + var found = ScanVersion(head, read); + if (found is not null) + { + return found; + } + } + throw new InvalidOperationException( + $"could not determine the Unity version from any *_Data/globalgamemanagers in {gameRoot}"); + } + + /// Find the first `N.N.NfN`-shaped ASCII run in a buffer. + private static Version? ScanVersion(byte[] buffer, int length) + { + var text = Encoding.ASCII.GetString(buffer, 0, Math.Max(length, 0)); + var match = System.Text.RegularExpressions.Regex.Match( + text, @"(\d+)\.(\d+)\.(\d+)[fpab]\d+"); + if (!match.Success) + { + return null; + } + return new Version( + int.Parse(match.Groups[1].Value), + int.Parse(match.Groups[2].Value), + int.Parse(match.Groups[3].Value)); + } + + /// Regenerate the interop assemblies unless the cache is current. + private static void EnsureInteropAssemblies(Context context, Action log) + { + var expected = ComputeHash(context); + if (File.Exists(context.HashPath) + && File.ReadAllText(context.HashPath).Trim() == expected + && Directory.Exists(context.InteropDir) + && Directory.EnumerateFiles(context.InteropDir, "*.dll").Any()) + { + log("interop assemblies are current"); + return; + } + + log("generating interop assemblies (first run for this game build; takes a few minutes)"); + var stopwatch = Stopwatch.StartNew(); + + Directory.CreateDirectory(context.InteropDir); + foreach (var stale in Directory.EnumerateFiles(context.InteropDir, "*.dll")) + { + File.Delete(stale); + } + + DownloadUnityLibs(context, log); + var dummies = RunCpp2Il(context, log); + RunGenerator(context, dummies, log); + + File.WriteAllText(context.HashPath, expected); + log($"interop assemblies generated in {stopwatch.Elapsed}"); + } + + /// + /// What the current output was built from. + /// + /// + /// Hashing the metadata and the binary means a game update invalidates the + /// cache automatically. Without this, a patch silently leaves mods compiled + /// and running against the previous build's type layout. + /// + private static string ComputeHash(Context context) + { + using var sha = SHA256.Create(); + var parts = new List + { + context.UnityVersion.ToString(), + FileFingerprint(context.MetadataPath), + FileFingerprint(context.GameAssemblyPath), + }; + var joined = string.Join("|", parts); + return Convert.ToHexString(sha.ComputeHash(Encoding.UTF8.GetBytes(joined))); + } + + /// + /// Size plus modification time, rather than a full content hash. + /// + /// + /// `GameAssembly.dll` is 100 MB; hashing it on every launch would add + /// seconds to startup to detect something size+mtime already catches. A + /// game update always changes both. + /// + private static string FileFingerprint(string path) + { + var info = new FileInfo(path); + return $"{info.Name}:{info.Length}:{info.LastWriteTimeUtc.Ticks}"; + } + + /// Fetch the stripped Unity base libraries for this version. + private static void DownloadUnityLibs(Context context, Action log) + { + if (Directory.Exists(context.UnityLibsDir) + && Directory.EnumerateFiles(context.UnityLibsDir, "*.dll").Any()) + { + log("unity base libraries already present"); + return; + } + + var version = + $"{context.UnityVersion.Major}.{context.UnityVersion.Minor}.{context.UnityVersion.Build}"; + var source = UnityBaseLibrariesSource.Replace("{VERSION}", version); + Directory.CreateDirectory(context.UnityLibsDir); + + log($"downloading unity base libraries {version}"); + using var client = new HttpClient(); + client.Timeout = TimeSpan.FromMinutes(5); + + // Buffered rather than streamed into ZipArchive: a zip's central + // directory is at the END of the file, so reading one requires seeking, + // and an HTTP response stream is forward-only. Handing it straight to + // ZipArchive throws "The stream must support seeking". The archive is a + // few tens of MB, so buffering it is the simple correct answer. + var payload = client.GetByteArrayAsync(source).GetAwaiter().GetResult(); + using var buffer = new MemoryStream(payload, writable: false); + using var archive = new ZipArchive(buffer, ZipArchiveMode.Read); + archive.ExtractToDirectory(context.UnityLibsDir, overwriteFiles: true); + log($"unity base libraries extracted ({payload.Length / (1024 * 1024)} MB)"); + } + + /// + /// Populate Cpp2IL's plugin registries. + /// + /// + /// + /// Cpp2IL is built as a plugin host: its instruction-set decoders, binary + /// format readers, processing layers and output formats all live behind + /// registries that are empty until something fills them. Its own console + /// frontend does that during startup - a library consumer gets nothing, and + /// the first symptom is InstructionSetHandlerNotRegisteredException: + /// Instruction set handler not registered for instruction set x86_64 + /// thrown from deep inside the application-context constructor. + /// + /// + /// Every set is registered, not just x86-64. It costs nothing, and it is + /// what makes this work unchanged on an ARM64 macOS build of the game rather + /// than only on the x86-64 one in front of us. + /// + /// + /// Registration is process-global and idempotent per registry, but calling + /// it twice throws on a duplicate key, so it is guarded by a flag: interop + /// generation can be re-entered when a mod is hot-reloaded. + /// + /// + private static bool _handlersRegistered; + + private static void RegisterCpp2IlHandlers() + { + if (_handlersRegistered) + { + return; + } + _handlersRegistered = true; + + InstructionSetRegistry.RegisterInstructionSet( + DefaultInstructionSets.X86_32); + InstructionSetRegistry.RegisterInstructionSet( + DefaultInstructionSets.X86_64); + InstructionSetRegistry.RegisterInstructionSet( + DefaultInstructionSets.WASM); + InstructionSetRegistry.RegisterInstructionSet( + DefaultInstructionSets.ARM_V7); + InstructionSetRegistry.RegisterInstructionSet( + DefaultInstructionSets.ARM_V8); + + // ELF/PE/Mach-O readers. Without these, loading the binary fails before + // instruction decoding is ever reached. + LibCpp2IlBinaryRegistry.RegisterBuiltInBinarySupport(); + } + + /// + /// Reconstruct dummy assemblies from the game's metadata. + /// + /// + /// The `AttributeInjectorProcessingLayer` is not optional: it injects the + /// attributes Il2CppInterop reads to correlate a managed member back to its + /// native address. Without it the generator produces assemblies whose + /// methods have nothing to call. + /// + private static List RunCpp2Il( + Context context, + Action log) + { + Cpp2IL.Core.Logging.Logger.WarningLog += (message, source) => + log($" cpp2il/{source}: {message.Trim()}"); + Cpp2IL.Core.Logging.Logger.ErrorLog += (message, source) => + log($" cpp2il/{source} ERROR: {message.Trim()}"); + + RegisterCpp2IlHandlers(); + + log("running Cpp2IL over the game metadata"); + // Cpp2IL speaks AssetRipper's UnityVersion; Il2CppInterop speaks + // System.Version. Convert at the boundary rather than letting either + // type leak through this class's own API. + var cpp2IlVersion = new AssetRipper.Primitives.UnityVersion( + (ushort)context.UnityVersion.Major, + (ushort)context.UnityVersion.Minor, + (ushort)context.UnityVersion.Build); + Cpp2IlApi.InitializeLibCpp2Il( + context.GameAssemblyPath, + context.MetadataPath, + cpp2IlVersion, + false); + + var appContext = Cpp2IlApi.CurrentAppContext + ?? throw new InvalidOperationException( + "Cpp2IL initialized without producing an application context"); + + var layers = new List { new AttributeInjectorProcessingLayer() }; + foreach (var layer in layers) + { + layer.PreProcess(appContext, layers); + } + foreach (var layer in layers) + { + layer.Process(appContext); + } + + var assemblies = new AsmResolverDllOutputFormatDefault().BuildAssemblies(appContext); + + // Release the 100 MB mapping before the generator starts allocating. + LibCpp2IlMain.Reset(); + Cpp2IlApi.CurrentAppContext = null; + + log($"Cpp2IL produced {assemblies.Count} dummy assemblies"); + return assemblies; + } + + /// Turn the dummies into runnable interop assemblies. + private static void RunGenerator( + Context context, + List dummies, + Action log) + { + log("generating interop assemblies"); + var options = new GeneratorOptions + { + GameAssemblyPath = context.GameAssemblyPath, + Source = dummies, + OutputDir = context.InteropDir, + UnityBaseLibsDir = Directory.Exists(context.UnityLibsDir) + ? context.UnityLibsDir + : null, + }; + + // No .AddLogger: the generator's logging extension lives on a host type + // whose shape differs across Il2CppInterop versions, and this call is + // already bracketed by our own start/finish/duration lines. Failures + // surface as an exception, which the caller reports. + Il2CppInteropGenerator.Create(options) + .AddInteropAssemblyGenerator() + .Run(); + } + + /// + /// Resolve interop assemblies by name. + /// + /// + /// A mod references `UnityEngine.CoreModule` and `Sons` by simple name. + /// Those live in the interop directory, which is not an application probing + /// path, so without this hook every mod fails with + /// `FileNotFoundException: Could not load file or assembly 'Sons'` the + /// instant it touches a game type. + /// + private static void RegisterAssemblyResolver(Context context, Action log) + { + AppDomain.CurrentDomain.AssemblyResolve += (_, args) => + { + var name = new AssemblyName(args.Name).Name; + if (string.IsNullOrEmpty(name)) + { + return null; + } + var candidate = Path.Combine(context.InteropDir, name + ".dll"); + if (!File.Exists(candidate)) + { + return null; + } + try + { + return Assembly.LoadFrom(candidate); + } + catch (Exception error) + { + log($"WARN could not load interop assembly {name}: {error.Message}"); + return null; + } + }; + log($"interop resolver registered for {context.InteropDir}"); + } + + /// + /// Start Il2CppInterop. + /// + /// + /// `AddHarmonySupport` is what lets a mod's `[HarmonyPatch]` classes target + /// IL2CPP methods; without it Harmony can only patch managed code, which in + /// this process is just the loader itself. + /// + private static void StartRuntime(Context context, Action log) + { + log("starting Il2CppInterop runtime"); + // No DetourProvider is supplied. Il2CppInterop only needs one for + // ClassInjector - registering a managed MonoBehaviour type with IL2CPP - + // and nothing here does that: the bridge drives itself from the SDK's + // per-frame callback rather than injecting a component. Calling game + // methods and reading fields needs no detours at all. If class + // injection is wanted later, this is where an IDetourProvider goes. + Il2CppInteropRuntime.Create(new RuntimeConfiguration + { + UnityVersion = context.UnityVersion, + + // Required, despite being nullable. See Il2CppDetourProvider: with + // this left null the runtime starts fine and the first Harmony patch + // of an IL2CPP method throws NullReferenceException from inside + // Il2CppInterop, with nothing in the stack naming this property. + DetourProvider = new Il2CppDetourProvider(), + }) + .AddHarmonySupport() + .Start(); + log("Il2CppInterop runtime started"); + } + + /// Preload every interop assembly so first use is not a stall. + internal static int PreloadInteropAssemblies(Context context, Action log) + { + var loaded = 0; + var files = Directory.EnumerateFiles(context.InteropDir, "*.dll").ToList(); + Parallel.ForEach(files, file => + { + // netstandard facades collide with the host's own and are resolved + // by the runtime, not by us. + var name = Path.GetFileNameWithoutExtension(file); + if (name.EndsWith("netstandard", StringComparison.OrdinalIgnoreCase)) + { + return; + } + try + { + Assembly.LoadFrom(file); + System.Threading.Interlocked.Increment(ref loaded); + } + catch + { + // A single unloadable interop assembly is not fatal; the ones a + // mod actually needs will surface their own error on use. + } + }); + log($"preloaded {loaded} of {files.Count} interop assemblies"); + return loaded; + } +} diff --git a/loaders/sons-managed/Modrix.Loader/Lifecycle.cs b/loaders/sons-managed/Modrix.Loader/Lifecycle.cs new file mode 100644 index 0000000..80d51c0 --- /dev/null +++ b/loaders/sons-managed/Modrix.Loader/Lifecycle.cs @@ -0,0 +1,108 @@ +// SPDX-License-Identifier: GPL-2.0-only + +using System; +using System.Collections.Generic; + +using SonsSdk; + +namespace Modrix.Loader; + +/// +/// Drives the mod lifecycle across the two threads it actually spans. +/// +/// +/// +/// The split matters and is not arbitrary: +/// +/// +/// Bootstrap thread - discovery, assembly loading, +/// construction, OnInitializeMod. None of this touches Unity, and +/// doing it here keeps the game's own startup unblocked. +/// Unity main thread - OnSdkInitialized, +/// OnGameStart, every per-frame update, and shutdown. Anything that +/// can reach the scene graph belongs here, and running it anywhere else is +/// the single most common way to corrupt an IL2CPP +/// process. +/// +/// +/// A mod that throws is reported and kept. Its remaining hooks still run, +/// because a mod that fails one hook is far more useful than a mod that silently +/// disappears - and the per-frame path has its own fault budget in +/// so a mod cannot fail 60 times a second forever. +/// +/// +internal static class Lifecycle +{ + /// Attribution for pump faults raised by mod update callbacks. + private const string PumpName = "mods"; + + /// + /// Hand the loaded mods over to the Unity main thread and start ticking them. + /// + /// + /// Called from the bootstrap thread. The main-thread work is queued rather + /// than run, because at this point the first Unity frame has not happened + /// yet - runs it at the start of the next one. + /// + /// The mods that loaded and constructed. + /// Progress and fault sink. + internal static void Attach(List mods, Action log) + { + UnityPump.Post(() => SdkInitialized(mods, log)); + UnityPump.OnFrame(PumpName, () => Tick(mods)); + log($"lifecycle attached: {mods.Count} mods will tick each frame"); + } + + /// + /// Fire OnSdkInitialized, on the main thread, exactly once. + /// + /// + /// This is the hook a mod uses for anything touching game state, so it is + /// deliberately the first thing that runs on the main thread - before any + /// update tick, so a mod's update can assume its own setup already ran. + /// + private static void SdkInitialized(List mods, Action log) + { + foreach (var mod in mods) + { + try + { + ModHost.Invoke(mod.Instance, "InvokeSdkInitialized"); + } + catch (Exception error) + { + log($" {mod.Id}: OnSdkInitialized threw - {ModHost.Describe(error)}"); + } + } + + // The SDK's own event, for code that subscribes rather than subclasses. + try + { + SdkEvents.OnSdkInitialized.Invoke(); + } + catch (Exception error) + { + log($" SdkEvents.OnSdkInitialized threw - {ModHost.Describe(error)}"); + } + log($"OnSdkInitialized dispatched to {mods.Count} mods on the main thread"); + } + + /// + /// One frame: every mod's update callback, then the SDK's update event. + /// + /// + /// Exceptions are NOT caught per mod here. wraps this + /// whole callback with a fault budget, and catching individually would mean a + /// mod throwing every frame is logged every frame - the exact log flood the + /// budget exists to prevent. The cost is that one throwing mod skips the rest + /// of the frame's mods; the budget drops it after three, which resolves that. + /// + private static void Tick(List mods) + { + foreach (var mod in mods) + { + ModHost.Invoke(mod.Instance, "InvokeUpdate"); + } + SdkEvents.OnInWorldUpdate.Invoke(); + } +} diff --git a/loaders/sons-managed/Modrix.Loader/MainThreadGate.cs b/loaders/sons-managed/Modrix.Loader/MainThreadGate.cs new file mode 100644 index 0000000..1a8c3cc --- /dev/null +++ b/loaders/sons-managed/Modrix.Loader/MainThreadGate.cs @@ -0,0 +1,150 @@ +// SPDX-License-Identifier: GPL-2.0-only + +using System; +using System.Reflection; +using System.Threading; + +using HarmonyLib; + +namespace Modrix.Loader; + +/// +/// Waits for the Unity main thread, then runs the rest of the loader on it. +/// +/// +/// +/// The loader is injected on a bootstrap thread so that minutes of interop +/// generation cannot stall the game's startup. That is the right trade, but it +/// leaves the loader on the wrong thread for everything that follows: mods call +/// into game types from OnInitializeMod, and an IL2CPP call from a thread +/// the runtime's collector never registered either aborts the process +/// ("Collecting from unknown thread") or simply never returns - with the mod's own +/// log line already written, so it looks like the mod worked and the loader +/// stopped. +/// +/// +/// What this used to do, and why it does not any more. The established +/// approach in this ecosystem - what BepInEx and RedLoader both do - is to detour +/// il2cpp_runtime_invoke, the runtime's universal managed-call dispatcher, +/// and wait for a known callback to arrive through it. That works, and it was +/// measurably unacceptable here: with the dispatcher detoured the game died on +/// roughly half of all launches, at the title screen, with no crash dump +/// and nothing in the log. With the detour removed and nothing else changed, four +/// launches out of four survived. The difference is exposure - the hook sits on +/// every managed call in the process, around 4,800 a second, each one a round trip +/// into CoreCLR. +/// +/// +/// The distinction from those loaders is that they hook the dispatcher from +/// native code with hand-written detour engines. Doing it from managed +/// code, through Harmony, puts a managed delegate in front of the runtime's own +/// dispatch path, and that is not a safe place for one. +/// +/// +/// So the gate now patches exactly one method: +/// SceneManager.Internal_ActiveSceneChanged. It is static, Unity calls it +/// from native code on the main thread when the active scene changes, and it runs +/// a handful of times per session rather than thousands of times a second. It is +/// also a real Unity safe point, which the middle of an arbitrary dispatch is not. +/// +/// +internal static class MainThreadGate +{ + /// Harmony identity, also what appears in Harmony's own logs. + private const string HarmonyId = "dev.modrix.loader.gate"; + + /// Interop assembly holding the hook target. + private const string CoreModuleAssembly = "UnityEngine.CoreModule"; + + /// Type declaring the hook target. + private const string HookType = "UnityEngine.SceneManagement.SceneManager"; + + /// + /// The callback whose first invocation means "Unity is up, on the main thread". + /// + /// + /// Static and called directly by Unity's native scene manager, so IL2CPP + /// cannot inline it away and a call site always exists. It is the same signal + /// BepInEx and RedLoader wait for, reached by a far narrower route. + /// + private const string HookMethod = "Internal_ActiveSceneChanged"; + + private static Action? _log; + private static Action? _continuation; + + /// 0 until the gate has opened; 1 afterwards. + private static int _fired; + + /// Managed thread id of the Unity main thread, or 0 before opening. + private static int _mainThreadId; + + /// True once the gate has handed control to the main thread. + internal static bool Opened => Volatile.Read(ref _fired) != 0; + + /// The Unity main thread's managed id, or 0 before the gate opens. + internal static int MainThreadId => Volatile.Read(ref _mainThreadId); + + /// + /// Install the gate. runs once, on the Unity + /// main thread, at the first active-scene change. + /// + /// The rest of the loader's startup. + /// Progress sink. + /// + /// The hook target is missing, which would mean the interop assemblies are not + /// what this loader expects. + /// + internal static void Open(Action continuation, Action log) + { + _continuation = continuation; + _log = log; + + var target = Assembly.Load(CoreModuleAssembly).GetType(HookType)?.GetMethod( + HookMethod, + BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) + ?? throw new InvalidOperationException( + $"{HookType}.{HookMethod} not found in {CoreModuleAssembly}"); + + var postfix = typeof(MainThreadGate).GetMethod( + nameof(Opening), + BindingFlags.Static | BindingFlags.NonPublic) + ?? throw new InvalidOperationException($"{nameof(Opening)} is missing"); + + new Harmony(HarmonyId).Patch(target, postfix: new HarmonyMethod(postfix)); + log($"main-thread gate armed on {HookType}.{HookMethod}"); + } + + /// + /// Runs on the Unity main thread when the active scene changes. + /// + /// + /// Nothing here may throw: Unity called us from native code, and an exception + /// crossing back terminates the process rather than being logged. + /// + private static void Opening() + { + if (Interlocked.Exchange(ref _fired, 1) != 0) + { + return; + } + + try + { + Volatile.Write(ref _mainThreadId, Environment.CurrentManagedThreadId); + _log?.Invoke($"main-thread gate opened on {HookMethod} " + + $"(thread {Environment.CurrentManagedThreadId})"); + _continuation?.Invoke(); + } + catch (Exception error) + { + try + { + _log?.Invoke($"ERROR main-thread startup failed: {ModHost.Describe(error)}"); + } + catch (Exception) + { + // Nowhere left to report to. + } + } + } +} diff --git a/loaders/sons-managed/Modrix.Loader/ModHost.cs b/loaders/sons-managed/Modrix.Loader/ModHost.cs new file mode 100644 index 0000000..ca5bb05 --- /dev/null +++ b/loaders/sons-managed/Modrix.Loader/ModHost.cs @@ -0,0 +1,364 @@ +// SPDX-License-Identifier: GPL-2.0-only + +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Text; +using System.Text.Json; + +namespace Modrix.Loader; + +/// +/// Discovers mods in <game>/Mods and drives their lifecycle. +/// +/// +/// +/// The on-disk layout is split, and not obviously so: the payload assembly sits +/// flat at Mods/<Name>.dll while its metadata lives in a +/// folder beside it at Mods/<Name>/manifest.json. Enumeration is +/// non-recursive for exactly that reason - recursing would find the same mod +/// twice and load it twice. +/// +/// +/// Every rejection is logged with its reason. A mod that silently does not load +/// is the single most common complaint in this ecosystem, and almost all of it +/// traces to one of the four checks below rather than to anything mysterious. +/// +/// +internal static class ModHost +{ + /// Assemblies the loader supplies; a mod shipping its own copy is ignored. + private static readonly string[] ReservedNames = + { + "Modrix.Loader", + "Modrix.Sons.Sdk", + }; + + /// A discovered mod and the instance driving it. + internal sealed class LoadedMod + { + internal LoadedMod(string id, string version, object instance, Type type) + { + Id = id; + Version = version; + Instance = instance; + Type = type; + } + + internal string Id { get; } + internal string Version { get; } + internal object Instance { get; } + internal Type Type { get; } + } + + /// + /// Loads every mod under and runs its + /// initialization hook. + /// + /// The game's Mods folder. + /// Where to report progress and rejections. + /// The mods that initialized successfully. + internal static List LoadAll(string modsDirectory, Action log) + { + var loaded = new List(); + if (!Directory.Exists(modsDirectory)) + { + log($"no Mods directory at {modsDirectory}"); + return loaded; + } + + // Non-recursive: the per-mod folder beside each DLL holds metadata, not + // more assemblies. + var candidates = Directory.GetFiles(modsDirectory, "*.dll", SearchOption.TopDirectoryOnly); + Array.Sort(candidates, StringComparer.OrdinalIgnoreCase); + log($"scanning {modsDirectory}: {candidates.Length} candidate assemblies"); + + foreach (var path in candidates) + { + var name = Path.GetFileNameWithoutExtension(path); + if (Array.IndexOf(ReservedNames, name) >= 0) + { + continue; + } + + try + { + var mod = TryLoad(path, name, modsDirectory, log); + if (mod is not null) + { + loaded.Add(mod); + } + } + catch (Exception error) + { + // One broken mod must never stop the others loading. + log($" {name}: FAILED - {Describe(error)}"); + } + } + + log($"loaded {loaded.Count} of {candidates.Length} mods"); + return loaded; + } + + /// Validate, load and construct a single mod. + private static LoadedMod? TryLoad( + string path, + string name, + string modsDirectory, + Action log) + { + var manifestPath = Path.Combine(modsDirectory, name, "manifest.json"); + if (!File.Exists(manifestPath)) + { + log($" {name}: skipped - no Mods/{name}/manifest.json"); + return null; + } + + var manifest = ReadManifest(manifestPath, log); + if (manifest is null) + { + return null; + } + if (!string.Equals(manifest.Value.Id, name, StringComparison.Ordinal)) + { + log($" {name}: skipped - manifest id '{manifest.Value.Id}' != assembly name"); + return null; + } + + var assembly = Assembly.LoadFrom(path); + var modType = FindModType(assembly); + if (modType is null) + { + log($" {name}: skipped - no SonsMod subclass"); + return null; + } + + var instance = Activator.CreateInstance(modType); + if (instance is null) + { + log($" {name}: skipped - could not construct {modType.FullName}"); + return null; + } + + // Patches go in BEFORE OnInitializeMod, so a mod's own initialization + // already sees its patched world. This is also the only thing that makes + // `HarmonyPatchAll = true` mean anything: the SDK exposes the flag but + // nothing acted on it, so every [HarmonyPatch] class in every mod was + // silently inert - the mod loaded, logged, and patched nothing. + ApplyHarmonyPatches(assembly, name, instance, log); + + var mod = new LoadedMod(manifest.Value.Id, manifest.Value.Version, instance, modType); + // A hook that throws does not un-load the mod. Its type is constructed + // and its later hooks may still work, so it is reported and kept rather + // than discarded - discarding it would also hide it from the mod list. + try + { + Invoke(instance, "InvokeInitialize"); + log($" {name} {manifest.Value.Version}: initialized ({modType.FullName})"); + } + catch (Exception error) + { + log($" {name} {manifest.Value.Version}: loaded, but OnInitializeMod threw - {Describe(error)}"); + } + return mod; + } + + /// + /// Run Harmony.PatchAll for a mod that asked for it. + /// + /// + /// The flag lives behind an internal property on the SDK's base class, so it + /// is read reflectively for the same reason the lifecycle shims are. A failing + /// patch is reported and the mod is kept: a mod whose patches did not apply is + /// still worth having loaded, and the alternative is a mod that vanishes with + /// no explanation. + /// + private static void ApplyHarmonyPatches( + Assembly assembly, + string name, + object instance, + Action log) + { + var property = instance.GetType().GetProperty( + "WantsHarmonyPatchAll", + BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public + | BindingFlags.FlattenHierarchy); + if (property?.GetValue(instance) is not true) + { + return; + } + + try + { + var harmony = new HarmonyLib.Harmony($"dev.modrix.mod.{name}"); + harmony.PatchAll(assembly); + var patched = harmony.GetPatchedMethods(); + var count = 0; + foreach (var _ in patched) + { + count++; + } + log($" {name}: applied Harmony patches ({count} method(s))"); + } + catch (Exception error) + { + log($" {name}: Harmony PatchAll failed - {Describe(error)}"); + } + } + + /// The mod's manifest fields the loader actually enforces. + private readonly struct Manifest + { + internal Manifest(string id, string version) + { + Id = id; + Version = version; + } + + internal string Id { get; } + internal string Version { get; } + } + + /// + /// Parse and validate manifest.json. + /// + /// + /// The version must parse as a .NET . A value like + /// 1.0.0-beta.1 is valid against the published JSON schema but throws + /// here, and a mod whose manifest throws is dropped with no other symptom - + /// which is why this is checked explicitly and reported. + /// + private static Manifest? ReadManifest(string path, Action log) + { + using var stream = File.OpenRead(path); + using var document = JsonDocument.Parse(stream); + var root = document.RootElement; + + if (!root.TryGetProperty("id", out var idElement)) + { + log($" {Path.GetFileName(path)}: skipped - manifest has no 'id'"); + return null; + } + var id = idElement.GetString() ?? string.Empty; + + var version = root.TryGetProperty("version", out var versionElement) + ? versionElement.GetString() ?? string.Empty + : string.Empty; + if (!Version.TryParse(version, out _)) + { + log($" {id}: skipped - version '{version}' is not a System.Version (use 1.0.0)"); + return null; + } + + if (root.TryGetProperty("type", out var typeElement) + && string.Equals(typeElement.GetString(), "Library", StringComparison.Ordinal)) + { + log($" {id}: skipped - type is Library, not Mod"); + return null; + } + + return new Manifest(id, version); + } + + /// The first concrete SonsMod subclass in the assembly. + private static Type? FindModType(Assembly assembly) + { + foreach (var type in assembly.GetTypes()) + { + if (type.IsAbstract || !type.IsClass) + { + continue; + } + for (var baseType = type.BaseType; baseType is not null; baseType = baseType.BaseType) + { + if (string.Equals(baseType.FullName, "SonsSdk.SonsMod", StringComparison.Ordinal)) + { + return type; + } + } + } + return null; + } + + /// + /// Render an exception usefully. + /// + /// + /// Reflection wraps everything a mod throws in + /// , whose own + /// message is the useless "Exception has been thrown by the target of an + /// invocation." Unwrapping is the difference between a report that names + /// the missing method and one that says nothing at all. + /// + internal static string Describe(Exception error) + { + var actual = error; + var hops = 0; + while (actual is TargetInvocationException wrapper + && wrapper.InnerException is not null + && hops < 8) + { + actual = wrapper.InnerException; + hops++; + } + var origin = actual.TargetSite is null + ? string.Empty + : $" in {actual.TargetSite.DeclaringType?.Name}.{actual.TargetSite.Name}"; + + // Everything below the outermost frame. Harmony in particular reports + // "IL Compile Error (unknown location)" and puts the actual cause - + // a missing method, an unresolvable type - in the inner chain, so + // stopping at the outer message describes the symptom and hides the bug. + var chain = new StringBuilder(); + var inner = actual.InnerException; + for (var depth = 0; inner is not null && depth < 8; depth++) + { + chain.Append($" <- {inner.GetType().Name}: {inner.Message}"); + inner = inner.InnerException; + } + return $"{actual.GetType().Name}{origin}: {actual.Message}{chain}"; + } + + /// + /// Call one of the SDK's internal lifecycle shims. + /// + /// + /// The lifecycle methods are protected for source compatibility with + /// RedLoader, so the host cannot call them directly; the SDK exposes + /// internal Invoke* shims instead. Those are internal to the + /// SDK assembly, not to this one, so reflection is the only route. + /// + internal static void Invoke(object instance, string shim) + { + ShimFor(instance.GetType(), shim)?.Invoke(instance, null); + } + + /// Cache of resolved lifecycle shims, keyed by type and shim name. + /// + /// InvokeUpdate runs for every mod on every frame. Resolving it by + /// reflection each time would put a metadata lookup per mod per frame on the + /// main thread, for a result that cannot change once the type is loaded. + /// + private static readonly Dictionary<(Type, string), MethodInfo?> Shims = new(); + + private static readonly object ShimGate = new(); + + /// Resolve a lifecycle shim once, then remember it - including its absence. + private static MethodInfo? ShimFor(Type type, string shim) + { + lock (ShimGate) + { + if (Shims.TryGetValue((type, shim), out var cached)) + { + return cached; + } + var method = type.GetMethod( + shim, + BindingFlags.Instance | BindingFlags.NonPublic + | BindingFlags.Public | BindingFlags.FlattenHierarchy); + Shims[(type, shim)] = method; + return method; + } + } +} diff --git a/loaders/sons-managed/Modrix.Loader/Modrix.Loader.csproj b/loaders/sons-managed/Modrix.Loader/Modrix.Loader.csproj new file mode 100644 index 0000000..6248139 --- /dev/null +++ b/loaders/sons-managed/Modrix.Loader/Modrix.Loader.csproj @@ -0,0 +1,86 @@ + + + + + + net6.0 + Modrix.Loader + Modrix.Loader + 0.1.0 + + 10.0 + enable + disable + true + true + + + embedded + false + false + en + + false + $(NoWarn);NETSDK1138 + + + true + + + + + + + + + + + + + + + + + + + diff --git a/loaders/sons-managed/Modrix.Loader/PumpBehaviour.cs b/loaders/sons-managed/Modrix.Loader/PumpBehaviour.cs new file mode 100644 index 0000000..4dd4c3e --- /dev/null +++ b/loaders/sons-managed/Modrix.Loader/PumpBehaviour.cs @@ -0,0 +1,216 @@ +// SPDX-License-Identifier: GPL-2.0-only + +using System; +using System.Reflection; +using System.Reflection.Emit; + +using Il2CppInterop.Runtime; +using Il2CppInterop.Runtime.Injection; + +namespace Modrix.Loader; + +/// +/// Replaces the bootstrap tick with a real Unity component. +/// +/// +/// +/// can produce ticks, and does so to get the loader +/// started - but it is the wrong thing to keep. Its ticks come from the middle of +/// an arbitrary il2cpp_runtime_invoke dispatch, which is not a safe +/// point: the runtime is part-way through handing a native call to managed +/// code, and running mod code there intermittently corrupts whatever the game was +/// doing. The symptom is exactly as unhelpful as it sounds - the game dies +/// somewhere inside scene loading, on maybe one launch in three, with no crash +/// dump and nothing in the loader log. +/// +/// +/// Unity's own Update is a safe point by definition, so the durable pump +/// is an injected MonoBehaviour on a DontDestroyOnLoad object - +/// what every IL2CPP loader ends up with. Once it is running the gate's detour is +/// removed and the unsafe ticking stops entirely. +/// +/// +/// Timing is the whole trick. Injecting a class calls back into the +/// runtime, so doing it from the gate's own callback deadlocks: the dispatcher +/// frame we are inside still holds runtime locks. Installing from a later pump +/// tick, once that frame has unwound, avoids it - which is why this is deferred +/// rather than done during startup. +/// +/// +/// The type is emitted at runtime because deriving from MonoBehaviour at +/// compile time would mean referencing UnityEngine.CoreModule, and the +/// interop assemblies are generated on the user's machine from the user's copy of +/// the game. Emitting against whatever the generated assemblies actually contain +/// cannot drift out of sync, because it is read from them. +/// +/// +internal static class PumpBehaviour +{ + /// Interop assembly holding the Unity types used here. + private const string CoreModule = "UnityEngine.CoreModule"; + + /// Name of the emitted component. + private const string BehaviourName = "ModrixPump"; + + /// Name of the host object, as it appears in the hierarchy. + private const string HostObjectName = "Modrix"; + + /// Set once the component is confirmed to be driving ticks. + private static bool _installed; + + /// True once Unity is calling the injected component's Update. + internal static bool Live => _installed; + + /// + /// Emit, inject and attach the pump component. + /// + /// + /// Must run on the Unity main thread, and must NOT run from inside the gate's + /// dispatcher callback - see the class remarks. + /// + /// Progress sink. + /// + /// A required Unity type or method is missing from the interop assemblies. + /// + internal static void Install(Action log) + { + if (_installed) + { + return; + } + + var unity = Assembly.Load(CoreModule); + var behaviour = Emit(Resolve(unity, "UnityEngine.MonoBehaviour")); + + ClassInjector.RegisterTypeInIl2Cpp(behaviour); + log($"injected {behaviour.Name} into il2cpp"); + + Attach(unity, behaviour); + _installed = true; + log($"pump component attached to a persistent '{HostObjectName}' object"); + } + + /// Look up a Unity type, failing with the name if it is absent. + private static Type Resolve(Assembly unity, string name) + { + return unity.GetType(name) + ?? throw new InvalidOperationException($"{name} not found in {CoreModule}"); + } + + /// + /// Define a MonoBehaviour subclass whose Update drives the pump. + /// + /// + /// Two details are mandatory rather than stylistic. The type must expose a + /// constructor taking an IntPtr and pass it to the base constructor - + /// that is how Il2CppInterop hands a managed wrapper its native object, and + /// without it injection fails. And Update must be public and + /// parameterless, because Unity finds it by name and signature. + /// + private static Type Emit(Type monoBehaviour) + { + var assembly = AssemblyBuilder.DefineDynamicAssembly( + new AssemblyName("Modrix.Loader.Dynamic"), AssemblyBuilderAccess.Run); + var module = assembly.DefineDynamicModule("Modrix.Loader.Dynamic"); + var type = module.DefineType( + BehaviourName, + TypeAttributes.Public | TypeAttributes.Class, + monoBehaviour); + + EmitPointerConstructor(type, monoBehaviour); + EmitUpdate(type); + + return type.CreateType() + ?? throw new InvalidOperationException($"could not create {BehaviourName}"); + } + + /// Emit public ModrixPump(IntPtr ptr) : base(ptr) { }. + private static void EmitPointerConstructor(TypeBuilder type, Type monoBehaviour) + { + var baseConstructor = monoBehaviour.GetConstructor( + BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, + binder: null, + types: new[] { typeof(IntPtr) }, + modifiers: null) + ?? throw new InvalidOperationException( + "MonoBehaviour has no IntPtr constructor - the interop assemblies " + + "were not produced by Il2CppInterop"); + + var constructor = type.DefineConstructor( + MethodAttributes.Public | MethodAttributes.HideBySig + | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, + CallingConventions.Standard, + new[] { typeof(IntPtr) }); + + var il = constructor.GetILGenerator(); + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldarg_1); + il.Emit(OpCodes.Call, baseConstructor); + il.Emit(OpCodes.Ret); + } + + /// Emit public void Update() => UnityPump.Tick();. + private static void EmitUpdate(TypeBuilder type) + { + var tick = typeof(UnityPump).GetMethod( + nameof(UnityPump.Tick), + BindingFlags.Static | BindingFlags.Public) + ?? throw new InvalidOperationException($"{nameof(UnityPump.Tick)} is missing"); + + var update = type.DefineMethod( + "Update", + MethodAttributes.Public | MethodAttributes.HideBySig, + typeof(void), + Type.EmptyTypes); + + var il = update.GetILGenerator(); + il.Emit(OpCodes.Call, tick); + il.Emit(OpCodes.Ret); + } + + /// + /// Create a scene object that survives scene loads and attach the component. + /// + /// + /// DontDestroyOnLoad is the point of this method. Without it the pump + /// dies the first time the player loads a save, and every mod silently stops + /// updating at exactly the moment the game becomes interesting. + /// + private static void Attach(Assembly unity, Type behaviour) + { + var gameObjectType = Resolve(unity, "UnityEngine.GameObject"); + var host = Activator.CreateInstance(gameObjectType, HostObjectName) + ?? throw new InvalidOperationException("could not create the host GameObject"); + + var dontDestroy = Resolve(unity, "UnityEngine.Object").GetMethod( + "DontDestroyOnLoad", + BindingFlags.Static | BindingFlags.Public) + ?? throw new InvalidOperationException("Object.DontDestroyOnLoad not found"); + dontDestroy.Invoke(null, new[] { host }); + + // AddComponent's il2cpp overload takes an Il2CppSystem.Type, which lives + // in a generated assembly this project cannot reference. Il2CppType.From + // returns exactly that type, so even calling it directly would not + // compile - hence reflection, and `object` all the way to the invoke. + var from = typeof(Il2CppType).GetMethod( + "From", + BindingFlags.Static | BindingFlags.Public, + binder: null, + types: new[] { typeof(Type) }, + modifiers: null) + ?? throw new InvalidOperationException("Il2CppType.From(Type) not found"); + var componentType = from.Invoke(null, new object[] { behaviour }) + ?? throw new InvalidOperationException( + $"il2cpp does not know {behaviour.Name} - injection did not take effect"); + + var addComponent = gameObjectType.GetMethod( + "AddComponent", + BindingFlags.Instance | BindingFlags.Public, + binder: null, + types: new[] { componentType.GetType() }, + modifiers: null) + ?? throw new InvalidOperationException( + "GameObject.AddComponent(Il2CppSystem.Type) not found"); + addComponent.Invoke(host, new object[] { componentType }); + } +} diff --git a/loaders/sons-managed/Modrix.Loader/UnityPump.cs b/loaders/sons-managed/Modrix.Loader/UnityPump.cs new file mode 100644 index 0000000..47ee6fc --- /dev/null +++ b/loaders/sons-managed/Modrix.Loader/UnityPump.cs @@ -0,0 +1,395 @@ +// SPDX-License-Identifier: GPL-2.0-only + +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Threading; + +using HarmonyLib; + +namespace Modrix.Loader; + +/// +/// Distributes the loader's per-frame tick to mods and to queued work. +/// +/// +/// +/// This type does not produce ticks, it only fans them out. They come from +/// - an injected MonoBehaviour whose +/// Update Unity calls like any other, which is the only per-frame callback +/// on this game that is both reachable and a safe point. That file records what +/// else was tried. +/// +/// +/// The tick body is held to one rule: it must never throw into Unity. It +/// runs over a hundred times a second on the main thread, so an escaping +/// exception is a dead game rather than a logged error. Every callback is +/// individually guarded, and one that throws repeatedly is dropped rather than +/// left to fail forever. +/// +/// +internal static class UnityPump +{ + /// + /// How many times one callback may throw before it is dropped. + /// + /// + /// A callback failing every frame produces thousands of identical log lines a + /// minute and buries whatever else went wrong. Three strikes is enough to + /// capture the stack trace and establish that it is not transient. + /// + private const int FaultsBeforeDrop = 3; + + /// Harmony identity, also what appears in Harmony's own logs. + private const string HarmonyId = "dev.modrix.loader.pump"; + + /// + /// Static, native-invoked, per-frame methods patched to obtain the tick. + /// + /// + /// + /// Every constraint in this list was established by killing the game: + /// + /// + /// Must be static. Patching the instance method + /// EventSystem.Update attaches cleanly and then kills the game on + /// every launch; patching statics - as + /// does - is reliable. + /// Must not be inlined or stripped. + /// Time.get_deltaTime is inlined into its callers and + /// Application.InvokeOnBeforeRender has no call site left, so both + /// patch successfully and never fire. + /// Must not be the runtime's dispatcher. Detouring + /// il2cpp_runtime_invoke gives a tick and costs half of all launches + /// - see . + /// Cannot be an injected component. + /// ClassInjector.RegisterTypeInIl2Cpp hooks runtime internals + /// through the same managed detour path and is fatal here, even from a real + /// Unity callback. + /// + /// + /// What satisfies all of it is the render loop. This game runs HDRP, so + /// Unity's native renderer calls + /// RenderPipelineManager.DoRenderLoop_Internal once per frame, and the + /// pipeline calls BeginContextRendering alongside it. Both are static + /// and both have real call sites. + /// + /// + private static readonly (string Type, string Method)[] Candidates = + { + ("UnityEngine.Rendering.RenderPipelineManager", "DoRenderLoop_Internal"), + ("UnityEngine.Rendering.RenderPipelineManager", "BeginContextRendering"), + }; + + /// Interop assembly holding the pump targets. + private const string CoreModuleAssembly = "UnityEngine.CoreModule"; + + private static readonly object Gate = new(); + + /// Frame callbacks, and the fault count for each. + private static readonly List Subscribers = new(); + + /// Work queued from other threads, to run on the next frame. + private static readonly Queue Pending = new(); + + /// Ticks are skipped until this time. See SonsSdk.LoaderControl. + private static readonly System.Diagnostics.Stopwatch SuspendClock = new(); + + private static long _suspendedUntilMs; + + private static Action? _log; + private static long _ticks; + private static int _mainThreadId; + private static bool _started; + + /// A frame callback plus how many times it has faulted. + private sealed class Subscriber + { + internal Subscriber(string name, Action action) + { + Name = name; + Action = action; + } + + internal string Name { get; } + internal Action Action { get; } + internal int Faults { get; set; } + internal bool Dropped { get; set; } + } + + /// Frames observed since the pump started. + internal static long Ticks => Interlocked.Read(ref _ticks); + + /// The Unity main thread's managed id, or 0 before the first tick. + internal static int MainThreadId => Volatile.Read(ref _mainThreadId); + + /// True when something has been queued for the main thread. + /// + /// Read from the dispatcher hook on every managed call once the loader is up, + /// so it is a plain count check under the existing lock rather than anything + /// cleverer. + /// + internal static bool HasPendingWork + { + get + { + lock (Gate) + { + return Pending.Count > 0; + } + } + } + + /// True when called from the Unity main thread. + internal static bool OnMainThread => + Environment.CurrentManagedThreadId == MainThreadId && MainThreadId != 0; + + /// Make the pump ready to receive ticks. + /// Where to report faults. + internal static void Start(Action log) + { + lock (Gate) + { + if (_started) + { + return; + } + _started = true; + _log = log; + } + // A mod that starts a scene load tells us, because we cannot safely + // detect one from the dispatcher. See SonsSdk.LoaderControl. + SuspendClock.Start(); + SonsSdk.LoaderControl.SuspendHook = seconds => Suspend(seconds, log); + // One queued no-op is enough: the next dispatch sees pending work, ticks + // once, and that tick runs every per-frame subscriber - including the + // mod that asked. + SonsSdk.LoaderControl.RequestTickHook = () => Post(() => { }); + + var postfix = typeof(UnityPump).GetMethod( + nameof(Tick), + BindingFlags.Static | BindingFlags.Public) + ?? throw new InvalidOperationException($"{nameof(Tick)} is missing"); + + var harmony = new Harmony(HarmonyId); + var unity = Assembly.Load(CoreModuleAssembly); + var attached = 0; + foreach (var (typeName, methodName) in Candidates) + { + try + { + var type = unity.GetType(typeName) + ?? throw new InvalidOperationException( + $"{typeName} not found in {CoreModuleAssembly}"); + foreach (var candidate in type.GetMethods( + BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) + { + if (!string.Equals(candidate.Name, methodName, StringComparison.Ordinal)) + { + continue; + } + harmony.Patch(candidate, postfix: new HarmonyMethod(postfix)); + log($"per-frame pump attached to {typeName}.{methodName}"); + attached++; + break; + } + } + catch (Exception error) + { + // More than one candidate exists precisely so that one being + // absent, stripped or unpatchable is survivable. + log($"per-frame pump could not attach to {typeName}.{methodName}: " + + $"{ModHost.Describe(error)}"); + } + } + + if (attached == 0) + { + throw new InvalidOperationException( + "no per-frame hook attached; mods would load but never update"); + } + } + + /// Stop ticking for a while, at a mod's request. + /// + /// Extends an existing suspension rather than replacing it, so two mods each + /// asking for quiet cannot shorten the other's window. + /// + private static void Suspend(float seconds, Action log) + { + var until = SuspendClock.ElapsedMilliseconds + (long)(seconds * 1000); + lock (Gate) + { + if (until > _suspendedUntilMs) + { + _suspendedUntilMs = until; + } + } + log($"per-frame pump suspended for {seconds:F0}s at a mod's request"); + } + + /// True while a mod has asked for the pump to stay quiet. + private static bool Suspended + { + get + { + lock (Gate) + { + return SuspendClock.ElapsedMilliseconds < _suspendedUntilMs; + } + } + } + + /// + /// Register a callback to run once per frame on the Unity main thread. + /// + /// Used to attribute faults in the log. + /// The callback. Must not block. + internal static void OnFrame(string name, Action action) + { + lock (Gate) + { + Subscribers.Add(new Subscriber(name, action)); + } + } + + /// + /// Queue work to run on the Unity main thread at the start of the next frame. + /// + /// + /// Fire-and-forget by design. Callers needing a result or a deadline build + /// that on top - a bridge command, for instance, posts a closure that + /// completes a TaskCompletionSource and waits on it with a timeout. + /// Baking a timeout in here would put the waiting inside the frame loop. + /// + /// The work to run. + internal static void Post(Action work) + { + lock (Gate) + { + Pending.Enqueue(work); + } + } + + /// + /// One frame, on the Unity main thread. + /// + /// + /// Public because it is also the target of a runtime-emitted Update + /// method (see ), which lives in a dynamic assembly + /// that cannot reach an internal member of this one. Nothing here may throw. + /// + public static void Tick() + { + if (Volatile.Read(ref _mainThreadId) == 0) + { + Volatile.Write(ref _mainThreadId, Environment.CurrentManagedThreadId); + Report($"first frame on main thread {Environment.CurrentManagedThreadId}"); + } + Heartbeat(Interlocked.Increment(ref _ticks)); + + // Queued work still runs while suspended - it is one-shot, explicitly + // requested, and usually the very thing that asked for the quiet window. + // Only the per-frame subscribers are held back. + DrainPending(); + if (!Suspended) + { + RunSubscribers(); + } + } + + /// Log that frames are arriving, at a decaying rate. + /// + /// Two questions have to be answerable from the log alone: "did the pump ever + /// tick?" and "is it still ticking?". The early marks answer the first without + /// waiting; the periodic mark answers the second without turning the log into + /// a frame counter. + /// + private static void Heartbeat(long tick) + { + const long Periodic = 3600; + if (tick == 1 || tick == 60 || tick == 600 || tick % Periodic == 0) + { + Report($"pump tick {tick}"); + } + } + + /// Run everything queued from other threads. + /// + /// The queue is drained into a batch under the lock and run outside it, so a + /// queued action may itself call without deadlocking. Work + /// queued during the drain waits for the next frame rather than extending + /// this one. + /// + private static void DrainPending() + { + var batch = new List(); + lock (Gate) + { + while (Pending.Count > 0) + { + batch.Add(Pending.Dequeue()); + } + } + + foreach (var work in batch) + { + try + { + work(); + } + catch (Exception error) + { + Report($"queued main-thread work threw: {ModHost.Describe(error)}"); + } + } + } + + /// Run each per-frame subscriber, guarding and dropping faulty ones. + private static void RunSubscribers() + { + Subscriber[] snapshot; + lock (Gate) + { + snapshot = Subscribers.ToArray(); + } + + foreach (var subscriber in snapshot) + { + if (subscriber.Dropped) + { + continue; + } + try + { + subscriber.Action(); + } + catch (Exception error) + { + subscriber.Faults++; + Report($"{subscriber.Name} frame callback threw " + + $"({subscriber.Faults}/{FaultsBeforeDrop}): {ModHost.Describe(error)}"); + if (subscriber.Faults >= FaultsBeforeDrop) + { + subscriber.Dropped = true; + Report($"{subscriber.Name} frame callback dropped after " + + $"{FaultsBeforeDrop} faults"); + } + } + } + } + + /// Log without ever throwing, because the caller is the frame loop. + private static void Report(string message) + { + try + { + _log?.Invoke(message); + } + catch (Exception) + { + // A failing log sink must not take the game with it. There is nowhere + // left to report this, which is precisely why it is empty. + } + } +} diff --git a/loaders/sons-managed/Modrix.Loader/nuget.config b/loaders/sons-managed/Modrix.Loader/nuget.config new file mode 100644 index 0000000..87482a8 --- /dev/null +++ b/loaders/sons-managed/Modrix.Loader/nuget.config @@ -0,0 +1,13 @@ + + + + + + + + + + diff --git a/loaders/sons-managed/Modrix.Sons.Sdk/Modrix.Sons.Sdk.csproj b/loaders/sons-managed/Modrix.Sons.Sdk/Modrix.Sons.Sdk.csproj new file mode 100644 index 0000000..0450ebe --- /dev/null +++ b/loaders/sons-managed/Modrix.Sons.Sdk/Modrix.Sons.Sdk.csproj @@ -0,0 +1,17 @@ + + + + + net6.0 + Modrix.Sons.Sdk + Modrix.Sons.Sdk + latest + disable + true + 0.1.0 + + false + + + diff --git a/loaders/sons-managed/Modrix.Sons.Sdk/Sdk.cs b/loaders/sons-managed/Modrix.Sons.Sdk/Sdk.cs new file mode 100644 index 0000000..3e73d04 --- /dev/null +++ b/loaders/sons-managed/Modrix.Sons.Sdk/Sdk.cs @@ -0,0 +1,330 @@ +// SPDX-License-Identifier: GPL-2.0-only +// +// Modrix.Sons.Sdk - the API Sons of the Forest mods are written against. +// +// The namespaces and type names here deliberately mirror RedLoader's +// (`RedLoader.RLog`, `SonsSdk.SonsMod`, `SonsSdk.SdkEvents`) rather than using +// Modrix-branded ones. That is the whole point: every Sons of the Forest mod +// ever written targets those names, and a source-compatible SDK means an +// existing mod builds against Modrix by changing nothing at all. Inventing +// `ModrixMod`/`ModrixLog` would have forced every mod author to fork their +// code for no benefit to anyone. +// +// Only the surface real mods actually use is implemented. It is deliberately +// small, and every member that the loader has not yet wired up says so at +// runtime instead of silently doing nothing - a mod author debugging a hook +// that never fires deserves a log line, not silence. + +using System; +using System.Collections.Generic; + +namespace RedLoader +{ + /// + /// A parameterless callback. Named for RedLoader/MelonLoader source + /// compatibility; it is an ordinary delegate. + /// + public delegate void LemonAction(); + + /// + /// A subscribable event. Mods reach this through + /// and typically cast to it explicitly, + /// which is why it is public rather than an implementation detail. + /// + /// The delegate type subscribers supply. + public class MelonEventBase where T : Delegate + { + private readonly List _subscribers = new(); + + private readonly struct Subscription + { + public Subscription(T action, int priority, bool once) + { + Action = action; + Priority = priority; + Once = once; + } + + public T Action { get; } + public int Priority { get; } + public bool Once { get; } + } + + /// Registers for this event. + /// The callback to invoke. + /// Lower runs earlier; ties keep insertion order. + /// Fire once, then drop it. + public void Subscribe(T action, int priority = 0, bool unsubscribeOnFirstInvocation = false) + { + if (action is null) + { + return; + } + + _subscribers.Add(new Subscription(action, priority, unsubscribeOnFirstInvocation)); + // Stable sort by priority: two mods registering at the same + // priority must keep the order they registered in, or load order + // stops being reproducible. + _subscribers.Sort(static (a, b) => a.Priority.CompareTo(b.Priority)); + } + + /// Removes a previously registered callback. + /// The callback to remove. + public void Unsubscribe(T action) + { + _subscribers.RemoveAll(s => Equals(s.Action, action)); + } + + /// + /// Invokes every subscriber. One subscriber throwing must not stop the + /// rest: a single bad mod should not silently disable every other + /// mod's per-frame work. + /// + public void Invoke() + { + if (_subscribers.Count == 0) + { + return; + } + + var snapshot = _subscribers.ToArray(); + foreach (var subscription in snapshot) + { + try + { + if (subscription.Action is Action plain) + { + plain(); + } + else + { + subscription.Action.DynamicInvoke(); + } + } + catch (Exception error) + { + RLog.Error($"event subscriber threw: {error}"); + } + + if (subscription.Once) + { + Unsubscribe(subscription.Action); + } + } + } + } + + /// + /// Mod logging. Output goes to the loader's log file and, when one is + /// attached, the console. + /// + public static class RLog + { + /// Where each line is written. Set by the loader at startup. + public static Action Sink { get; set; } + + /// Writes an informational line. + /// The message. + public static void Msg(object message) => Write("INFO", message); + + /// Writes a warning. + /// The message. + public static void Warning(object message) => Write("WARN", message); + + /// Writes an error. + /// The message. + public static void Error(object message) => Write("ERROR", message); + + private static void Write(string level, object message) + { + var line = $"[{level}] {message}"; + var sink = Sink; + if (sink is not null) + { + try + { + sink(line); + return; + } + catch + { + // A broken sink must never take a mod down with it; fall + // through to the console below. + } + } + + Console.WriteLine(line); + } + } +} + +namespace SonsSdk +{ + using RedLoader; + + /// + /// Base class for every Sons of the Forest mod. + /// + /// + /// The loader constructs one instance per discovered mod assembly, then + /// drives the lifecycle in this order: + /// + /// - before the game's + /// systems exist. Configuration only; touching game state here will + /// throw. + /// - once the game and + /// SDK are up. This is where game state becomes safe to touch. + /// - a world has loaded. + /// then + /// - on shutdown. + /// + /// + public abstract class SonsMod + { + /// + /// Apply every [HarmonyPatch] class in this assembly during + /// initialization. Set it in the constructor. + /// + protected bool HarmonyPatchAll { get; set; } + + /// + /// A per-frame callback. Assign a method in the constructor; the + /// loader invokes it once per frame on the main thread. + /// + /// + /// This is the only per-frame hook, and it runs on Unity's main + /// thread - work queued from any other thread must be marshalled + /// through it. + /// + protected Action OnUpdateCallback { get; set; } + + /// The mod's id, from its manifest.json. + public string Id { get; internal set; } = string.Empty; + + /// The mod's version, from its manifest.json. + public string Version { get; internal set; } = string.Empty; + + /// Called before the game's systems exist. + protected virtual void OnInitializeMod() { } + + /// Called once the game and SDK are ready. + protected virtual void OnSdkInitialized() { } + + /// Called when a world has finished loading. + protected virtual void OnGameStart() { } + + /// Called after a scene is unloaded. + /// The scene's build index. + /// The scene's name. + public virtual void OnSceneWasUnloaded(int buildIndex, string sceneName) { } + + /// Called as the game shuts down. + protected virtual void OnApplicationQuit() { } + + /// Called last, after . + protected virtual void OnDeinitializeMod() { } + + // --- loader entry points ------------------------------------------- + // The lifecycle methods above are `protected` for source compatibility + // with RedLoader, so the host cannot call them directly. These + // internal shims are how the loader drives a mod. + + internal void InvokeInitialize() => OnInitializeMod(); + + internal void InvokeSdkInitialized() => OnSdkInitialized(); + + internal void InvokeGameStart() => OnGameStart(); + + internal void InvokeApplicationQuit() => OnApplicationQuit(); + + internal void InvokeDeinitialize() => OnDeinitializeMod(); + + internal void InvokeUpdate() => OnUpdateCallback?.Invoke(); + + internal bool WantsHarmonyPatchAll => HarmonyPatchAll; + } + + /// + /// Game lifecycle events a mod can subscribe to. + /// + /// + /// Lets a mod ask the loader to stop ticking across a risky transition. + /// + /// + /// + /// The loader's per-frame tick is driven from a detour on IL2CPP's dispatcher + /// rather than from a Unity callback, because on this game nothing else + /// works. That is fine in steady state and dangerous during a scene load: the + /// tick lands in the middle of a native-to-managed transition, and running mod + /// code there while the world is being torn down and rebuilt kills the process + /// - reliably enough that loading a save with the pump running does not + /// survive. + /// + /// + /// So a mod that triggers a transition says so. This is deliberately explicit + /// rather than automatic: the loader cannot detect a load starting without + /// calling into the game from the very context that is unsafe. + /// + /// + /// The hook is assigned by the loader at startup, exactly like + /// . If no loader is present the call is a + /// no-op, so a mod can use it unconditionally. + /// + /// + public static class LoaderControl + { + /// Assigned by the loader. Takes the number of seconds to pause. + public static Action? SuspendHook { get; set; } + + /// Assigned by the loader. Asks for one main-thread tick. + public static Action? RequestTickHook { get; set; } + + /// + /// Stop per-frame mod updates for a while. + /// + /// + /// How long to stay quiet. Generous is correct - a load that finishes + /// early costs nothing, one that overruns costs the process. + /// + public static void SuspendUpdates(float seconds) + { + SuspendHook?.Invoke(seconds); + } + + /// + /// Ask the loader to run one main-thread tick soon. + /// + /// + /// + /// The loader does not tick continuously by default. Its tick comes from a + /// detour on IL2CPP's dispatcher rather than from a Unity callback, and + /// entering mod code from there is not safe at an arbitrary moment - often + /// enough to kill the game that background ticking is not worth its cost. + /// + /// + /// So a mod with work waiting says so, and pays the risk only when it has + /// something to do. Calling this with nothing queued is harmless; calling + /// it from any thread is fine. + /// + /// + public static void RequestTick() + { + RequestTickHook?.Invoke(); + } + } + + public static class SdkEvents + { + /// + /// Fires every frame while a world is loaded - not at the menu. This + /// is the hook for gameplay logic that needs the player to exist. + /// + public static readonly MelonEventBase OnInWorldUpdate = new(); + + /// Fires once when a world has finished loading. + public static readonly MelonEventBase OnGameStart = new(); + + /// Fires once when the SDK is ready. + public static readonly MelonEventBase OnSdkInitialized = new(); + } +} diff --git a/loaders/sons-managed/README.md b/loaders/sons-managed/README.md new file mode 100644 index 0000000..0a35bd0 --- /dev/null +++ b/loaders/sons-managed/README.md @@ -0,0 +1,49 @@ + + +# `sons-managed`: the managed half of the Sons of the Forest loader + +One project today: `Modrix.Loader`, the assembly CoreCLR loads when the native +proxy hands off. + +```sh +dotnet build -c Release Modrix.Loader/Modrix.Loader.csproj +# -> Modrix.Loader/bin/Release/net6.0/Modrix.Loader.dll +``` + +Deployed to `/_Modrix/net6/Modrix.Loader.dll`, which is also the +`sentinel` that `games/sonsoftheforest/game.toml` uses to decide whether the +loader is installed. + +## Three things that are not stylistic choices + +**`net6.0`.** The proxy hosts BepInEx's `mini-coreclr` 6.0.7, and +`coreclr_create_delegate` loads this assembly into *that* runtime. A net8 or net9 +assembly fails with a bare `TypeLoadException`, inside a game, under Proton. +`NETSDK1138` ("net6.0 is out of support") is expected and suppressed rather than +"fixed" by retargeting. Building it on a modern SDK downloads the .NET 6 +targeting pack from NuGet on first build. + +**`Modrix.Loader.Entrypoint.Start()`: zero parameters, void return.** +`coreclr_create_delegate` builds a reverse-P/Invoke stub from the method's own +signature. An extra parameter compiles fine and corrupts the stack at call time. +The type name and method name are hard-coded on the native side +(`src/layout.rs`); changing either here without changing both there produces +`coreclr_create_delegate returned 0x80131522` and nothing else. + +**`Entrypoint` is `internal`.** CoreCLR resolves the entry point reflectively and +does not need it public: RedLoader's `Doorstop.Entrypoint` is `internal` for the +same reason. Nothing else should ever call it. + +## Everything is caught + +An exception escaping `Start` crosses back through the reverse-P/Invoke stub and +tears the process down: the user sees the game close with no window, no dialog +and no log. `Start` therefore catches everything and writes +`/_Modrix/crash_.log`. A crash file with a stack trace is the +whole difference between a bug report and "it just closes". + +## M0 scope + +Read the `MODRIX_*` environment block the proxy published, append the milestone +line to `_Modrix/Latest.log`, echo the environment for diagnosis, return. No mod +discovery, no `manifest.json`, no Il2CppInterop, no SDK: those are M2 and M3. diff --git a/loaders/sons-proxy/.gitignore b/loaders/sons-proxy/.gitignore new file mode 100644 index 0000000..1ecf02d --- /dev/null +++ b/loaders/sons-proxy/.gitignore @@ -0,0 +1,4 @@ +# SPDX-License-Identifier: GPL-2.0-only +# Build outputs. The root .gitignore only covers /target at the repo root. +/target +/dist diff --git a/loaders/sons-proxy/Cargo.lock b/loaders/sons-proxy/Cargo.lock new file mode 100644 index 0000000..f5573ed --- /dev/null +++ b/loaders/sons-proxy/Cargo.lock @@ -0,0 +1,83 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "modrix-sons-proxy" +version = "0.1.0" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" diff --git a/loaders/sons-proxy/Cargo.toml b/loaders/sons-proxy/Cargo.toml new file mode 100644 index 0000000..e5e21ea --- /dev/null +++ b/loaders/sons-proxy/Cargo.toml @@ -0,0 +1,81 @@ +# SPDX-License-Identifier: GPL-2.0-only + +# This is a SEPARATE cargo workspace on purpose. +# +# The main Modrix workspace sets `unsafe_code = "forbid"` because the deploy +# engine touches users' game files. An in-process injector cannot be written +# without `unsafe`, and rather than weaken that guarantee for 13 crates so one +# crate can use FFI, the injector lives outside the workspace entirely. The root +# manifest declares `members = ["crates/*"]`, so `loaders/` is naturally +# excluded and `cargo build` at the root never sees this package. +# +# See README.md for the unsafe policy that applies HERE instead. +[workspace] +resolver = "3" + +[package] +name = "modrix-sons-proxy" +version = "0.1.0" +edition = "2024" +rust-version = "1.96" +license = "GPL-2.0-only" +authors = ["Modrix contributors"] +description = "version.dll proxy that hosts CoreCLR inside Sons of the Forest" +publish = false + +[lib] +name = "modrix_sons_proxy" +crate-type = ["cdylib"] + +# windows-sys is the ONLY dependency, and only when targeting Windows. On a +# Linux host the pure modules (layout, log formatting, errors, the export name +# table) still compile and their tests still run, which is what makes any of +# this testable without a Windows box. +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.59", features = [ + "Win32_Foundation", + "Win32_System_LibraryLoader", + "Win32_System_SystemInformation", + "Win32_System_Environment", +] } + +# A Rust panic must never unwind across the FFI boundary into Unity's stack. +# `abort` makes that structurally impossible; the code paths below return +# `Result` and log instead, so an abort would itself be a bug. +[profile.dev] +panic = "abort" +overflow-checks = true + +[profile.release] +panic = "abort" +overflow-checks = true +opt-level = "s" +lto = true +codegen-units = 1 + +# Modrix house lints. The one deliberate difference from the root workspace is +# `unsafe_code`: allowed here, but every `unsafe` block must carry a `// SAFETY:` +# comment, which `undocumented_unsafe_blocks` upgrades from advice to a hard +# error. +[lints.rust] +unsafe_code = "allow" +missing_docs = "deny" +unreachable_code = "deny" +unreachable_patterns = "deny" +unused = { level = "deny", priority = -1 } + +[lints.clippy] +pedantic = { level = "warn", priority = -1 } +unwrap_used = "deny" +panic = "deny" +todo = "deny" +unimplemented = "deny" +expect_used = "warn" +indexing_slicing = "deny" +arithmetic_side_effects = "warn" +mem_forget = "deny" +undocumented_unsafe_blocks = "deny" +multiple_unsafe_ops_per_block = "deny" +allow_attributes = "warn" +allow_attributes_without_reason = "warn" +dbg_macro = "warn" diff --git a/loaders/sons-proxy/README.md b/loaders/sons-proxy/README.md new file mode 100644 index 0000000..ddc39a1 --- /dev/null +++ b/loaders/sons-proxy/README.md @@ -0,0 +1,279 @@ + + +# `modrix-sons-proxy`: the Sons of the Forest injection proxy + +A Windows `version.dll` that loads before Sons of the Forest starts, forwards +every real `version.dll` export so the game is unaffected, waits for the IL2CPP +runtime, hosts CoreCLR, and calls one managed method. + +**This is milestone M0 and only M0.** Its entire purpose is to answer one +question with evidence: *can managed .NET code run inside this IL2CPP game, +under Proton, without breaking it?* There is no mod loading here. See +[`../../docs/SONS-LOADER.md`](../../docs/SONS-LOADER.md) for where it goes next. + +--- + +## The unsafe policy + +The main Modrix workspace declares `unsafe_code = "forbid"` because the deploy +engine rewrites users' game directories, and a memory-safety bug there costs +someone their saves. An in-process injector cannot exist without `unsafe`. + +**This crate is therefore not in that workspace.** It is a separate Cargo +workspace under `loaders/`, which the root manifest's `members = ["crates/*"]` +never sees. `cargo build`, `cargo clippy` and `cargo test` at the repository root +are completely unaffected: that is verified, not assumed. + +In exchange for being allowed `unsafe`, the rules here are *stricter* than the +main workspace in the ways that matter: + +| Rule | Where | +| --- | --- | +| `clippy::undocumented_unsafe_blocks` = **deny** | every `unsafe` block carries a `// SAFETY:` comment justifying it | +| `clippy::multiple_unsafe_ops_per_block` = **deny** | one unsafe operation per block, so no comment covers two things | +| All FFI confined to `src/win.rs` | one file to audit for pointer mistakes | +| `panic = "abort"` in every profile | unwinding across the FFI boundary into Unity's stack is UB; making it impossible is cheaper than being careful | +| `unwrap_used`, `panic`, `todo`, `unimplemented`, `indexing_slicing` = **deny** | identical to the main workspace | +| `missing_docs` = **deny**, `# Errors` on every fallible fn | identical to the main workspace | +| Functions ≤ 60 lines, ≤ 5 arguments | identical to the main workspace (`clippy.toml`) | + +Everything that *can* be safe Rust is safe Rust. `layout`, `log`, `error` and the +export name table have no FFI at all, compile on Linux, and carry the unit tests, +which is why `cargo test` is meaningful on a machine that cannot run the +artefact. + +### Where the `unsafe` actually is + +1. **`src/exports.rs`**: seventeen `#[unsafe(naked)]` forwarders. +2. **`src/win.rs`**: `LoadLibraryW`, `GetProcAddress`, `GetModuleHandleW`, + `GetModuleFileNameW`, `GetSystemDirectoryW`, `SetEnvironmentVariableW`, + `GetLastError`, and the `ntdll!wine_get_version` probe. +3. **`src/coreclr.rs`**: two hosting calls and the managed delegate call. +4. **`src/il2cpp.rs`**: one call to `il2cpp_domain_get`. +5. **`src/lib.rs`**: `DllMain` itself. + +That is the whole list. + +--- + +## How the export forwarding works, and why not the other two ways + +Each of the seventeen exports is a naked function that tail-jumps through a +pointer table filled in at `DLL_PROCESS_ATTACH`: + +```asm +mov rax, qword ptr [rip + SLOTS + N*8] +test rax, rax +je .null ; real DLL lacked the export: return 0 (= failure) +jmp rax ; tail jump - arguments and return value untouched +``` + +`RAX` is scratch and is not an argument register in the Microsoft x64 calling +convention, and `RSP` is never touched, so register *and* stack arguments arrive +intact and the real function returns straight to the game. + +- **Doorstop** emits `void *exp_X(void) { return __X__(); }` and depends on the + compiler tail-calling at `-Os`. That is correct by luck; `VerInstallFileW` + takes seven arguments and would be corrupted by any prologue. +- **MelonLoader** rewrites its own stubs at runtime with + `VirtualProtect(PAGE_EXECUTE_READWRITE)` + `mov r11, addr; jmp r11`. Correct, + but it leaves our `.text` writable-and-executable for the life of the process. + +`injection.md` names the naked `jmp` thunk "the only strictly correct +implementation". It also needs no RWX memory, so it is what this crate does. This +is a deliberate, documented deviation from decision **D6** in `PLAN.md`, which +chose MelonLoader's stub patching; both are unconditionally correct, and this one +is smaller and does not make our own code writable. + +The seventeen names come verbatim from Doorstop's +`src/windows/proxy/proxylist.txt`; guessing the set gets a missing-import dialog +on launch instead of a game. `build-windows.sh` asserts all seventeen are in the +produced PE, and a unit test asserts each thunk owns its own table slot. + +--- + +## Building + +Requires the pinned toolchain (`rust-toolchain.toml` handles it) and a Windows +target. Cross-compiling from Linux needs `mingw-w64`: + +```sh +rustup target add x86_64-pc-windows-gnu # done automatically by rust-toolchain.toml +./build-windows.sh # -> dist/version.dll +./build-windows.sh --managed # + dist/_Modrix/net6/Modrix.Loader.dll +./build-windows.sh --managed --coreclr /win-x64 # + the runtime +``` + +`dist/` is a staging tree. **The script never writes outside this directory.** + +To build by hand: + +```sh +cargo build --release --target x86_64-pc-windows-gnu +cp target/x86_64-pc-windows-gnu/release/modrix_sons_proxy.dll version.dll +``` + +The file name is what matters: the Windows loader keys on it, not on the PE +export-directory name. Doorstop ships the identical binary as `winhttp.dll` and +RedLoader renames it to `version.dll`. + +`x86_64-pc-windows-msvc` also works (`MODRIX_PROXY_TARGET=x86_64-pc-windows-msvc`) +if the MSVC toolchain is available; nothing in the source is GNU-specific. + +### Checks + +```sh +cargo fmt --all +cargo clippy --target x86_64-pc-windows-gnu --all-targets --all-features -- -D warnings +cargo clippy --all-targets --all-features -- -D warnings # host, for the pure modules +cargo test # host +``` + +--- + +## The runtime this needs + +BepInEx `mini-coreclr` 6.0.7, `win-x64`: + + + +187 files including `coreclr.dll`, `clrjit.dll`, `System.Private.CoreLib.dll` and +a `.version` stamp reading `6.0.7`. It deliberately contains **no `hostfxr.dll`**, +which is exactly why this crate uses `coreclr_initialize` / +`coreclr_create_delegate` directly rather than `nethost`/`hostfxr`, and why no +`runtimeconfig.json` is involved. Verified: that `coreclr.dll` exports nine +symbols, among them both hosting entry points. + +It is **not vendored into this repository** (67 MB staged). Download it, unzip +it, and point `--coreclr` at the `win-x64` folder. + +--- + +## Installing: read this before touching a game directory + +> **The proxy slot is single-occupancy.** A game has exactly one `version.dll`. +> MelonLoader and RedLoader both claim it; BepInEx 6 IL2CPP claims `winhttp.dll`. +> Whichever loader loses the race never runs, and the user gets a game with half +> its mods missing and no error anywhere. On the reference machine +> **MelonLoader currently owns `version.dll`** (10,810,880 bytes, PE export name +> `MelonLoader.Bootstrap.dll`). Move it aside; do not overwrite it. + +Nothing in this repository installs itself. `Engine::install_loader` is +deliberately unimplemented: M0 is the payload that will make it worth writing. + +```sh +SOTF="$HOME/.local/share/Steam/steamapps/common/Sons Of The Forest" + +# 1. Park the incumbent loader. Reversible; keep the backup. +mv "$SOTF/version.dll" "$SOTF/version.melonloader.bak" + +# 2. Install the M0 payload. +cp dist/version.dll "$SOTF/version.dll" +mkdir -p "$SOTF/_Modrix/net6" "$SOTF/_Modrix/dotnet" +cp dist/_Modrix/net6/Modrix.Loader.dll "$SOTF/_Modrix/net6/" +cp -r dist/_Modrix/dotnet/. "$SOTF/_Modrix/dotnet/" +``` + +Resulting layout: + +``` +Sons Of The Forest/ + SonsOfTheForest.exe + version.dll <- this crate + version.melonloader.bak <- the incumbent, parked + _Modrix/ + Latest.log <- created on first launch + net6/Modrix.Loader.dll + dotnet/coreclr.dll, .version, System.Private.CoreLib.dll, ... (187 files) +``` + +### Proton: the one setting without which nothing happens + +Wine prefers its own builtin `version.dll` and the failure is **completely +silent**: the game launches perfectly and nothing injects. In Steam → +Sons of the Forest → Properties → Launch Options: + +``` +WINEDLLOVERRIDES="version=n,b" %command% +``` + +`n` = prefer the native (our) DLL, `b` = fall back to Wine's builtin. +`games/sonsoftheforest/game.toml` already declares this under `[launch.env]`, and +Modrix surfaces it as a launch-readiness warning, but Steam owns the game +process, so only the user's launch options can actually carry it. + +--- + +## The M0 acceptance test + +Single, binary, on the real install. + +1. Install as above, with the launch option set. +2. Launch the game from Steam and reach the main menu. +3. `cat "$SOTF/_Modrix/Latest.log"` + +**Pass** requires all four milestone lines, in this order: + +``` +[modrix] proxy attached, real version.dll = C:\windows\system32\version.dll +[modrix] il2cpp runtime ready (poll trigger), domain = 0x00007ff... (non-zero) +[modrix] coreclr up, runtime = 6.0.7 +[modrix] managed entrypoint reached: Modrix.Loader 0.1.0 +``` + +…**and the game must still play normally.** Start a new game, move around, quit. +A loader that produces the log and a broken game is a failed M0. + +Additional lines are expected and are not failures: `host = wine `, the +`env MODRIX_* = …` echo from the managed side, `managed runtime = …`. + +> **Note on line 2.** `PLAN.md` §3 writes this line as +> `il2cpp_init intercepted`. That wording belongs to **M0b**, which IAT-hooks +> `kernel32!GetProcAddress` in `UnityPlayer.dll` and returns its own +> `il2cpp_init`. M0 uses the lower-risk poll trigger `PLAN.md` itself prescribes +> ("*implemented first as the lower-risk path, with the IAT hook as M0b*"), so +> the line says what actually happened. Polling proves the runtime is **up**; +> interception would additionally prove we are **ahead of it**. + +### Reading a failure + +| Symptom | Meaning | +| --- | --- | +| `_Modrix/Latest.log` does not exist | The proxy never loaded. Nine times out of ten this is a missing `WINEDLLOVERRIDES`. | +| Only line 1 | IL2CPP never came up within 120 s, or `GameAssembly.dll` is not loaded under this name. | +| `ERROR bootstrap failed: coreclr not found at …` | The `dotnet/` copy is missing or incomplete. | +| `ERROR bootstrap failed: coreclr_initialize returned 0x…` | CoreCLR itself refused to start: the `host = wine …` line above it is the first thing to report. | +| `coreclr_create_delegate returned 0x80070002` | `Modrix.Loader.dll` is not on `APP_PATHS`; check `_Modrix/net6/`. | +| `_Modrix/crash_.log` exists | Managed code ran and threw. The file holds the full exception. | +| Game closes instantly with no log at all | Revert: restore `version.melonloader.bak` and report it. | + +### Reverting + +```sh +rm -f "$SOTF/version.dll" +mv "$SOTF/version.melonloader.bak" "$SOTF/version.dll" +rm -rf "$SOTF/_Modrix" +``` + +The game is untouched otherwise: nothing here writes to `SonsOfTheForest_Data`, +`GameAssembly.dll`, `boot.config` or any save. + +--- + +## Known risks in M0 (none of them retired yet) + +1. **Does CoreCLR initialize under this Proton build?** Unknown. RedLoader warns + that Wine below 7.16 lacks `RtlRestoreContext` for 32-bit processes; this is + 64-bit, so the warning does not apply directly, but nothing has been measured. + The `host = wine ` line exists to make the answer reportable. +2. **UCRT under Wine.** The produced DLL imports `api-ms-win-crt-*` (Rust's + `windows-gnu` targets link the UCRT, not `msvcrt`). Proton ships + `ucrtbase.dll`, so this should resolve, but if the proxy fails to load at all + with no log, this is the second thing to check after `WINEDLLOVERRIDES`. +3. **`std::thread::spawn` from `DllMain`.** The spawn happens under the loader + lock; the thread does not run until the lock is released, which is the + documented, widely used pattern. Nothing heavier than `CreateThread` runs + inside `DllMain`; CoreCLR is deliberately loaded on the spawned thread. +4. **Case sensitivity.** RedLoader's own config and shell script disagree + (`Redloader.dll` vs `RedLoader.dll`) and Wine's case folding hides it. Every + path here is exact-case and nothing depends on folding. diff --git a/loaders/sons-proxy/build-windows.sh b/loaders/sons-proxy/build-windows.sh new file mode 100755 index 0000000..3be3a43 --- /dev/null +++ b/loaders/sons-proxy/build-windows.sh @@ -0,0 +1,96 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: GPL-2.0-only +# +# Builds the Sons of the Forest proxy DLL and stages an installable `_Modrix` +# tree under `dist/`. Nothing is ever written outside this directory - installing +# into a game folder is a deliberate, manual step (see README.md), because the +# proxy slot is single-occupancy and overwriting another loader's `version.dll` +# breaks both. +# +# ./build-windows.sh # proxy only +# ./build-windows.sh --managed # + Modrix.Loader.dll +# ./build-windows.sh --coreclr # + the runtime +# +# Cross-compiles from Linux with the mingw-w64 linker by default. On Windows, or +# with the MSVC toolchain installed, pass MODRIX_PROXY_TARGET=x86_64-pc-windows-msvc. + +set -euo pipefail + +HERE="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +MANAGED_DIR="$(cd -- "$HERE/../sons-managed/Modrix.Loader" && pwd)" +TARGET="${MODRIX_PROXY_TARGET:-x86_64-pc-windows-gnu}" +PROFILE="${MODRIX_PROXY_PROFILE:-release}" +DIST="$HERE/dist" + +want_managed=0 +coreclr_src="" +while [[ $# -gt 0 ]]; do + case "$1" in + --managed) want_managed=1; shift ;; + --coreclr) coreclr_src="${2:-}"; shift 2 ;; + *) echo "unknown argument: $1" >&2; exit 2 ;; + esac +done + +echo "==> building $TARGET ($PROFILE)" +cargo build --profile "$PROFILE" --target "$TARGET" --manifest-path "$HERE/Cargo.toml" + +built="$HERE/target/$TARGET/$PROFILE/modrix_sons_proxy.dll" +[[ -f "$built" ]] || { echo "expected $built" >&2; exit 1; } + +# The Windows loader keys on the FILE name, not on the PE export-directory name, +# which is why renaming the artefact is all that is needed to occupy the slot. +# Doorstop ships the identical binary as winhttp.dll and RedLoader renames it. +rm -rf "$DIST" +mkdir -p "$DIST/_Modrix/net6" "$DIST/_Modrix/dotnet" +cp "$built" "$DIST/version.dll" +echo "==> staged $DIST/version.dll" + +echo "==> verifying the seventeen version.dll exports" +python3 - "$DIST/version.dll" <<'PY' +import sys +try: + import pefile +except ImportError: + print(" SKIPPED (python module `pefile` is not installed)") + sys.exit(0) + +expected = { + "GetFileVersionInfoA", "GetFileVersionInfoByHandle", "GetFileVersionInfoExA", + "GetFileVersionInfoExW", "GetFileVersionInfoSizeA", "GetFileVersionInfoSizeExA", + "GetFileVersionInfoSizeExW", "GetFileVersionInfoSizeW", "GetFileVersionInfoW", + "VerFindFileA", "VerFindFileW", "VerInstallFileA", "VerInstallFileW", + "VerLanguageNameA", "VerLanguageNameW", "VerQueryValueA", "VerQueryValueW", +} +pe = pefile.PE(sys.argv[1]) +found = {e.name.decode() for e in pe.DIRECTORY_ENTRY_EXPORT.symbols if e.name} +missing = expected - found +if missing: + print(" MISSING: " + ", ".join(sorted(missing))) + sys.exit(1) +if pe.FILE_HEADER.Machine != 0x8664: + print(f" WRONG MACHINE: {pe.FILE_HEADER.Machine:#x}, expected 0x8664") + sys.exit(1) +print(f" OK - all 17 present, x86-64, {len(found)} exports total") +PY + +if [[ $want_managed -eq 1 ]]; then + echo "==> building Modrix.Loader (net6.0)" + dotnet build -c Release "$MANAGED_DIR/Modrix.Loader.csproj" + cp "$MANAGED_DIR/bin/Release/net6.0/Modrix.Loader.dll" "$DIST/_Modrix/net6/" + echo "==> staged $DIST/_Modrix/net6/Modrix.Loader.dll" +fi + +if [[ -n "$coreclr_src" ]]; then + [[ -f "$coreclr_src/coreclr.dll" ]] || { + echo "no coreclr.dll under $coreclr_src - point --coreclr at mini-coreclr's win-x64 folder" >&2 + exit 1 + } + echo "==> copying the vendored runtime" + cp -r "$coreclr_src/." "$DIST/_Modrix/dotnet/" + echo "==> staged $(find "$DIST/_Modrix/dotnet" -type f | wc -l) runtime files" +fi + +echo +echo "dist tree ready. It is NOT installed anywhere - see README.md, 'Installing'." +find "$DIST" -maxdepth 3 -mindepth 1 -not -path '*/dotnet/*' | sort diff --git a/loaders/sons-proxy/clippy.toml b/loaders/sons-proxy/clippy.toml new file mode 100644 index 0000000..9354403 --- /dev/null +++ b/loaders/sons-proxy/clippy.toml @@ -0,0 +1,21 @@ +# SPDX-License-Identifier: GPL-2.0-only +# Same Power of Ten thresholds as the main workspace (see the root clippy.toml). +too-many-lines-threshold = 60 +too-many-arguments-threshold = 5 + +# Product and technology names that read better unbackticked in prose. ".." +# keeps clippy's own defaults. The loader-specific half of this list is why the +# file exists at all: this crate's doc comments are mostly about other people's +# software. +doc-valid-idents = [ + "Modrix", "CoreCLR", "IL2CPP", "Il2CppInterop", "RedLoader", "MelonLoader", + "BepInEx", "Doorstop", "GameAssembly", "UnityPlayer", "Unity", "Proton", + "Dobby", "MonoBehaviour", "AppDomain", "macOS", "..", +] + +# Production code stays panic-free and bounded. Test code may assert directly. +allow-unwrap-in-tests = true +allow-expect-in-tests = true +allow-panic-in-tests = true +allow-dbg-in-tests = true +allow-indexing-slicing-in-tests = true diff --git a/loaders/sons-proxy/rust-toolchain.toml b/loaders/sons-proxy/rust-toolchain.toml new file mode 100644 index 0000000..e4310d9 --- /dev/null +++ b/loaders/sons-proxy/rust-toolchain.toml @@ -0,0 +1,8 @@ +# SPDX-License-Identifier: GPL-2.0-only +# Pinned to the same toolchain as the main workspace so lint behaviour matches. +# `targets` makes `rustup` fetch the Windows std automatically - the proxy is a +# Windows PE even when it is cross-compiled from Linux. +[toolchain] +channel = "1.96.0" +components = ["clippy", "rustfmt"] +targets = ["x86_64-pc-windows-gnu"] diff --git a/loaders/sons-proxy/src/coreclr.rs b/loaders/sons-proxy/src/coreclr.rs new file mode 100644 index 0000000..1508ff8 --- /dev/null +++ b/loaders/sons-proxy/src/coreclr.rs @@ -0,0 +1,224 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Hosting CoreCLR with the two exports Doorstop uses, and nothing else. +//! +//! # Why not hostfxr +//! +//! MelonLoader goes through `nethost`/`hostfxr`, which resolves frameworks +//! properly and can use a system .NET - at the cost of needing `hostfxr.dll`, a +//! `*.runtimeconfig.json`, and a correct `DOTNET_ROOT` inside a Proton prefix. +//! Doorstop instead calls `coreclr_initialize` and `coreclr_create_delegate` +//! directly against a vendored runtime. That is two symbols, no config file and +//! no framework resolution, and it is the route already proven to work in this +//! exact game under this exact Proton prefix (PLAN.md D5). BepInEx's +//! `mini-coreclr` 6.0.7 `win-x64` ships `coreclr.dll` but deliberately no +//! `hostfxr.dll`, so this is also the only route that runtime supports. +//! +//! `coreclr_initialize` is given two properties. `APP_PATHS` - the corlib +//! directory, the managed host directory and the interop directory - is the +//! probing list, and is the one property Doorstop passes. +//! `TRUSTED_PLATFORM_ASSEMBLIES` is ours; see +//! `Layout::trusted_platform_assemblies` for why running without it breaks +//! Harmony in a way whose error message names none of this. + +use crate::error::Error; +use crate::layout::{ + CORECLR_FILE_NAME, DOMAIN_FRIENDLY_NAME, ENTRY_METHOD, ENTRY_TYPE, Layout, MANAGED_ASSEMBLY, +}; +use core::ffi::c_void; +use core::mem::MaybeUninit; +use std::ffi::CString; + +/// `int coreclr_initialize(const char*, const char*, int, const char**, const char**, void**, unsigned int*)`. +type CoreclrInitialize = unsafe extern "system" fn( + exe_path: *const u8, + app_domain_friendly_name: *const u8, + property_count: i32, + property_keys: *const *const u8, + property_values: *const *const u8, + host_handle: *mut *mut c_void, + domain_id: *mut u32, +) -> u32; + +/// `int coreclr_create_delegate(void*, unsigned int, const char*, const char*, const char*, void**)`. +type CoreclrCreateDelegate = unsafe extern "system" fn( + host_handle: *mut c_void, + domain_id: u32, + assembly_name: *const u8, + type_name: *const u8, + method_name: *const u8, + delegate: *mut *mut c_void, +) -> u32; + +/// The managed entrypoint: zero parameters, void return. Non-negotiable - +/// `coreclr_create_delegate` builds the reverse-P/Invoke stub from the method's +/// own signature, so any other shape corrupts the stack on call. +type ManagedStart = unsafe extern "system" fn(); + +/// A live CoreCLR host, plus the two hosting functions resolved from it. +pub struct Host { + handle: *mut c_void, + domain_id: u32, + create_delegate: CoreclrCreateDelegate, +} + +/// Loads the vendored `coreclr.dll` and initializes it. +/// +/// # Errors +/// +/// - [`Error::Missing`] when `_Modrix/dotnet/coreclr.dll` is absent. +/// - [`Error::Win32`] when it cannot be loaded. +/// - [`Error::MissingExport`] when either hosting symbol is absent, which means +/// the vendored runtime is not the one this code was written against. +/// - [`Error::InteriorNul`] when a path contains a NUL byte. +/// - [`Error::CoreClr`] with the HRESULT when initialization itself fails. +pub fn start(layout: &Layout) -> Result { + let coreclr_path = layout.coreclr_path(); + if !coreclr_path.is_file() { + return Err(Error::Missing { + what: "coreclr", + path: coreclr_path, + }); + } + let module = crate::win::load_library(&coreclr_path)?; + let initialize = resolve::(module, "coreclr_initialize")?; + let create_delegate = resolve::(module, "coreclr_create_delegate")?; + + let exe = cstring( + &layout.process_path().to_string_lossy(), + "MODRIX_PROCESS_PATH", + )?; + let domain_name = cstring(DOMAIN_FRIENDLY_NAME, "domain name")?; + let app_paths_key = cstring("APP_PATHS", "APP_PATHS key")?; + let app_paths_value = cstring(&layout.app_paths(), "APP_PATHS value")?; + // See `Layout::trusted_platform_assemblies`. Without this second property, + // managed code still runs, but every Harmony patch of an IL2CPP method fails + // because Mono.Cecil cannot resolve `System.Private.CoreLib`. + let trusted_key = cstring( + "TRUSTED_PLATFORM_ASSEMBLIES", + "TRUSTED_PLATFORM_ASSEMBLIES key", + )?; + let trusted_value = cstring( + &layout.trusted_platform_assemblies(), + "TRUSTED_PLATFORM_ASSEMBLIES value", + )?; + let keys = [ + app_paths_key.as_ptr().cast::(), + trusted_key.as_ptr().cast::(), + ]; + let values = [ + app_paths_value.as_ptr().cast::(), + trusted_value.as_ptr().cast::(), + ]; + + let mut handle = MaybeUninit::<*mut c_void>::uninit(); + let mut domain_id = MaybeUninit::::uninit(); + // SAFETY: every pointer is a live NUL-terminated buffer owned by this frame, + // the two arrays hold exactly `property_count` entries, and the two out + // parameters are writable and correctly typed. + let hr = unsafe { + initialize( + exe.as_ptr().cast::(), + domain_name.as_ptr().cast::(), + 2, + keys.as_ptr(), + values.as_ptr(), + handle.as_mut_ptr(), + domain_id.as_mut_ptr(), + ) + }; + if hr != 0 { + return Err(Error::CoreClr { + op: "coreclr_initialize", + hr, + }); + } + // SAFETY: `coreclr_initialize` returning 0 means both out parameters were + // written. + let handle = unsafe { handle.assume_init() }; + // SAFETY: as above. + let domain_id = unsafe { domain_id.assume_init() }; + Ok(Host { + handle, + domain_id, + create_delegate, + }) +} + +impl Host { + /// Builds a delegate to `Modrix.Loader.Entrypoint.Start` and calls it. + /// + /// The call is synchronous: managed code runs to completion on this thread + /// before the function returns. For M0 that is a handful of file writes. + /// + /// # Errors + /// + /// [`Error::InteriorNul`] for a malformed name, or [`Error::CoreClr`] with + /// the HRESULT when the assembly, type or method cannot be resolved - + /// `0x80070002` here means `Modrix.Loader.dll` is not on `APP_PATHS`. + pub fn run_managed_entrypoint(&self) -> Result<(), Error> { + let assembly = cstring(MANAGED_ASSEMBLY, "managed assembly name")?; + let type_name = cstring(ENTRY_TYPE, "managed type name")?; + let method = cstring(ENTRY_METHOD, "managed method name")?; + let mut delegate = MaybeUninit::<*mut c_void>::uninit(); + // SAFETY: `self.handle` and `self.domain_id` came from a successful + // `coreclr_initialize`, the three names are live NUL-terminated buffers, + // and `delegate` is a writable out parameter. + let hr = unsafe { + (self.create_delegate)( + self.handle, + self.domain_id, + assembly.as_ptr().cast::(), + type_name.as_ptr().cast::(), + method.as_ptr().cast::(), + delegate.as_mut_ptr(), + ) + }; + if hr != 0 { + return Err(Error::CoreClr { + op: "coreclr_create_delegate", + hr, + }); + } + // SAFETY: a 0 HRESULT means `delegate` was written. + let raw = unsafe { delegate.assume_init() }; + if raw.is_null() { + return Err(Error::CoreClr { + op: "coreclr_create_delegate", + hr: 0, + }); + } + // SAFETY: CoreCLR produced a reverse-P/Invoke stub for a `static void + // Start()`, which is exactly `ManagedStart`. + let start = unsafe { core::mem::transmute::<*mut c_void, ManagedStart>(raw) }; + // SAFETY: calling that stub. Managed exceptions are caught inside + // `Start`, so nothing propagates back across this boundary. + unsafe { start() }; + Ok(()) + } +} + +/// Resolves a hosting symbol and transmutes it to its function type. +fn resolve( + module: windows_sys::Win32::Foundation::HMODULE, + symbol: &'static str, +) -> Result { + const { + assert!( + size_of::() == size_of::(), + "T must be a bare function pointer" + ); + }; + let address = crate::win::proc_address(module, symbol).ok_or(Error::MissingExport { + module: CORECLR_FILE_NAME, + symbol, + })?; + // SAFETY: the address came from `GetProcAddress` on `coreclr.dll`, and the + // const assertion above pins `T` to pointer size. The caller names `T` as + // the documented signature of `symbol`. + Ok(unsafe { core::mem::transmute_copy::(&address) }) +} + +/// UTF-8 `CString` for a C API, with the field named in the error. +fn cstring(text: &str, what: &'static str) -> Result { + CString::new(text).map_err(|_| Error::InteriorNul(what)) +} diff --git a/loaders/sons-proxy/src/error.rs b/loaders/sons-proxy/src/error.rs new file mode 100644 index 0000000..d981542 --- /dev/null +++ b/loaders/sons-proxy/src/error.rs @@ -0,0 +1,137 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! The one error type the proxy uses. +//! +//! Hand-rolled rather than `thiserror`, because this crate ships inside the +//! game process and deliberately depends on nothing but `windows-sys`. Every +//! variant carries enough context to identify the failing step from a single +//! log line, since a failure here happens on a user's machine under Proton with +//! no debugger attached. + +use core::fmt; +use std::path::PathBuf; + +/// Everything that can go wrong between `DLL_PROCESS_ATTACH` and the managed +/// entrypoint returning. +#[derive(Debug)] +pub enum Error { + /// A Win32 call failed. `op` names the call; `code` is `GetLastError()`. + Win32 { + /// The Win32 function that failed, e.g. `"LoadLibraryW"`. + op: &'static str, + /// The value `GetLastError()` returned immediately afterwards. + code: u32, + }, + /// A file the loader needs is not on disk. + Missing { + /// What the file is for, e.g. `"coreclr"`. + what: &'static str, + /// Where it was looked for. + path: PathBuf, + }, + /// A module was loaded but did not export a symbol we require. + MissingExport { + /// Module file name, e.g. `"coreclr.dll"`. + module: &'static str, + /// The symbol that was absent. + symbol: &'static str, + }, + /// A string destined for a C API contained an interior NUL byte. + InteriorNul(&'static str), + /// A CoreCLR hosting call returned a non-zero HRESULT. + CoreClr { + /// The hosting function, e.g. `"coreclr_initialize"`. + op: &'static str, + /// The HRESULT it returned. + hr: u32, + }, + /// A bounded wait expired. + Timeout { + /// What was being waited for. + what: &'static str, + /// How long the wait lasted, in seconds. + secs: u64, + }, + /// The process path could not be turned into a game directory. + NoGameRoot(PathBuf), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Win32 { op, code } => write!(f, "{op} failed, GetLastError = {code}"), + Self::Missing { what, path } => write!(f, "{what} not found at {}", path.display()), + Self::MissingExport { module, symbol } => { + write!(f, "{module} does not export {symbol}") + } + Self::InteriorNul(what) => write!(f, "{what} contains an interior NUL byte"), + Self::CoreClr { op, hr } => write!(f, "{op} returned 0x{hr:08x}"), + Self::Timeout { what, secs } => write!(f, "timed out after {secs}s waiting for {what}"), + Self::NoGameRoot(path) => { + write!(f, "cannot derive the game root from {}", path.display()) + } + } + } +} + +impl std::error::Error for Error {} + +#[cfg(test)] +mod tests { + use super::Error; + use std::path::PathBuf; + + #[test] + fn every_variant_renders_its_context() { + let cases = [ + Error::Win32 { + op: "LoadLibraryW", + code: 126, + }, + Error::Missing { + what: "coreclr", + path: PathBuf::from("/x/coreclr.dll"), + }, + Error::MissingExport { + module: "coreclr.dll", + symbol: "coreclr_initialize", + }, + Error::InteriorNul("APP_PATHS"), + Error::CoreClr { + op: "coreclr_initialize", + hr: 0x8007_000e, + }, + Error::Timeout { + what: "GameAssembly.dll", + secs: 120, + }, + Error::NoGameRoot(PathBuf::from("/")), + ]; + for case in cases { + let rendered = case.to_string(); + assert!(!rendered.is_empty()); + // A bare Debug-style rendering would be useless in a user's log. + assert!(!rendered.starts_with('{')); + } + } + + #[test] + fn win32_error_names_the_call_and_code() { + let msg = Error::Win32 { + op: "LoadLibraryW", + code: 126, + } + .to_string(); + assert!(msg.contains("LoadLibraryW")); + assert!(msg.contains("126")); + } + + #[test] + fn coreclr_hresult_is_hex_padded() { + let msg = Error::CoreClr { + op: "coreclr_initialize", + hr: 0x8007_000e, + } + .to_string(); + assert!(msg.contains("0x8007000e"), "{msg}"); + } +} diff --git a/loaders/sons-proxy/src/exports.rs b/loaders/sons-proxy/src/exports.rs new file mode 100644 index 0000000..9adb0e4 --- /dev/null +++ b/loaders/sons-proxy/src/exports.rs @@ -0,0 +1,188 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! The seventeen `version.dll` exports, forwarded to the real system DLL. +//! +//! # Why a naked `jmp` and not a C-style thunk +//! +//! Unity Doorstop emits `void *exp_X(void) { return __X__(); }` - a +//! zero-argument C function - and relies on the compiler tail-calling at `-Os` +//! so that RCX/RDX/R8/R9 and any stack arguments survive. That is correct only +//! by luck: at `-O0`, or with a stack-protector prologue, the thunk clobbers the +//! frame and any export taking more than four arguments (`VerInstallFileW` takes +//! seven) receives garbage. +//! +//! MelonLoader avoids the problem by rewriting its own export stubs at runtime +//! with `VirtualProtect(PAGE_EXECUTE_READWRITE)` + `mov r11, addr; jmp r11`. +//! That is unconditionally correct, but it makes our own `.text` writable and +//! executable for the life of the process, which is a needless liability inside +//! a game's address space. +//! +//! A `#[unsafe(naked)]` function that loads a pointer and tail-jumps is +//! unconditionally correct *and* needs no RWX memory - `injection.md` names it +//! "the only strictly correct implementation". Emitted code, verified with +//! `objdump` on the cross-compiled DLL: +//! +//! ```text +//! mov rax, qword ptr [rip + SLOTS + N*8] +//! test rax, rax +//! je .null +//! jmp rax +//! .null: +//! xor eax, eax +//! ret +//! ``` +//! +//! RAX is scratch and is not an argument register in the Microsoft x64 calling +//! convention, so every argument - register and stack - reaches the real +//! function untouched, and the real function's `ret` returns straight to the +//! game. `rsp` is never adjusted, so stack arguments keep their offsets. +//! +//! The null branch exists only for the case where the real DLL loaded but did +//! not export a name; returning 0 reads as failure to every one of these APIs. +//! It cannot happen with a genuine `version.dll`, and the miss is logged. +//! +//! Rust exports `#[unsafe(no_mangle)] pub extern` functions from a `cdylib` +//! with `dllexport` automatically, so no `.def` file is involved and the export +//! names are undecorated. `build-windows.sh` asserts all seventeen are present +//! in the produced PE. + +use core::sync::atomic::AtomicUsize; + +/// Number of exports a `version.dll` proxy must provide. +/// +/// Taken verbatim from Doorstop's `src/windows/proxy/proxylist.txt` and +/// confirmed against the released binary; guessing this set gets the game a +/// missing-import dialog on launch. +pub const SLOT_COUNT: usize = 17; + +#[expect( + clippy::declare_interior_mutable_const, + reason = "the const is only a zero-initialiser for the static array; it is never read as a value" +)] +const EMPTY_SLOT: AtomicUsize = AtomicUsize::new(0); + +/// Resolved addresses of the real exports, indexed the same as [`EXPORT_NAMES`]. +/// +/// Written once from `DLL_PROCESS_ATTACH` and read by the naked thunks. The +/// thunks read the slot with a plain `mov`, which is a benign race on x86-64: +/// the store is a single aligned 8-byte write under TSO, so a reader sees either +/// the old zero (and returns failure) or the final address, never a tear. +pub static SLOTS: [AtomicUsize; SLOT_COUNT] = [EMPTY_SLOT; SLOT_COUNT]; + +/// Declares one forwarder, and records its name and slot index so a +/// transcription mistake is a failing test rather than a corrupt jump. +macro_rules! version_exports { + ($( ($index:expr, $name:ident) ),+ $(,)?) => { + /// Export names in slot order. + pub const EXPORT_NAMES: [&str; SLOT_COUNT] = [ $( stringify!($name) ),+ ]; + + /// The slot index each entry of [`EXPORT_NAMES`] was declared with. + /// + /// Exists so a transcription mistake in the table above - a repeated or + /// out-of-order index, which would silently make one export jump to + /// another's target - is caught by a unit test instead of by a user. + pub const DECLARED_SLOTS: [usize; SLOT_COUNT] = [ $( $index ),+ ]; + + $( + #[doc = concat!("Forwards `", stringify!($name), "` to the real `version.dll`.")] + #[doc = ""] + #[doc = "The declared signature is a placeholder: this is a naked tail-jump, so"] + #[doc = "the real export's arguments and return value pass through unchanged."] + #[doc = "It is never called from Rust."] + #[doc = ""] + #[doc = "# Safety"] + #[doc = ""] + #[doc = "Callable only by the Windows loader on behalf of a module that imported"] + #[doc = "this name, with that export's real argument list."] + #[cfg(all(windows, target_arch = "x86_64"))] + #[unsafe(naked)] + #[unsafe(no_mangle)] + pub unsafe extern "system" fn $name() { + core::arch::naked_asm!( + "mov rax, qword ptr [rip + {slots} + {offset}]", + "test rax, rax", + "je 2f", + "jmp rax", + "2:", + "xor eax, eax", + "ret", + slots = sym SLOTS, + offset = const ($index * 8usize), + ) + } + )+ + }; +} + +version_exports![ + (0, GetFileVersionInfoA), + (1, GetFileVersionInfoByHandle), + (2, GetFileVersionInfoExA), + (3, GetFileVersionInfoExW), + (4, GetFileVersionInfoSizeA), + (5, GetFileVersionInfoSizeExA), + (6, GetFileVersionInfoSizeExW), + (7, GetFileVersionInfoSizeW), + (8, GetFileVersionInfoW), + (9, VerFindFileA), + (10, VerFindFileW), + (11, VerInstallFileA), + (12, VerInstallFileW), + (13, VerLanguageNameA), + (14, VerLanguageNameW), + (15, VerQueryValueA), + (16, VerQueryValueW), +]; + +#[cfg(test)] +mod tests { + use super::{DECLARED_SLOTS, EXPORT_NAMES, SLOT_COUNT, SLOTS}; + use core::sync::atomic::Ordering; + use std::collections::BTreeSet; + + #[test] + fn every_thunk_owns_exactly_its_table_index() { + // A wrong index here would make one export jump to another export's + // target - which "works" for the game right up until it does not. + let expected: Vec = (0..SLOT_COUNT).collect(); + assert_eq!(DECLARED_SLOTS.to_vec(), expected); + } + + #[test] + fn the_table_is_the_doorstop_proxylist() { + // Verbatim from Doorstop src/windows/proxy/proxylist.txt (version set). + let expected = BTreeSet::from([ + "GetFileVersionInfoA", + "GetFileVersionInfoByHandle", + "GetFileVersionInfoExA", + "GetFileVersionInfoExW", + "GetFileVersionInfoSizeA", + "GetFileVersionInfoSizeExA", + "GetFileVersionInfoSizeExW", + "GetFileVersionInfoSizeW", + "GetFileVersionInfoW", + "VerFindFileA", + "VerFindFileW", + "VerInstallFileA", + "VerInstallFileW", + "VerLanguageNameA", + "VerLanguageNameW", + "VerQueryValueA", + "VerQueryValueW", + ]); + assert_eq!( + EXPORT_NAMES.iter().copied().collect::>(), + expected + ); + assert_eq!( + EXPORT_NAMES.len(), + SLOT_COUNT, + "duplicate name in the table" + ); + } + + #[test] + fn slots_start_null_so_an_unresolved_export_fails_closed() { + assert_eq!(SLOTS.len(), EXPORT_NAMES.len()); + assert!(SLOTS.iter().all(|slot| slot.load(Ordering::SeqCst) == 0)); + } +} diff --git a/loaders/sons-proxy/src/il2cpp.rs b/loaders/sons-proxy/src/il2cpp.rs new file mode 100644 index 0000000..b6f3c09 --- /dev/null +++ b/loaders/sons-proxy/src/il2cpp.rs @@ -0,0 +1,55 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Detecting that the game's IL2CPP runtime exists - **without calling it**. +//! +//! # Why there is no `il2cpp_domain_get` probe here +//! +//! The obvious readiness check is to poll `il2cpp_domain_get` until it returns +//! non-null: it is an exported accessor, and reading a static that is null +//! before `il2cpp_init` looks harmless. +//! +//! It is not. Doing it kills the game, with a message box reading +//! **"Collecting from unknown thread"**. IL2CPP's garbage collector maintains a +//! registry of threads it is allowed to see, built as the runtime starts. A +//! call that reaches the runtime from a thread absent from that registry +//! aborts the process. Our bootstrap thread is necessarily absent: the GC was +//! initialised before the thread existed, and registering it means calling +//! `il2cpp_thread_attach`, which needs the very domain pointer we were trying +//! to fetch. +//! +//! This was isolated by bisection, not deduction. With the proxy stopping +//! after "GameAssembly.dll mapped" the game runs to 304 log lines and no +//! crash; letting it make the single accessor call drops that to 35 lines and +//! a crash. Waiting longer changes nothing - the thread is wrong, not early. +//! +//! So this module only ever asks the *Windows loader* a question, never the +//! runtime. `GetModuleHandleW` reports whether `GameAssembly.dll` is mapped, +//! which is all the proxy needs: it proves the game is far enough along to host +//! CoreCLR, and CoreCLR hosting is completely independent of IL2CPP anyway. +//! +//! Managed code that wants to touch IL2CPP must attach properly, from the +//! game's own main thread, which is the SDK's job and not the proxy's. + +use core::time::Duration; +use std::time::Instant; + +/// Module that carries the IL2CPP runtime in a Unity IL2CPP build. Its presence +/// is the signal; its exports are deliberately never called from here. +const GAME_ASSEMBLY: &str = "GameAssembly.dll"; + +/// Blocks until `GameAssembly.dll` is mapped, returning its base address. +/// +/// Pure observation: this calls `GetModuleHandleW` and nothing else, so it +/// cannot perturb the runtime it is waiting for. +#[must_use] +pub fn wait_for_module(timeout: Duration, poll_interval: Duration) -> Option { + let started = Instant::now(); + loop { + if let Some(handle) = crate::win::module_handle(GAME_ASSEMBLY) { + return Some(handle as usize); + } + if started.elapsed() >= timeout { + return None; + } + std::thread::sleep(poll_interval); + } +} diff --git a/loaders/sons-proxy/src/layout.rs b/loaders/sons-proxy/src/layout.rs new file mode 100644 index 0000000..5c45da1 --- /dev/null +++ b/loaders/sons-proxy/src/layout.rs @@ -0,0 +1,446 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Where everything lives on disk, derived once from the process path. +//! +//! This module is pure: no FFI, no Windows types, no I/O except the one +//! best-effort read of the runtime stamp. That is deliberate - path derivation +//! is the part most likely to be wrong under Proton (the CWD is not the game +//! directory, and Wine's case folding hides casing mistakes), so it is the part +//! that has to be unit-testable on a Linux host. +//! +//! The names below must stay in lockstep with `games/sonsoftheforest/game.toml` +//! (`install_root`, `sentinel`, `[launch] log`). If one moves, both move. + +use std::path::{Path, PathBuf}; + +/// Loader install root, relative to the game directory. +pub const LOADER_DIR_NAME: &str = "_Modrix"; +/// Vendored CoreCLR directory, relative to [`LOADER_DIR_NAME`]. +pub const DOTNET_DIR_NAME: &str = "dotnet"; +/// Managed host directory, relative to [`LOADER_DIR_NAME`]. +pub const MANAGED_DIR_NAME: &str = "net6"; +/// Generated IL2CPP interop assemblies, relative to [`LOADER_DIR_NAME`]. +pub const INTEROP_DIR_NAME: &str = "interop"; +/// Log file name, relative to [`LOADER_DIR_NAME`]. +pub const LOG_FILE_NAME: &str = "Latest.log"; +/// Previous session's log, kept so a run that killed the game is still readable. +pub const PREVIOUS_LOG_FILE_NAME: &str = "Previous.log"; +/// The CoreCLR shared library we host. +pub const CORECLR_FILE_NAME: &str = "coreclr.dll"; +/// BepInEx's `mini-coreclr` drops this stamp file beside `coreclr.dll`. +pub const VERSION_STAMP_NAME: &str = ".version"; + +/// Managed assembly name, WITHOUT extension - this is what +/// `coreclr_create_delegate` wants. +pub const MANAGED_ASSEMBLY: &str = "Modrix.Loader"; +/// Fully qualified managed type hosting the entrypoint. +pub const ENTRY_TYPE: &str = "Modrix.Loader.Entrypoint"; +/// Managed entrypoint method. Zero parameters, void return, non-negotiable. +pub const ENTRY_METHOD: &str = "Start"; +/// The AppDomain friendly name passed to `coreclr_initialize`. +pub const DOMAIN_FRIENDLY_NAME: &str = "Modrix Domain"; + +/// `APP_PATHS` uses the platform path-list separator. The proxy only ever runs +/// as a Windows PE (under Wine on Linux), so this is always `;` - deriving it +/// from the *host* would be wrong when cross-compiling. +const APP_PATHS_SEPARATOR: char = ';'; + +/// Every path the loader needs, resolved from the game executable's own path. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Layout { + process_path: PathBuf, + game_root: PathBuf, + loader_dir: PathBuf, + dotnet_dir: PathBuf, + interop_dir: PathBuf, + managed_dir: PathBuf, +} + +impl Layout { + /// Derives the layout from the full path of the running executable. + /// + /// # Errors + /// + /// Returns [`crate::error::Error::NoGameRoot`] when `process_path` has no + /// parent directory, which would mean Windows handed us a bare file name. + pub fn from_process_path(process_path: PathBuf) -> Result { + let game_root = process_path + .parent() + .ok_or_else(|| crate::error::Error::NoGameRoot(process_path.clone()))? + .to_path_buf(); + let loader_dir = game_root.join(LOADER_DIR_NAME); + let dotnet_dir = loader_dir.join(DOTNET_DIR_NAME); + let interop_dir = loader_dir.join(INTEROP_DIR_NAME); + let managed_dir = loader_dir.join(MANAGED_DIR_NAME); + Ok(Self { + process_path, + game_root, + loader_dir, + dotnet_dir, + interop_dir, + managed_dir, + }) + } + + /// Full path of the running game executable. + #[must_use] + pub fn process_path(&self) -> &Path { + &self.process_path + } + + /// Directory containing the game executable. + #[must_use] + pub fn game_root(&self) -> &Path { + &self.game_root + } + + /// `/_Modrix`. + #[must_use] + pub fn loader_dir(&self) -> &Path { + &self.loader_dir + } + + /// `/_Modrix/dotnet`. + #[must_use] + pub fn dotnet_dir(&self) -> &Path { + &self.dotnet_dir + } + + /// `/_Modrix/net6`. + #[must_use] + pub fn managed_dir(&self) -> &Path { + &self.managed_dir + } + + /// `/_Modrix/Latest.log`. + #[must_use] + pub fn log_path(&self) -> PathBuf { + self.loader_dir.join(LOG_FILE_NAME) + } + + /// `/_Modrix/dotnet/coreclr.dll`. + #[must_use] + pub fn coreclr_path(&self) -> PathBuf { + self.dotnet_dir.join(CORECLR_FILE_NAME) + } + + /// The value of the single `APP_PATHS` property CoreCLR is initialized with: + /// the corlib directory, the host directory, then the interop directory. + /// + /// Doorstop passes exactly one property and the first two of these. The + /// third is ours: a mod's own assembly references the *game's* assemblies by + /// name (`Sons`, `UnityEngine.CoreModule`), and without the interop + /// directory on the probing path the runtime cannot find them - the mod + /// loads, then throws `FileNotFoundException: Could not load file or + /// assembly 'Sons'` the moment it touches a game type. + #[must_use] + pub fn app_paths(&self) -> String { + format!( + "{}{APP_PATHS_SEPARATOR}{}{APP_PATHS_SEPARATOR}{}", + self.dotnet_dir.display(), + self.managed_dir.display(), + self.interop_dir.display() + ) + } + + /// `/_Modrix/interop`, where generated reference assemblies live. + #[must_use] + pub fn interop_dir(&self) -> &Path { + &self.interop_dir + } + + /// Whether the running process is the Unity player this loader belongs to. + /// + /// A `version.dll` next to the game is loaded by *every* PE started from that + /// directory, not only the game. Under Proton that is a real and frequent + /// occurrence - Steam's helpers, Wine services and the game's own crash + /// handler all qualify - and every one of them ran the full bootstrap: + /// truncating `Latest.log`, then blocking 120 seconds waiting for a + /// `GameAssembly.dll` that process will never map. The visible symptom is a + /// loader log that keeps resetting to six lines and a `timed out waiting for + /// GameAssembly.dll module` error while the game is plainly running, with + /// nothing indicating a second process is involved at all. + /// + /// Unity's own layout settles it. A player executable always sits beside a + /// data directory named after it - `SonsOfTheForest.exe` next to + /// `SonsOfTheForest_Data`. No helper process satisfies that, and it holds for + /// every Unity game rather than being specific to this one. + #[must_use] + pub fn owns_game(&self) -> bool { + let Some(stem) = self.process_path.file_stem().and_then(|s| s.to_str()) else { + return false; + }; + self.game_root.join(format!("{stem}_Data")).is_dir() + } + + /// The `TRUSTED_PLATFORM_ASSEMBLIES` property: every managed assembly the + /// runtime ships, by full path. + /// + /// Doorstop does not pass this, and for simply *running* managed code it is + /// not needed - `APP_PATHS` probing covers that. It is needed the moment + /// anything asks the runtime where the platform assemblies are, because + /// nothing else answers that question: + /// + /// - `AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")` is exactly this + /// value, and returns null when it is not passed. + /// - Mono.Cecil resolves platform assemblies *only* from there + /// (`SearchTrustedPlatformAssemblies`). With it unset, Cecil cannot resolve + /// `System.Private.CoreLib`. + /// - Harmony builds delegate types through Cecil, so with it unset **every + /// Harmony patch of an IL2CPP method fails** with `IL Compile Error + /// (unknown location)` - a message that says nothing about any of this. + /// + /// Assemblies are listed runtime-first so that a name shipped by both the + /// runtime and the managed host resolves to the runtime's copy, which is the + /// same precedence `APP_PATHS` gives. + /// + /// Unreadable directories yield an empty contribution rather than an error: + /// a missing managed directory is already reported by the delegate lookup + /// with a far clearer message than anything available here. + #[must_use] + pub fn trusted_platform_assemblies(&self) -> String { + let mut paths: Vec = Vec::new(); + for dir in [&self.dotnet_dir, &self.managed_dir] { + let mut found = managed_assemblies_in(dir); + // Sorted so the property is byte-stable across launches; directory + // order is not guaranteed and a shifting value makes any + // resolution bug look intermittent. + found.sort(); + paths.extend(found); + } + paths.join(&APP_PATHS_SEPARATOR.to_string()) + } + + /// The `MODRIX_*` environment block the managed entrypoint reads instead of + /// re-deriving any of these paths itself. + /// + /// `game_assembly` is the mapped base of `GameAssembly.dll`. It is deliberately + /// NOT an IL2CPP domain pointer - obtaining one would mean calling into the + /// runtime from an unregistered thread, which aborts the game (see + /// `il2cpp.rs`). Managed code must attach to IL2CPP itself, on the main thread. + /// the log line renders it so the two can be eyeballed against each other. + #[must_use] + pub fn env_pairs(&self, game_assembly: usize) -> Vec<(&'static str, String)> { + vec![ + ("MODRIX_INITIALIZED", "TRUE".to_owned()), + ( + "MODRIX_PROCESS_PATH", + self.process_path.display().to_string(), + ), + ("MODRIX_GAME_ROOT", self.game_root.display().to_string()), + ("MODRIX_LOADER_DIR", self.loader_dir.display().to_string()), + ("MODRIX_GAME_ASSEMBLY", format_address(game_assembly)), + ] + } +} + +/// Full paths of every `.dll` directly inside `dir`, or empty if unreadable. +/// +/// Not recursive: CoreCLR's trusted list is a flat set of assemblies, and a +/// runtime layout nests only culture-specific satellites, which do not belong +/// on it. +fn managed_assemblies_in(dir: &Path) -> Vec { + let Ok(entries) = std::fs::read_dir(dir) else { + return Vec::new(); + }; + let mut found = Vec::new(); + for entry in entries.flatten() { + let path = entry.path(); + let is_dll = path + .extension() + .and_then(|ext| ext.to_str()) + .is_some_and(|ext| ext.eq_ignore_ascii_case("dll")); + if is_dll && path.is_file() { + found.push(path.display().to_string()); + } + } + found +} + +/// Renders a module base for logs and for `MODRIX_GAME_ASSEMBLY`. +#[must_use] +pub fn format_address(address: usize) -> String { + format!("0x{address:016x}") +} + +/// Reads the runtime version out of `mini-coreclr`'s `.version` stamp. +/// +/// The file is two lines - a commit hash then a version, e.g. `6.0.7` - so the +/// last non-empty line is the version. Returns `None` when the stamp is absent +/// or unreadable; the caller logs `unknown` rather than failing, because a +/// missing stamp does not stop the runtime from working. +#[must_use] +pub fn read_runtime_version(dotnet_dir: &Path) -> Option { + let raw = std::fs::read_to_string(dotnet_dir.join(VERSION_STAMP_NAME)).ok()?; + raw.lines() + .map(str::trim) + .rfind(|line| !line.is_empty()) + .map(str::to_owned) +} + +#[cfg(test)] +mod tests { + use super::{Layout, format_address, read_runtime_version}; + use std::path::PathBuf; + + fn layout() -> Layout { + Layout::from_process_path(PathBuf::from("/game/SonsOfTheForest.exe")).unwrap() + } + + #[test] + fn derives_every_directory_from_the_exe_path() { + let l = layout(); + assert_eq!(l.game_root(), PathBuf::from("/game")); + assert_eq!(l.loader_dir(), PathBuf::from("/game/_Modrix")); + assert_eq!(l.dotnet_dir(), PathBuf::from("/game/_Modrix/dotnet")); + assert_eq!(l.managed_dir(), PathBuf::from("/game/_Modrix/net6")); + assert_eq!(l.log_path(), PathBuf::from("/game/_Modrix/Latest.log")); + assert_eq!( + l.coreclr_path(), + PathBuf::from("/game/_Modrix/dotnet/coreclr.dll") + ); + } + + #[test] + fn log_path_matches_the_game_definition() { + // games/sonsoftheforest/game.toml declares `[launch] log = "_Modrix/Latest.log"`. + let l = layout(); + let relative = l + .log_path() + .strip_prefix(l.game_root()) + .unwrap() + .to_path_buf(); + assert_eq!(relative, PathBuf::from("_Modrix").join("Latest.log")); + } + + #[test] + fn app_paths_is_corlib_then_host_then_interop() { + let paths = layout().app_paths(); + let parts: Vec<&str> = paths.split(';').collect(); + assert_eq!(parts.len(), 3, "{paths}"); + assert!(parts.first().unwrap().ends_with("dotnet"), "{paths}"); + assert!(parts.get(1).unwrap().ends_with("net6"), "{paths}"); + // Without this a mod loads and then cannot resolve `Sons` or + // `UnityEngine.CoreModule` the instant it touches a game type. + assert!(parts.get(2).unwrap().ends_with("interop"), "{paths}"); + } + + #[test] + fn trusted_platform_assemblies_lists_runtime_then_host_dlls() { + // Without this property Cecil cannot resolve System.Private.CoreLib, and + // every Harmony patch of an IL2CPP method fails with a message that + // mentions neither Cecil nor this property. The ordering matters too: + // runtime first, so a name present in both resolves to the runtime copy. + let root = std::env::temp_dir().join("modrix-sons-proxy-tpa"); + let dotnet = root.join("_Modrix").join("dotnet"); + let net6 = root.join("_Modrix").join("net6"); + std::fs::create_dir_all(&dotnet).unwrap(); + std::fs::create_dir_all(&net6).unwrap(); + std::fs::write(dotnet.join("System.Private.CoreLib.dll"), b"x").unwrap(); + std::fs::write(dotnet.join("coreclr.dll"), b"x").unwrap(); + std::fs::write(net6.join("Modrix.Loader.dll"), b"x").unwrap(); + // Not an assembly: must not appear. + std::fs::write(net6.join("Modrix.Loader.deps.json"), b"{}").unwrap(); + + let layout = Layout::from_process_path(root.join("SonsOfTheForest.exe")).unwrap(); + let value = layout.trusted_platform_assemblies(); + let parts: Vec<&str> = value.split(';').collect(); + + assert_eq!(parts.len(), 3, "{value}"); + assert!( + parts.iter().all(|p| std::path::Path::new(p) + .extension() + .is_some_and(|ext| ext.eq_ignore_ascii_case("dll"))), + "{value}" + ); + assert!( + value.contains("System.Private.CoreLib.dll"), + "corlib is the whole point: {value}" + ); + assert!(!value.contains("deps.json"), "{value}"); + // Runtime entries precede host entries. + let corelib = value.find("System.Private.CoreLib.dll").unwrap(); + let loader = value.find("Modrix.Loader.dll").unwrap(); + assert!(corelib < loader, "{value}"); + + std::fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn trusted_platform_assemblies_is_empty_when_nothing_is_installed() { + let layout = + Layout::from_process_path(PathBuf::from("/nonexistent-modrix/SonsOfTheForest.exe")) + .unwrap(); + assert_eq!(layout.trusted_platform_assemblies(), ""); + } + + #[test] + fn only_the_unity_player_owns_the_game() { + // A version.dll beside the game is loaded by every PE started from that + // directory. Letting a helper process bootstrap truncates the real run's + // log and then blocks two minutes waiting for GameAssembly.dll. + let root = std::env::temp_dir().join("modrix-sons-proxy-owns"); + std::fs::create_dir_all(root.join("SonsOfTheForest_Data")).unwrap(); + + let player = Layout::from_process_path(root.join("SonsOfTheForest.exe")).unwrap(); + assert!(player.owns_game(), "the Unity player must own the game"); + + // Same directory, no matching _Data folder: a helper, not the player. + let helper = Layout::from_process_path(root.join("steamerrorreporter64.exe")).unwrap(); + assert!(!helper.owns_game(), "a helper process must not bootstrap"); + + std::fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn a_bare_file_name_has_no_game_root() { + assert!(Layout::from_process_path(PathBuf::from("/")).is_err()); + } + + #[test] + fn env_pairs_cover_the_documented_five() { + let pairs = layout().env_pairs(0x0000_7ffb_1234_5678); + let names: Vec<&str> = pairs.iter().map(|(n, _)| *n).collect(); + assert_eq!( + names, + [ + "MODRIX_INITIALIZED", + "MODRIX_PROCESS_PATH", + "MODRIX_GAME_ROOT", + "MODRIX_LOADER_DIR", + "MODRIX_GAME_ASSEMBLY" + ] + ); + assert_eq!(pairs.first().unwrap().1, "TRUE"); + assert_eq!(pairs.get(4).unwrap().1, "0x00007ffb12345678"); + } + + #[test] + fn domain_is_zero_padded_hex() { + assert_eq!(format_address(0), "0x0000000000000000"); + assert_eq!(format_address(1), "0x0000000000000001"); + } + + #[test] + fn runtime_version_is_the_last_non_empty_line_of_the_stamp() { + // Byte-for-byte what `mini-coreclr-Release.zip` 6.0.7 ships in + // `win-x64/.version`, CRLF included - checked with `od -c`. A naive + // `read_to_string().trim()` would yield the commit hash, not the version. + let dir = std::env::temp_dir().join("modrix-sons-proxy-version-stamp"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write( + dir.join(super::VERSION_STAMP_NAME), + "0ec02c8c96e2eda06dc5b5edfdbdba0f36415082\r\n6.0.7\r\n", + ) + .unwrap(); + assert_eq!(read_runtime_version(&dir).as_deref(), Some("6.0.7")); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn missing_runtime_stamp_is_not_an_error() { + assert_eq!( + read_runtime_version(&PathBuf::from("/nonexistent-modrix-dir")), + None + ); + } +} diff --git a/loaders/sons-proxy/src/lib.rs b/loaders/sons-proxy/src/lib.rs new file mode 100644 index 0000000..e408e2f --- /dev/null +++ b/loaders/sons-proxy/src/lib.rs @@ -0,0 +1,287 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! `version.dll` proxy that boots a .NET 6 runtime inside Sons of the Forest. +//! +//! # What this is +//! +//! Sons of the Forest is an IL2CPP Unity build: its C# was compiled ahead of +//! time to native code, so there is no `Assembly-CSharp.dll` to patch and +//! nothing for a file-copying mod manager to do. Making it moddable at all +//! requires getting code into the running process. `UnityPlayer.dll` imports +//! `VERSION.dll`, so a DLL of that name next to the game executable is loaded by +//! Windows before the game's first frame. This crate is that DLL. +//! +//! # Milestone M0 - and only M0 +//! +//! This crate proves one claim: **managed .NET code can run inside the game, and +//! the game still plays**. The chain is +//! +//! 1. `DLL_PROCESS_ATTACH` - forward our seventeen exports to the real +//! `version.dll` so the game is unaffected, and fix the working directory, +//! which Steam does not set to the game folder. +//! 2. A spawned thread waits for `GameAssembly.dll` to export a non-null +//! `il2cpp_domain_get()`. No hooking - see [`il2cpp`]. +//! 3. `coreclr_initialize` + `coreclr_create_delegate` against the vendored +//! runtime in `_Modrix/dotnet` - see [`coreclr`]. +//! 4. `Modrix.Loader.Entrypoint.Start()` writes the last line of +//! `_Modrix/Latest.log`. +//! +//! Deliberately **not** here: `Il2CppInterop`, Dobby or any detour, +//! `il2cpp_runtime_invoke` hooking, the `Internal_ActiveSceneChanged` trigger, +//! mod discovery, `manifest.json`, the SDK, and installation. Those are M1-M3. +//! +//! # The unsafe policy +//! +//! The main Modrix workspace sets `unsafe_code = "forbid"`, and this crate is +//! outside it precisely so that stays true. In exchange, the rules here are +//! stricter than "unsafe is allowed": +//! +//! - `undocumented_unsafe_blocks` and `multiple_unsafe_ops_per_block` are +//! **deny**, so every `unsafe` block does exactly one thing and says why it is +//! sound. +//! - All FFI is confined to [`win`]; the rest of the crate is ordinary Rust. +//! - `panic = "abort"` in every profile, because unwinding into Unity's stack is +//! undefined behaviour. Fallible paths return `Result` and log. +//! - `unwrap_used`, `panic`, `indexing_slicing` are denied exactly as in the +//! main workspace. +//! +//! # Nothing here fails loudly on its own +//! +//! A DLL that fails inside a game process has no console, no stderr and no +//! dialog. Every step therefore reports into `_Modrix/Latest.log` and every +//! failure is swallowed after being logged: a broken loader must leave a +//! playable game behind, not a crash. + +pub mod error; +pub mod exports; +pub mod layout; +pub mod log; + +#[cfg(windows)] +pub(crate) mod coreclr; +#[cfg(windows)] +pub(crate) mod il2cpp; +#[cfg(windows)] +pub(crate) mod proxy; +#[cfg(windows)] +pub(crate) mod win; + +#[cfg(windows)] +pub use attach::DllMain; + +#[cfg(windows)] +mod attach { + use crate::error::Error; + use crate::layout::Layout; + use core::ffi::c_void; + use core::time::Duration; + use windows_sys::Win32::Foundation::{BOOL, HMODULE, TRUE}; + + /// `fdwReason` value Windows passes when the DLL is first mapped. + const DLL_PROCESS_ATTACH: u32 = 1; + + /// How long to wait for IL2CPP. Sons of the Forest reaches `il2cpp_init` in + /// a few seconds; two minutes covers a cold Proton prefix on a slow disk + /// without hanging a thread for the life of the process. + const IL2CPP_TIMEOUT: Duration = Duration::from_mins(2); + /// Poll spacing. `il2cpp_domain_get` is a static read, so this is cheap. + const IL2CPP_POLL: Duration = Duration::from_millis(100); + + /// How far the proxy is allowed to get, for bisecting a startup crash. + /// + /// Injecting into a game means a fault shows up as "the game closed", with + /// no stack and no message. Rather than guess which step is at fault, set + /// `MODRIX_PROXY_STAGE` and let the log say how far it got: + /// + /// | value | stops after | + /// |-------|-------------| + /// | 0 | forwarding the exports (proves the thunks are safe) | + /// | 1 | + fixing the working directory | + /// | 2 | + spawning the bootstrap thread | + /// | 3 | + waiting for `GameAssembly.dll` to be mapped | + /// | 4 | + calling `il2cpp_domain_get` | + /// | 5 | everything (the default) | + fn stage() -> u8 { + std::env::var("MODRIX_PROXY_STAGE") + .ok() + .and_then(|raw| raw.trim().parse::().ok()) + .unwrap_or(5) + } + + /// DLL entry point. + /// + /// Reached through mingw's `DllMainCRTStartup`, which is the PE entry point + /// of the produced binary - verified by disassembling the cross-compiled + /// DLL, not assumed. + /// + /// Only export forwarding and the working-directory fix happen here. Loading + /// CoreCLR under the loader lock would be asking for a deadlock, so the real + /// work is moved to a spawned thread that also gives the game time to bring + /// IL2CPP up. + /// + /// # Safety + /// + /// Called by the Windows loader with the module's own instance handle. Never + /// call it from Rust. + #[unsafe(no_mangle)] + pub unsafe extern "system" fn DllMain( + instance: HMODULE, + reason: u32, + _reserved: *mut c_void, + ) -> BOOL { + if reason == DLL_PROCESS_ATTACH { + on_process_attach(instance); + } + // Returning FALSE would fail the load and take the game with it. Every + // failure above has already been logged. + TRUE + } + + /// Everything that must happen before the game's first import call. + fn on_process_attach(instance: HMODULE) { + let Ok(process_path) = std::env::current_exe() else { + return; + }; + let Ok(layout) = Layout::from_process_path(process_path) else { + return; + }; + // Only the game's own process may bootstrap, but EVERY process that loads + // this DLL must still get its exports forwarded - it may have loaded us + // because it genuinely wanted `version.dll`. So the export forwarding + // below is unconditional and only the loader work is gated. + // + // Without the gate, each of the several other PEs Proton starts from this + // directory truncates `Latest.log` and then blocks 120 seconds waiting for + // a `GameAssembly.dll` it will never map. See `Layout::owns_game`. + let owns_game = layout.owns_game(); + let log_path = layout.log_path(); + if owns_game { + crate::log::reset(&log_path); + } + + let stage = stage(); + let log = |message: &str| { + if owns_game { + crate::log::line(&log_path, message); + } + }; + log(&format!("stage limit = {stage}")); + + // Doorstop's `fix_cwd`. Under Steam the working directory is Steam's, + // not the game's, so every relative path the loader touches would + // resolve somewhere else entirely. Only ours to change - moving another + // process's working directory is not the proxy's business. + if owns_game + && stage >= 1 + && let Err(err) = std::env::set_current_dir(layout.game_root()) + { + log(&format!("WARN cannot set working directory: {err}")); + } + + match crate::proxy::install(instance, layout.game_root()) { + Ok(attached) => { + log(&crate::log::proxy_attached(&attached.slot, &attached.real)); + if !attached.missing.is_empty() { + let names = attached.missing.join(", "); + log(&format!("WARN unresolved exports: {names}")); + } + } + // The game may still run - it only calls a couple of these APIs - + // so this is reported, not fatal. + Err(err) => log(&format!("ERROR proxy attach failed: {err}")), + } + + if !owns_game { + return; + } + + log("stage 1 ok (cwd)"); + if stage < 2 { + log("stopping: stage < 2"); + return; + } + spawn_bootstrap(layout); + } + + /// Moves the runtime work off the loader lock. + /// + /// The handle is dropped deliberately: this thread outlives the caller and + /// nothing joins it. + fn spawn_bootstrap(layout: Layout) { + let log_path = layout.log_path(); + let spawned = std::thread::Builder::new() + .name("modrix-bootstrap".to_owned()) + .spawn(move || run_bootstrap(&layout)); + if let Err(err) = spawned { + crate::log::line( + &log_path, + &format!("ERROR cannot spawn bootstrap thread: {err}"), + ); + } + } + + /// Bootstrap thread body. Logs its own failure and returns; the game plays on. + fn run_bootstrap(layout: &Layout) { + let log_path = layout.log_path(); + if let Some(wine) = crate::win::wine_version() { + crate::log::line(&log_path, &format!("host = wine {wine}")); + } + if let Err(err) = bootstrap(layout) { + crate::log::line(&log_path, &format!("ERROR bootstrap failed: {err}")); + } + } + + /// Wait for IL2CPP, publish the environment, start CoreCLR, hand off. + fn bootstrap(layout: &Layout) -> Result<(), Error> { + let log_path = layout.log_path(); + let stage = stage(); + crate::log::line(&log_path, "stage 2 ok (bootstrap thread)"); + + if stage < 3 { + crate::log::line(&log_path, "stopping: stage < 3"); + return Ok(()); + } + + // Wait for the module, and then do NOT call into it. + // + // The obvious readiness probe - poll `il2cpp_domain_get` until it + // returns non-null - kills the game. IL2CPP's garbage collector tracks + // the threads it knows about, and any call that reaches the runtime + // from a thread it never registered aborts the process with + // "Collecting from unknown thread". Our bootstrap thread is by + // definition unknown to it: the GC was initialised before we existed, + // and attaching requires a domain we would have to call in to obtain. + // + // Waiting longer does not help - this is not a timing problem. The + // thread is wrong, not early. + // + // Nothing here actually needs the domain. CoreCLR hosting is entirely + // independent of IL2CPP, so the fix is simply to stop asking: wait for + // the module to prove the game is up (a pure `GetModuleHandleW` loop + // that touches nothing), then start the runtime. Managed code that + // wants IL2CPP attaches properly, from the main thread, later. + let game_assembly = + crate::il2cpp::wait_for_module(IL2CPP_TIMEOUT, IL2CPP_POLL).ok_or(Error::Timeout { + what: "GameAssembly.dll module", + secs: IL2CPP_TIMEOUT.as_secs(), + })?; + crate::log::line(&log_path, &crate::log::game_assembly_mapped(game_assembly)); + + if stage < 4 { + crate::log::line(&log_path, "stopping: stage < 4"); + return Ok(()); + } + + // Published before the delegate call so the managed side never has to + // re-derive a path, and never disagrees with the native side about one. + for (name, value) in layout.env_pairs(game_assembly) { + crate::win::set_env(name, &value)?; + } + + let host = crate::coreclr::start(layout)?; + let version = crate::layout::read_runtime_version(layout.dotnet_dir()) + .unwrap_or_else(|| "unknown".to_owned()); + crate::log::line(&log_path, &crate::log::coreclr_up(&version)); + + host.run_managed_entrypoint() + } +} diff --git a/loaders/sons-proxy/src/log.rs b/loaders/sons-proxy/src/log.rs new file mode 100644 index 0000000..85a4d50 --- /dev/null +++ b/loaders/sons-proxy/src/log.rs @@ -0,0 +1,166 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! `_Modrix/Latest.log` - the only diagnostic channel the proxy has. +//! +//! There is no console. Under Proton a failure inside `DllMain` closes the game +//! with no window, no stderr and no crash dump, so anything that is not written +//! to this file did not happen as far as the user is concerned. Every write is +//! therefore best-effort and never propagates an error: failing to log must not +//! be the reason the game dies. +//! +//! Native code writes the first three milestone lines; the managed entrypoint +//! appends the fourth. Both open the file in append mode, and native writing +//! stops before the managed call, so the two never interleave. + +use crate::layout::PREVIOUS_LOG_FILE_NAME; +use std::fmt::Write as _; +use std::io::Write as _; +use std::path::Path; + +/// Prefix every line the loader emits carries, so the log can be grepped and so +/// lines from the game's own stdout redirection are distinguishable. +pub const TAG: &str = "[modrix]"; + +/// Rotates the log to `Previous.log`, truncates it, and ensures its parent exists. +/// +/// Called once, at `DLL_PROCESS_ATTACH`. +pub fn reset(path: &Path) { + if let Some(parent) = path.parent() { + let _ = std::fs::create_dir_all(parent); + } + // Keep one generation. The reason is not tidiness: when the loader takes the + // game down, the run that explains why is the one being overwritten right + // now - and the game is relaunched often enough (Steam, Proton, a crash + // handler) that the evidence is gone before anyone can read it. Whatever + // killed the previous run is in Previous.log. + if path.is_file() { + let previous = path.with_file_name(PREVIOUS_LOG_FILE_NAME); + let _ = std::fs::rename(path, previous); + } + let _ = std::fs::write(path, b""); +} + +/// Appends one tagged line. Best-effort; a failure is silently dropped. +pub fn line(path: &Path, message: &str) { + let mut record = + String::with_capacity(TAG.len().saturating_add(message.len()).saturating_add(2)); + let _ = writeln!(record, "{TAG} {message}"); + let opened = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(path); + if let Ok(mut file) = opened { + let _ = file.write_all(record.as_bytes()); + let _ = file.flush(); + } +} + +/// Milestone 1: the proxy is loaded and the real system DLL is behind it. +/// +/// `slot` is our own file name (`version.dll`), derived rather than assumed, so +/// the same binary dropped in as `winhttp.dll` reports the truth. +#[must_use] +pub fn proxy_attached(slot: &str, real: &Path) -> String { + format!("proxy attached, real {slot} = {}", real.display()) +} + +/// Milestone 2: the game's IL2CPP module is mapped. +/// +/// Deliberately reports the module base rather than an IL2CPP domain. Fetching +/// a domain means calling `il2cpp_domain_get`, and doing that from the +/// bootstrap thread aborts the game with "Collecting from unknown thread" - the +/// runtime's GC rejects calls from threads it never registered. See `il2cpp.rs` +/// for the bisection that established this. +/// +/// So this proves only "the game is up far enough to host a runtime", which is +/// all the proxy needs. It does *not* prove we are ahead of the game, which is +/// what intercepting `il2cpp_init` would buy. +#[must_use] +pub fn game_assembly_mapped(base: usize) -> String { + format!( + "GameAssembly.dll mapped at {} (no runtime call made)", + crate::layout::format_address(base) + ) +} + +/// Milestone 3: CoreCLR initialized and a delegate to managed code exists. +#[must_use] +pub fn coreclr_up(runtime_version: &str) -> String { + format!("coreclr up, runtime = {runtime_version}") +} + +#[cfg(test)] +mod tests { + use super::{TAG, coreclr_up, game_assembly_mapped, line, proxy_attached, reset}; + use std::path::{Path, PathBuf}; + + fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir() + .join("modrix-sons-proxy-log") + .join(name); + let _ = std::fs::remove_dir_all(&dir); + dir.join("_Modrix").join("Latest.log") + } + + #[test] + fn reset_creates_the_loader_directory_and_empties_the_file() { + let path = scratch("reset"); + line(&path, "written before reset"); + reset(&path); + assert!(path.parent().unwrap().is_dir()); + assert_eq!(std::fs::read_to_string(&path).unwrap(), ""); + std::fs::remove_dir_all(path.parent().unwrap().parent().unwrap()).unwrap(); + } + + #[test] + fn reset_keeps_the_previous_run_alongside() { + // When the loader kills the game, Steam relaunches it and the next + // attach truncates the only record of why. One generation is kept so the + // failing run is still readable afterwards. + let path = scratch("rotate"); + // `reset` first, because `line` is a no-op until the directory exists - + // in production `reset` always runs at DLL_PROCESS_ATTACH before any + // line is written, so this mirrors the real order. + reset(&path); + line(&path, "the run that crashed"); + reset(&path); + let previous = path.with_file_name("Previous.log"); + assert!(previous.is_file(), "Previous.log was not created"); + assert!( + std::fs::read_to_string(&previous) + .unwrap() + .contains("the run that crashed") + ); + assert_eq!(std::fs::read_to_string(&path).unwrap(), ""); + std::fs::remove_dir_all(path.parent().unwrap().parent().unwrap()).unwrap(); + } + + #[test] + fn lines_are_tagged_appended_and_newline_terminated() { + let path = scratch("append"); + reset(&path); + line(&path, "first"); + line(&path, "second"); + let body = std::fs::read_to_string(&path).unwrap(); + assert_eq!(body, format!("{TAG} first\n{TAG} second\n")); + std::fs::remove_dir_all(path.parent().unwrap().parent().unwrap()).unwrap(); + } + + #[test] + fn logging_to_an_unwritable_path_does_not_panic() { + // A directory is never openable as a file; the write must be swallowed. + line(Path::new("/"), "this cannot be written"); + } + + #[test] + fn milestone_lines_match_the_documented_acceptance_text() { + assert_eq!( + proxy_attached("version.dll", Path::new("C:/windows/system32/version.dll")), + "proxy attached, real version.dll = C:/windows/system32/version.dll" + ); + assert_eq!( + game_assembly_mapped(0x0000_7ffb_1234_5678), + "GameAssembly.dll mapped at 0x00007ffb12345678 (no runtime call made)" + ); + assert_eq!(coreclr_up("6.0.7"), "coreclr up, runtime = 6.0.7"); + } +} diff --git a/loaders/sons-proxy/src/proxy.rs b/loaders/sons-proxy/src/proxy.rs new file mode 100644 index 0000000..3e7ecd3 --- /dev/null +++ b/loaders/sons-proxy/src/proxy.rs @@ -0,0 +1,98 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Finding the DLL we are standing in front of, and binding our exports to it. +//! +//! The slot name is derived from our own file name rather than hard-coded, so +//! the same binary works when dropped in as `winhttp.dll` or `winmm.dll` - both +//! of which `UnityPlayer.dll` also imports. Only the `version.dll` export set is +//! compiled in today, so another slot forwards nothing; the derived name is what +//! makes that visible in the log instead of mysterious. + +use crate::error::Error; +use crate::exports::{EXPORT_NAMES, SLOTS}; +use core::sync::atomic::Ordering; +use std::path::{Path, PathBuf}; +use windows_sys::Win32::Foundation::HMODULE; + +/// Outcome of a successful attach. +pub struct Attached { + /// Our own file name, e.g. `version.dll`. + pub slot: String, + /// The real DLL now backing our exports. + pub real: PathBuf, + /// Export names the real DLL did not provide. Empty in every healthy case. + pub missing: Vec<&'static str>, +} + +/// Resolves the real DLL behind this proxy and points every export thunk at it. +/// +/// Search order, matching what Doorstop and MelonLoader between them establish: +/// a user-supplied `_original.dll` or `_alt.dll` in the game +/// directory first, so the proxy can be chained in front of another loader, then +/// `%SystemDirectory%\.dll`. Our own file is skipped, since loading it +/// would bind every export back to these thunks and hang the first caller. +/// +/// # Errors +/// +/// Returns [`Error::Win32`] if our own module path cannot be read or the real +/// DLL cannot be loaded, and [`Error::Missing`] if no candidate exists. +pub fn install(self_module: HMODULE, game_root: &Path) -> Result { + let own = crate::win::module_file_name(self_module)?; + let slot = own.file_name().map_or_else( + || "version.dll".to_owned(), + |name| name.to_string_lossy().into_owned(), + ); + let stem = own.file_stem().map_or_else( + || "version".to_owned(), + |name| name.to_string_lossy().into_owned(), + ); + + let real = resolve_real_path(&own, &stem, game_root)?; + let handle = crate::win::load_library(&real)?; + let missing = bind_exports(handle); + Ok(Attached { + slot, + real, + missing, + }) +} + +/// Picks the first candidate that exists on disk and is not this very file. +fn resolve_real_path(own: &Path, stem: &str, game_root: &Path) -> Result { + let system = crate::win::system_directory()?; + let candidates = [ + game_root.join(format!("{stem}_original.dll")), + game_root.join(format!("{stem}_alt.dll")), + system.join(format!("{stem}.dll")), + ]; + let own_key = path_key(own); + for candidate in &candidates { + if path_key(candidate) != own_key && candidate.is_file() { + return Ok(candidate.clone()); + } + } + Err(Error::Missing { + what: "real proxy target", + path: system.join(format!("{stem}.dll")), + }) +} + +/// Windows paths are case-insensitive; comparing raw strings would let us load +/// ourselves whenever Wine or Steam hands back different casing. +fn path_key(path: &Path) -> String { + path.to_string_lossy().to_lowercase().replace('/', "\\") +} + +/// Writes each resolved export address into its slot, returning the misses. +fn bind_exports(handle: HMODULE) -> Vec<&'static str> { + let mut missing = Vec::new(); + for (index, name) in EXPORT_NAMES.iter().enumerate() { + let Some(slot) = SLOTS.get(index) else { + continue; + }; + match crate::win::proc_address(handle, name) { + Some(address) => slot.store(address, Ordering::SeqCst), + None => missing.push(*name), + } + } + missing +} diff --git a/loaders/sons-proxy/src/win.rs b/loaders/sons-proxy/src/win.rs new file mode 100644 index 0000000..5148cd5 --- /dev/null +++ b/loaders/sons-proxy/src/win.rs @@ -0,0 +1,201 @@ +// SPDX-License-Identifier: GPL-2.0-only +//! Thin, checked wrappers over the handful of Win32 calls the proxy needs. +//! +//! Everything `unsafe` in this crate that is not an export thunk lives here, so +//! there is exactly one file to audit for FFI mistakes. Each wrapper converts a +//! Win32 failure into [`Error`] with the call's name attached, because a bare +//! `GetLastError` number in a log is not actionable. +//! +//! Nothing in here allocates on behalf of Windows: buffers are Rust `Vec` +//! and every loop is bounded. + +use crate::error::Error; +use std::ffi::OsString; +use std::os::windows::ffi::{OsStrExt as _, OsStringExt as _}; +use std::path::{Path, PathBuf}; + +use windows_sys::Win32::Foundation::{GetLastError, HMODULE}; +use windows_sys::Win32::System::Environment::SetEnvironmentVariableW; +use windows_sys::Win32::System::LibraryLoader::{ + GetModuleFileNameW, GetModuleHandleW, GetProcAddress, LoadLibraryW, +}; +use windows_sys::Win32::System::SystemInformation::GetSystemDirectoryW; + +/// Longest path we will accept from Windows, in UTF-16 code units. +/// +/// `\\?\`-prefixed paths reach 32,767; the loop below starts small and grows to +/// this, which is a hard bound rather than "until it fits". +const MAX_PATH_UNITS: usize = 32_768; + +/// Encodes a Rust string as a NUL-terminated UTF-16 buffer for the `*W` APIs. +fn wide(text: &str) -> Vec { + std::ffi::OsStr::new(text) + .encode_wide() + .chain(std::iter::once(0)) + .collect() +} + +/// Encodes a path as a NUL-terminated UTF-16 buffer. +fn wide_path(path: &Path) -> Vec { + path.as_os_str() + .encode_wide() + .chain(std::iter::once(0)) + .collect() +} + +/// Encodes an ASCII symbol name as a NUL-terminated byte buffer for +/// `GetProcAddress`, which is ANSI-only. +fn ansi(symbol: &str) -> Vec { + let mut bytes = symbol.as_bytes().to_vec(); + bytes.push(0); + bytes +} + +/// The last Win32 error, as an [`Error`] naming the call that produced it. +fn last_error(op: &'static str) -> Error { + // SAFETY: `GetLastError` reads thread-local state, takes no arguments and + // has no failure mode. + let code = unsafe { GetLastError() }; + Error::Win32 { op, code } +} + +/// Full path of a loaded module. Pass the `DllMain` instance handle to learn our +/// own file name, which is what decides which proxy slot we are occupying. +/// +/// # Errors +/// +/// Returns [`Error::Win32`] if `GetModuleFileNameW` fails or if the path is +/// longer than [`MAX_PATH_UNITS`]. +pub fn module_file_name(module: HMODULE) -> Result { + let mut capacity: usize = 260; + // Bounded: capacity doubles from 260, so at most 8 iterations to 32768. + for _ in 0..8 { + let mut buffer = vec![0u16; capacity]; + let request = u32::try_from(capacity).unwrap_or(u32::MAX); + // SAFETY: `buffer` owns `capacity` writable u16s and `request` is that + // same count, so the call cannot write out of bounds. + let written = unsafe { GetModuleFileNameW(module, buffer.as_mut_ptr(), request) }; + let written = usize::try_from(written).unwrap_or(0); + if written == 0 { + return Err(last_error("GetModuleFileNameW")); + } + if written < capacity { + buffer.truncate(written); + return Ok(PathBuf::from(OsString::from_wide(&buffer))); + } + capacity = capacity.saturating_mul(2).min(MAX_PATH_UNITS); + } + Err(Error::Win32 { + op: "GetModuleFileNameW", + code: 0, + }) +} + +/// `%SystemDirectory%`, i.e. where the genuine `version.dll` lives. +/// +/// # Errors +/// +/// Returns [`Error::Win32`] if `GetSystemDirectoryW` fails or reports a path +/// longer than [`MAX_PATH_UNITS`]. +pub fn system_directory() -> Result { + let mut buffer = vec![0u16; MAX_PATH_UNITS]; + let request = u32::try_from(buffer.len()).unwrap_or(u32::MAX); + // SAFETY: `buffer` owns `request` writable u16s. + let written = unsafe { GetSystemDirectoryW(buffer.as_mut_ptr(), request) }; + let written = usize::try_from(written).unwrap_or(0); + if written == 0 || written >= buffer.len() { + return Err(last_error("GetSystemDirectoryW")); + } + buffer.truncate(written); + Ok(PathBuf::from(OsString::from_wide(&buffer))) +} + +/// Loads a DLL by absolute path. +/// +/// # Errors +/// +/// Returns [`Error::Win32`] with the `LoadLibraryW` failure code. +pub fn load_library(path: &Path) -> Result { + let encoded = wide_path(path); + // SAFETY: `encoded` is NUL-terminated and outlives the call. + let handle = unsafe { LoadLibraryW(encoded.as_ptr()) }; + if handle.is_null() { + Err(last_error("LoadLibraryW")) + } else { + Ok(handle) + } +} + +/// Handle of an already-loaded module, or `None` if it is not loaded yet. +/// +/// Does not take a reference on the module and does not load it - which is +/// exactly what the IL2CPP poll needs. +#[must_use] +pub fn module_handle(name: &str) -> Option { + let encoded = wide(name); + // SAFETY: `encoded` is NUL-terminated and outlives the call. + let handle = unsafe { GetModuleHandleW(encoded.as_ptr()) }; + if handle.is_null() { None } else { Some(handle) } +} + +/// Address of an exported symbol, or `None` when the module does not export it. +/// +/// Returned as `usize` rather than a typed pointer so the caller has to name the +/// signature it is transmuting to at the point of use. +#[must_use] +pub fn proc_address(module: HMODULE, symbol: &str) -> Option { + let encoded = ansi(symbol); + // SAFETY: `encoded` is a NUL-terminated ANSI name that outlives the call, + // and `module` came from `LoadLibraryW`/`GetModuleHandleW`. + let found = unsafe { GetProcAddress(module, encoded.as_ptr()) }; + found.map(|address| address as usize) +} + +/// Sets a process environment variable in the Win32 environment block. +/// +/// Used rather than [`std::env::set_var`] because CoreCLR and the managed side +/// both read through `GetEnvironmentVariableW`, and because Rust's wrapper +/// carries a stricter safety contract about concurrent `getenv` that we cannot +/// honour inside a running game. +/// +/// # Errors +/// +/// Returns [`Error::Win32`] with the `SetEnvironmentVariableW` failure code. +pub fn set_env(name: &str, value: &str) -> Result<(), Error> { + let name_w = wide(name); + let value_w = wide(value); + // SAFETY: both buffers are NUL-terminated and outlive the call. The write + // races only with other threads reading the same variable; nothing in the + // game reads MODRIX_* and the managed side only reads it after this returns. + let ok = unsafe { SetEnvironmentVariableW(name_w.as_ptr(), value_w.as_ptr()) }; + if ok == 0 { + Err(last_error("SetEnvironmentVariableW")) + } else { + Ok(()) + } +} + +/// Wine's version string, or `None` on real Windows. +/// +/// `ntdll!wine_get_version` is the same probe RedLoader uses. It is logged +/// rather than acted on: CoreCLR's behaviour under Wine is the largest unknown +/// in M0, and knowing the exact Wine/Proton build from the user's own log is the +/// difference between a diagnosis and a guess. +#[must_use] +pub fn wine_version() -> Option { + type WineGetVersion = unsafe extern "system" fn() -> *const u8; + let ntdll = module_handle("ntdll.dll")?; + let address = proc_address(ntdll, "wine_get_version")?; + // SAFETY: the symbol exists in this ntdll, and Wine documents it as a + // no-argument function returning a static NUL-terminated ASCII string. + let get_version = unsafe { core::mem::transmute::(address) }; + // SAFETY: calling the function just resolved, with its documented signature. + let raw = unsafe { get_version() }; + if raw.is_null() { + return None; + } + // SAFETY: Wine returns a pointer to a static NUL-terminated string that + // lives for the life of the process. + let text = unsafe { core::ffi::CStr::from_ptr(raw.cast()) }; + Some(text.to_string_lossy().into_owned()) +} diff --git a/rust-toolchain.toml b/rust-toolchain.toml index f1d05fb..7ebf9af 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -2,5 +2,5 @@ # Pinned toolchain: strict lints change between releases, so we pin to keep CI # reproducible. Bump deliberately. [toolchain] -channel = "1.96.0" +channel = "1.99.1" components = ["clippy", "rustfmt"] diff --git a/skills/modrix-usage/SKILL.md b/skills/modrix-usage/SKILL.md index 6d5d4d1..997662c 100644 --- a/skills/modrix-usage/SKILL.md +++ b/skills/modrix-usage/SKILL.md @@ -34,6 +34,36 @@ engine, same data. 5. Plugin games: `plugins auto-sort`, then review `plugins list`. 6. `deploy` → `verify`. Report the numbers. +## Launching and testing a change + +Some games declare how to start themselves and which mod loader they need. +`game capabilities` reports `launch` and `mod_loader`; when either is false the +commands below do not apply to that game and will say so. + +1. `loader status` / `loader_status` - **check this before anything else on a + loader game.** It reports whether the loader is installed, whether interop + assemblies exist, and whether a *rival* loader occupies the proxy slot. A + game has exactly one such slot, so two loaders never coexist: installing over + one silently breaks both. If `conflict` is set, stop and tell the user which + loader is in the way rather than working around it. +2. `deploy` → `launch` (or `deploy_and_launch` / `modrix launch --deploy`) to + push a change and start the game in one step. +3. `log --since ` / `read_game_log` to watch it boot. Pass the returned + `next_cursor` back as `since` to follow along without re-reading. A + `truncated: true` result means the game restarted and the log began again - + reset your view, do not treat it as corruption. + +**On Linux and macOS, read the launch warning.** Windows-only games run under +Proton/Wine, where a loader's proxy DLL is ignored unless the game's Steam +launch options carry the environment the definition asks for (typically +`WINEDLLOVERRIDES="version=n,b" %command%`). Modrix cannot inject it, because +Steam owns the game process. Without it the game starts perfectly and **no mods +load, with no error** - so if a user reports "my mods stopped working" on Linux, +check `launch`'s `readiness` before investigating anything else. + +`launch` is fire-and-forget: it returns as soon as the game is handed off, not +when the game is ready. Poll the log if you need to know it actually started. + ## Rules of engagement - Never edit the game directory by hand; hand-placed files show up as