diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md index 0789449..0987c34 100644 --- a/.github/CODE_OF_CONDUCT.md +++ b/.github/CODE_OF_CONDUCT.md @@ -1,23 +1,15 @@ # Code of Conduct -Bullet follows the [Contributor Covenant, version 2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/). +Bullet follows the [Contributor Covenant v2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/). -## In short +## Standards -- Be respectful and welcoming, whatever someone's experience, background or identity. -- Discuss ideas, not people. Criticism is fine; insults, harassment and personal attacks are not. -- No sharing of other people's private information, accounts or credentials. -- Do not use this project or its community to cheat against, harass or harm other players. -- Keep discussion of bans, anti-cheat evasion or account trading out of the project spaces. +- Be respectful and welcoming regardless of experience or background. +- Critique code and ideas, never people. Harassment, insults, and personal attacks are not tolerated. +- Never share private data, accounts, or credentials. +- Do not use Bullet or community spaces to harass players, bypass anti-cheat, or discuss account trading. -## Scope +## Scope & Reporting -This applies to the GitHub repository (issues, pull requests, discussions) and to the -[Bullet Discord](https://discord.gg/e2dH2nUjd9). - -## Enforcement - -Report unacceptable behavior privately to the maintainer, Isllan Toso, through [isllan.dev](https://isllan.dev/), or -through a [private security advisory](https://github.com/Isllanrx/Bullet/security/advisories/new) if it involves a -security issue. Reports are handled confidentially. Maintainers may remove content and warn, suspend or ban -participants, following the enforcement guidelines of the Contributor Covenant. +Applies across GitHub (issues, PRs, discussions) and the [Bullet Discord](https://discord.gg/e2dH2nUjd9). +Report violations privately via [isllan.dev](https://isllan.dev/) or a [private security advisory](https://github.com/Isllanrx/Bullet/security/advisories/new). Maintainers handle reports confidentially and may warn, suspend, or ban violators. diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 78c1962..e0a9de1 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -1,61 +1,30 @@ # Contributing to Bullet -Thanks for helping. Bullet is a small project with a high bar for anything that touches the game, so this -page explains what makes a contribution easy to accept. - -## Before you start - -- **Questions and ideas:** ask on [Discord](https://discord.gg/e2dH2nUjd9) first. A quick chat often saves a - pull request that heads in the wrong direction. -- **Bugs:** open an issue with the bug template and **attach the log** from `%LOCALAPPDATA%\Bullet\logs` for - the match where it failed. -- **Security issues:** never in public. See [SECURITY.md](SECURITY.md). - -## Development setup - -1. Windows 10/11 x64, [Rust](https://rustup.rs) (the toolchain in `rust-toolchain.toml` installs itself) and, - for the installer, [Inno Setup 6](https://jrsoftware.org/isinfo.php). -2. `cargo build` and `cargo xtask check` must pass before you open a pull request, and `cargo deny check` too - when dependencies changed. -3. Read the README of the crate you are changing (`crates//README.md`) and the relevant page in - [`docs/`](../docs/README.md). - -## Rules the code follows - -- No `unwrap()` or `expect()` outside tests. Errors are handled or propagated with context. -- Every discarded `Result` (`let _ = …`) carries `// ignore-ok: `. -- Background tasks go through the `Supervisor`, never a bare `tokio::spawn`. -- The shared state only changes through the named transitions in `bullet-core::state`. -- Binary parsing checks every offset; bad input returns a typed error and never panics. -- Code, logs and docs are in English. Text shown to users goes through the translation tables. -- No comments in code files (Rust, HTML/CSS/JS, TypeScript, YAML, TOML, the installer script). Names, types - and tests say what the code does; the reason behind it goes in `docs/`, the crate README or a decision - record. The only comments allowed are one-line tool directives: `// ignore-ok: `, `# zizmor: ignore[...]` - and the version after a pinned action SHA. `cargo xtask check` enforces this, and - `cargo xtask comments --strip` removes the rest after proving the code is unchanged. -- No code file over 400 lines and no folder with more than 5 code files, tests included. `cargo xtask check` - enforces both. -- No hardcoded drive letters, folders, servers or languages. -- Log state changes, never inside a loop. -- A new dependency needs a short written justification in the pull request. - -## Pull requests - -- Keep them focused: one change, with the reason explained in the description. -- Fill in the checklist in the pull request template. -- **Anything that changes what happens in game** (injection, game modes, party mode) must include evidence - from a real match: the Bullet log, and what you saw. Passing tests is not enough for these changes. -- CI must be green. After a maintainer approves, the pull request merges automatically once every required - check passes. Changes to workflows, the installer, `xtask`, the toolchain and dependency policy, the lockfile, the - injection trigger, the injector code and its trust check, the party cipher or the relay's deploy config are - merged by hand. - -## Releases - -Nobody bumps the version by hand. The merge publishes a pre-release whose version is the last release plus one -minor (the next major for a pull request labelled `breaking`), and it becomes the latest release only after it has -been tested in a real match. See [docs/build-and-ci.md](../docs/build-and-ci.md). - -## License - -By contributing, you agree that your contributions are licensed under the [MIT License](../LICENSE). +Thanks for contributing! Because Bullet integrates with the League Client, every change is held to a clear quality bar. + +## Before You Start + +- **Questions & setup help:** ask on [Discord](https://discord.gg/e2dH2nUjd9) before starting large changes. +- **Bug reports:** use the issue template and attach the bundle from **Support → Export diagnostics** (`%LOCALAPPDATA%\Bullet\logs` on Windows or `~/Library/Application Support/Bullet/logs` on macOS). +- **Security issues:** report privately — see [SECURITY.md](SECURITY.md). + +## Development Setup + +1. Install [Rust](https://rustup.rs) (toolchain from `rust-toolchain.toml`). On Windows, install [Inno Setup 6](https://jrsoftware.org/isinfo.php) to build installers. +2. Run `cargo xtask check` (and `cargo deny check` if dependencies changed) before opening a PR. + +## Code Standards + +- No `unwrap()` or `expect()` outside tests; propagate errors with context. +- Every discarded `Result` (`let _ = ...`) must include `// ignore-ok: `. +- Spawn background tasks through `Supervisor`, never bare `tokio::spawn`. +- Mutate shared state only through named transitions in `bullet-core::state`. +- Validate all offsets in binary parsers; malformed input must return a typed error, never panic. +- Keep code, logs, and docs in English; place user-facing strings in i18n tables. +- No comments in source files (only `// ignore-ok: `, `# zizmor: ignore[...]`, and pinned action tags), max 400 lines per code file, and max 5 code files per folder (enforced by `cargo xtask check`). +- Keep OS-specific logic isolated behind `#[cfg(windows)]` / `#[cfg(target_os = "macos")]`. + +## Pull Requests & License + +- Keep PRs focused on a single change and include real-match verification logs for gameplay/injection changes. +- All CI checks must pass. Contributions are licensed under the [MIT License](../LICENSE). diff --git a/.github/SECURITY.md b/.github/SECURITY.md index e55f67a..f0d1f4a 100644 --- a/.github/SECURITY.md +++ b/.github/SECURITY.md @@ -1,48 +1,28 @@ -# Security policy +# Security Policy -## Reporting a vulnerability +## Reporting a Vulnerability -Please report security issues **privately** through -[GitHub Security Advisories](https://github.com/Isllanrx/Bullet/security/advisories/new). Do not open a -public issue or post details on Discord. +Report security vulnerabilities **privately** via [GitHub Security Advisories](https://github.com/Isllanrx/Bullet/security/advisories/new). Please do not open public issues or post exploit details on Discord. -Useful details to include: +Include when possible: -- the Bullet version (Explorer → `bullet.exe` → Properties → Details), -- what an attacker could do, and under which conditions, -- steps to reproduce, and the log from `%LOCALAPPDATA%\Bullet\logs` if relevant. +- Bullet version, OS (Windows / macOS), and architecture (`x86_64` / `arm64`), +- Impact and reproduction steps, +- Diagnostic logs from **Support → Export diagnostics**. -Maintainer: Isllan Toso, [isllan.dev](https://isllan.dev/). +Maintainer: **Isllan Toso** — [isllan.dev](https://isllan.dev/). Acknowledgements are sent within a few days, and fixes ship first as a pre-release. -You will get an acknowledgement within a few days. Fixes ship as a new pre-release first and are credited in -the release notes unless you prefer otherwise. +## Scope & Supported Versions -## Scope +**In scope:** `bullet` desktop binary, Windows installer/uninstaller, `install.ps1`, in-app updater, GitHub StarGate auth, Party Mode E2EE protocol & relay (`relay-worker/`, `crates/bullet-relay`), macOS Mach-O patcher, and `.github/` workflows. -In scope: +**Out of scope:** The League of Legends client/game and Riot anti-cheat enforcement (see [Disclaimer](../README.md#disclaimer--license)). -- `bullet.exe`, the installer and the uninstaller, -- the bridge and launcher (`bullet_launcher.exe`, `bullet_bridge.dll`), built from the private `bullet_ltk` repository during official releases, -- the GitHub sign-in that checks the repository star, -- the party mode protocol, its encryption and the relay (`relay-worker/`, `crates/bullet-relay`), -- the terminal install script (`install.ps1`) and the in-app update, which verify the installer before running it, -- the build and release pipeline in `.github/`. +Only the latest release and latest pre-release receive security updates. -Out of scope: +## Verifying a Download -- the League of Legends client or game, -- detection or penalties by Riot's anti-cheat. Using Bullet is at your own risk, as the README's disclaimer - explains. - -## Supported versions - -Only the latest release and the latest pre-release receive security fixes. - -## Verifying a download - -Every installer published by the release workflow comes with a `SHA256SUMS` file, its signature -(`SHA256SUMS.sig`) and a build provenance attestation. Bullet itself checks the signed checksum list before it runs -an update, and `install.ps1` checks the installer against `SHA256SUMS`. Releases are not code-signed: +Every release includes `SHA256SUMS`, its Ed25519 signature (`SHA256SUMS.sig`), and a GitHub build provenance attestation: ```powershell Get-FileHash .\Bullet-Setup--x64.exe -Algorithm SHA256 diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml new file mode 100644 index 0000000..7ebfc3c --- /dev/null +++ b/.github/workflows/fuzz.yml @@ -0,0 +1,36 @@ +name: Fuzzing + +on: + push: + branches: [main] + pull_request: + schedule: + - cron: '23 4 * * 1' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: fuzz-${{ github.ref }} + cancel-in-progress: true + +env: + FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true + +jobs: + fuzz-tests: + name: Property and fuzz tests + runs-on: windows-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Run WAD, RST, Party, and Lockfile fuzz suites + run: | + cargo test --locked -p bullet-wad --test property_fuzz_tests + cargo test --locked -p bullet-classic --test rigorous_rst_tft_tests + cargo test --locked -p bullet-party --test rigorous_protocol_tests + cargo test --locked -p bullet-lcu --test rigorous_lockfile_tests diff --git a/Cargo.lock b/Cargo.lock index 7c30dba..f837b2a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -637,6 +637,7 @@ dependencies = [ "bullet-core", "bullet-platform", "bullet-wad", + "libc", "serde", "serde_json", "sha2", diff --git a/Cargo.toml b/Cargo.toml index 6705849..91f7da8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,6 +26,10 @@ edition = "2024" rust-version = "1.85" license = "MIT" repository = "https://github.com/Isllanrx/Bullet" +homepage = "https://github.com/Isllanrx/Bullet" +description = "Bullet — Open-source League of Legends skin changer, chroma selector, TFT cosmetic unlocker, and custom mod manager (.fantome / .modpkg) for Windows, written in Rust." +keywords = ["league-of-legends", "lol-skin-changer", "custom-skins", "fantome", "tft"] +categories = ["games", "GUI"] [workspace.dependencies] tokio = { version = "1", features = ["full"] } diff --git a/README.md b/README.md index a78424b..6ffdc4c 100644 --- a/README.md +++ b/README.md @@ -5,125 +5,96 @@

Bullet

- A League of Legends skin changer for Windows, written in Rust.
- The right skin loads into the match — every mode, every time. -

- -

- CI - OpenSSF Scorecard - Release - Downloads - Platform - Rust stable - MIT - Discord + Open-source League of Legends skin changer and custom mod manager (.fantome / .modpkg) for Windows and macOS, written in Rust.

Download · - Discord community · - Report a bug + Installation Guide (Discord) · + Technical Wiki · + Issues

+> [!WARNING] +> **Educational Project & Disclaimer:** Bullet is developed strictly for **educational and research purposes**. It is provided as is, without warranty of any kind. The author takes **no responsibility** for any account penalties, bans, damages, or consequences resulting from using or misusing this software. You use it at your own risk. + --- -Pick any skin in Bullet's own window during champion select. Bullet builds a copy of the game files that contain -it, and when the game starts it reads that copy instead of its own. The game installation is never modified. +## Overview + +Bullet reads your installed League of Legends archives (`DATA/FINAL/Champions/*.wad.client`) to generate and load skins, chromas, Exalted forms (`Ctrl+5`), TFT cosmetics, and custom mods locally at match start without modifying Riot's game files.

Bullet in Champion Select - Bullet in Game + Bullet In-Game Preview

-> [!IMPORTANT] -> **Educational project**, provided as is, without warranty. The author accepts no responsibility for any damage, -> account penalty or loss caused by its use. See the [Disclaimer](#disclaimer). - -## Features +## Installation -- **Every skin and chroma**, including form skins, chosen in champion select and loaded when the game starts. -- **Random skin and history**: roll one, or reuse the last skin you played on each champion. -- **Custom mods**: `.fantome`, `.zip` and `.modpkg`, checked and adjusted against the current patch before use. -- **Classic Rift**: legacy champion models, generated from your installed game. -- **Party mode**: friends see each other's skins through an end-to-end encrypted relay, up to five players. Friends - in the same lobby need no code. -- **Always up to date**: skins are generated from the game you have installed, so a patch never breaks them. -- **Safe by design**: runs without administrator rights, never writes to the game folder, verifies every binary - and collects no telemetry. -- **Updates you approve**, verified against the release's signed checksum list. -- English, Portuguese and Spanish. **Free and open source**: if you paid for it, you were scammed. +> **Step-by-step installation tutorial:** Full setup instructions and support are inside our **[Discord server](https://discord.gg/e2dH2nUjd9)**. -## Installation +### Windows (10 / 11 x64) -1. **Install Bullet.** Download `Bullet-Setup--x64.exe` from - [Releases](https://github.com/Isllanrx/Bullet/releases/latest) and run it, or from PowerShell (not as - administrator): +Download [`Bullet-Setup-x64.exe`](https://github.com/Isllanrx/Bullet/releases/latest) or run in **PowerShell**: - ```powershell - irm https://raw.githubusercontent.com/Isllanrx/Bullet/main/install.ps1 | iex - ``` +```powershell +irm https://raw.githubusercontent.com/Isllanrx/Bullet/main/install.ps1 | iex +``` - The script checks the installer against the release's `SHA256SUMS` before installing. Bullet is not - code-signed, so Windows SmartScreen may warn about the installer. +Or install with Cargo: -2. **The injection tools come with it.** The installer places Bullet's LTF bridge tools, `bullet_launcher.exe` and - `bullet_bridge.dll`, in `C:\Program Files\Bullet\tools`. Bullet integrates with the official Mod Manager to apply - overlays cleanly in-game. +```powershell +cargo install --git https://github.com/Isllanrx/Bullet.git bullet-app --locked +``` -3. **Start Bullet** from the Start menu, normally (not as administrator). It lives in the system tray. - On the first start Bullet asks you to sign in with GitHub: it shows a code, opens github.com and you enter the - code there. Bullet then checks that your account starred this repository. The check repeats on every start; while - offline, a check from the last 7 days is accepted. The sign-in is stored for your Windows account only. +### macOS (Intel `x86_64` & Apple Silicon) -## Usage +Run in **Terminal**: -1. Open the League client and Bullet, in either order. -2. Pick a champion in champion select. Bullet's window lists its skins and chromas. -3. Choose one and play. +```bash +command -v cargo >/dev/null 2>&1 || curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y && source "$HOME/.cargo/env"; cargo install --git https://github.com/Isllanrx/Bullet.git bullet-app --locked && bullet +``` -Custom mods go into the category folders under `%LOCALAPPDATA%\Bullet\custom_mods`, or are imported from the -**Mods** tab. Party rooms are created from the tray, or offered automatically when friends running Bullet share -your lobby. Optional settings are listed in [`.env.example`](.env.example). +For in-client mode on macOS, launch League with remote debugging enabled: -## Troubleshooting +```bash +open -a "League of Legends" --args --remote-debugging-port=46359 +``` -Logs are in `%LOCALAPPDATA%\Bullet\logs` (the tray opens the folder); `BULLET_LOG=debug` adds detail. **Export -diagnostics** in the control panel zips everything needed for a report. If a skin or mod breaks match loading, -turn off **Inject skins** in the control panel. Close other skin tools while Bullet runs: two injectors conflict. +## Features -Attach the log when you open an [issue](https://github.com/Isllanrx/Bullet/issues), or ask on -[Discord](https://discord.gg/e2dH2nUjd9). Security issues go through a -[private advisory](https://github.com/Isllanrx/Bullet/security/advisories/new). +- **Skins, Chromas & Forms (`Ctrl+5`):** Supports 170+ champions and 9,000+ skins, chromas, Exalted, Ultimate, and Hall of Legends forms, plus localized loading-screen names. +- **Window & In-Client Modes:** Use Bullet's desktop window or the native in-client carousel without Pengu Loader. +- **Customize Identity & TFT:** Summoner Icons, Borders, Banners, Titles, Tokens, and TFT Tacticians, Booms, Portals, and Arenas. +- **Custom Mods (`.fantome`, `.modpkg`, `.zip`):** Import and repair custom skins, maps, HUDs, fonts, and announcers. +- **Party Mode:** End-to-end encrypted (`X25519` + `ChaCha20-Poly1305`) skin and identity sync with up to 5 friends. +- **All Regions & Languages:** Works across all Riot servers (including WeGame/CN), Classic Rift (JADE), and supports **English**, **Português (BR)**, and **Español**. -## Building from source +## FAQ -```powershell -cargo xtask check -cargo xtask package -cargo xtask installer -``` +**Where is the full installation tutorial?** +Inside our Discord server: **[discord.gg/e2dH2nUjd9](https://discord.gg/e2dH2nUjd9)**. -Contributions: [CONTRIBUTING.md](.github/CONTRIBUTING.md). +**Does Bullet modify my League of Legends installation?** +No. Overlays are built separately and loaded in memory at match start. Your game files stay untouched. -## Acknowledgements +**Does it require Administrator privileges or Pengu Loader?** +No. On Windows it runs as a standard user (`asInvoker`) and does not use Pengu Loader. -Bullet was inspired by [Rose](https://github.com/Alban1911/Rose) and built by studying the open projects listed in -[THIRD-PARTY-NOTICES.md](THIRD-PARTY-NOTICES.md). Maintained by **Isllan Toso** — [isllan.dev](https://isllan.dev/). +**Can other players see my skin?** +Only locally, unless you and your friends enable **Party Mode** inside Bullet. -## Disclaimer +**Where can I read how Bullet works internally?** +Check the **[Technical Wiki](https://github.com/Isllanrx/Bullet/wiki)**. -Bullet is published **for educational purposes**, **as is, without warranty of any kind**, as stated in the MIT -license. The author assumes no responsibility for any damage caused by its use, including account suspensions or -bans. Using third-party software with League of Legends goes against Riot Games' Terms of Service: you decide -whether to use it and bear the consequences. Bullet only changes what you see on your own machine. It is not -affiliated with or endorsed by Riot Games; League of Legends is a trademark of Riot Games, Inc. +## Build from Source -

- Made with Slint -

+```powershell +cargo xtask check +cargo xtask package +cargo xtask installer +``` ## License -- **Source Code:** The source code in this repository is licensed under the [MIT License](LICENSE). -- **Third-Party Components:** Licensed under their respective terms as listed in [THIRD-PARTY-NOTICES.md](THIRD-PARTY-NOTICES.md). +[MIT License](LICENSE) · [THIRD-PARTY-NOTICES.md](THIRD-PARTY-NOTICES.md) diff --git a/crates/bullet-app/Cargo.toml b/crates/bullet-app/Cargo.toml index f4dd3d3..cac4c1a 100644 --- a/crates/bullet-app/Cargo.toml +++ b/crates/bullet-app/Cargo.toml @@ -7,7 +7,7 @@ rust-version.workspace = true license.workspace = true repository.workspace = true publish = false -description = "League of Legends skin changer for Windows" +description = "Bullet — League of Legends skin changer, chroma selector, TFT cosmetic unlocker, and custom mod manager (.fantome / .modpkg) for Windows" [lib] name = "bullet_app" diff --git a/crates/bullet-app/src/boot/cli.rs b/crates/bullet-app/src/boot/cli.rs index 0a3f325..04f171f 100644 --- a/crates/bullet-app/src/boot/cli.rs +++ b/crates/bullet-app/src/boot/cli.rs @@ -1,6 +1,15 @@ use anyhow::Result; pub async fn handle_cli_args(args: &[String]) -> Result> { + match bullet_inject::macos_patcher::run_cli_patcher(args) { + Ok(Some(code)) => return Ok(Some(code)), + Ok(None) => {} + Err(e) => { + eprintln!("macOS patcher CLI failed: {e}"); + return Ok(Some(1)); + } + } + if args .iter() .any(|a| a == "--native-diagnostics" || a == "--diagnostics") @@ -38,3 +47,38 @@ pub fn attach_parent_console() { let _ = AttachConsole(0xFFFF_FFFF); // ignore-ok: attach console to parent when run from terminal } } + +#[cfg(target_os = "macos")] +pub fn run_macos_main( + grace: std::time::Duration, + entry: fn() -> std::pin::Pin> + Send>>, +) -> Result<()> { + let args: Vec = std::env::args().collect(); + if args + .iter() + .any(|a| a == "--macos-patcher" || a == "--native-diagnostics" || a == "--diagnostics") + { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build()?; + if let Some(code) = runtime.block_on(handle_cli_args(&args))? { + std::process::exit(code); + } + } + let worker = std::thread::Builder::new() + .name("bullet-runtime".into()) + .spawn(move || -> Result<()> { + let runtime = tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build()?; + let outcome = runtime.block_on(entry()); + runtime.shutdown_timeout(grace); + std::process::exit(i32::from(outcome.is_err())); + })?; + if let Err(e) = bullet_platform::run_interface_on_main_thread() { + tracing::warn!(error = %e, "macOS main-thread interface loop returned"); + } + worker + .join() + .map_err(|_| anyhow::anyhow!("bullet-runtime thread panicked"))? +} diff --git a/crates/bullet-app/src/boot/startup/injector.rs b/crates/bullet-app/src/boot/startup/injector.rs index 6bc1262..5af0807 100644 --- a/crates/bullet-app/src/boot/startup/injector.rs +++ b/crates/bullet-app/src/boot/startup/injector.rs @@ -2,43 +2,56 @@ use tracing::{info, warn}; use crate::trigger; +#[cfg_attr(target_os = "macos", allow(unused_variables))] pub fn injector_unusable(paths: &trigger::ResolvedPaths) -> bool { - use bullet_app::startup::{InjectorRefusal, injector_refusal}; + #[cfg(target_os = "macos")] + { + info!( + bullet_version = %bullet_platform::version::display_version(), + "Built-in macOS Mach-O engine ready" + ); + return false; + } + #[cfg(not(target_os = "macos"))] + { + use bullet_app::startup::{InjectorRefusal, injector_refusal}; - let text = bullet_platform::i18n::text(); - let (title, body) = match injector_refusal(&paths.native_host_exe, &paths.native_dll_path) { - None => { - info!( - host = %paths.native_host_exe.display(), - dll = %paths.native_dll_path.display(), - bullet_version = %bullet_platform::version::display_version(), - "Native engine found and accepted" - ); - warn_if_manager_outdated(text); - return false; - } - Some(InjectorRefusal::Missing) => { - warn!( - tools = %paths.tools_dir.display(), - "Bullet stopped at startup: the native engine is missing from the tools folder" - ); - (text.missing_tools_title, text.missing_tools_body) - } - Some(InjectorRefusal::NotTrusted(files)) => { - for (file, error) in &files { + let text = bullet_platform::i18n::text(); + let (title, body) = match injector_refusal(&paths.native_host_exe, &paths.native_dll_path) { + None => { + info!( + host = %paths.native_host_exe.display(), + dll = %paths.native_dll_path.display(), + bullet_version = %bullet_platform::version::display_version(), + "Native engine found and accepted" + ); + warn_if_manager_outdated(text); + return false; + } + Some(InjectorRefusal::Missing) => { warn!( - file = %file.display(), - error = %error, - "Bullet stopped at startup: a native engine file is not signed by Bullet's publisher" + tools = %paths.tools_dir.display(), + "Bullet stopped at startup: the native engine is missing from the tools folder" ); + (text.missing_tools_title, text.missing_tools_body) } - (text.broken_tools_title, text.broken_tools_body) - } - }; - bullet_platform::shell::message_box_warning(title, body); - true + Some(InjectorRefusal::NotTrusted(files)) => { + for (file, error) in &files { + warn!( + file = %file.display(), + error = %error, + "Bullet stopped at startup: a native engine file is not signed by Bullet's publisher" + ); + } + (text.broken_tools_title, text.broken_tools_body) + } + }; + bullet_platform::shell::message_box_warning(title, body); + true + } } +#[cfg_attr(target_os = "macos", allow(dead_code))] fn warn_if_manager_outdated(text: &bullet_platform::i18n::Text) { use bullet_inject::ltf::{MIN_MANAGER_VERSION, ManagerInstallState, check_manager_install}; use bullet_platform::i18n::fill; diff --git a/crates/bullet-app/src/boot/startup/library.rs b/crates/bullet-app/src/boot/startup/library.rs index dbe244d..f15c064 100644 --- a/crates/bullet-app/src/boot/startup/library.rs +++ b/crates/bullet-app/src/boot/startup/library.rs @@ -91,27 +91,24 @@ pub fn spawn_prewarm( let spawned = std::thread::Builder::new() .name("bullet-prewarm".into()) .spawn(move || { - let game_disk = bullet_platform::disk::disk_kind(&game_dir).as_str(); - let state_disk = bullet_platform::disk::disk_kind(&cache_dir).as_str(); - let started = std::time::Instant::now(); - match bullet_inject::overlay_builder::get_or_index_game(&game_dir) { - Ok(index) => info!( - wads = index.len(), - elapsed_ms = started.elapsed().as_millis(), - game_disk, - state_disk, - "Game WAD index ready" - ), - Err(e) => warn!(error = %e, "Game WAD index not prewarmed; the first build indexes on demand"), - } let _background = bullet_platform::process::BackgroundThread::enter(); - let busy = || bullet_app::update_check::is_busy(gate_state.borrow().phase); + let busy = || { + let phase = gate_state.borrow().phase; + bullet_app::update_check::is_busy(phase) + || matches!( + phase, + bullet_core::phase::GamePhase::Lobby + | bullet_core::phase::GamePhase::Matchmaking + ) + }; while !gate_token.is_cancelled() && busy() { std::thread::sleep(std::time::Duration::from_secs(2)); } - bullet_classic::generator::remove_stale_generated(&game_dir, &generated_dir, || { - gate_token.is_cancelled() || busy() - }); + bullet_classic::generator::remove_stale_generated( + &game_dir, + &generated_dir, + || gate_token.is_cancelled() || busy(), + ); let report = bullet_app::mod_repair::repair_custom_mods( &mod_roots, &game_dir, @@ -125,7 +122,7 @@ pub fn spawn_prewarm( bullet_classic::generator::prewarm_companions(&game_dir, &cache_dir, || { if gate_token.is_cancelled() { bullet_classic::generator::PrewarmGate::Stop - } else if bullet_app::update_check::is_busy(gate_state.borrow().phase) { + } else if busy() { bullet_classic::generator::PrewarmGate::Wait } else { bullet_classic::generator::PrewarmGate::Go diff --git a/crates/bullet-app/src/boot/startup/star_gate/mod.rs b/crates/bullet-app/src/boot/startup/star_gate/mod.rs index bb94672..de71d59 100644 --- a/crates/bullet-app/src/boot/startup/star_gate/mod.rs +++ b/crates/bullet-app/src/boot/startup/star_gate/mod.rs @@ -167,6 +167,8 @@ async fn star_lost(state_dir: &Path) -> Option { } } +const STAR_RECHECK_COOLDOWN: std::time::Duration = std::time::Duration::from_secs(300); + pub async fn watch_star( state_dir: PathBuf, mut state: bullet_core::state::StateReceiver, @@ -174,6 +176,7 @@ pub async fn watch_star( token: CancellationToken, ) { let mut last = GamePhase::None; + let mut last_confirmed: Option = None; loop { tokio::select! { () = token.cancelled() => return, @@ -187,7 +190,7 @@ pub async fn watch_star( let entered = phase != last && matches!(phase, GamePhase::Matchmaking | GamePhase::ChampSelect); last = phase; - if !entered { + if !entered || last_confirmed.is_some_and(|t| t.elapsed() < STAR_RECHECK_COOLDOWN) { continue; } if let Some(login) = star_lost(&state_dir).await { @@ -200,6 +203,7 @@ pub async fn watch_star( shutdown.cancel(); return; } + last_confirmed = Some(std::time::Instant::now()); } } diff --git a/crates/bullet-app/src/boot/startup/update.rs b/crates/bullet-app/src/boot/startup/update.rs index 0f04547..1c3176a 100644 --- a/crates/bullet-app/src/boot/startup/update.rs +++ b/crates/bullet-app/src/boot/startup/update.rs @@ -1,3 +1,4 @@ +#[cfg(windows)] use std::os::windows::process::CommandExt; use std::path::PathBuf; use std::time::Duration; @@ -174,6 +175,7 @@ pub fn run_installer(install: Option, instance_guard: Option { + bullet_app::control_panel::ManagerStatus::Ready { + version: version.map(bullet_platform::version::format_version), + } + } + bullet_inject::ltf::ManagerInstallState::Outdated { found, .. } => { + bullet_app::control_panel::ManagerStatus::Outdated { + found: bullet_platform::version::format_version(found), + required: bullet_platform::version::format_version( + bullet_inject::ltf::MIN_MANAGER_VERSION, + ), + } + } + bullet_inject::ltf::ManagerInstallState::Missing => { + bullet_app::control_panel::ManagerStatus::Missing + } + }; let facts = bullet_app::control_panel::Facts { status: controller.status(), party_line, @@ -79,13 +97,19 @@ pub fn panel_links_for( injection: bullet_platform::preferences::INJECTION.is_enabled(), random_skin: bullet_platform::preferences::RANDOM_SKIN.is_enabled(), light_loading: bullet_platform::preferences::LIGHT_LOADING.is_enabled(), + in_client_ui: bullet_platform::preferences::IN_CLIENT_UI.is_enabled(), autostart, tools_present: bullet_app::control_panel::tools_present(&tools), + manager, game_found: bullet_app::control_panel::game_found(&game_dir), lcu_connected, elevated, update: notices.bullet.available().map(|latest| latest.to_string()), custom_mods: notices.custom_mods.summary(), + stats: bullet_platform::paths::state_dir() + .ok() + .map(|dir| bullet_app::stats::load_summary(&dir)) + .unwrap_or_default(), }; let snapshot = bullet_app::control_panel::snapshot(&facts, bullet_platform::i18n::text()); let failing: Vec = snapshot @@ -203,6 +227,25 @@ impl TrayActions { Err(e) => warn!(error = %e, "Could not change the light match loading setting"), } } + bullet_platform::tray::TrayEvent::ToggleInClientUi => { + match bullet_platform::preferences::IN_CLIENT_UI.toggle() { + Ok(enabled) => { + info!( + enabled, + "In-client skin selection changed from the control panel" + ); + if !enabled { + let tools = vec![self.tools_dir.clone()]; + drop(tokio::spawn(async move { + bullet_inject::ltf::deactivate_in_client_ui(&tools).await; + })); + } + } + Err(e) => { + warn!(error = %e, "Could not change the in-client skin selection setting") + } + } + } bullet_platform::tray::TrayEvent::OpenLogs => { match self.logs_dir { Some(ref dir) => { @@ -266,12 +309,39 @@ impl TrayActions { ), } } + bullet_platform::tray::TrayEvent::RepairSkins => { + let mods = self.mods_dir.clone(); + let state = self.state_dir.clone(); + let game = bullet_platform::paths::discover_game_dir().unwrap_or_default(); + drop(tokio::task::spawn_blocking(move || { + let report = + bullet_app::control_panel::repair_skins_and_mods(&mods, &state, &game); + info!( + repaired = report.repaired.len(), + incompatible = report.incompatible.len(), + "Manual skin and mod repair completed" + ); + })); + } + bullet_platform::tray::TrayEvent::RepairClient => { + let state = self.state_dir.clone(); + drop(tokio::task::spawn_blocking(move || { + bullet_app::control_panel::repair_client(&state); + info!("Manual client and Bullet cache repair completed"); + })); + } bullet_platform::tray::TrayEvent::OpenRelease => { let page = bullet_app::update_check::release_page(); if let Err(e) = bullet_platform::shell::open_web_page(&page) { warn!(error = %e, page = %page, "Could not open the release page"); } } + bullet_platform::tray::TrayEvent::OpenProject => { + let page = bullet_platform::star_gate::REPOSITORY_URL; + if let Err(e) = bullet_platform::shell::open_web_page(page) { + warn!(error = %e, page = %page, "Could not open the GitHub repository page"); + } + } bullet_platform::tray::TrayEvent::ToggleAutostart => { match bullet_platform::autostart::toggle() { Ok(enabled) => info!(enabled, "Start with Windows changed from the tray"), diff --git a/crates/bullet-app/src/diagnostics/control_panel/export.rs b/crates/bullet-app/src/diagnostics/control_panel/export.rs index efcfadc..f8ac08b 100644 --- a/crates/bullet-app/src/diagnostics/control_panel/export.rs +++ b/crates/bullet-app/src/diagnostics/control_panel/export.rs @@ -50,6 +50,7 @@ fn recent_logs( } } logs.sort(); + logs.reverse(); Ok(logs) } @@ -98,14 +99,33 @@ fn write_zip( .compression_method(zip::CompressionMethod::Deflated); let stored = deflated.compression_method(zip::CompressionMethod::Stored); let mut total = 0u64; + let mut included = 0usize; for (name, path) in files { let image = name.starts_with("screenshots/"); + let raw_len = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0); + if total + raw_len > DIAGNOSTIC_MAX_BYTES { + if included > 0 { + warn!( + file = %name, + bytes = raw_len, + "Skipping oversized file in diagnostics export to stay within budget" + ); + continue; + } + return Err(format!( + "logs larger than the diagnostic limit ({} bytes after {name})", + total + raw_len + )); + } let mut bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?; if !image { bytes = redact::redact(&String::from_utf8_lossy(&bytes), profile).into_bytes(); } total += bytes.len() as u64; if total > DIAGNOSTIC_MAX_BYTES { + if included > 0 { + continue; + } return Err(format!( "logs larger than the diagnostic limit ({total} bytes after {name})" )); @@ -113,6 +133,7 @@ fn write_zip( zip.start_file(name.as_str(), if image { stored } else { deflated }) .map_err(|e| format!("{name}: {e}"))?; zip.write_all(&bytes).map_err(|e| format!("{name}: {e}"))?; + included += 1; } zip.finish() .map_err(|e| format!("{}: {e}", partial.display()))?; diff --git a/crates/bullet-app/src/diagnostics/control_panel/mod.rs b/crates/bullet-app/src/diagnostics/control_panel/mod.rs index b4034af..5cdac4a 100644 --- a/crates/bullet-app/src/diagnostics/control_panel/mod.rs +++ b/crates/bullet-app/src/diagnostics/control_panel/mod.rs @@ -9,6 +9,13 @@ mod redact; pub use export::export_diagnostics; +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ManagerStatus { + Ready { version: Option }, + Outdated { found: String, required: String }, + Missing, +} + #[derive(Debug, Clone)] pub struct Facts { pub status: String, @@ -18,13 +25,16 @@ pub struct Facts { pub injection: bool, pub random_skin: bool, pub light_loading: bool, + pub in_client_ui: bool, pub autostart: bool, pub tools_present: bool, + pub manager: ManagerStatus, pub game_found: bool, pub lcu_connected: bool, pub elevated: bool, pub update: Option, pub custom_mods: Option, + pub stats: bullet_platform::panel::PanelStats, } #[must_use] @@ -76,6 +86,7 @@ pub fn snapshot(facts: &Facts, text: &Text) -> PanelSnapshot { injection: facts.injection, random_skin: facts.random_skin, light_loading: facts.light_loading, + in_client_ui: facts.in_client_ui, autostart: facts.autostart, update_line: facts.update.as_deref().map(|latest| { fill( @@ -84,6 +95,7 @@ pub fn snapshot(facts: &Facts, text: &Text) -> PanelSnapshot { bullet_platform::version::display_version(), ) }), + stats: facts.stats.clone(), checks: vec![ check( text.check_injector, @@ -95,6 +107,24 @@ pub fn snapshot(facts: &Facts, text: &Text) -> PanelSnapshot { } .to_owned(), ), + { + let (ok, detail) = match &facts.manager { + ManagerStatus::Ready { version: Some(v) } => { + (true, format!("{} (v{v})", text.detail_ok)) + } + ManagerStatus::Ready { version: None } => (true, text.detail_ok.to_owned()), + ManagerStatus::Outdated { found, required } => ( + false, + fill( + &fill(text.detail_manager_outdated, "found", found), + "required", + required, + ), + ), + ManagerStatus::Missing => (false, text.detail_manager_missing.to_owned()), + }; + check(text.check_manager, ok, detail) + }, check( text.check_game, facts.game_found, @@ -143,5 +173,56 @@ pub fn tools_present(files: &[PathBuf]) -> bool { files.iter().all(|file| file.is_file()) } +pub fn repair_skins_and_mods( + mods_dir: &std::path::Path, + state_dir: &std::path::Path, + game_dir: &std::path::Path, +) -> crate::mod_repair::RepairReport { + let _ = std::fs::remove_file(state_dir.join("mod_repair.json")); // ignore-ok: force fresh repair scan + if let Ok(data_dir) = bullet_platform::paths::data_dir() { + let generated_dir = data_dir.join("mods"); + if let Ok(entries) = std::fs::read_dir(&generated_dir) { + for entry in entries.flatten() { + let name = entry.file_name(); + if let Some(s) = name.to_str() { + if s.starts_with("std_") || s == "bullet_loading_name" { + let _ = std::fs::remove_dir_all(entry.path()); // ignore-ok: clear cached generated skin mod + } + } + } + } + } + let resolved_game = bullet_platform::paths::normalize_game_dir(game_dir) + .or_else(bullet_platform::paths::discover_game_dir) + .unwrap_or_else(|| game_dir.to_path_buf()); + crate::mod_repair::repair_custom_mods( + &[mods_dir.to_path_buf()], + &resolved_game, + state_dir, + &|| false, + ) +} + +pub fn repair_client(state_dir: &std::path::Path) { + if let Ok(data_dir) = bullet_platform::paths::data_dir() { + for sub in ["staging", "overlay"] { + let _ = std::fs::remove_dir_all(data_dir.join(sub)); // ignore-ok: clear transient overlay/staging cache + } + } + let _ = std::fs::remove_file(state_dir.join("ltf_journal.json")); // ignore-ok: clear stale journal + #[cfg(windows)] + if let Ok(Some(pid)) = bullet_platform::process::ProcessFinder::find_any_process(&[ + "ltk-manager.exe", + "LTK Manager.exe", + ]) { + let _ = bullet_platform::process::terminate_process(pid); // ignore-ok: restart stalled mod manager + } + if let Ok(local_app) = std::env::var("LOCALAPPDATA") { + let bridge_dir = std::path::PathBuf::from(local_app).join("BulletBridge"); + let _ = std::fs::remove_file(bridge_dir.join("port.txt")); // ignore-ok: reset bridge discovery + let _ = std::fs::remove_file(bridge_dir.join("token.txt")); // ignore-ok: reset bridge token + } +} + #[cfg(test)] mod tests; diff --git a/crates/bullet-app/src/diagnostics/control_panel/tests.rs b/crates/bullet-app/src/diagnostics/control_panel/tests.rs index 2270133..917392b 100644 --- a/crates/bullet-app/src/diagnostics/control_panel/tests.rs +++ b/crates/bullet-app/src/diagnostics/control_panel/tests.rs @@ -10,13 +10,18 @@ fn facts() -> Facts { injection: true, random_skin: true, light_loading: true, + in_client_ui: false, autostart: false, tools_present: true, + manager: ManagerStatus::Ready { + version: Some("1.33.0".into()), + }, game_found: true, lcu_connected: true, elevated: false, update: None, custom_mods: None, + stats: bullet_platform::panel::PanelStats::default(), } } @@ -187,17 +192,37 @@ fn test_a_room_you_created_says_so_until_you_leave() { #[test] fn test_missing_pieces_are_reported() { let text = Language::Portuguese.text(); - let snapshot = snapshot( + let snap = snapshot( &Facts { tools_present: false, + manager: ManagerStatus::Missing, game_found: false, lcu_connected: false, ..facts() }, text, ); - let details: Vec<&str> = snapshot.checks.iter().map(|c| c.detail.as_str()).collect(); + let details: Vec<&str> = snap.checks.iter().map(|c| c.detail.as_str()).collect(); assert!(details.contains(&text.detail_injector_missing)); + assert!(details.contains(&text.detail_manager_missing)); assert!(details.contains(&text.detail_game_missing)); assert!(details.contains(&text.detail_client_waiting)); + + let outdated = snapshot( + &Facts { + manager: ManagerStatus::Outdated { + found: "1.29.0".into(), + required: "1.33.0".into(), + }, + ..facts() + }, + text, + ); + let row = outdated + .checks + .into_iter() + .find(|c| c.label == text.check_manager) + .expect("manager check row"); + assert!(!row.ok); + assert!(row.detail.contains("1.29.0") && row.detail.contains("1.33.0")); } diff --git a/crates/bullet-app/src/game/live_game/data.rs b/crates/bullet-app/src/game/live_game/data.rs index 671202c..6f0ddd3 100644 --- a/crates/bullet-app/src/game/live_game/data.rs +++ b/crates/bullet-app/src/game/live_game/data.rs @@ -16,6 +16,7 @@ pub struct GameEvent { pub time: f64, pub killer: Option, pub victim: Option, + pub result: Option, } #[derive(Debug, Clone, PartialEq)] @@ -81,6 +82,7 @@ pub fn parse_all_game_data(json: &Value) -> Option { time: e.get("EventTime").and_then(Value::as_f64).unwrap_or(0.0), killer: as_champion(e.get("KillerName").and_then(Value::as_str)), victim: as_champion(e.get("VictimName").and_then(Value::as_str)), + result: e.get("Result").and_then(Value::as_str).map(str::to_owned), }) .collect() }) diff --git a/crates/bullet-app/src/game/live_game/mod.rs b/crates/bullet-app/src/game/live_game/mod.rs index 784ff2a..5c14ac9 100644 --- a/crates/bullet-app/src/game/live_game/mod.rs +++ b/crates/bullet-app/src/game/live_game/mod.rs @@ -106,16 +106,23 @@ struct MatchWatch { roster_logged: bool, warned_event_ids: bool, warned_silence: bool, + recorded_result: bool, last_error: Option, } impl MatchWatch { - fn observe(&mut self, data: &AllGameData, live: &LiveGame, now: SystemTime) { + fn observe( + &mut self, + data: &AllGameData, + live: &LiveGame, + now: SystemTime, + selected_skin_id: Option, + ) { self.answered += 1; self.timeline.push((now, data.game_time)); if !self.roster_logged { if data.players.is_empty() { - return self.finish(data, live, now); + return self.finish(data, live, now, selected_skin_id); } self.roster_logged = true; if !data.players.iter().any(|p| p.local) { @@ -150,10 +157,16 @@ impl MatchWatch { } } } - self.finish(data, live, now); + self.finish(data, live, now, selected_skin_id); } - fn finish(&mut self, data: &AllGameData, live: &LiveGame, now: SystemTime) { + fn finish( + &mut self, + data: &AllGameData, + live: &LiveGame, + now: SystemTime, + selected_skin_id: Option, + ) { if !self.warned_event_ids && data.events.iter().any(|e| e.id < 0) { self.warned_event_ids = true; warn!( @@ -170,6 +183,25 @@ impl MatchWatch { victim = ?event.victim, "Live game event" ); + if !self.recorded_result && event.name == "GameEnd" { + let won = match event.result.as_deref() { + Some("Win") => Some(true), + Some("Lose") => Some(false), + _ => None, + }; + if let Some(won) = won { + self.recorded_result = true; + if let Ok(state_dir) = bullet_platform::paths::state_dir() { + let local = data.players.iter().find(|p| p.local); + let champ = local.map(|p| p.champion.as_str()).unwrap_or_default(); + let skin_name = local.map(|p| p.skin_name.as_str()).unwrap_or_default(); + let skin_id = selected_skin_id.unwrap_or(0); + crate::game::stats::record_match( + &state_dir, skin_id, champ, skin_name, won, + ); + } + } + } } self.last_event = data.events.iter().map(|e| e.id).fold(seen, i64::max); self.last_players = data.players.clone(); @@ -261,8 +293,15 @@ pub async fn run( } if let Some(current) = &mut watch { current.polls += 1; + let picked = { + let st = state_rx.borrow(); + st.overlay_target + .as_ref() + .map(|t| t.chroma_id.unwrap_or(t.skin_id)) + .or(st.selected_skin_id) + }; match poll(&client).await { - Ok(data) => current.observe(&data, &live, SystemTime::now()), + Ok(data) => current.observe(&data, &live, SystemTime::now(), picked), Err(e) => { debug!(error = %e, "Live game data not available yet"); if current.polls >= SILENT_POLLS_BEFORE_WARNING diff --git a/crates/bullet-app/src/game/live_game/tests.rs b/crates/bullet-app/src/game/live_game/tests.rs index 0d70fe8..69d2d51 100644 --- a/crates/bullet-app/src/game/live_game/tests.rs +++ b/crates/bullet-app/src/game/live_game/tests.rs @@ -57,6 +57,7 @@ fn a_skin_change_during_the_match_updates_what_is_marked() { &data, &live, SystemTime::UNIX_EPOCH + Duration::from_secs(1_000), + None, ); assert_eq!(watch.last_event, 2, "every event is seen once"); assert_eq!(live.latest().map(|s| s.skin_id), Some(0)); @@ -66,6 +67,7 @@ fn a_skin_change_during_the_match_updates_what_is_marked() { &data, &live, SystemTime::UNIX_EPOCH + Duration::from_secs(1_060), + None, ); let latest = live.latest().expect("snapshot"); assert_eq!((latest.skin_id, latest.game_time), (44, 700.0)); diff --git a/crates/bullet-app/src/game/mod.rs b/crates/bullet-app/src/game/mod.rs index a72f33f..e9381a8 100644 --- a/crates/bullet-app/src/game/mod.rs +++ b/crates/bullet-app/src/game/mod.rs @@ -1,3 +1,4 @@ pub mod auto_accept; pub mod game_log_trace; pub mod live_game; +pub mod stats; diff --git a/crates/bullet-app/src/game/stats.rs b/crates/bullet-app/src/game/stats.rs new file mode 100644 index 0000000..f3c00bc --- /dev/null +++ b/crates/bullet-app/src/game/stats.rs @@ -0,0 +1,179 @@ +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use bullet_platform::fs::atomic_write; +use bullet_platform::panel::{PanelSkinStat, PanelStats}; +use serde::{Deserialize, Serialize}; +use tracing::{debug, warn}; + +const STATS_FILE: &str = "skin_stats.json"; +const TOP_SKINS: usize = 3; + +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] +pub struct SkinRecord { + pub skin_id: u32, + pub champion_name: String, + pub skin_name: String, + pub wins: u32, + pub losses: u32, + pub last_played: u64, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] +pub struct MatchStats { + pub wins: u32, + pub losses: u32, + #[serde(default)] + pub skins: BTreeMap, +} + +fn stats_path(state_dir: &Path) -> PathBuf { + state_dir.join(STATS_FILE) +} + +#[must_use] +pub fn winrate_pct(wins: u32, losses: u32) -> u8 { + let total = wins.saturating_add(losses); + if total == 0 { + return 0; + } + let rounded = (u64::from(wins) * 100 + u64::from(total) / 2) / u64::from(total); + u8::try_from(rounded.min(100)).unwrap_or(100) +} + +#[must_use] +pub fn load(state_dir: &Path) -> MatchStats { + let path = stats_path(state_dir); + let Ok(bytes) = std::fs::read(&path) else { + return MatchStats::default(); + }; + match serde_json::from_slice(&bytes) { + Ok(stats) => stats, + Err(e) => { + warn!(path = %path.display(), error = %e, "Skin stats file could not be parsed; starting fresh"); + MatchStats::default() + } + } +} + +pub fn record_match( + state_dir: &Path, + skin_id: u32, + champion_name: &str, + skin_name: &str, + won: bool, +) { + let mut stats = load(state_dir); + if won { + stats.wins = stats.wins.saturating_add(1); + } else { + stats.losses = stats.losses.saturating_add(1); + } + if skin_id > 0 { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + let entry = stats.skins.entry(skin_id).or_insert_with(|| SkinRecord { + skin_id, + champion_name: champion_name.to_owned(), + skin_name: skin_name.to_owned(), + wins: 0, + losses: 0, + last_played: now, + }); + if !skin_name.is_empty() { + entry.skin_name = skin_name.to_owned(); + } + if !champion_name.is_empty() { + entry.champion_name = champion_name.to_owned(); + } + if won { + entry.wins = entry.wins.saturating_add(1); + } else { + entry.losses = entry.losses.saturating_add(1); + } + entry.last_played = now; + } + if let Ok(json) = serde_json::to_vec_pretty(&stats) { + if let Err(e) = atomic_write(&stats_path(state_dir), &json, false) { + warn!(error = %e, "Could not save skin match stats"); + } else { + debug!( + skin_id, + won, + total_wins = stats.wins, + total_losses = stats.losses, + "Match stats recorded" + ); + } + } +} + +#[must_use] +pub fn load_summary(state_dir: &Path) -> PanelStats { + let stats = load(state_dir); + let mut ranked: Vec<&SkinRecord> = stats.skins.values().collect(); + ranked.sort_by(|a, b| { + let ga = a.wins.saturating_add(a.losses); + let gb = b.wins.saturating_add(b.losses); + gb.cmp(&ga) + .then_with(|| winrate_pct(b.wins, b.losses).cmp(&winrate_pct(a.wins, a.losses))) + .then_with(|| b.last_played.cmp(&a.last_played)) + }); + let top = ranked + .into_iter() + .take(TOP_SKINS) + .map(|rec| { + let name = if !rec.skin_name.is_empty() { + rec.skin_name.clone() + } else if !rec.champion_name.is_empty() { + format!("{} #{}", rec.champion_name, rec.skin_id % 1000) + } else { + format!("Skin #{}", rec.skin_id) + }; + PanelSkinStat { + name, + wins: rec.wins, + losses: rec.losses, + winrate: winrate_pct(rec.wins, rec.losses), + } + }) + .collect(); + PanelStats { + wins: stats.wins, + losses: stats.losses, + winrate: winrate_pct(stats.wins, stats.losses), + top, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn records_wins_losses_and_ranks_top_skins() { + let dir = std::env::temp_dir().join(format!("bullet-stats-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); // ignore-ok: test temp dir cleanup + std::fs::create_dir_all(&dir).unwrap(); + + record_match(&dir, 238031, "Zed", "Debonair Zed", true); + record_match(&dir, 238031, "Zed", "Debonair Zed", true); + record_match(&dir, 238031, "Zed", "Debonair Zed", false); + record_match(&dir, 157009, "Yasuo", "Nightbringer Yasuo", true); + + let summary = load_summary(&dir); + assert_eq!(summary.wins, 3); + assert_eq!(summary.losses, 1); + assert_eq!(summary.winrate, 75); + assert_eq!(summary.top.len(), 2); + assert_eq!(summary.top[0].name, "Debonair Zed"); + assert_eq!(summary.top[0].winrate, 67); + assert_eq!(summary.top[1].name, "Nightbringer Yasuo"); + assert_eq!(summary.top[1].winrate, 100); + + let _ = std::fs::remove_dir_all(&dir); // ignore-ok: test temp dir teardown + } +} diff --git a/crates/bullet-app/src/lib.rs b/crates/bullet-app/src/lib.rs index 743bd65..9df9268 100644 --- a/crates/bullet-app/src/lib.rs +++ b/crates/bullet-app/src/lib.rs @@ -7,7 +7,7 @@ mod selection; mod updates; pub use diagnostics::{control_panel, native_integration, startup}; -pub use game::{auto_accept, live_game}; +pub use game::{auto_accept, live_game, stats}; pub use party::party_manager; pub(crate) use selection::book_store; pub use selection::{ diff --git a/crates/bullet-app/src/logging.rs b/crates/bullet-app/src/logging.rs index 953c680..35ace92 100644 --- a/crates/bullet-app/src/logging.rs +++ b/crates/bullet-app/src/logging.rs @@ -9,13 +9,28 @@ use tracing_subscriber::{EnvFilter, fmt, layer::SubscriberExt, util::SubscriberI const LOG_FILES_KEPT: usize = 7; const DEFAULT_FILTER: &str = "info"; +const NOISY_HTTP_CRATES: &str = + "hyper_util=warn,hyper=warn,reqwest=warn,rustls=warn,h2=warn,tungstenite=warn,mio=warn"; + +fn normalize_filter_spec(value: &str) -> String { + let trimmed = value.trim(); + if !trimmed.contains(',') + && !trimmed.contains('=') + && (trimmed.eq_ignore_ascii_case("debug") || trimmed.eq_ignore_ascii_case("trace")) + { + format!("{trimmed},{NOISY_HTTP_CRATES}") + } else { + trimmed.to_owned() + } +} fn env_filter(rejected: &mut Vec) -> EnvFilter { for var in [bullet_core::env::LOG, "RUST_LOG"] { if let Ok(value) = std::env::var(var) { let value = value.trim(); if !value.is_empty() { - match EnvFilter::try_new(value) { + let spec = normalize_filter_spec(value); + match EnvFilter::try_new(&spec) { Ok(filter) => return filter, Err(e) => { rejected.push(format!("{var}='{value}': {e}")); @@ -130,7 +145,15 @@ mod tests { assert_eq!(env_filter(&mut Vec::new()).to_string(), DEFAULT_FILTER); unsafe { std::env::set_var("BULLET_LOG", "debug") }; - assert_eq!(env_filter(&mut Vec::new()).to_string(), "debug"); + let rendered = env_filter(&mut Vec::new()).to_string(); + assert!(rendered.contains("debug")); + assert!(rendered.contains("hyper_util=warn")); + assert!(rendered.contains("reqwest=warn")); + + unsafe { std::env::set_var("BULLET_LOG", "bullet_app=trace,hyper_util=debug") }; + let explicit = env_filter(&mut Vec::new()).to_string(); + assert!(explicit.contains("bullet_app=trace")); + assert!(explicit.contains("hyper_util=debug")); unsafe { std::env::set_var("BULLET_LOG", "=,,,=") }; assert_eq!(env_filter(&mut Vec::new()).to_string(), DEFAULT_FILTER); diff --git a/crates/bullet-app/src/main.rs b/crates/bullet-app/src/main.rs index c81ddc7..f1f9fd1 100644 --- a/crates/bullet-app/src/main.rs +++ b/crates/bullet-app/src/main.rs @@ -14,6 +14,7 @@ const INSTANCE_NAME: &str = "bullet"; const BLOCKING_TASKS_GRACE: std::time::Duration = std::time::Duration::from_secs(3); +#[cfg(not(target_os = "macos"))] fn main() -> Result<()> { boot::cli::attach_parent_console(); let runtime = tokio::runtime::Builder::new_multi_thread() @@ -24,6 +25,11 @@ fn main() -> Result<()> { outcome } +#[cfg(target_os = "macos")] +fn main() -> Result<()> { + boot::cli::run_macos_main(BLOCKING_TASKS_GRACE, || Box::pin(run())) +} + async fn run() -> Result<()> { let args: Vec = std::env::args().collect(); if let Some(code) = boot::cli::handle_cli_args(&args).await? { @@ -180,6 +186,11 @@ async fn run() -> Result<()> { enabled = light_loading, "Light match loading setting loaded" ); + let in_client_ui = bullet_platform::preferences::IN_CLIENT_UI.load(); + info!( + enabled = in_client_ui, + "In-client skin selection setting loaded" + ); let update_notice = bullet_app::update_check::UpdateNotice::default(); let live_game = bullet_app::live_game::LiveGame::default(); @@ -318,7 +329,7 @@ async fn run() -> Result<()> { }; if instance_guard.is_some() { - boot::tasks::spawn_activation_listener(&mut supervisor, panel_links); + boot::tasks::spawn_activation_listener(&mut supervisor, panel_links.clone()); } match bullet_platform::overlay_window::OverlayWindow::spawn() { @@ -330,7 +341,8 @@ async fn run() -> Result<()> { state_rx.clone(), library_root, mods_config, - ); + ) + .with_panel_links(panel_links); supervisor.spawn_essential("overlay-session", move |child_token| async move { session.run(child_token).await; drop(overlay); @@ -353,6 +365,7 @@ async fn run() -> Result<()> { info!("Shutting down supervised tasks"); supervisor.shutdown().await; + bullet_inject::ltf::shutdown_bridge().await; let dropped = logging.dropped.dropped_lines(); if dropped > 0 { warn!( diff --git a/crates/bullet-app/src/selection/catalog/classic.rs b/crates/bullet-app/src/selection/catalog/classic.rs index 8c1f753..11876b7 100644 --- a/crates/bullet-app/src/selection/catalog/classic.rs +++ b/crates/bullet-app/src/selection/catalog/classic.rs @@ -94,6 +94,7 @@ pub fn build_classic_catalog( quote: None, mods: ModsPanel::default(), notice: None, + party: Default::default(), }; (catalog, dropped) } diff --git a/crates/bullet-app/src/selection/catalog/mod.rs b/crates/bullet-app/src/selection/catalog/mod.rs index 276dfc3..81a36a2 100644 --- a/crates/bullet-app/src/selection/catalog/mod.rs +++ b/crates/bullet-app/src/selection/catalog/mod.rs @@ -145,6 +145,7 @@ pub fn build_catalog(library: &ChampionLibrary, assets: Option<&ChampionAssets>) notice: None, classic: false, lobby: Vec::new(), + party: Default::default(), } } @@ -388,7 +389,9 @@ mod preview; pub use classic::{build_classic_catalog, load_classic_catalog}; use preview::PREVIEW_FETCHES; -pub use preview::{PreviewFetches, chroma_preview_fetches}; +pub use preview::{ + PreviewFetches, UrgentPreview, chroma_preview_fetches, fetch_single_chroma_preview, +}; #[cfg(test)] mod tests; diff --git a/crates/bullet-app/src/selection/catalog/preview.rs b/crates/bullet-app/src/selection/catalog/preview.rs index 5dcf48e..e15e142 100644 --- a/crates/bullet-app/src/selection/catalog/preview.rs +++ b/crates/bullet-app/src/selection/catalog/preview.rs @@ -1,10 +1,12 @@ use super::*; -pub(super) const PREVIEW_FETCHES: usize = 4; +pub(super) const PREVIEW_FETCHES: usize = 16; pub type PreviewFetches = futures_util::stream::BoxStream<'static, (u32, Result, String>)>; +pub type UrgentPreview = futures_util::future::BoxFuture<'static, (u32, Result, String>)>; + pub fn chroma_preview_fetches(previews: Vec<(u32, String)>) -> PreviewFetches { use futures_util::StreamExt; futures_util::stream::once(lcu_client()) @@ -25,6 +27,18 @@ pub fn chroma_preview_fetches(previews: Vec<(u32, String)>) -> PreviewFetches { .boxed() } +pub fn fetch_single_chroma_preview(chroma_id: u32, path: String) -> UrgentPreview { + use futures_util::FutureExt; + async move { + let image = match lcu_client().await { + Some(client) => fetch_chroma_preview(&client, &path).await, + None => Err("the League client could not be reached".to_owned()), + }; + (chroma_id, image) + } + .boxed() +} + pub(super) async fn fetch_chroma_preview( client: &bullet_lcu::client::LcuClient, path: &str, diff --git a/crates/bullet-app/src/selection/mod_repair/mod.rs b/crates/bullet-app/src/selection/mod_repair/mod.rs index 120ce7d..0f82216 100644 --- a/crates/bullet-app/src/selection/mod_repair/mod.rs +++ b/crates/bullet-app/src/selection/mod_repair/mod.rs @@ -264,6 +264,18 @@ pub fn repair_custom_mods( warn!(game_dir = %game_dir.display(), "Custom mods not checked at startup: the game executable was not found"); return report; }; + let mut root_mods = Vec::with_capacity(roots.len()); + let mut total_mods = 0usize; + for root in roots { + let mut mods = Vec::new(); + collect_mods(root, &mut mods); + total_mods += mods.len(); + root_mods.push((root, mods)); + } + if total_mods == 0 { + debug!("No custom mods found; skipping game WAD indexing at startup"); + return report; + } let game = match get_or_index_game(game_dir) { Ok(game) => game, Err(e) => { @@ -290,9 +302,7 @@ pub fn repair_custom_mods( let mut unstamped = 0usize; let mut first_unstamped: Option = None; let mut repairer = Repairer::new(&game, &hashes); - for root in roots { - let mut mods = Vec::new(); - collect_mods(root, &mut mods); + for (root, mods) in root_mods { let cx = Context { root, state: state_dir, diff --git a/crates/bullet-app/src/selection/mod_repair/restore_tests.rs b/crates/bullet-app/src/selection/mod_repair/restore_tests.rs index 3220c26..e9eb5eb 100644 --- a/crates/bullet-app/src/selection/mod_repair/restore_tests.rs +++ b/crates/bullet-app/src/selection/mod_repair/restore_tests.rs @@ -106,6 +106,7 @@ fn test_restore_waits_for_a_running_check_and_a_check_waits_for_restore() { let _ = std::fs::remove_dir_all(&dir); // ignore-ok: cleanup } +#[cfg(windows)] #[test] fn test_a_restore_that_cannot_put_a_file_back_reports_it_and_keeps_the_rest_consistent() { let dir = temp("restore_fail"); diff --git a/crates/bullet-app/src/selection/overlay_session/choice.rs b/crates/bullet-app/src/selection/overlay_session/choice.rs index 823e4e1..4c83d6c 100644 --- a/crates/bullet-app/src/selection/overlay_session/choice.rs +++ b/crates/bullet-app/src/selection/overlay_session/choice.rs @@ -72,7 +72,10 @@ pub(super) fn handle_command( } OverlayCommand::SetMods { .. } + | OverlayCommand::SetIdentity { .. } + | OverlayCommand::JoinLobbyParty | OverlayCommand::OpenModsFolder + | OverlayCommand::OpenPanel | OverlayCommand::ImportMod { .. } | OverlayCommand::ChromaPreview { .. } | OverlayCommand::FocusChampion { .. } diff --git a/crates/bullet-app/src/selection/overlay_session/mod.rs b/crates/bullet-app/src/selection/overlay_session/mod.rs index f6d21e2..79cae7d 100644 --- a/crates/bullet-app/src/selection/overlay_session/mod.rs +++ b/crates/bullet-app/src/selection/overlay_session/mod.rs @@ -86,11 +86,17 @@ pub struct OverlaySession { preview_fetches: Option, + urgent_preview: Option, + preview_tally: PreviewTally, pending_import: Option, warm_turn: std::sync::Arc, + + panel_links: Option, + + global_mods_loaded: bool, } #[derive(Debug, Clone)] @@ -116,6 +122,9 @@ impl OverlaySession { ) -> Self { let historic = historic_store::load(&mods.state_dir); let presets = preset_store::load(&mods.state_dir); + if let Some(identity) = mods::load_identity(&mods.state_dir) { + bullet_core::state::set_local_identity(&state_tx, Some(identity)); + } Self { controller, commands, @@ -137,66 +146,41 @@ impl OverlaySession { random_declined: None, chroma_previews: std::collections::HashMap::new(), preview_fetches: None, + urgent_preview: None, preview_tally: PreviewTally::default(), pending_import: None, warm_turn: std::sync::Arc::default(), + panel_links: None, + global_mods_loaded: false, } } + #[must_use] + pub fn with_panel_links(mut self, links: Option) -> Self { + self.panel_links = links; + self + } + pub async fn run(mut self, token: CancellationToken) { let mut shown = false; + let mut in_client_active = false; let mut catalog_key = CatalogKey::default(); let mut catalog_champion: Option = None; let mut catalog: Option = None; let mut party_shown = None; + let tools_dirs: Vec = self + .mods + .injection_tools + .iter() + .filter_map(|p| p.parent().map(PathBuf::from)) + .collect(); loop { tokio::select! { _ = token.cancelled() => break, command = self.commands.recv() => { match command { - Some(OverlayCommand::SetMods { selection }) => { - self.apply_mod_request(&selection, catalog_champion); - } - Some(OverlayCommand::OpenModsFolder) => self.open_mods_folder(), - Some(OverlayCommand::Clear) => { - self.dismiss_historic(); - self.random_declined = catalog_champion; - handle_command(&self.state_tx, OverlayCommand::Clear, catalog.as_ref()); - } - Some(OverlayCommand::Random) => self.roll_random(catalog.as_ref()), - Some(OverlayCommand::ChromaPreview { id }) => { - self.send_chroma_preview(id, catalog.as_ref()); - } - Some(OverlayCommand::TogglePreset) => self.toggle_preset(catalog_champion), - Some(OverlayCommand::SetProfile { name }) => { - if self.presets.switch_to(&name) { - info!(profile = %name, "Skin profile switched"); - self.profile_changed(catalog_champion); - } - } - Some(OverlayCommand::NewProfile) => { - let locale = catalog.as_ref().and_then(|c| c.locale.clone()); - self.new_profile(locale.as_deref(), catalog_champion); - } - Some(OverlayCommand::DeleteProfile) => { - if let Some(name) = self.presets.delete_active() { - info!(profile = %name, "Skin profile deleted; the default profile is active"); - self.profile_changed(catalog_champion); - } - } - Some(OverlayCommand::FocusChampion { id }) => { - if focus_lobby_champion(&self.state_tx, id) { - info!(champion_id = id, "Lobby champion shown in the overlay"); - } - } - Some(OverlayCommand::ImportMod { category }) => { - let locale = catalog.as_ref().and_then(|c| c.locale.clone()); - let alias = catalog.as_ref().and_then(|c| c.alias.clone()); - self.start_import(category, catalog_champion, alias, locale.as_deref()); - } - Some(command) => handle_command(&self.state_tx, command, catalog.as_ref()), - + Some(cmd) => self.dispatch_command(cmd, catalog_champion, catalog.as_ref()), None => { warn!("Overlay command channel closed; the selection UI is gone"); break; @@ -213,8 +197,12 @@ impl OverlaySession { Some((id, Err(reason))) => self.count_failed_preview(id, reason), None => self.finish_preview_fetches(), }, + (id, outcome) = next_urgent_preview(&mut self.urgent_preview) => match outcome { + Ok(image) => self.deliver_chroma_preview(id, image), + Err(reason) => debug!(chroma_id = id, reason, "Urgent chroma preview on hover not fetched"), + }, () = tokio::time::sleep(TRACK_INTERVAL) => { - let (wanted, finalization, champion, target_stale, target, lcu_skin, confirmed, lobby) = { + let (wanted, finalization, mut champion, target_stale, target, lcu_skin, confirmed, lobby, phase) = { let state = self.state_rx.borrow_and_update(); ( wanted_for_state(&state), @@ -225,8 +213,12 @@ impl OverlaySession { state.selected_skin_id, state.injection == InjectionStatus::Confirmed, state.lobby.as_ref().map(bullet_core::lobby::LobbyPicks::champions), + state.phase, ) }; + if phase == GamePhase::Reconnect && champion.is_none() { + champion = self.recover_reconnect_champion().await; + } let party = { let state = self.state_rx.borrow(); bullet_core::party::party_summary( @@ -246,7 +238,10 @@ impl OverlaySession { self.lobby_auto.clear(); } - let placement = track_once(&self.controller, wanted); + let in_client = bullet_platform::preferences::IN_CLIENT_UI.is_enabled(); + let use_in_client = in_client && phase != GamePhase::Reconnect; + let hide_slint = use_in_client && in_client_active; + let placement = track_once(&self.controller, wanted && !hide_slint); let now_shown = placement.is_some(); if now_shown != shown { shown = now_shown; @@ -268,12 +263,10 @@ impl OverlaySession { }; if key != catalog_key { catalog_key = key.clone(); - if champion != catalog_champion { - self.chroma_previews.clear(); - } catalog_champion = champion; catalog = self.refresh_catalog(champion, key.lobby.as_deref()).await; self.preview_fetches = None; + self.urgent_preview = None; if let Some(built) = catalog.as_ref() { self.start_preview_fetches(built.chroma_preview_paths()); } @@ -300,10 +293,32 @@ impl OverlaySession { self.track_historic(champion_id, built, target.as_ref(), lcu_skin); self.random_when_nothing_chosen(champion_id, built, finalization, lcu_skin); } + let selected_id = self + .state_rx + .borrow() + .overlay_target + .as_ref() + .filter(|t| Some(t.champion_id) == champion) + .map(OverlayTarget::package_entry_id); + let in_client_catalog = self + .in_client_catalog_snapshot(wanted, use_in_client, phase, catalog.as_ref()) + .await; + let (in_client_cmds, active) = bullet_inject::ltf::sync_in_client_ui( + use_in_client, + &tools_dirs, + in_client_catalog.as_ref(), + selected_id, + ) + .await; + in_client_active = active; + for cmd in in_client_cmds { + self.dispatch_command(cmd, catalog_champion, catalog.as_ref()); + } } } } + let _ = bullet_inject::ltf::sync_in_client_ui(false, &tools_dirs, None, None).await; // ignore-ok: drain in-client commands on shutdown self.controller.hide(); info!("Overlay session terminated"); } @@ -340,17 +355,11 @@ impl OverlaySession { if !self.mods.injection_tools.iter().all(|file| file.is_file()) { built.notice = Some(catalog::CatalogNotice::ToolsMissing); } - let chromas = built - .skins - .iter() - .map(|skin| skin.chromas.len()) - .sum::(); + let chromas: usize = built.skins.iter().map(|s| s.chromas.len()).sum(); let without_preview: Vec = built .skins .iter() - .flat_map(|skin| skin.chromas.iter()) - .filter(|chroma| !chroma.has_preview) - .map(|chroma| chroma.id) + .flat_map(|s| s.chromas.iter().filter(|c| !c.has_preview).map(|c| c.id)) .collect(); info!( champion_id, @@ -378,7 +387,7 @@ mod choice; use choice::handle_command; pub use choice::{RandomFallback, should_roll_random}; use import::{PendingImport, next_import}; -use preview::{PreviewTally, next_preview}; +use preview::{PreviewTally, next_preview, next_urgent_preview}; mod import; mod mods; mod preview; diff --git a/crates/bullet-app/src/selection/overlay_session/mods.rs b/crates/bullet-app/src/selection/overlay_session/mods.rs index 3ebf2bc..9da5096 100644 --- a/crates/bullet-app/src/selection/overlay_session/mods.rs +++ b/crates/bullet-app/src/selection/overlay_session/mods.rs @@ -1,5 +1,30 @@ use super::*; +pub(super) fn load_identity( + state_dir: &std::path::Path, +) -> Option { + let raw = std::fs::read_to_string(state_dir.join("identity.json")).ok()?; + let parsed: bullet_core::identity::IdentityLoadout = serde_json::from_str(&raw).ok()?; + parsed.normalized() +} + +fn save_identity( + state_dir: &std::path::Path, + loadout: Option<&bullet_core::identity::IdentityLoadout>, +) { + let path = state_dir.join("identity.json"); + match loadout { + Some(value) => { + if let Ok(bytes) = serde_json::to_vec(value) { + let _ = bullet_platform::fs::atomic_write(&path, &bytes, false); // ignore-ok: best-effort identity persistence + } + } + None => { + let _ = std::fs::remove_file(&path); // ignore-ok: identity file may not exist yet + } + } +} + impl OverlaySession { pub(super) fn warm_champion(&self, alias: Option) { let Some(alias) = alias else { @@ -12,40 +37,21 @@ impl OverlaySession { return; }; let cache_dir = self.mods.state_dir.clone(); - let state_rx = self.state_rx.clone(); let turn = std::sync::Arc::clone(&self.warm_turn); let mine = turn.fetch_add(1, std::sync::atomic::Ordering::AcqRel) + 1; drop(tokio::task::spawn_blocking(move || { - let started = std::time::Instant::now(); + if turn.load(std::sync::atomic::Ordering::Acquire) != mine + || bullet_classic::generator::companion_cache_is_current( + &game_dir, &cache_dir, &alias, + ) + { + return; + } if let Err(e) = bullet_classic::generator::StandardChampion::open(&game_dir, &alias) .map(|champion| champion.with_cache_dir(&cache_dir).companions()) { debug!(error = %e, "Companion characters not indexed ahead of the build"); } - let skin_bin = bullet_wad::hash::wad_path_hash(&format!( - "data/characters/{}/skins/skin0.bin", - alias.to_ascii_lowercase() - )); - match bullet_inject::overlay_builder::read_wads_ahead(&game_dir, &[skin_bin], &|| { - state_rx.borrow().phase.is_in_game() - || turn.load(std::sync::atomic::Ordering::Acquire) != mine - }) { - Ok(read) => info!( - alias = %alias, - files = read.files, - bytes = read.bytes, - elapsed_ms = started.elapsed().as_millis(), - "Champion WAD read ahead; the patcher build finds it in the file cache" - ), - Err(bullet_inject::error::InjectError::Cancelled) => debug!( - alias = %alias, - elapsed_ms = started.elapsed().as_millis(), - "Champion WAD read-ahead stopped: another champion took its place or the match started" - ), - Err(e) => { - warn!(alias = %alias, error = %e, "Champion WAD not read ahead; the patcher build reads it from the disk") - } - } })); } @@ -127,4 +133,160 @@ impl OverlaySession { self.controller.set_mod_selection(next.view(champion)); } + + pub(super) fn dispatch_command( + &mut self, + command: OverlayCommand, + catalog_champion: Option, + catalog: Option<&Catalog>, + ) { + match command { + OverlayCommand::SetMods { selection } => { + self.apply_mod_request(&selection, catalog_champion); + } + OverlayCommand::SetIdentity { loadout } => { + let clean = loadout.and_then(bullet_core::identity::IdentityLoadout::normalized); + save_identity(&self.mods.state_dir, clean.as_ref()); + bullet_core::state::set_local_identity(&self.state_tx, clean); + info!("Customize Identity loadout updated"); + } + OverlayCommand::JoinLobbyParty => { + bullet_core::state::set_party_share(&self.state_tx, true); + drop(tokio::task::spawn_blocking(|| { + let _ = bullet_platform::party_dialog::dismiss_lobby_invite(); // ignore-ok: dialog may not be open + })); + info!("Party: joined lobby sharing from in-client button"); + } + OverlayCommand::OpenModsFolder => self.open_mods_folder(), + OverlayCommand::OpenPanel => { + if let Some(links) = self.panel_links.clone() { + bullet_platform::panel::show_panel(links); + } + } + OverlayCommand::Clear => { + self.dismiss_historic(); + self.random_declined = catalog_champion; + handle_command(&self.state_tx, OverlayCommand::Clear, catalog); + } + OverlayCommand::Random => self.roll_random(catalog), + OverlayCommand::ChromaPreview { id } => { + self.send_chroma_preview(id, catalog); + } + OverlayCommand::TogglePreset => self.toggle_preset(catalog_champion), + OverlayCommand::SetProfile { name } => { + if self.presets.switch_to(&name) { + info!(profile = %name, "Skin profile switched"); + self.profile_changed(catalog_champion); + } + } + OverlayCommand::NewProfile => { + let locale = catalog.and_then(|c| c.locale.clone()); + self.new_profile(locale.as_deref(), catalog_champion); + } + OverlayCommand::DeleteProfile => { + if let Some(name) = self.presets.delete_active() { + info!(profile = %name, "Skin profile deleted; the default profile is active"); + self.profile_changed(catalog_champion); + } + } + OverlayCommand::FocusChampion { id } => { + if focus_lobby_champion(&self.state_tx, id) { + info!(champion_id = id, "Lobby champion shown in the overlay"); + } + } + OverlayCommand::ImportMod { category } => { + let locale = catalog.and_then(|c| c.locale.clone()); + let alias = catalog.and_then(|c| c.alias.clone()); + self.start_import(category, catalog_champion, alias, locale.as_deref()); + } + other => handle_command(&self.state_tx, other, catalog), + } + } + + pub(super) async fn recover_reconnect_champion(&mut self) -> Option { + let client = bullet_lcu::client::LcuClient::discover().await.ok()?; + let live = bullet_lcu::live_selection::resolve_live_selection(&client, None) + .await + .ok()?; + info!( + champion_id = live.champion_id, + skin_id = live.skin_id, + "Recovered champion on reconnect screen so skin selection is available" + ); + bullet_core::state::set_champion(&self.state_tx, live.champion_id); + if live.skin_id != 0 { + bullet_core::state::set_selected_skin(&self.state_tx, live.skin_id); + } + Some(live.champion_id) + } + + fn party_view(&self) -> bullet_core::overlay::InClientPartyView { + let state = self.state_rx.borrow(); + let connected = match state.party_status { + bullet_core::party::PartyStatus::Connected { members } => members, + _ => 0, + }; + let joinable_friends = if !state.party_share + && connected >= 2 + && bullet_core::party::may_ask_to_share(state.phase) + { + connected - 1 + } else { + 0 + }; + let peer_identities = state + .party_peers + .iter() + .filter_map(|p| { + p.identity + .as_ref() + .filter(|id| !id.is_empty()) + .map(|id| (p.puuid.clone(), id.clone())) + }) + .collect(); + bullet_core::overlay::InClientPartyView { + joinable_friends, + connected_members: if state.party_share { connected } else { 0 }, + local_identity: state.local_identity.clone(), + peer_identities, + } + } + + pub(super) async fn in_client_catalog_snapshot( + &mut self, + wanted: bool, + use_in_client: bool, + phase: GamePhase, + catalog: Option<&Catalog>, + ) -> Option { + if !use_in_client || phase == GamePhase::InProgress { + return None; + } + let party = self.party_view(); + if let Some(active) = catalog.filter(|_| wanted) { + let mut copy = active.clone(); + copy.mods.selection = self.state_rx.borrow().mods.view(Some(copy.champion_id)); + copy.party = party; + return Some(copy); + } + if !self.global_mods_loaded { + let roots = self.mods.roots.clone(); + let scanned = tokio::task::spawn_blocking(move || { + bullet_core::mods::scan_catalog(&roots, None, &|_| true) + }) + .await + .unwrap_or_default(); + self.mod_catalog = scanned; + self.global_mods_loaded = true; + } + let selection = self.state_rx.borrow().mods.view(None); + Some(Catalog { + mods: ModsPanel { + available: self.mod_catalog.clone(), + selection, + }, + party, + ..Catalog::default() + }) + } } diff --git a/crates/bullet-app/src/selection/overlay_session/preview.rs b/crates/bullet-app/src/selection/overlay_session/preview.rs index da6fdaf..f1b0bde 100644 --- a/crates/bullet-app/src/selection/overlay_session/preview.rs +++ b/crates/bullet-app/src/selection/overlay_session/preview.rs @@ -1,5 +1,7 @@ use super::*; +const MAX_CACHED_PREVIEWS: usize = 512; + pub(super) async fn next_preview( fetches: &mut Option, ) -> Option<(u32, Result, String>)> { @@ -9,6 +11,19 @@ pub(super) async fn next_preview( } } +pub(super) async fn next_urgent_preview( + urgent: &mut Option, +) -> (u32, Result, String>) { + match urgent { + Some(task) => { + let result = task.await; + *urgent = None; + result + } + None => std::future::pending().await, + } +} + #[derive(Debug, Default)] pub(super) struct PreviewTally { asked: usize, @@ -30,39 +45,48 @@ impl OverlaySession { self.controller.set_chroma_preview(chroma_id, image.clone()); return; } - if self.preview_fetches.is_some() { - debug!( - chroma_id, - asked = self.preview_tally.asked, - fetched = self.preview_tally.fetched, - failed = self.preview_tally.failed, - "Chroma preview asked while previews are still being fetched; it is shown when it arrives" - ); - return; - } let Some(path) = catalog.and_then(|c| c.chroma_preview_path(chroma_id)) else { debug!(chroma_id, "Chroma preview asked for an entry without one"); return; }; - debug!(chroma_id, path, "Chroma preview fetched again on hover"); - self.start_preview_fetches(vec![(chroma_id, path.to_owned())]); + debug!(chroma_id, path, "Chroma preview urgently fetched on hover"); + self.urgent_preview = Some(catalog::fetch_single_chroma_preview( + chroma_id, + path.to_owned(), + )); } pub(super) fn start_preview_fetches(&mut self, previews: Vec<(u32, String)>) { - if previews.is_empty() { + let mut missing = Vec::with_capacity(previews.len()); + for (id, path) in previews { + if let Some(image) = self.chroma_previews.get(&id) { + self.controller.set_chroma_preview(id, image.clone()); + } else { + missing.push((id, path)); + } + } + if missing.is_empty() { return; } self.preview_tally = PreviewTally { - asked: previews.len(), + asked: missing.len(), started: Some(std::time::Instant::now()), ..PreviewTally::default() }; - self.preview_fetches = Some(catalog::chroma_preview_fetches(previews)); + self.preview_fetches = Some(catalog::chroma_preview_fetches(missing)); } pub(super) fn deliver_chroma_preview(&mut self, chroma_id: u32, image: std::sync::Arc<[u8]>) { - self.preview_tally.fetched += 1; - self.preview_tally.bytes += image.len(); + let first_time = !self.chroma_previews.contains_key(&chroma_id); + if first_time { + self.preview_tally.fetched += 1; + self.preview_tally.bytes += image.len(); + if self.chroma_previews.len() >= MAX_CACHED_PREVIEWS { + if let Some(&evict) = self.chroma_previews.keys().next() { + self.chroma_previews.remove(&evict); + } + } + } debug!( chroma_id, bytes = image.len(), diff --git a/crates/bullet-app/src/selection/overlay_session/tests/mod.rs b/crates/bullet-app/src/selection/overlay_session/tests/mod.rs index d7565cb..7b92c37 100644 --- a/crates/bullet-app/src/selection/overlay_session/tests/mod.rs +++ b/crates/bullet-app/src/selection/overlay_session/tests/mod.rs @@ -124,6 +124,7 @@ fn zed_catalog() -> Catalog { notice: None, classic: false, lobby: Vec::new(), + party: Default::default(), } } @@ -282,3 +283,12 @@ fn test_the_random_skin_never_overrides_a_choice() { assert!(!should_roll_random(157, blocked), "{blocked:?}"); } } + +#[tokio::test] +async fn in_client_ui_stub_returns_no_commands_when_not_linked() { + let cat = zed_catalog(); + let (cmds, active) = + bullet_inject::ltf::sync_in_client_ui(false, &[], Some(&cat), Some(238_001)).await; + assert!(cmds.is_empty()); + assert!(!active); +} diff --git a/crates/bullet-app/src/trigger/arm/arming.rs b/crates/bullet-app/src/trigger/arm/arming.rs index 0c72148..3f6aec9 100644 --- a/crates/bullet-app/src/trigger/arm/arming.rs +++ b/crates/bullet-app/src/trigger/arm/arming.rs @@ -246,7 +246,11 @@ impl InjectionTrigger { ) -> Option { let client = self.lcu_client().await?; - let owned = match client.get_owned_skin_ids().await { + let (owned_res, parent) = tokio::join!( + client.get_owned_skin_ids(), + parent_skin(&client, champ_id, entry_id) + ); + let owned = match owned_res { Ok(owned) => owned, Err(e) => { warn!( @@ -258,7 +262,6 @@ impl InjectionTrigger { } }; - let parent = parent_skin(&client, champ_id, entry_id).await; let skin_id = bullet_lcu::skin_registration::skin_to_register(champ_id, entry_id, parent, &owned); info!( diff --git a/crates/bullet-app/src/trigger/mod.rs b/crates/bullet-app/src/trigger/mod.rs index 864c10e..d3a477a 100644 --- a/crates/bullet-app/src/trigger/mod.rs +++ b/crates/bullet-app/src/trigger/mod.rs @@ -353,6 +353,9 @@ impl InjectionTrigger { } drop(arming); + if let Some(running) = active_overlay.take() { + running.shutdown().await; + } if let Some(stale) = armed.take() { stale.overlay.shutdown().await; } diff --git a/crates/bullet-app/src/trigger/prepare/mods.rs b/crates/bullet-app/src/trigger/prepare/mods.rs index 4d0af7d..2441be0 100644 --- a/crates/bullet-app/src/trigger/prepare/mods.rs +++ b/crates/bullet-app/src/trigger/prepare/mods.rs @@ -7,9 +7,27 @@ impl InjectionTrigger { } let mut mods = Vec::new(); + let mut loading_picks = Vec::new(); for (champ_id, entry_id) in key.picks() { match self.prepare_mods(champ_id, entry_id).await { - Some(prepared) => mods.extend(prepared), + Some(prepared) => { + if let Some(first) = prepared.first() { + let parent_skin_id = { + let state = self.state_rx.borrow(); + state + .overlay_target + .as_ref() + .filter(|t| t.champion_id == champ_id) + .map(|t| t.skin_id) + }; + loading_picks.push(bullet_classic::loading_name::LoadingNamePick { + mod_folder: self.paths.mods_dir.join(first), + skin_id: entry_id, + parent_skin_id, + }); + } + mods.extend(prepared); + } None if !key.lobby => return None, None => warn!( champ_id, @@ -19,6 +37,7 @@ impl InjectionTrigger { } } + let mut other_mod_paths: Vec = Vec::new(); if key.mods != 0 { let (selection, champions) = { let state = self.state_rx.borrow(); @@ -60,7 +79,12 @@ impl InjectionTrigger { }) .await; match staged { - Ok(staged) => mods.extend(staged), + Ok(staged) => { + for name in &staged { + other_mod_paths.push(self.paths.mods_dir.join(name)); + } + mods.extend(staged); + } Err(e) => { warn!(error = %e, "Custom mod staging task failed; continuing without them") } @@ -68,7 +92,28 @@ impl InjectionTrigger { } if key.party != 0 { - mods.extend(self.party_mods(key).await); + let party = self.party_mods(key).await; + for name in &party { + other_mod_paths.push(self.paths.mods_dir.join(name)); + } + mods.extend(party); + } + + if !loading_picks.is_empty() { + let game_dir = self.effective_game_dir(None); + let mods_dir = self.paths.mods_dir.clone(); + if let Ok(Some(loading_mod)) = tokio::task::spawn_blocking(move || { + bullet_classic::loading_name::build_loading_name_mod( + &game_dir, + &mods_dir, + &loading_picks, + &other_mod_paths, + ) + }) + .await + { + mods.push(loading_mod); + } } if mods.is_empty() { diff --git a/crates/bullet-app/src/trigger/prepare/paths.rs b/crates/bullet-app/src/trigger/prepare/paths.rs index 416e61e..9bce4a5 100644 --- a/crates/bullet-app/src/trigger/prepare/paths.rs +++ b/crates/bullet-app/src/trigger/prepare/paths.rs @@ -112,22 +112,39 @@ pub enum ToolsSource { } pub(crate) fn resolve_tools_dir(candidates: &[PathBuf]) -> (PathBuf, ToolsSource) { - let complete = |dir: &PathBuf| { - (dir.join(LTF_LAUNCHER_EXE).is_file() && dir.join(LTF_BRIDGE_DLL).is_file()) - || (dir.join("bullet-br.exe").is_file() && dir.join("bullet-br.dll").is_file()) - }; - if let Some(dir) = candidates.iter().find(|dir| complete(dir)) { - info!(tools = %dir.display(), "Injection tools found"); - return (dir.clone(), ToolsSource::Own); + #[cfg(target_os = "macos")] + { + let dir = candidates.first().cloned().unwrap_or_default(); + info!(tools = %dir.display(), "Built-in macOS Mach-O engine active"); + return (dir, ToolsSource::Own); + } + #[cfg(not(target_os = "macos"))] + { + let complete = |dir: &PathBuf| { + (dir.join(LTF_LAUNCHER_EXE).is_file() && dir.join(LTF_BRIDGE_DLL).is_file()) + || (dir.join("bullet-br.exe").is_file() && dir.join("bullet-br.dll").is_file()) + }; + if let Some(dir) = candidates.iter().find(|dir| complete(dir)) { + info!(tools = %dir.display(), "Injection tools found"); + return (dir.clone(), ToolsSource::Own); + } + ( + candidates.first().cloned().unwrap_or_default(), + ToolsSource::Missing, + ) } - ( - candidates.first().cloned().unwrap_or_default(), - ToolsSource::Missing, - ) } +#[cfg_attr(target_os = "macos", allow(unused_variables))] pub fn required_tool_files(paths: &ResolvedPaths) -> Vec { - vec![paths.native_host_exe.clone(), paths.native_dll_path.clone()] + #[cfg(target_os = "macos")] + { + Vec::new() + } + #[cfg(not(target_os = "macos"))] + { + vec![paths.native_host_exe.clone(), paths.native_dll_path.clone()] + } } pub fn tools_ready(paths: &ResolvedPaths) -> bool { diff --git a/crates/bullet-app/src/trigger/support.rs b/crates/bullet-app/src/trigger/support.rs index 0b2db51..b2bb2fb 100644 --- a/crates/bullet-app/src/trigger/support.rs +++ b/crates/bullet-app/src/trigger/support.rs @@ -50,9 +50,7 @@ impl InjectionTrigger { .or_else(|| bullet_platform::paths::normalize_game_dir(&self.paths.game_dir)) .or_else(bullet_platform::paths::discover_game_dir) .unwrap_or_else(|| self.paths.game_dir.clone()); - if dir.is_dir() { - bullet_inject::overlay_builder::prewarm_game_index(&dir); - } else { + if !dir.is_dir() { warn!(game = %dir.display(), "The game folder is not known or does not exist; the overlay build may fail"); } dir diff --git a/crates/bullet-app/src/trigger/tests/mod.rs b/crates/bullet-app/src/trigger/tests/mod.rs index f0c1a0a..ee4b56f 100644 --- a/crates/bullet-app/src/trigger/tests/mod.rs +++ b/crates/bullet-app/src/trigger/tests/mod.rs @@ -280,6 +280,7 @@ fn with_party(mut state: bullet_core::state::AppState) -> bullet_core::state::Ap champion_id: 103, skin_id: 103_015, chroma_id: None, + identity: None, }]; state } diff --git a/crates/bullet-app/src/updates/self_update/mod.rs b/crates/bullet-app/src/updates/self_update/mod.rs index 41125db..8e4bc19 100644 --- a/crates/bullet-app/src/updates/self_update/mod.rs +++ b/crates/bullet-app/src/updates/self_update/mod.rs @@ -13,6 +13,7 @@ use crate::update_check::{REPOSITORY, Version}; const SUMS_FILE: &str = "SHA256SUMS"; pub const SIGNATURE_FILE: &str = "SHA256SUMS.sig"; +#[cfg(windows)] const FILE_SHARE_READ: u32 = 1; pub const SILENT_INSTALL: [&str; 6] = [ @@ -152,12 +153,16 @@ pub fn can_install(phase: GamePhase) -> bool { pub fn open_verified(setup: &StagedSetup) -> Result { use std::io::Read; - use std::os::windows::fs::OpenOptionsExt; let path = &setup.path; - let mut file = std::fs::OpenOptions::new() - .read(true) - .share_mode(FILE_SHARE_READ) + let mut opts = std::fs::OpenOptions::new(); + opts.read(true); + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + opts.share_mode(FILE_SHARE_READ); + } + let mut file = opts .open(path) .map_err(|e| format!("{}: {e}", path.display()))?; let mut hasher = Sha256::new(); diff --git a/crates/bullet-app/src/updates/self_update/tests.rs b/crates/bullet-app/src/updates/self_update/tests.rs index cf90274..3ae0073 100644 --- a/crates/bullet-app/src/updates/self_update/tests.rs +++ b/crates/bullet-app/src/updates/self_update/tests.rs @@ -140,8 +140,11 @@ fn test_the_installer_is_hashed_again_and_held_before_it_runs() { sha256: encode_hex(&Sha256::digest(b"setup")), }; let held = open_verified(&staged).expect("verified"); - assert!(std::fs::write(&path, b"swapped").is_err()); - assert!(std::fs::remove_file(&path).is_err()); + #[cfg(windows)] + { + assert!(std::fs::write(&path, b"swapped").is_err()); + assert!(std::fs::remove_file(&path).is_err()); + } drop(held); std::fs::write(&path, b"swapped").expect("rewrite"); assert!(open_verified(&staged).is_err()); diff --git a/crates/bullet-classic/src/animation/gear/form_gear/mod.rs b/crates/bullet-classic/src/animation/gear/form_gear/mod.rs index 4158cfd..ae0ec6b 100644 --- a/crates/bullet-classic/src/animation/gear/form_gear/mod.rs +++ b/crates/bullet-classic/src/animation/gear/form_gear/mod.rs @@ -5,7 +5,7 @@ use bullet_wad::prop::{parse_prop_file, serialize_prop_file}; use tracing::warn; use crate::error::ClassicError; -use crate::form_state::{form_active, form_parts}; +use crate::form_state::{form_active, form_parts, keep_default_visible}; use crate::gear_toggle::{GearSwap, bin_error, h, named, pointer}; use crate::vfx_markers::{FIELD_EMBED, FIELD_LIST2, FIELD_POINTER, embed, text}; @@ -216,7 +216,8 @@ pub fn gear_coverage( .filter(|name| !name.is_empty()) .map(h) .collect(); - let plan = material_plan(gear_bodies, swaps, &hidden)?; + let normalized = keep_default_visible(swaps, &hidden); + let plan = material_plan(gear_bodies, &normalized, &hidden)?; Ok(GearCoverage { idle_forms: gears.iter().filter(|g| idle_override(g).is_some()).count(), material_parts: plan.overrides.len(), diff --git a/crates/bullet-classic/src/animation/gear/form_gear/tests.rs b/crates/bullet-classic/src/animation/gear/form_gear/tests.rs index 721dd28..7c14155 100644 --- a/crates/bullet-classic/src/animation/gear/form_gear/tests.rs +++ b/crates/bullet-classic/src/animation/gear/form_gear/tests.rs @@ -307,3 +307,54 @@ fn test_a_part_hidden_from_the_start_counts_only_where_a_form_shows_it() { "the first form never shows the part, so it needs no copy" ); } + +#[test] +fn sahn_uzal_persistent_face_keeps_base_material_in_form_0_and_copies_for_form_1() { + let gears = vec![ + gear(Vec::new()), + gear(vec![mesh(vec![named( + "materialOverride", + list(vec![material("Persistent", 99)]), + )])]), + gear(Vec::new()), + ]; + let raw = vec![ + GearSwap { + show: vec![h("Form1"), h("Weapon1")], + hide: vec![h("Form2"), h("Weapon2")], + equip: None, + transition: None, + }, + GearSwap { + show: vec![h("Form2"), h("Weapon2"), h("Persistent")], + hide: vec![h("Form1"), h("Weapon1")], + equip: None, + transition: None, + }, + GearSwap { + show: vec![h("Form2"), h("Weapon2"), h("Persistent")], + hide: vec![h("Form1"), h("Weapon1")], + equip: None, + transition: None, + }, + ]; + let initially_hidden: BTreeSet = [h("Form2"), h("Weapon2")].into_iter().collect(); + let normalized = keep_default_visible(&raw, &initially_hidden); + let plan = material_plan(&gears, &normalized, &initially_hidden).expect("plan"); + assert!( + plan.overrides.is_empty(), + "form 0 uses the skin's own Persistent material; form 1 must not overwrite it" + ); + assert_eq!(plan.copies.len(), 1); + assert_eq!(plan.copies[0].name, "Persistent_F1"); + assert_eq!(plan.copies[0].form, 1); + let moved = with_copies(&normalized, &plan.copies); + let parts = form_parts(&moved); + assert!(parts[0].0.contains(&h("Persistent"))); + assert!(!parts[0].1.contains(&h("Persistent"))); + assert!(parts[0].1.contains(&h("Persistent_F1"))); + assert!(parts[1].0.contains(&h("Persistent_F1"))); + assert!(parts[1].1.contains(&h("Persistent"))); + assert!(parts[2].0.contains(&h("Persistent"))); + assert!(!parts[2].1.contains(&h("Persistent"))); +} diff --git a/crates/bullet-classic/src/animation/graph/form_state/mod.rs b/crates/bullet-classic/src/animation/graph/form_state/mod.rs index 1f45d51..953299f 100644 --- a/crates/bullet-classic/src/animation/graph/form_state/mod.rs +++ b/crates/bullet-classic/src/animation/graph/form_state/mod.rs @@ -74,6 +74,29 @@ pub fn form_drivers(markers: &[u32]) -> Vec { .collect() } +#[must_use] +pub fn keep_default_visible(swaps: &[GearSwap], initially_hidden: &BTreeSet) -> Vec { + let touched: BTreeSet = swaps + .iter() + .flat_map(|s| s.show.iter().chain(s.hide.iter()).copied()) + .collect(); + swaps + .iter() + .map(|swap| { + let mut next = swap.clone(); + for &part in &touched { + if !initially_hidden.contains(&part) + && !next.show.contains(&part) + && !next.hide.contains(&part) + { + next.show.push(part); + } + } + next + }) + .collect() +} + #[must_use] pub fn form_parts(swaps: &[GearSwap]) -> Vec<(Vec, Vec)> { let parts: BTreeSet = swaps.iter().flat_map(|s| s.show.iter().copied()).collect(); diff --git a/crates/bullet-classic/src/animation/graph/form_state/tests.rs b/crates/bullet-classic/src/animation/graph/form_state/tests.rs index 8a38b23..fe7839d 100644 --- a/crates/bullet-classic/src/animation/graph/form_state/tests.rs +++ b/crates/bullet-classic/src/animation/graph/form_state/tests.rs @@ -163,3 +163,28 @@ fn test_skins_without_forms_or_skin_object_are_left_alone() { .is_none() ); } + +#[test] +fn default_visible_part_shown_by_another_form_stays_visible_in_form_0() { + let raw = vec![ + GearSwap { + show: vec![h("Form1"), h("Weapon1")], + hide: vec![h("Form2"), h("Weapon2")], + equip: None, + transition: None, + }, + GearSwap { + show: vec![h("Form2"), h("Weapon2"), h("Persistent")], + hide: vec![h("Form1"), h("Weapon1")], + equip: None, + transition: None, + }, + ]; + let initially_hidden: BTreeSet = [h("Form2"), h("Weapon2")].into_iter().collect(); + let normalized = keep_default_visible(&raw, &initially_hidden); + let parts = form_parts(&normalized); + assert!(parts[0].0.contains(&h("Persistent"))); + assert!(!parts[0].1.contains(&h("Persistent"))); + assert!(parts[1].0.contains(&h("Persistent"))); + assert!(!parts[1].1.contains(&h("Persistent"))); +} diff --git a/crates/bullet-classic/src/audio/sound_bank/mod.rs b/crates/bullet-classic/src/audio/sound_bank/mod.rs index bb89a69..bf41667 100644 --- a/crates/bullet-classic/src/audio/sound_bank/mod.rs +++ b/crates/bullet-classic/src/audio/sound_bank/mod.rs @@ -33,7 +33,7 @@ fn corrupt(what: String) -> ClassicError { ClassicError::Audio(what) } -pub fn parse(bytes: &[u8]) -> Result { +pub fn parse_with_objects(bytes: &[u8]) -> Result<(SoundBank, Vec), ClassicError> { let r = Reader::new(bytes, corrupt); if r.take::<4>(0)? != *HEADER { return Err(r.fail("not a Wwise sound bank")); @@ -49,8 +49,12 @@ pub fn parse(bytes: &[u8]) -> Result { at += 8 + size; } let bank = SoundBank { sections }; - bank.objects()?; - Ok(bank) + let objects = bank.objects()?; + Ok((bank, objects)) +} + +pub fn parse(bytes: &[u8]) -> Result { + Ok(parse_with_objects(bytes)?.0) } impl SoundBank { diff --git a/crates/bullet-classic/src/generation/generator/baseskin/banks.rs b/crates/bullet-classic/src/generation/generator/baseskin/banks.rs index 7877ef0..b930d1e 100644 --- a/crates/bullet-classic/src/generation/generator/baseskin/banks.rs +++ b/crates/bullet-classic/src/generation/generator/baseskin/banks.rs @@ -1,5 +1,5 @@ -use std::collections::{BTreeMap, BTreeSet}; -use std::path::Path; +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::path::{Path, PathBuf}; use bullet_wad::hash::wad_path_hash; use bullet_wad::wad::WadFile; @@ -83,77 +83,80 @@ pub(super) struct ParsedEventBank { pub version: u32, sections: Vec
, objects: Vec, + event_index: HashMap, pub modified: bool, } impl ParsedEventBank { pub fn parse_bytes(bytes: &[u8]) -> Result { - let bank = sound_bank::parse(bytes)?; + let (bank, objects) = sound_bank::parse_with_objects(bytes)?; let version = bank .version() .ok_or_else(|| ClassicError::Audio("bank has no BKHD chunk".into()))?; - let objects = bank.objects()?; + let mut event_index = HashMap::new(); + for (idx, obj) in objects.iter().enumerate() { + if obj.kind == HIRC_EVENT { + event_index.entry(obj.id).or_insert(idx); + } + } Ok(Self { version, sections: bank.sections, objects, + event_index, modified: false, }) } pub fn event_ids(&self) -> Vec { - self.objects - .iter() - .filter(|o| o.kind == HIRC_EVENT) - .map(|o| o.id) - .collect() + self.event_index.keys().copied().collect() } pub fn has_event(&self, event_id: u32) -> bool { - self.objects - .iter() - .any(|o| o.kind == HIRC_EVENT && o.id == event_id) + self.event_index.contains_key(&event_id) } pub fn event_actions(&self, event_id: u32) -> Option> { - let obj = self - .objects - .iter() - .find(|o| o.kind == HIRC_EVENT && o.id == event_id)?; + let &idx = self.event_index.get(&event_id)?; + let obj = self.objects.get(idx)?; decode_actions(&obj.payload, self.version) } pub fn set_or_add_event(&mut self, event_id: u32, actions: &[u32]) { let body = encode_actions(actions, self.version); - let mut found = false; - for obj in &mut self.objects { - if obj.kind == HIRC_EVENT && obj.id == event_id { - found = true; + if let Some(&idx) = self.event_index.get(&event_id) { + if let Some(obj) = self.objects.get_mut(idx) { if obj.payload != body { - obj.payload = body.clone(); + obj.payload = body; self.modified = true; } } - } - if !found { + } else { + let idx = self.objects.len(); self.objects.push(Object { kind: HIRC_EVENT, id: event_id, payload: body, }); + self.event_index.insert(event_id, idx); self.modified = true; } } pub fn remove_event(&mut self, event_id: u32) -> bool { - let before = self.objects.len(); + if self.event_index.remove(&event_id).is_none() { + return false; + } self.objects .retain(|o| !(o.kind == HIRC_EVENT && o.id == event_id)); - let changed = self.objects.len() != before; - if changed { - self.modified = true; + self.event_index.clear(); + for (idx, obj) in self.objects.iter().enumerate() { + if obj.kind == HIRC_EVENT { + self.event_index.entry(obj.id).or_insert(idx); + } } - changed + self.modified = true; + true } pub fn write(&self) -> Result, ClassicError> { @@ -289,10 +292,15 @@ pub(super) fn sidecar_path(source: &str) -> String { format!("{prefix}{stem}_basetag_events.bnk") } +pub(super) struct LocaleWadSlot { + path: PathBuf, + opened: Option>, +} + pub(super) fn load_bank( main_wad: &WadFile, wad_root: &Path, - locale_wads: &mut Option>, + locale_wads: &mut Option>, bank_path: &str, ) -> Option { let lower = bank_path.to_ascii_lowercase(); @@ -315,22 +323,26 @@ pub(super) fn load_bank( bank, }); } - let wads = locale_wads.get_or_insert_with(|| discover_locale_wads(main_wad.path())); - for lwad in wads.iter() { - if let Ok(Some(bytes)) = lwad.read(hash) { - if let Ok(bank) = ParsedEventBank::parse_bytes(&bytes) { - return Some(LoadedBank { - path: bank_path.to_owned(), - localized: true, - bank, - }); - } + let slots = locale_wads.get_or_insert_with(|| discover_locale_wad_paths(main_wad.path())); + for slot in slots.iter_mut() { + let wad_opt = slot + .opened + .get_or_insert_with(|| WadFile::open(&slot.path).ok()); + if let Some(lwad) = wad_opt.as_ref() + && let Ok(Some(bytes)) = lwad.read(hash) + && let Ok(bank) = ParsedEventBank::parse_bytes(&bytes) + { + return Some(LoadedBank { + path: bank_path.to_owned(), + localized: true, + bank, + }); } } None } -fn discover_locale_wads(main_path: &Path) -> Vec { +fn discover_locale_wad_paths(main_path: &Path) -> Vec { let Some(dir) = main_path.parent() else { return Vec::new(); }; @@ -357,9 +369,10 @@ fn discover_locale_wads(main_path: &Path) -> Vec { continue; }; if is_locale_segment(locale) { - if let Ok(wad) = WadFile::open(&p) { - out.push(wad); - } + out.push(LocaleWadSlot { + path: p, + opened: None, + }); } } out diff --git a/crates/bullet-classic/src/generation/generator/cycle/form_cycle.rs b/crates/bullet-classic/src/generation/generator/cycle/form_cycle.rs index 10160ed..9b48c26 100644 --- a/crates/bullet-classic/src/generation/generator/cycle/form_cycle.rs +++ b/crates/bullet-classic/src/generation/generator/cycle/form_cycle.rs @@ -76,6 +76,14 @@ impl StandardChampion { }; let generated = generated.as_slice(); let swaps = swaps_of(&gear_bodies)?; + let initially_hidden: BTreeSet = + crate::form_marker::mesh_text(generated, "initialSubmeshToHide")? + .unwrap_or_default() + .split(|c: char| c.is_whitespace() || matches!(c, ',' | '|' | ':')) + .filter(|name| !name.is_empty()) + .map(prop_key_hash) + .collect(); + let swaps = crate::form_state::keep_default_visible(&swaps, &initially_hidden); let mut coverage = crate::form_gear::gear_coverage(source, &gear_bodies, &swaps)?; coverage.model = merged.as_ref().map(|m| m.outcome()); if coverage.mesh_swap { @@ -92,13 +100,6 @@ impl StandardChampion { .into_iter() .map(|name| name.to_ascii_lowercase()) .collect(); - let initially_hidden: BTreeSet = - crate::form_marker::mesh_text(generated, "initialSubmeshToHide")? - .unwrap_or_default() - .split(|c: char| c.is_whitespace() || matches!(c, ',' | '|' | ':')) - .filter(|name| !name.is_empty()) - .map(prop_key_hash) - .collect(); let mut materials = crate::form_gear::material_plan(&gear_bodies, &swaps, &initially_hidden)?; materials diff --git a/crates/bullet-classic/src/generation/generator/slots/record/mod.rs b/crates/bullet-classic/src/generation/generator/slots/record/mod.rs index bcaf72e..24cf2cc 100644 --- a/crates/bullet-classic/src/generation/generator/slots/record/mod.rs +++ b/crates/bullet-classic/src/generation/generator/slots/record/mod.rs @@ -29,34 +29,6 @@ pub(crate) fn skin_bin_facts(bytes: &[u8]) -> Option { }) } -pub(crate) fn object_changes(source: &[u8], generated: &[u8]) -> Vec { - let (Ok(before), Ok(after)) = (parse_prop_file(source), parse_prop_file(generated)) else { - return Vec::new(); - }; - after - .entries - .iter() - .map(|made| { - let original = before - .entries - .iter() - .find(|e| e.class_hash == made.class_hash); - let changes = original.map(|o| bullet_wad::prop::diff_fields(&o.body, &made.body)); - serde_json::json!({ - "class": format!("{:08x}", made.class_hash), - "key": format!("{:08x}", made.key_hash), - "source_key": original.map(|o| format!("{:08x}", o.key_hash)), - "bytes": made.body.len(), - "field_changes": match changes { - Some(Ok(list)) => serde_json::to_value(list).unwrap_or_default(), - Some(Err(e)) => serde_json::json!({ "unreadable": e.to_string() }), - None => serde_json::json!({ "unreadable": "no object of this class in the source bin" }), - }, - }) - }) - .collect() -} - pub(crate) fn generated_bin_record( alias: &str, character: &str, @@ -78,14 +50,6 @@ pub(crate) fn generated_bin_record( }; let before = facts(source, "source"); let after = facts(generated, "generated"); - let objects = object_changes(source, generated); - let changed_fields: usize = objects - .iter() - .filter_map(|o| o["field_changes"].as_array().map(Vec::len)) - .sum(); - let unreadable = objects - .iter() - .any(|o| o["field_changes"].get("unreadable").is_some()); let source_checksum = format!("{:016x}", bullet_wad::hash::content_checksum(source)); let generated_checksum = format!("{:016x}", bullet_wad::hash::content_checksum(generated)); let graph = after.animation_graph.map(|h| format!("{h:08x}")); @@ -104,25 +68,8 @@ pub(crate) fn generated_bin_record( classification_after = ?after.classification, animation_graph = ?graph, animation_graph_is_source = before.animation_graph == after.animation_graph, - changed_fields, - unreadable_objects = unreadable, "Skin bin generated for slot 0" ); - for object in &objects { - if let Some(list) = object["field_changes"].as_array() { - for change in list { - debug!( - alias, - character, - class = %object["class"], - path = %change["path"], - before = %change["before"], - after = %change["after"], - "Generated field differs from the source bin" - ); - } - } - } debug!(alias, character, source_skin, links = ?after.links, "Skin bin links"); serde_json::json!({ "character": character, @@ -133,11 +80,11 @@ pub(crate) fn generated_bin_record( "source_checksum": source_checksum, "generated_bytes": generated.len(), "generated_checksum": generated_checksum, + "source_objects": before.objects, + "kept_objects": after.objects, "links": after.links, - "source_links": before.links, "classification_before": before.classification, "classification_after": after.classification, "animation_graph": graph, - "objects": objects, }) } diff --git a/crates/bullet-classic/src/generation/generator/store/standard.rs b/crates/bullet-classic/src/generation/generator/store/standard.rs index 10603b7..1d0f49d 100644 --- a/crates/bullet-classic/src/generation/generator/store/standard.rs +++ b/crates/bullet-classic/src/generation/generator/store/standard.rs @@ -19,9 +19,7 @@ impl StandardChampion { return Err(ClassicError::InvalidAlias(alias.to_owned())); } let wad_path = game_dir - .join("DATA") - .join("FINAL") - .join("Champions") + .join("DATA/FINAL/Champions") .join(format!("{alias}.wad.client")); let wad = WadFile::open(&wad_path).map_err(ClassicError::Wad)?; let stamp = wad_stamp(&wad_path); @@ -40,7 +38,11 @@ impl StandardChampion { self.options = options; self } - + #[must_use] + pub fn with_cache_dir(mut self, cache_dir: &Path) -> Self { + self.cache_dir = Some(cache_dir.to_path_buf()); + self + } fn slot0_identity(&self, character: &str) -> Option { identity_at(&self.wad, character, 0).map(|identity| SlotIdentity { classification: identity @@ -49,7 +51,6 @@ impl StandardChampion { ..identity }) } - fn finish_slot0( &self, character: &str, @@ -71,18 +72,13 @@ impl StandardChampion { Ok(skin_bin) } - #[must_use] - pub fn with_cache_dir(mut self, cache_dir: &Path) -> Self { - self.cache_dir = Some(cache_dir.to_path_buf()); - self - } - #[must_use] pub fn has_skin(&self, skin: u32) -> bool { - let main = self.alias.to_ascii_lowercase(); - self.wad.contains(wad_path_hash(&skin_bin(&main, skin))) + self.wad.contains(wad_path_hash(&skin_bin( + &self.alias.to_ascii_lowercase(), + skin, + ))) } - #[must_use] pub fn skin_numbers(&self, limit: u32) -> Vec { (0..limit).filter(|n| self.has_skin(*n)).collect() @@ -150,6 +146,10 @@ impl StandardChampion { self.wad.contains(wad_path_hash(&path.to_ascii_lowercase())) } + pub fn read_path(&self, path: &str) -> Result>, ClassicError> { + Ok(self.wad.read(wad_path_hash(&path.to_ascii_lowercase()))?) + } + pub fn read_skin_bin( &self, character: &str, @@ -193,7 +193,7 @@ impl StandardChampion { self.build(skin, base_skin, Some(form), mods_dir) } - pub(crate) fn gear_body(&self, source: &[u8], key: u32) -> Result, ClassicError> { + pub fn gear_body(&self, source: &[u8], key: u32) -> Result, ClassicError> { let parsed = parse_prop_file(source).map_err(|e| ClassicError::Bin(e.to_string()))?; if let Some(entry) = parsed.entries.iter().find(|e| e.key_hash == key) { return Ok(entry.body.clone()); @@ -214,14 +214,23 @@ impl StandardChampion { ) -> Result { let main = self.alias.to_ascii_lowercase(); let target_bin = skin_bin(&main, skin); - if !self.wad.contains(wad_path_hash(&target_bin)) { - return Err(ClassicError::SkinNotFound { - champion_id: 0, - skin_id: skin, - }); - } + let source = + self.wad + .read(wad_path_hash(&target_bin))? + .ok_or(ClassicError::SkinNotFound { + champion_id: 0, + skin_id: skin, + })?; - let game_parent = self.parent_skin(skin); + let game_parent = match slot_identity(&source) { + Ok(identity) => { + (identity.parent != 0 && identity.parent != skin).then_some(identity.parent) + } + Err(e) => { + warn!(alias = %self.alias, skin, error = %e, "Skin identity unreadable; the client's parent skin is used"); + None + } + }; if game_parent.is_some() && base_skin.is_some() && game_parent != base_skin { debug!( alias = %self.alias, @@ -246,7 +255,7 @@ impl StandardChampion { "game_wad": self.wad_stamp, "generator": reuse::generator_stamp(), "options": format!("{:?}", self.options), - "baseskin_rebase": 9, + "baseskin_rebase": 10, }); let _claim = reuse::Claim::wait_for(&final_dir); if reuse::already_built(&final_dir, &key) { @@ -265,10 +274,6 @@ impl StandardChampion { .join(format!("{}.wad.client", self.alias)); let characters_dir = wad_root.join("data").join("characters"); - let source = self - .wad - .read(wad_path_hash(&target_bin))? - .ok_or_else(|| ClassicError::Bin(format!("{main} skin{skin}.bin not found in WAD")))?; let bins_dir = characters_dir.join(&main).join("skins"); std::fs::create_dir_all(&bins_dir)?; let retargeted = @@ -381,10 +386,8 @@ impl StandardChampion { meta.join("manifest.json"), serde_json::to_vec_pretty(&manifest).map_err(|e| ClassicError::Bin(e.to_string()))?, )?; - remove_if_present(&final_dir)?; std::fs::rename(&partial, &final_dir)?; - info!( alias = %self.alias, skin, @@ -392,7 +395,6 @@ impl StandardChampion { folder = %folder, "Standard skin mod generated directly from installed game WAD" ); - Ok(folder) } } diff --git a/crates/bullet-classic/src/generation/loading_name/mod.rs b/crates/bullet-classic/src/generation/loading_name/mod.rs new file mode 100644 index 0000000..95de4fd --- /dev/null +++ b/crates/bullet-classic/src/generation/loading_name/mod.rs @@ -0,0 +1,372 @@ +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use std::time::{Instant, UNIX_EPOCH}; + +use bullet_wad::wad::WadFile; +use tracing::{debug, info, warn}; + +use crate::generator::StandardChampion; + +mod records; +pub mod rst; + +#[cfg(test)] +mod tests; + +pub use records::{champion_aliases, ships_language_table}; + +pub const MOD_FOLDER: &str = "bullet_loading_name"; + +#[derive(Debug, Clone)] +pub struct LoadingNamePick { + pub mod_folder: PathBuf, + pub skin_id: u32, + pub parent_skin_id: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Strategy { + StringOverrides, + LooseTable, + Unsupported, +} + +struct CachedTable { + path: PathBuf, + len: u64, + modified: u64, + bytes: Arc>, +} + +static TABLE_CACHE: Mutex> = Mutex::new(None); + +#[must_use] +pub fn client_locale(game_dir: &Path) -> Option { + let settings = game_dir + .parent()? + .join("Config") + .join("LeagueClientSettings.yaml"); + let text = std::fs::read_to_string(settings).ok()?; + let mut in_globals = false; + let mut globals_indent = 0usize; + for line in text.lines() { + let trimmed = line.trim(); + if trimmed.is_empty() || trimmed.starts_with('#') { + continue; + } + let indent = line + .bytes() + .take_while(|&b| b == b' ' || b == b'\t') + .count(); + if !in_globals { + if trimmed == "globals:" { + in_globals = true; + globals_indent = indent; + } + continue; + } + if indent <= globals_indent { + break; + } + if let Some(rest) = trimmed.strip_prefix("locale:") { + let val = rest.trim().trim_matches('"').trim_matches('\''); + let bytes = val.as_bytes(); + if bytes.len() == 5 + && bytes[2] == b'_' + && bytes[0].is_ascii_alphabetic() + && bytes[1].is_ascii_alphabetic() + && bytes[3].is_ascii_alphabetic() + && bytes[4].is_ascii_alphabetic() + { + return Some(val.to_owned()); + } + } + } + None +} + +#[must_use] +pub fn language_wad(game_dir: &Path) -> Option { + let wads = records::language_wads(game_dir); + if let Some(locale) = client_locale(game_dir) { + let target = format!("global.{}.wad.client", locale.to_ascii_lowercase()); + if let Some(found) = wads.iter().find(|p| { + p.file_name() + .and_then(|n| n.to_str()) + .is_some_and(|n| n.eq_ignore_ascii_case(&target)) + }) { + return Some(found.clone()); + } + } + if wads.len() == 1 { + return wads.into_iter().next(); + } + None +} + +#[must_use] +pub fn strategy_for(game_dir: &Path) -> Strategy { + let locale = client_locale(game_dir) + .unwrap_or_else(|| "en_us".to_owned()) + .to_ascii_lowercase(); + let has_en_us = records::language_wads(game_dir).iter().any(|p| { + p.file_name() + .and_then(|n| n.to_str()) + .is_some_and(|n| n.eq_ignore_ascii_case("global.en_us.wad.client")) + }); + if !has_en_us { + return Strategy::LooseTable; + } + if locale == "en_us" { + Strategy::StringOverrides + } else { + Strategy::Unsupported + } +} + +fn read_table_cached(wad_path: &Path) -> Option>> { + let meta = std::fs::metadata(wad_path).ok()?; + let len = meta.len(); + let modified = meta + .modified() + .ok() + .and_then(|t| t.duration_since(UNIX_EPOCH).ok()) + .map_or(0, |d| d.as_secs()); + + if let Ok(guard) = TABLE_CACHE.lock() + && let Some(cached) = guard.as_ref() + && cached.path == wad_path + && cached.len == len + && cached.modified == modified + { + return Some(Arc::clone(&cached.bytes)); + } + + let wad = WadFile::open(wad_path).ok()?; + let raw = wad.read(rst::table_hash()).ok()??; + let arc = Arc::new(raw); + if let Ok(mut guard) = TABLE_CACHE.lock() { + *guard = Some(CachedTable { + path: wad_path.to_path_buf(), + len, + modified, + bytes: Arc::clone(&arc), + }); + } + Some(arc) +} + +fn resolve_skin_display_name( + game_dir: &Path, + table: &[u8], + alias: &str, + skin_id: u32, + parent_skin_id: Option, +) -> Option { + let skin_num = skin_id % 1000; + let parent_num = parent_skin_id + .map(|id| id % 1000) + .filter(|&n| n != 0 && n != skin_num) + .or_else(|| { + StandardChampion::open(game_dir, alias) + .ok() + .and_then(|champ| champ.parent_skin(skin_num)) + }); + + let mut candidates = Vec::with_capacity(2); + if let Some(parent) = parent_num { + candidates.push(parent); + } + if skin_num != 0 && !candidates.contains(&skin_num) { + candidates.push(skin_num); + } + + for num in candidates { + let key = format!("game_character_skin_displayname_{alias}_{num}"); + if let Some(name) = rst::read_text(table, rst::key_hash(&key)) + && !name.trim().is_empty() + { + return Some(name); + } + } + None +} + +fn remove_dir_quiet(path: &Path) { + if path.exists() { + let _ = std::fs::remove_dir_all(path); // ignore-ok: best-effort cleanup of stale loading name mod + } +} + +pub fn build_loading_name_mod( + game_dir: &Path, + mods_dir: &Path, + picks: &[LoadingNamePick], + other_mods: &[PathBuf], +) -> Option { + let started = Instant::now(); + let final_dir = mods_dir.join(MOD_FOLDER); + let active_picks: Vec<&LoadingNamePick> = picks + .iter() + .filter(|p| p.skin_id != 0 && p.skin_id % 1000 != 0) + .collect(); + if active_picks.is_empty() { + remove_dir_quiet(&final_dir); + return None; + } + + let strategy = strategy_for(game_dir); + if strategy == Strategy::Unsupported { + info!( + "Install has Global.en_US.wad.client alongside another locale; keeping champion name on loading screen" + ); + remove_dir_quiet(&final_dir); + return None; + } + + if strategy == Strategy::LooseTable + && other_mods.iter().any(|other| ships_language_table(other)) + { + info!( + "Another active mod carries its own lol.stringtable; keeping champion name on loading screen" + ); + remove_dir_quiet(&final_dir); + return None; + } + + let Some(wad_path) = language_wad(game_dir) else { + debug!("Game language WAD could not be resolved; skipping loading screen skin name"); + remove_dir_quiet(&final_dir); + return None; + }; + let Some(table) = read_table_cached(&wad_path) else { + warn!(wad = %wad_path.display(), "Could not read lol.stringtable from language WAD"); + remove_dir_quiet(&final_dir); + return None; + }; + + let partial = mods_dir.join(format!("{MOD_FOLDER}.partial")); + remove_dir_quiet(&partial); + if std::fs::create_dir_all(partial.join("META")).is_err() { + return None; + } + + let mut texts: BTreeMap = BTreeMap::new(); + let mut descriptions: Vec = Vec::new(); + let mut total_repointed = 0usize; + + for pick in active_picks { + for alias in champion_aliases(&pick.mod_folder) { + let Some(skin_display) = resolve_skin_display_name( + game_dir, + &table, + &alias, + pick.skin_id, + pick.parent_skin_id, + ) else { + continue; + }; + let champ_key = format!("{}{alias}", rst::RECORD_KEY_PREFIX); + let Some(champ_display) = rst::read_text(&table, rst::key_hash(&champ_key)) else { + continue; + }; + + let repointed = + records::repoint_champion_records(game_dir, &pick.mod_folder, &alias, &partial); + total_repointed += repointed; + texts.insert(champ_key, skin_display.clone()); + if repointed > 0 { + texts.insert( + format!("{}{alias}", rst::RECORD_KEY_OWN_PREFIX), + champ_display, + ); + } + descriptions.push(skin_display); + break; + } + } + + if texts.is_empty() { + remove_dir_quiet(&partial); + remove_dir_quiet(&final_dir); + return None; + } + + let description = descriptions.join(", "); + let info_json = match strategy { + Strategy::StringOverrides => serde_json::json!({ + "Author": "Bullet", + "Description": description, + "Name": "Loading screen name", + "Version": "1.0.0", + "Layers": { + "base": { + "Name": "base", + "Priority": 0, + "StringOverrides": { + "en_us": texts + } + } + } + }), + Strategy::LooseTable => { + let updates: Vec<(String, String)> = texts.into_iter().collect(); + let Some(patched_table) = rst::with_texts(&table, &updates) else { + remove_dir_quiet(&partial); + return None; + }; + let table_dst = partial + .join("RAW") + .join("DATA") + .join("Menu") + .join("en_US") + .join("lol.stringtable"); + if let Some(parent) = table_dst.parent() + && std::fs::create_dir_all(parent).is_err() + { + remove_dir_quiet(&partial); + return None; + } + if std::fs::write(&table_dst, patched_table).is_err() { + remove_dir_quiet(&partial); + return None; + } + serde_json::json!({ + "Author": "Bullet", + "Description": description, + "Name": "Loading screen name", + "Version": "1.0.0" + }) + } + Strategy::Unsupported => { + remove_dir_quiet(&partial); + return None; + } + }; + + let Ok(info_bytes) = serde_json::to_vec(&info_json) else { + remove_dir_quiet(&partial); + return None; + }; + if std::fs::write(partial.join("META").join("info.json"), info_bytes).is_err() { + remove_dir_quiet(&partial); + return None; + } + + remove_dir_quiet(&final_dir); + if let Err(e) = std::fs::rename(&partial, &final_dir) { + warn!(error = %e, "Could not finalize loading screen skin name mod"); + remove_dir_quiet(&partial); + return None; + } + + info!( + names = ?descriptions, + strategy = ?strategy, + repointed_records = total_repointed, + elapsed_ms = started.elapsed().as_millis(), + "Loading screen skin name mod built" + ); + Some(MOD_FOLDER.to_owned()) +} diff --git a/crates/bullet-classic/src/generation/loading_name/records.rs b/crates/bullet-classic/src/generation/loading_name/records.rs new file mode 100644 index 0000000..ae6649e --- /dev/null +++ b/crates/bullet-classic/src/generation/loading_name/records.rs @@ -0,0 +1,241 @@ +use std::path::{Path, PathBuf}; + +use bullet_wad::hash::wad_path_hash; +use bullet_wad::wad::WadFile; + +use super::rst; + +fn form_records(alias: &str) -> &'static [&'static str] { + match alias.to_ascii_lowercase().as_str() { + "cassiopeia" => &["cassiopeia_death"], + "elise" => &["elisespider"], + "fiddlesticks" => &["fiddlestickseffigy"], + "fizz" => &["fizzbait", "fizzshark", "jade_fizzbait", "jade_fizzshark"], + "kogmaw" => &["jade_kogmawdead", "kogmawdead"], + "locke" => &["locketotem"], + "lux" => &[ + "luxair", + "luxdark", + "luxfire", + "luxice", + "luxmagma", + "luxmystic", + "luxnature", + "luxstorm", + "luxwater", + ], + "monkeyking" => &["monkeykingflying"], + "nasus" => &["jade_nasusult", "nasusult"], + "nidalee" => &["jade_nidaleecougar", "nidaleecougar"], + "orianna" => &["oriannaball", "oriannanoball"], + "quinn" => &["quinnvalor"], + "rammus" => &["jade_rammusdbc", "jade_rammuspb", "rammusdbc", "rammuspb"], + "shyvana" => &["jade_shyvanadragon", "shyvanadragon"], + "sona" => &["sonadjgenre01", "sonadjgenre02", "sonadjgenre03"], + "swain" => &["jade_swaindemonform", "swaindemonform"], + "syndra" => &["syndraorbs", "syndrasphere"], + "zed" => &["zedshadow"], + "zoe" => &["zoeorbs"], + _ => &[], + } +} + +pub(super) fn language_wads(game_dir: &Path) -> Vec { + let localized = game_dir.join("DATA").join("FINAL").join("Localized"); + let Ok(entries) = std::fs::read_dir(localized) else { + return Vec::new(); + }; + let mut wads: Vec = entries + .flatten() + .map(|e| e.path()) + .filter(|p| { + p.is_file() + && p.file_name().and_then(|n| n.to_str()).is_some_and(|n| { + let lower = n.to_ascii_lowercase(); + lower.starts_with("global.") + && lower.ends_with(".wad.client") + && lower != "global.wad.client" + }) + }) + .collect(); + wads.sort(); + wads +} + +fn dir_contains_stringtable(dir: &Path, table_hex: &str) -> bool { + let Ok(entries) = std::fs::read_dir(dir) else { + return false; + }; + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + if dir_contains_stringtable(&path, table_hex) { + return true; + } + } else if let Some(name) = path.file_name().and_then(|n| n.to_str()) { + let lower = name.to_ascii_lowercase(); + if lower == "lol.stringtable" || lower == format!("{table_hex}.stringtable") { + return true; + } + } + } + false +} + +#[must_use] +pub fn ships_language_table(mod_dir: &Path) -> bool { + let hash = rst::table_hash(); + let hex = format!("{hash:016x}"); + for raw_name in ["RAW", "raw"] { + let raw_dir = mod_dir.join(raw_name); + if raw_dir.is_dir() && dir_contains_stringtable(&raw_dir, &hex) { + return true; + } + } + for wad_name in ["WAD", "wad"] { + let wad_dir = mod_dir.join(wad_name); + let Ok(entries) = std::fs::read_dir(&wad_dir) else { + continue; + }; + for entry in entries.flatten() { + let path = entry.path(); + let Some(name) = path.file_name().and_then(|n| n.to_str()) else { + continue; + }; + let lower = name.to_ascii_lowercase(); + if !lower.starts_with("global.") || !lower.ends_with(".wad.client") { + continue; + } + if path.is_dir() && dir_contains_stringtable(&path, &hex) { + return true; + } + if path.is_file() + && let Ok(wad) = WadFile::open(&path) + && wad.contains(hash) + { + return true; + } + } + } + false +} + +#[must_use] +pub fn champion_aliases(mod_dir: &Path) -> Vec { + let mut aliases = Vec::new(); + for wad_name in ["WAD", "wad"] { + let wad_dir = mod_dir.join(wad_name); + let Ok(entries) = std::fs::read_dir(&wad_dir) else { + continue; + }; + for entry in entries.flatten() { + let Some(name) = entry.file_name().to_str().map(str::to_owned) else { + continue; + }; + let lower = name.to_ascii_lowercase(); + let Some(stem) = lower.strip_suffix(".wad.client") else { + continue; + }; + let prefix_len = stem.find('.').unwrap_or(stem.len()); + let alias = &name[..prefix_len]; + if alias.is_empty() || alias.eq_ignore_ascii_case("global") { + continue; + } + if !aliases + .iter() + .any(|a: &String| a.eq_ignore_ascii_case(alias)) + { + aliases.push(alias.to_owned()); + } + } + } + aliases +} + +fn record_rel_path(character: &str) -> String { + let lower = character.to_ascii_lowercase(); + format!("data/characters/{lower}/{lower}.bin") +} + +fn read_character_record( + game_dir: &Path, + mod_dir: &Path, + alias: &str, + character: &str, + installed_wad: Option<&WadFile>, +) -> Option> { + let rel = record_rel_path(character); + let hash = wad_path_hash(&rel); + for wad_name in ["WAD", "wad"] { + let candidate = mod_dir.join(wad_name).join(format!("{alias}.wad.client")); + if candidate.is_file() + && let Ok(wad) = WadFile::open(&candidate) + && let Ok(Some(bytes)) = wad.read(hash) + { + return Some(bytes); + } + if candidate.is_dir() { + let loose = candidate.join(&rel); + if loose.is_file() + && let Ok(bytes) = std::fs::read(&loose) + { + return Some(bytes); + } + let hashed = candidate.join(format!("{hash:016x}.bin")); + if hashed.is_file() + && let Ok(bytes) = std::fs::read(&hashed) + { + return Some(bytes); + } + } + } + if let Some(wad) = installed_wad + && let Ok(Some(bytes)) = wad.read(hash) + { + return Some(bytes); + } + let fallback = game_dir + .join("DATA") + .join("FINAL") + .join("Champions") + .join(format!("{alias}.wad.client")); + WadFile::open(&fallback).ok()?.read(hash).ok()? +} + +pub(super) fn repoint_champion_records( + game_dir: &Path, + mod_dir: &Path, + alias: &str, + partial_dir: &Path, +) -> usize { + let installed_path = game_dir + .join("DATA") + .join("FINAL") + .join("Champions") + .join(format!("{alias}.wad.client")); + let installed_wad = WadFile::open(&installed_path).ok(); + let lower_alias = alias.to_ascii_lowercase(); + let mut repointed = 0usize; + for character in + std::iter::once(lower_alias.as_str()).chain(form_records(alias).iter().copied()) + { + let Some(raw) = + read_character_record(game_dir, mod_dir, alias, character, installed_wad.as_ref()) + else { + continue; + }; + let Some(patched) = rst::patch_record_key(&raw, alias) else { + continue; + }; + let dst = partial_dir.join("RAW").join(record_rel_path(character)); + if let Some(parent) = dst.parent() + && std::fs::create_dir_all(parent).is_err() + { + continue; + } + if std::fs::write(&dst, patched).is_ok() { + repointed += 1; + } + } + repointed +} diff --git a/crates/bullet-classic/src/generation/loading_name/rst.rs b/crates/bullet-classic/src/generation/loading_name/rst.rs new file mode 100644 index 0000000..b7c3509 --- /dev/null +++ b/crates/bullet-classic/src/generation/loading_name/rst.rs @@ -0,0 +1,142 @@ +use bullet_wad::hash::{content_checksum, wad_path_hash}; + +pub const RST_MASK: u64 = (1u64 << 38) - 1; +pub const TABLE_PATH: &str = "data/menu/en_us/lol.stringtable"; +pub const RECORD_KEY_PREFIX: &str = "game_character_displayname_"; +pub const RECORD_KEY_OWN_PREFIX: &str = "bllt_character_displayname_"; + +#[must_use] +pub fn table_hash() -> u64 { + wad_path_hash(TABLE_PATH) +} + +#[must_use] +pub fn key_hash(key: &str) -> u64 { + let lower = key.to_ascii_lowercase(); + content_checksum(lower.as_bytes()) & RST_MASK +} + +fn parse_header(table: &[u8]) -> Option<(usize, usize)> { + if table.len() < 8 || &table[..3] != b"RST" || table[3] != 5 { + return None; + } + let count = u32::from_le_bytes([table[4], table[5], table[6], table[7]]) as usize; + let text_start = 8usize.checked_add(count.checked_mul(8)?)?; + if text_start > table.len() { + return None; + } + Some((count, text_start)) +} + +#[must_use] +pub fn read_text(table: &[u8], hash: u64) -> Option { + let (count, text_start) = parse_header(table)?; + for i in 0..count { + let pos = 8 + i * 8; + let entry = u64::from_le_bytes([ + table[pos], + table[pos + 1], + table[pos + 2], + table[pos + 3], + table[pos + 4], + table[pos + 5], + table[pos + 6], + table[pos + 7], + ]); + if (entry & RST_MASK) != hash { + continue; + } + let offset = usize::try_from(entry >> 38).ok()?; + let at = text_start.checked_add(offset)?; + if at >= table.len() { + return None; + } + let rel_end = table[at..].iter().position(|&b| b == 0)?; + return Some(String::from_utf8_lossy(&table[at..at + rel_end]).into_owned()); + } + None +} + +#[must_use] +pub fn with_texts(table: &[u8], updates: &[(String, String)]) -> Option> { + let (count, text_start) = parse_header(table)?; + let mut entries = Vec::with_capacity(count + updates.len()); + for i in 0..count { + let pos = 8 + i * 8; + entries.push(u64::from_le_bytes([ + table[pos], + table[pos + 1], + table[pos + 2], + table[pos + 3], + table[pos + 4], + table[pos + 5], + table[pos + 6], + table[pos + 7], + ])); + } + let mut appended = Vec::new(); + let base_text_len = table.len().checked_sub(text_start)?; + let mut added_new_key = false; + + for (key, value) in updates { + let kh = key_hash(key); + let offset = base_text_len.checked_add(appended.len())?; + let offset_u64 = u64::try_from(offset).ok()?; + let new_entry = kh | (offset_u64 << 38); + appended.extend_from_slice(value.as_bytes()); + appended.push(0); + + if let Some(slot) = entries.iter_mut().find(|e| (**e & RST_MASK) == kh) { + *slot = new_entry; + } else { + entries.push(new_entry); + added_new_key = true; + } + } + + if added_new_key { + entries.sort_unstable_by_key(|e| *e & RST_MASK); + } + + let total_entries = u32::try_from(entries.len()).ok()?; + let mut out = Vec::with_capacity(8 + entries.len() * 8 + base_text_len + appended.len()); + out.extend_from_slice(&table[..4]); + out.extend_from_slice(&total_entries.to_le_bytes()); + for e in entries { + out.extend_from_slice(&e.to_le_bytes()); + } + out.extend_from_slice(&table[text_start..]); + out.extend_from_slice(&appended); + Some(out) +} + +#[must_use] +pub fn patch_record_key(record: &[u8], alias: &str) -> Option> { + let target = format!("{RECORD_KEY_PREFIX}{alias}"); + let target_bytes = target.as_bytes(); + let len_u16 = u16::try_from(target_bytes.len()).ok()?; + let len_bytes = len_u16.to_le_bytes(); + let own_prefix = RECORD_KEY_OWN_PREFIX.as_bytes(); + let pattern_len = 2usize.checked_add(target_bytes.len())?; + if record.len() < pattern_len { + return None; + } + + let mut out = record.to_vec(); + let mut found = false; + let mut i = 0usize; + let limit = record.len() - pattern_len; + while i <= limit { + if out[i] == len_bytes[0] + && out[i + 1] == len_bytes[1] + && out[i + 2..i + pattern_len].eq_ignore_ascii_case(target_bytes) + { + out[i + 2..i + 2 + own_prefix.len()].copy_from_slice(own_prefix); + found = true; + i += pattern_len; + } else { + i += 1; + } + } + found.then_some(out) +} diff --git a/crates/bullet-classic/src/generation/loading_name/tests.rs b/crates/bullet-classic/src/generation/loading_name/tests.rs new file mode 100644 index 0000000..5b03eee --- /dev/null +++ b/crates/bullet-classic/src/generation/loading_name/tests.rs @@ -0,0 +1,315 @@ +use bullet_wad::hash::wad_path_hash; + +use super::*; + +fn make_rst_v5(texts: &[(&str, &str)]) -> Vec { + let mut items: Vec<(u64, &str)> = texts.iter().map(|(k, v)| (rst::key_hash(k), *v)).collect(); + items.sort_by_key(|(h, _)| *h); + let mut entries = Vec::with_capacity(items.len()); + let mut body = Vec::new(); + for (hash, text) in items { + entries.push(hash | ((body.len() as u64) << 38)); + body.extend_from_slice(text.as_bytes()); + body.push(0); + } + let mut out = Vec::new(); + out.extend_from_slice(b"RST\x05"); + out.extend_from_slice(&(entries.len() as u32).to_le_bytes()); + for e in entries { + out.extend_from_slice(&e.to_le_bytes()); + } + out.extend_from_slice(&body); + out +} + +fn make_wad_v3(entries: &[(u64, &[u8])]) -> Vec { + let header_len = 272usize; + let toc_len = entries.len() * 32; + let mut offset = (header_len + toc_len) as u32; + let mut out = Vec::new(); + out.extend_from_slice(b"RW\x03\x03"); + out.resize(260, 0); + out.extend_from_slice(&0u64.to_le_bytes()); + out.extend_from_slice(&(entries.len() as u32).to_le_bytes()); + for (hash, data) in entries { + let len = data.len() as u32; + out.extend_from_slice(&hash.to_le_bytes()); + out.extend_from_slice(&offset.to_le_bytes()); + out.extend_from_slice(&len.to_le_bytes()); + out.extend_from_slice(&len.to_le_bytes()); + out.push(0); + out.push(0); + out.extend_from_slice(&0u16.to_le_bytes()); + out.extend_from_slice(&0u64.to_le_bytes()); + offset += len; + } + for (_, data) in entries { + out.extend_from_slice(data); + } + out +} + +fn make_record(key: &str) -> Vec { + let mut out = vec![0x01, 0x02]; + out.extend_from_slice(&(key.len() as u16).to_le_bytes()); + out.extend_from_slice(key.as_bytes()); + out.push(0x03); + out +} + +fn temp_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "bullet_loading_name_test_{name}_{}_{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()) + )); + std::fs::create_dir_all(&dir).expect("create temp dir"); + dir +} + +fn setup_game( + root: &Path, + languages: &[(&str, &str)], + locale: Option<&str>, +) -> (PathBuf, PathBuf, PathBuf) { + let game = root.join("League of Legends").join("Game"); + let loc_dir = game.join("DATA").join("FINAL").join("Localized"); + std::fs::create_dir_all(&loc_dir).expect("mkdir localized"); + for (lang, skin_name) in languages { + let table = make_rst_v5(&[ + ("game_character_displayname_Zed", "Zed"), + ("game_character_displayname_Yasuo", "Yasuo"), + ("game_character_skin_displayname_Zed_1", skin_name), + ]); + let wad = make_wad_v3(&[(rst::table_hash(), &table)]); + std::fs::write(loc_dir.join(format!("Global.{lang}.wad.client")), wad).expect("write wad"); + } + let champ_dir = game.join("DATA").join("FINAL").join("Champions"); + std::fs::create_dir_all(&champ_dir).expect("mkdir champs"); + let zed_bin = make_record("game_character_displayname_Zed"); + let shadow_bin = make_record("game_character_displayname_Zed"); + let zed_wad = make_wad_v3(&[ + (wad_path_hash("data/characters/zed/zed.bin"), &zed_bin), + ( + wad_path_hash("data/characters/zedshadow/zedshadow.bin"), + &shadow_bin, + ), + ]); + std::fs::write(champ_dir.join("Zed.wad.client"), zed_wad).expect("write zed wad"); + if let Some(loc) = locale { + let cfg = root.join("League of Legends").join("Config"); + std::fs::create_dir_all(&cfg).expect("mkdir config"); + std::fs::write( + cfg.join("LeagueClientSettings.yaml"), + format!("install:\n globals:\n locale: \"{loc}\"\n region: \"BR\"\n"), + ) + .expect("write settings"); + } + let mods = root.join("mods"); + let skin_mod = mods.join("std_zed_1"); + std::fs::create_dir_all(skin_mod.join("WAD").join("Zed.wad.client")).expect("mkdir skin mod"); + (game, mods, skin_mod) +} + +#[test] +fn rst_v5_round_trip_preserves_utf8_and_other_entries() { + let table = make_rst_v5(&[ + ("game_character_displayname_Zed", "Zed"), + ("game_character_displayname_Yasuo", "Yasuo"), + ]); + let updated = rst::with_texts( + &table, + &[ + ( + "game_character_displayname_Zed".into(), + "Lâmina do Trovão".into(), + ), + ("bllt_character_displayname_Zed".into(), "Zed".into()), + ], + ) + .expect("patch rst"); + + assert_eq!( + rst::read_text(&updated, rst::key_hash("game_character_displayname_Zed")).as_deref(), + Some("Lâmina do Trovão") + ); + assert_eq!( + rst::read_text(&updated, rst::key_hash("bllt_character_displayname_Zed")).as_deref(), + Some("Zed") + ); + assert_eq!( + rst::read_text(&updated, rst::key_hash("game_character_displayname_Yasuo")).as_deref(), + Some("Yasuo") + ); +} + +#[test] +fn record_key_patch_preserves_length_and_is_case_insensitive() { + let raw = make_record("Game_Character_DisplayName_Zed"); + let patched = rst::patch_record_key(&raw, "zed").expect("patch record"); + assert_eq!(patched.len(), raw.len()); + assert!( + patched + .windows("bllt_character_displayname_Zed".len()) + .any(|w| w == b"bllt_character_displayname_Zed") + ); + assert!(rst::patch_record_key(b"unrelated", "Zed").is_none()); +} + +#[test] +fn en_us_install_uses_string_overrides_and_repoints_champion_and_forms() { + let root = temp_dir("en_us"); + let (game, mods, skin_mod) = setup_game(&root, &[("en_US", "Shockblade Zed")], Some("en_US")); + + let built = build_loading_name_mod( + &game, + &mods, + &[LoadingNamePick { + mod_folder: skin_mod, + skin_id: 238_001, + parent_skin_id: None, + }], + &[], + ); + assert_eq!(built.as_deref(), Some(MOD_FOLDER)); + + let out = mods.join(MOD_FOLDER); + assert!(!out.join("RAW/DATA/Menu/en_US/lol.stringtable").exists()); + let info: serde_json::Value = + serde_json::from_slice(&std::fs::read(out.join("META/info.json")).expect("read info.json")) + .expect("parse info.json"); + assert_eq!( + info["Layers"]["base"]["StringOverrides"]["en_us"]["game_character_displayname_Zed"], + "Shockblade Zed" + ); + assert_eq!( + info["Layers"]["base"]["StringOverrides"]["en_us"]["bllt_character_displayname_Zed"], + "Zed" + ); + let zed_bin = std::fs::read(out.join("RAW/data/characters/zed/zed.bin")).expect("read zed.bin"); + let shadow_bin = std::fs::read(out.join("RAW/data/characters/zedshadow/zedshadow.bin")) + .expect("read zedshadow.bin"); + assert!(zed_bin.windows(4).any(|w| w == b"bllt")); + assert!(shadow_bin.windows(4).any(|w| w == b"bllt")); + let _ = std::fs::remove_dir_all(&root); // ignore-ok: best-effort test temp cleanup +} + +#[test] +fn non_en_us_install_writes_loose_table_and_skips_when_other_mod_ships_table() { + let root = temp_dir("pt_br"); + let (game, mods, skin_mod) = + setup_game(&root, &[("pt_BR", "Zed Lâmina do Trovão")], Some("pt_BR")); + + let font = mods.join("custom_font"); + std::fs::create_dir_all(font.join("RAW/DATA/Menu/en_US")).expect("mkdir font"); + std::fs::write(font.join("RAW/DATA/Menu/en_US/lol.stringtable"), b"RST\x05") + .expect("write font table"); + + assert!( + build_loading_name_mod( + &game, + &mods, + &[LoadingNamePick { + mod_folder: skin_mod.clone(), + skin_id: 238_001, + parent_skin_id: None, + }], + std::slice::from_ref(&font), + ) + .is_none() + ); + + let built = build_loading_name_mod( + &game, + &mods, + &[LoadingNamePick { + mod_folder: skin_mod, + skin_id: 238_001, + parent_skin_id: None, + }], + &[], + ); + assert_eq!(built.as_deref(), Some(MOD_FOLDER)); + let table = std::fs::read( + mods.join(MOD_FOLDER) + .join("RAW/DATA/Menu/en_US/lol.stringtable"), + ) + .expect("read loose table"); + assert_eq!( + rst::read_text(&table, rst::key_hash("game_character_displayname_Zed")).as_deref(), + Some("Zed Lâmina do Trovão") + ); + assert_eq!( + rst::read_text(&table, rst::key_hash("bllt_character_displayname_Zed")).as_deref(), + Some("Zed") + ); + let _ = std::fs::remove_dir_all(&root); // ignore-ok: best-effort test temp cleanup +} + +#[test] +fn chroma_inherits_parent_skin_name_and_base_skin_builds_nothing() { + let root = temp_dir("chroma"); + let (game, mods, skin_mod) = setup_game(&root, &[("en_US", "Shockblade Zed")], Some("en_US")); + + assert!( + build_loading_name_mod( + &game, + &mods, + &[LoadingNamePick { + mod_folder: skin_mod.clone(), + skin_id: 238_000, + parent_skin_id: None, + }], + &[], + ) + .is_none() + ); + + let built = build_loading_name_mod( + &game, + &mods, + &[LoadingNamePick { + mod_folder: skin_mod, + skin_id: 238_004, + parent_skin_id: Some(238_001), + }], + &[], + ); + assert_eq!(built.as_deref(), Some(MOD_FOLDER)); + let info: serde_json::Value = serde_json::from_slice( + &std::fs::read(mods.join(MOD_FOLDER).join("META/info.json")).expect("read info"), + ) + .expect("parse info"); + assert_eq!(info["Description"], "Shockblade Zed"); + let _ = std::fs::remove_dir_all(&root); // ignore-ok: best-effort test temp cleanup +} + +#[test] +fn non_en_us_locale_alongside_en_us_wad_is_unsupported() { + let root = temp_dir("mixed_locale"); + let (game, mods, skin_mod) = setup_game( + &root, + &[ + ("en_US", "Shockblade Zed"), + ("pt_BR", "Zed Lâmina do Trovão"), + ], + Some("pt_BR"), + ); + assert_eq!(strategy_for(&game), Strategy::Unsupported); + assert!( + build_loading_name_mod( + &game, + &mods, + &[LoadingNamePick { + mod_folder: skin_mod, + skin_id: 238_001, + parent_skin_id: None, + }], + &[], + ) + .is_none() + ); + let _ = std::fs::remove_dir_all(&root); // ignore-ok: best-effort test temp cleanup +} diff --git a/crates/bullet-classic/src/generation/mod.rs b/crates/bullet-classic/src/generation/mod.rs index adc4cef..6e95abd 100644 --- a/crates/bullet-classic/src/generation/mod.rs +++ b/crates/bullet-classic/src/generation/mod.rs @@ -1,3 +1,5 @@ pub mod builder; pub mod client_data; pub mod generator; +pub mod loading_name; +pub mod tft; diff --git a/crates/bullet-classic/src/generation/tft/mod.rs b/crates/bullet-classic/src/generation/tft/mod.rs new file mode 100644 index 0000000..8bd710c --- /dev/null +++ b/crates/bullet-classic/src/generation/tft/mod.rs @@ -0,0 +1,217 @@ +use std::path::{Path, PathBuf}; + +use bullet_wad::hash::{prop_key_hash, wad_path_hash}; +use bullet_wad::prop::{parse_prop_file, serialize_prop_file}; +use bullet_wad::wad::WadFile; +use serde::{Deserialize, Serialize}; +use tracing::{debug, info, warn}; + +use crate::error::ClassicError; + +pub const TFT_MOD_FOLDER: &str = "bullet_tft_cosmetics"; +pub const DEFAULT_TACTICIAN_DONOR: &str = "data/characters/pettftavatar/skins/skin1.bin"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum TftCategory { + Tactician, + Boom, + Portal, + Arena, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct TftSwap { + pub donor_id: u32, + pub donor_path: String, + pub target_id: u32, + pub target_path: String, + pub name: String, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct TftLoadout { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tactician: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub boom: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub portal: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub arena: Option, +} + +impl TftLoadout { + #[must_use] + pub fn is_empty(&self) -> bool { + self.tactician.is_none() + && self.boom.is_none() + && self.portal.is_none() + && self.arena.is_none() + } +} + +fn normalize_asset_path(raw: &str) -> Option { + let clean = raw + .trim() + .replace('\\', "/") + .trim_start_matches('/') + .to_ascii_lowercase(); + if clean.is_empty() + || clean.contains("..") + || !clean.starts_with("data/") + || !clean + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'/' | b'_' | b'-' | b'.')) + { + return None; + } + Some(clean) +} + +fn prop_record_key_from_bin_path(bin_path: &str) -> Option { + let no_data = bin_path.strip_prefix("data/").unwrap_or(bin_path); + let stem = no_data.strip_suffix(".bin")?; + Some(stem.to_owned()) +} + +fn remap_prop_bytes( + raw: &[u8], + donor_path: &str, + target_path: &str, +) -> Result, ClassicError> { + let mut prop = parse_prop_file(raw)?; + let target_key = prop_record_key_from_bin_path(target_path) + .map(|k| prop_key_hash(&k)) + .unwrap_or(0); + let donor_key = prop_record_key_from_bin_path(donor_path) + .map(|k| prop_key_hash(&k)) + .unwrap_or(0); + if target_key != 0 && donor_key != 0 && target_key != donor_key { + for entry in &mut prop.entries { + if entry.key_hash == target_key { + entry.key_hash = donor_key; + } + } + } + Ok(serialize_prop_file(&prop)?) +} + +fn wad_path_for(game_dir: &Path, category: TftCategory) -> PathBuf { + let final_dir = game_dir.join("DATA").join("FINAL"); + match category { + TftCategory::Tactician => final_dir.join("Companions.wad.client"), + TftCategory::Boom | TftCategory::Portal => final_dir.join("Global.wad.client"), + TftCategory::Arena => final_dir + .join("Maps") + .join("Shipping") + .join("Map22.wad.client"), + } +} + +fn apply_swap( + game_dir: &Path, + partial_dir: &Path, + category: TftCategory, + swap: &TftSwap, +) -> Result { + let Some(donor) = normalize_asset_path(&swap.donor_path) else { + warn!(donor = %swap.donor_path, ?category, "Invalid TFT donor path; skipped"); + return Ok(false); + }; + let Some(target) = normalize_asset_path(&swap.target_path) else { + warn!(target = %swap.target_path, ?category, "Invalid TFT target path; skipped"); + return Ok(false); + }; + if donor == target { + return Ok(false); + } + + let wad_file_path = wad_path_for(game_dir, category); + if !wad_file_path.is_file() { + debug!(wad = %wad_file_path.display(), ?category, "TFT WAD archive not present"); + return Ok(false); + } + + let wad = WadFile::open(&wad_file_path)?; + let hash = wad_path_hash(&target); + let Some(raw) = wad.read(hash)? else { + warn!(target = %target, wad = %wad_file_path.display(), "TFT target entry missing in WAD"); + return Ok(false); + }; + + let output = if target.ends_with(".bin") && donor.ends_with(".bin") { + remap_prop_bytes(&raw, &donor, &target)? + } else { + raw + }; + + let dst = partial_dir.join("RAW").join(&donor); + if let Some(parent) = dst.parent() { + std::fs::create_dir_all(parent)?; + } + std::fs::write(&dst, output)?; + Ok(true) +} + +fn remove_dir_quiet(path: &Path) { + if path.exists() { + let _ = std::fs::remove_dir_all(path); // ignore-ok: cleanup of previous TFT staging dir + } +} + +pub fn build_tft_mod( + game_dir: &Path, + mods_dir: &Path, + loadout: &TftLoadout, +) -> Result, ClassicError> { + let final_dir = mods_dir.join(TFT_MOD_FOLDER); + if loadout.is_empty() { + remove_dir_quiet(&final_dir); + return Ok(None); + } + + let partial = mods_dir.join(format!("{TFT_MOD_FOLDER}.partial")); + remove_dir_quiet(&partial); + std::fs::create_dir_all(partial.join("META"))?; + + let mut applied = Vec::new(); + let pairs = [ + (TftCategory::Tactician, loadout.tactician.as_ref()), + (TftCategory::Boom, loadout.boom.as_ref()), + (TftCategory::Portal, loadout.portal.as_ref()), + (TftCategory::Arena, loadout.arena.as_ref()), + ]; + + for (category, maybe_swap) in pairs { + if let Some(swap) = maybe_swap + && apply_swap(game_dir, &partial, category, swap)? + { + applied.push(swap.name.clone()); + } + } + + if applied.is_empty() { + remove_dir_quiet(&partial); + remove_dir_quiet(&final_dir); + return Ok(None); + } + + let info = serde_json::json!({ + "Author": "Bullet", + "Description": applied.join(", "), + "Name": "Bullet TFT Cosmetics", + "Version": "1.0.0" + }); + let info_bytes = serde_json::to_vec(&info) + .map_err(|e| ClassicError::Io(std::io::Error::other(e.to_string())))?; + std::fs::write(partial.join("META").join("info.json"), info_bytes)?; + + remove_dir_quiet(&final_dir); + std::fs::rename(&partial, &final_dir)?; + info!(items = ?applied, "TFT cosmetics mod built"); + Ok(Some(TFT_MOD_FOLDER.to_owned())) +} + +#[cfg(test)] +mod tests; diff --git a/crates/bullet-classic/src/generation/tft/tests.rs b/crates/bullet-classic/src/generation/tft/tests.rs new file mode 100644 index 0000000..e317f58 --- /dev/null +++ b/crates/bullet-classic/src/generation/tft/tests.rs @@ -0,0 +1,173 @@ +use bullet_wad::hash::{prop_key_hash, wad_path_hash}; +use bullet_wad::prop::{PropEntry, PropFile, parse_prop_file, serialize_prop_file}; +use bullet_wad::writer::{WadWriter, optimal_raw}; + +use super::*; + +struct TempDir(PathBuf); + +impl TempDir { + fn new(tag: &str) -> Self { + let dir = std::env::temp_dir().join(format!( + "bullet_tft_test_{tag}_{}_{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()) + )); + std::fs::create_dir_all(&dir).expect("create temp dir"); + Self(dir) + } + + fn path(&self) -> &Path { + &self.0 + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); // ignore-ok: best-effort test cleanup + } +} + +fn sample_prop(record_key: &str) -> Vec { + let file = PropFile { + version: 2, + links: vec!["characters/pettftavatar/skins/root.bin".into()], + entries: vec![PropEntry { + class_hash: prop_key_hash("SkinCharacterDataProperties"), + key_hash: prop_key_hash(record_key), + body: vec![0, 0, 0, 0], + }], + }; + serialize_prop_file(&file).expect("valid prop") +} + +fn write_test_wad(path: &Path, entries: Vec<(&str, Vec)>) { + let mut writer = WadWriter::default(); + for (p, data) in entries { + writer.insert(wad_path_hash(p), optimal_raw(data).expect("encode")); + } + writer.write_to_file(path, &|| false).expect("write wad"); +} + +#[test] +fn builds_tft_mod_remapping_tactician_boom_portal_and_arena() { + let dir = TempDir::new("full"); + let game_dir = dir.path().join("Game"); + let mods_dir = dir.path().join("mods"); + + let target_tactician = "data/characters/petpenguknight/skins/skin12.bin"; + let target_boom = "data/loadouts/tftdamageskins/boom_star.bin"; + let target_portal = "data/loadouts/tftzoomskins/portal_void.bin"; + let target_arena = "data/maps/shipping/map22/arena_celestial.materials.bin"; + + write_test_wad( + &game_dir.join("DATA/FINAL/Companions.wad.client"), + vec![( + target_tactician, + sample_prop("characters/petpenguknight/skins/skin12"), + )], + ); + write_test_wad( + &game_dir.join("DATA/FINAL/Global.wad.client"), + vec![ + ( + target_boom, + sample_prop("loadouts/tftdamageskins/boom_star"), + ), + ( + target_portal, + sample_prop("loadouts/tftzoomskins/portal_void"), + ), + ], + ); + write_test_wad( + &game_dir.join("DATA/FINAL/Maps/Shipping/Map22.wad.client"), + vec![( + target_arena, + sample_prop("maps/shipping/map22/arena_celestial.materials"), + )], + ); + + let loadout = TftLoadout { + tactician: Some(TftSwap { + donor_id: 1, + donor_path: DEFAULT_TACTICIAN_DONOR.into(), + target_id: 12, + target_path: target_tactician.into(), + name: "Chibi Pengu".into(), + }), + boom: Some(TftSwap { + donor_id: 1, + donor_path: "data/loadouts/tftdamageskins/base.bin".into(), + target_id: 99, + target_path: target_boom.into(), + name: "Star Boom".into(), + }), + portal: Some(TftSwap { + donor_id: 1, + donor_path: "data/loadouts/tftzoomskins/base.bin".into(), + target_id: 42, + target_path: target_portal.into(), + name: "Void Portal".into(), + }), + arena: Some(TftSwap { + donor_id: 1, + donor_path: "data/maps/shipping/map22/base.materials.bin".into(), + target_id: 77, + target_path: target_arena.into(), + name: "Celestial Arena".into(), + }), + }; + + let built = build_tft_mod(&game_dir, &mods_dir, &loadout).expect("build ok"); + assert_eq!(built.as_deref(), Some(TFT_MOD_FOLDER)); + + let mod_root = mods_dir.join(TFT_MOD_FOLDER); + assert!(mod_root.join("META/info.json").is_file()); + + let remapped = std::fs::read(mod_root.join("RAW").join(DEFAULT_TACTICIAN_DONOR)) + .expect("remapped tactician bin"); + let parsed = parse_prop_file(&remapped).expect("valid remapped prop"); + assert_eq!( + parsed.entries[0].key_hash, + prop_key_hash("characters/pettftavatar/skins/skin1") + ); + assert!( + mod_root + .join("RAW/data/loadouts/tftdamageskins/base.bin") + .is_file() + ); + assert!( + mod_root + .join("RAW/data/loadouts/tftzoomskins/base.bin") + .is_file() + ); + assert!( + mod_root + .join("RAW/data/maps/shipping/map22/base.materials.bin") + .is_file() + ); +} + +#[test] +fn rejects_path_traversal_and_cleans_empty_loadout() { + let dir = TempDir::new("hostile"); + let game_dir = dir.path().join("Game"); + let mods_dir = dir.path().join("mods"); + + let hostile = TftLoadout { + tactician: Some(TftSwap { + donor_id: 1, + donor_path: "../outside.bin".into(), + target_id: 2, + target_path: "data/characters/pet/skins/skin1.bin".into(), + name: "Hostile".into(), + }), + ..TftLoadout::default() + }; + let built = build_tft_mod(&game_dir, &mods_dir, &hostile).expect("no error"); + assert_eq!(built, None); + assert!(!mods_dir.join(TFT_MOD_FOLDER).exists()); +} diff --git a/crates/bullet-classic/src/lib.rs b/crates/bullet-classic/src/lib.rs index 9fb95d1..e3f974f 100644 --- a/crates/bullet-classic/src/lib.rs +++ b/crates/bullet-classic/src/lib.rs @@ -12,7 +12,7 @@ pub use animation::{ form_state, form_trace, form_transition, form_vfx, forms, gear_toggle, vfx_markers, }; pub use audio::{form_sound, sound_bank}; -pub use generation::{builder, client_data, generator}; +pub use generation::{builder, client_data, generator, loading_name, tft}; pub use mesh::{mesh_merge, skeleton, skinned_mesh}; pub mod error; diff --git a/crates/bullet-classic/tests/real_skins_12_domains_tests.rs b/crates/bullet-classic/tests/real_skins_12_domains_tests.rs new file mode 100644 index 0000000..e930b15 --- /dev/null +++ b/crates/bullet-classic/tests/real_skins_12_domains_tests.rs @@ -0,0 +1,400 @@ +use std::collections::BTreeSet; +use std::path::Path; + +use bullet_classic::forms::{gear_keys, skn_submesh_names}; +use bullet_classic::gear_toggle::gear_swap; +use bullet_classic::generator::StandardChampion; +use bullet_classic::loading_name::rst; +use bullet_wad::hash::{prop_key_hash as h, wad_path_hash}; +use bullet_wad::prop::parse_prop_file; +use bullet_wad::prop::tree::{self, Value}; + +const SKIN_DATA_CLASS: u32 = 0x9b67_e9f6; +const VFX_SYSTEM_CLASS: u32 = 0x45cd_8998; +const STATIC_MATERIAL_CLASS: u32 = 0xff9d_3409; + +fn split_submesh_list(raw: &str) -> BTreeSet { + raw.split(|c: char| c.is_whitespace() || matches!(c, ',' | '|' | ':')) + .filter(|s| !s.is_empty()) + .map(h) + .collect() +} + +fn raw_text(value: &Value) -> Option { + match value { + Value::Raw { kind: 16, bytes } if bytes.len() >= 2 => { + Some(String::from_utf8_lossy(&bytes[2..]).into_owned()) + } + _ => None, + } +} + +fn hashes_of(fields: &[tree::Field], name: &str) -> Vec { + tree::field(fields, h(name)) + .and_then(Value::items) + .map(|items| items.iter().filter_map(Value::as_u32).collect()) + .unwrap_or_default() +} + +fn valid_texture_bytes(bytes: &[u8]) -> bool { + (bytes.len() >= 12 + && bytes.starts_with(b"TEX\0") + && u16::from_le_bytes([bytes[4], bytes[5]]) > 0 + && u16::from_le_bytes([bytes[6], bytes[7]]) > 0) + || (bytes.len() >= 128 && bytes.starts_with(b"DDS ")) + || bytes.starts_with(b"\x89PNG\r\n\x1a\n") + || bytes.starts_with(b"\xFF\xD8\xFF") + || (bytes.len() >= 12 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WEBP") +} + +fn has_skin_numbered_ref(value: &str, character: &str) -> bool { + for segment in value.split('_') { + let low = segment.to_ascii_lowercase(); + if let Some(at) = low.rfind("skin") { + let after = &low[at + 4..]; + let digit_len = after.bytes().take_while(u8::is_ascii_digit).count(); + let (digits, tail, head) = (&after[..digit_len], &after[digit_len..], &low[..at]); + if !digits.is_empty() + && digits.bytes().any(|b| b != b'0') + && head.bytes().all(|b| b.is_ascii_alphabetic()) + && tail.bytes().all(|b| b.is_ascii_alphabetic()) + { + return true; + } + } + } + let lower = value.to_ascii_lowercase(); + let needle = format!("{}skin", character.to_ascii_lowercase()); + let mut from = 0; + while let Some(pos) = lower[from..].find(&needle) { + let after = from + pos + needle.len(); + if lower + .as_bytes() + .get(after) + .is_some_and(|b| b.is_ascii_digit() && *b != b'0') + { + return true; + } + from = after; + } + false +} + +fn verify_audio_and_deep_entries( + champion: &StandardChampion, + main: &str, + wad_root: &Path, + gen_bytes: &[u8], + gen_fields: &[tree::Field], +) { + let gen_prop = parse_prop_file(gen_bytes).expect("parse gen prop"); + let mut defined_keys: BTreeSet = gen_prop.entries.iter().map(|e| e.key_hash).collect(); + for link in &gen_prop.links { + let lower = link.to_ascii_lowercase(); + if let Some(b) = std::fs::read(wad_root.join(&lower)) + .ok() + .or_else(|| champion.read_path(&lower).ok().flatten()) + && let Ok(lp) = parse_prop_file(&b) + { + defined_keys.extend(lp.entries.into_iter().map(|e| e.key_hash)); + } + } + for entry in &gen_prop.entries { + let ef = tree::parse_fields(&entry.body).expect("parse entry fields"); + if entry.class_hash == VFX_SYSTEM_CLASS { + assert!(!ef.is_empty()); + } else if entry.class_hash == STATIC_MATERIAL_CLASS + && let Some(samplers) = tree::field(&ef, h("samplerValues")).and_then(Value::items) + { + for s in samplers.iter().filter_map(Value::fields) { + if let Some(tex) = tree::field(s, h("textureName")) + .or_else(|| tree::field(s, h("texturePath"))) + .and_then(raw_text) + { + let lower = tex.to_ascii_lowercase(); + if let Some(b) = std::fs::read(wad_root.join(&lower)) + .ok() + .or_else(|| champion.read_path(&lower).ok().flatten()) + { + assert!(valid_texture_bytes(&b), "invalid sampler texture {lower}"); + } + } + } + } + } + if let Some(resolver) = tree::field(gen_fields, h("mResourceResolver")).and_then(Value::as_u32) + && resolver != 0 + { + assert!(defined_keys.contains(&resolver)); + } + if let Some(cname) = tree::field(gen_fields, h("championSkinName")).and_then(raw_text) { + assert!(!has_skin_numbered_ref(&cname, main), "stale name {cname}"); + } + if let Some(audio) = tree::field(gen_fields, h("skinAudioProperties")).and_then(Value::fields) { + if let Some(tags) = tree::field(audio, h("tagEventList")).and_then(Value::items) { + for t in tags.iter().filter_map(raw_text) { + assert!(!has_skin_numbered_ref(&t, main), "stale audio tag {t}"); + } + } + if let Some(units) = tree::field(audio, h("bankUnits")).and_then(Value::items) { + for uf in units.iter().filter_map(Value::fields) { + if let Some(uname) = tree::field(uf, h("name")).and_then(raw_text) { + assert!(!has_skin_numbered_ref(&uname, main), "stale unit {uname}"); + } + if let Some(paths) = tree::field(uf, h("bankPath")).and_then(Value::items) { + for p in paths.iter().filter_map(raw_text) { + let lower = p.to_ascii_lowercase(); + let local = wad_root.join(&lower); + if local.is_file() && lower.ends_with(".bnk") { + let b = std::fs::read(&local).expect("read bnk"); + assert!(bullet_classic::sound_bank::parse(&b).is_ok()); + } + } + } + } + } + } +} + +fn verify_generated_exalted_or_form_skin(game_dir: &Path, alias: &str, skin: u32) { + let dir = std::env::temp_dir().join(format!( + "bullet_12domain_{}_{}_{}", + alias.to_ascii_lowercase(), + skin, + std::process::id() + )); + let _ = std::fs::remove_dir_all(&dir); // ignore-ok: pre-clean test scratch dir + std::fs::create_dir_all(&dir).expect("create scratch dir"); + + let champion = StandardChampion::open(game_dir, alias).expect("open champion"); + let main = alias.to_ascii_lowercase(); + let folder = champion + .build_mod(skin, None, &dir) + .expect("build_mod succeeds"); + let mod_root = dir.join(&folder); + let wad_root = mod_root.join("WAD").join(format!("{alias}.wad.client")); + + for meta in ["META/info.json", "META/manifest.json"] { + let bytes = std::fs::read(mod_root.join(meta)).expect("read meta"); + serde_json::from_slice::(&bytes).expect("valid meta json"); + } + + let src_bytes = champion + .read_skin_bin(&main, skin) + .expect("read source skin") + .expect("source skin present"); + let gen_bytes = std::fs::read( + wad_root + .join("data/characters") + .join(&main) + .join("skins/skin0.bin"), + ) + .expect("read generated skin0.bin"); + + let src_prop = parse_prop_file(&src_bytes).expect("parse source prop"); + let gen_prop = parse_prop_file(&gen_bytes).expect("parse generated prop"); + for link in &src_prop.links { + assert!( + gen_prop.links.contains(link), + "{alias} skin{skin} dropped link {link}" + ); + } + + let src_skin = src_prop + .entries + .iter() + .find(|e| e.class_hash == SKIN_DATA_CLASS) + .expect("src skin entry"); + let gen_skin = gen_prop + .entries + .iter() + .find(|e| e.class_hash == SKIN_DATA_CLASS) + .expect("gen skin entry"); + let src_fields = tree::parse_fields(&src_skin.body).expect("src fields"); + let gen_fields = tree::parse_fields(&gen_skin.body).expect("gen fields"); + verify_audio_and_deep_entries(&champion, &main, &wad_root, &gen_bytes, &gen_fields); + + let graph_of = |f: &[tree::Field]| { + tree::field(f, h("skinAnimationProperties")) + .and_then(Value::fields) + .and_then(|a| tree::field(a, h("animationGraphData"))) + .and_then(Value::as_u32) + }; + assert_eq!(graph_of(&src_fields), graph_of(&gen_fields)); + + let gen_mesh = tree::field(&gen_fields, h("skinMeshProperties")) + .and_then(Value::fields) + .expect("gen skinMeshProperties"); + let skn_rel = tree::field(gen_mesh, h("simpleSkin")) + .and_then(raw_text) + .expect("simpleSkin") + .to_ascii_lowercase(); + let skl_rel = tree::field(gen_mesh, h("skeleton")) + .and_then(raw_text) + .expect("skeleton") + .to_ascii_lowercase(); + assert_ne!(wad_path_hash(&skn_rel), 0); + assert_ne!(wad_path_hash(&skl_rel), 0); + + let skn_bytes = std::fs::read(wad_root.join(&skn_rel)) + .ok() + .or_else(|| champion.read_path(&skn_rel).ok().flatten()) + .expect("skn bytes"); + let parsed_skn = bullet_classic::skinned_mesh::parse(&skn_bytes).expect("parse skn"); + parsed_skn + .validate_submesh_indices() + .expect("valid submesh indices"); + assert!(!parsed_skn.submeshes.is_empty() && (52..=72).contains(&parsed_skn.vertex_size)); + let skn_parts = skn_submesh_names(&skn_bytes).expect("skn submesh names"); + let skn_hashes: BTreeSet = skn_parts.iter().map(|n| h(n)).collect(); + + let skl_bytes = std::fs::read(wad_root.join(&skl_rel)) + .ok() + .or_else(|| champion.read_path(&skl_rel).ok().flatten()) + .expect("skl bytes"); + let parsed_skl = bullet_classic::skeleton::parse(&skl_bytes).expect("parse skl"); + assert!(!parsed_skl.joints.is_empty()); + + if let Some(items) = tree::field(gen_mesh, h("materialOverride")).and_then(Value::items) { + for item in items { + if let Some(sub) = item + .fields() + .and_then(|f| tree::field(f, h("submesh"))) + .and_then(raw_text) + && sub + .rsplit_once("_F") + .is_some_and(|(_, t)| !t.is_empty() && t.bytes().all(|b| b.is_ascii_digit())) + { + assert!(skn_hashes.contains(&h(&sub)), "missing part {sub}"); + } + } + } + + let src_mesh = tree::field(&src_fields, h("skinMeshProperties")) + .and_then(Value::fields) + .expect("src skinMeshProperties"); + let src_skn_rel = tree::field(src_mesh, h("simpleSkin")) + .and_then(raw_text) + .expect("src simpleSkin") + .to_ascii_lowercase(); + let src_skn_bytes = champion + .read_path(&src_skn_rel) + .expect("read src skn") + .expect("src skn present"); + let src_skn_parts = skn_submesh_names(&src_skn_bytes).expect("src skn names"); + let src_init_hide = tree::field(src_mesh, h("initialSubmeshToHide")) + .and_then(raw_text) + .map(|s| split_submesh_list(&s)) + .unwrap_or_default(); + + let keys = gear_keys(&src_bytes).expect("gear keys"); + if keys.len() >= 2 && champion.gear_count(0) == 0 { + let gear0_body = champion.gear_body(&src_bytes, keys[0]).expect("gear 0"); + let gear0_hide: BTreeSet = gear_swap(&gear0_body) + .expect("gear 0 swap") + .hide + .into_iter() + .collect(); + let gen_init_hide = tree::field(gen_mesh, h("initialSubmeshToHide")) + .and_then(raw_text) + .map(|s| split_submesh_list(&s)) + .unwrap_or_default(); + + let mut src_cond_hide = BTreeSet::new(); + if let Some(conds) = + tree::field(&src_fields, h("PersistentEffectConditions")).and_then(Value::items) + { + for cf in conds.iter().filter_map(Value::fields) { + src_cond_hide.extend(hashes_of(cf, "SubmeshesToHide")); + } + } + + let mut cond_hide = BTreeSet::new(); + if let Some(conds) = + tree::field(&gen_fields, h("PersistentEffectConditions")).and_then(Value::items) + { + for cf in conds.iter().filter_map(Value::fields) { + if tree::field(cf, h("OwnerCondition")).and_then(Value::class) + == Some(h("NotMaterialDriver")) + { + cond_hide.extend(hashes_of(cf, "SubmeshesToHide")); + } + } + } + + for part in &src_skn_parts { + let ph = h(part); + if !src_init_hide.contains(&ph) + && !gear0_hide.contains(&ph) + && !src_cond_hide.contains(&ph) + { + assert!(!gen_init_hide.contains(&ph)); + assert!(!cond_hide.contains(&ph)); + } + } + } + + for form in 0..champion.gear_count(skin) as u32 { + let f_folder = champion + .build_mod_form(skin, None, form, &dir) + .expect("build_mod_form"); + let f_wad = dir + .join(&f_folder) + .join("WAD") + .join(format!("{alias}.wad.client")); + let f_bin = std::fs::read( + f_wad + .join("data/characters") + .join(&main) + .join("skins/skin0.bin"), + ) + .expect("read form skin0.bin"); + let f_prop = parse_prop_file(&f_bin).expect("parse form prop"); + let f_skin = f_prop + .entries + .iter() + .find(|e| e.class_hash == SKIN_DATA_CLASS) + .expect("form skin entry"); + let f_fields = tree::parse_fields(&f_skin.body).expect("form fields"); + verify_audio_and_deep_entries(&champion, &main, &f_wad, &f_bin, &f_fields); + } + + let record_rel = format!("data/characters/{main}/{main}.bin"); + if let Ok(Some(rec)) = champion.read_path(&record_rel) + && let Some(patched) = rst::patch_record_key(&rec, alias) + { + assert!(parse_prop_file(&patched).is_ok()); + } + + let _ = std::fs::remove_dir_all(&dir); // ignore-ok: cleanup test scratch dir +} + +#[test] +fn real_game_exalted_and_form_skins_pass_all_12_domain_validations() { + let candidates = [ + Path::new(r"D:\Riot Games\League of Legends\Game"), + Path::new(r"C:\Riot Games\League of Legends\Game"), + ]; + let Some(game_dir) = candidates.into_iter().find(|p| { + p.join("DATA/FINAL/Champions/Mordekaiser.wad.client") + .is_file() + }) else { + return; + }; + + for (alias, skin) in [ + ("Mordekaiser", 54), + ("Sett", 66), + ("Diana", 77), + ("Lux", 7), + ("Sona", 6), + ("Morgana", 80), + ("Jinx", 60), + ("MissFortune", 16), + ("Viego", 43), + ("Ahri", 85), + ("Kaisa", 71), + ] { + verify_generated_exalted_or_form_skin(game_dir, alias, skin); + } +} diff --git a/crates/bullet-classic/tests/rigorous_rst_tft_tests.rs b/crates/bullet-classic/tests/rigorous_rst_tft_tests.rs new file mode 100644 index 0000000..4baa783 --- /dev/null +++ b/crates/bullet-classic/tests/rigorous_rst_tft_tests.rs @@ -0,0 +1,106 @@ +use bullet_classic::loading_name::rst; + +struct XorShift64(u64); + +impl XorShift64 { + fn next_u64(&mut self) -> u64 { + let mut x = self.0; + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + self.0 = x; + x + } + + fn next_bytes(&mut self, len: usize) -> Vec { + (0..len).map(|_| (self.next_u64() & 0xFF) as u8).collect() + } +} + +fn build_rst_v5(entries: &[(&str, &str)]) -> Vec { + let mut table = Vec::new(); + table.extend_from_slice(b"RST"); + table.push(5); + table.extend_from_slice(&0u32.to_le_bytes()); + let updates: Vec<(String, String)> = entries + .iter() + .map(|(k, v)| ((*k).to_owned(), (*v).to_owned())) + .collect(); + rst::with_texts(&table, &updates).expect("valid rst") +} + +#[test] +fn property_rst_v5_roundtrip_preserves_multilingual_texts() { + let initial = [ + ("game_character_displayname_zyra", "Zyra"), + ( + "game_character_skin_displayname_zyra_36", + "Spirit Blossom Zyra", + ), + ("game_character_skin_displayname_ahri_85", "阿狸 灵魂莲华"), + ("game_character_skin_displayname_zed_1", "칼날폭풍 제드"), + ("game_character_skin_displayname_lux_7", "Elementalist Lux"), + ]; + let table = build_rst_v5(&initial); + + for (key, expected) in &initial { + assert_eq!( + rst::read_text(&table, rst::key_hash(key)).as_deref(), + Some(*expected) + ); + } + + let patched = rst::with_texts( + &table, + &[ + ( + "game_character_displayname_zyra".into(), + "Zyra Florescer Espiritual".into(), + ), + ("bllt_character_displayname_zyra".into(), "Zyra".into()), + ], + ) + .expect("patch ok"); + + assert_eq!( + rst::read_text(&patched, rst::key_hash("game_character_displayname_zyra")).as_deref(), + Some("Zyra Florescer Espiritual") + ); + assert_eq!( + rst::read_text(&patched, rst::key_hash("bllt_character_displayname_zyra")).as_deref(), + Some("Zyra") + ); + assert_eq!( + rst::read_text( + &patched, + rst::key_hash("game_character_skin_displayname_ahri_85") + ) + .as_deref(), + Some("阿狸 灵魂莲华") + ); +} + +#[test] +fn fuzz_malformed_rst_and_character_records_never_panic() { + let mut rng = XorShift64(0x1234_5678_9ABC_DEF0); + let base_table = build_rst_v5(&[("game_character_displayname_zed", "Zed")]); + + for iter in 0..1500u32 { + let buf = if iter % 3 == 0 { + let mut copy = base_table.clone(); + let idx = (rng.next_u64() as usize) % copy.len().max(1); + copy[idx] ^= 0xFF; + if iter % 6 == 0 && copy.len() > 1 { + copy.truncate((rng.next_u64() as usize) % copy.len()); + } + copy + } else { + let len = (rng.next_u64() % 256) as usize; + rng.next_bytes(len) + }; + + let _ = rst::read_text(&buf, rng.next_u64() & rst::RST_MASK); // ignore-ok: fuzz test asserts no panic + let _ = rst::with_texts(&buf, &[("k".into(), "X".into())]); // ignore-ok: fuzz test asserts no panic + let _ = rst::patch_record_key(&buf, "Zed"); // ignore-ok: fuzz test asserts no panic + } +} diff --git a/crates/bullet-core/src/domain/mod.rs b/crates/bullet-core/src/domain/mod.rs index 9cc9493..20dd76a 100644 --- a/crates/bullet-core/src/domain/mod.rs +++ b/crates/bullet-core/src/domain/mod.rs @@ -1,6 +1,7 @@ mod play; mod skins; +pub use play::identity; pub use play::lobby; pub use play::overlay; pub use play::party; diff --git a/crates/bullet-core/src/domain/play/identity.rs b/crates/bullet-core/src/domain/play/identity.rs new file mode 100644 index 0000000..cab30fb --- /dev/null +++ b/crates/bullet-core/src/domain/play/identity.rs @@ -0,0 +1,168 @@ +use serde::{Deserialize, Serialize}; + +const MAX_PATH_LEN: usize = 200; +const MAX_TITLE_LEN: usize = 64; +const MAX_BORDER_LEN: usize = 48; +const MAX_TOKENS: usize = 3; + +#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct IdentityLoadout { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub icon_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub border: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub banner: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub title: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub tokens: Vec, +} + +fn valid_asset_path(value: &str) -> bool { + if value.is_empty() || value.len() > MAX_PATH_LEN || value.contains("..") { + return false; + } + let allowed_prefix = value.starts_with("/lol-game-data/assets/") + || value.starts_with("/fe/lol-static-assets/") + || value.starts_with("fe/lol-static-assets/"); + if !allowed_prefix { + return false; + } + value + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'/' | b'_' | b'-' | b'.')) +} + +fn valid_border(value: &str) -> bool { + if value.is_empty() || value.len() > MAX_BORDER_LEN { + return false; + } + value + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b':')) +} + +fn valid_title(value: &str) -> bool { + let trimmed = value.trim(); + if trimmed.is_empty() || trimmed.chars().count() > MAX_TITLE_LEN { + return false; + } + !trimmed + .chars() + .any(|c| c.is_control() || matches!(c, '<' | '>' | '"' | '\'' | '\\')) +} + +fn valid_token(value: &str) -> bool { + if valid_asset_path(value) { + return true; + } + !value.is_empty() + && value.len() <= 32 + && value + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b':')) +} + +impl IdentityLoadout { + #[must_use] + pub fn is_empty(&self) -> bool { + self.icon_id.is_none() + && self.border.is_none() + && self.banner.is_none() + && self.title.is_none() + && self.tokens.is_empty() + } + + pub fn validate(&self) -> Result<(), &'static str> { + if let Some(icon) = self.icon_id + && icon == 0 + { + return Err("icon_id"); + } + if let Some(border) = self.border.as_deref() + && !valid_border(border) + { + return Err("border"); + } + if let Some(banner) = self.banner.as_deref() + && !valid_asset_path(banner) + { + return Err("banner"); + } + if let Some(title) = self.title.as_deref() + && !valid_title(title) + { + return Err("title"); + } + if self.tokens.len() > MAX_TOKENS { + return Err("tokens count"); + } + for token in &self.tokens { + if !valid_token(token) { + return Err("token"); + } + } + Ok(()) + } + + #[must_use] + pub fn normalized(mut self) -> Option { + self.icon_id = self.icon_id.filter(|&id| id > 0); + self.border = self.border.filter(|b| valid_border(b)); + self.banner = self.banner.filter(|b| valid_asset_path(b)); + self.title = self + .title + .map(|t| t.trim().to_owned()) + .filter(|t| valid_title(t)); + self.tokens.retain(|t| valid_token(t)); + self.tokens.truncate(MAX_TOKENS); + (!self.is_empty()).then_some(self) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn valid_identity_passes_and_rejects_css_injection() { + let ok = IdentityLoadout { + icon_id: Some(29), + border: Some("CHALLENGER".into()), + banner: Some("/lol-game-data/assets/v1/regalia/banner_challenger.png".into()), + title: Some("Bot Diff".into()), + tokens: vec![ + "/lol-game-data/assets/assets/challenges/config/101000/tokens/challenger.png" + .into(), + "101000:CHALLENGER".into(), + ], + }; + assert!(ok.validate().is_ok()); + assert!(!ok.is_empty()); + + let css_inj = IdentityLoadout { + banner: Some("/lol-game-data/assets/x.png);background:url(evil".into()), + ..IdentityLoadout::default() + }; + assert!(css_inj.validate().is_err()); + + let traversal = IdentityLoadout { + banner: Some("/lol-game-data/assets/../secrets.txt".into()), + ..IdentityLoadout::default() + }; + assert!(traversal.validate().is_err()); + + let xss_title = IdentityLoadout { + title: Some("".into()), + ..IdentityLoadout::default() + }; + assert!(xss_title.validate().is_err()); + + let too_many_tokens = IdentityLoadout { + tokens: vec!["a".into(), "b".into(), "c".into(), "d".into()], + ..IdentityLoadout::default() + }; + assert!(too_many_tokens.validate().is_err()); + } +} diff --git a/crates/bullet-core/src/domain/play/mod.rs b/crates/bullet-core/src/domain/play/mod.rs index cdede29..e4c31b1 100644 --- a/crates/bullet-core/src/domain/play/mod.rs +++ b/crates/bullet-core/src/domain/play/mod.rs @@ -1,3 +1,4 @@ +pub mod identity; pub mod lobby; pub mod overlay; pub mod party; diff --git a/crates/bullet-core/src/domain/play/overlay.rs b/crates/bullet-core/src/domain/play/overlay.rs index 811f684..43206d4 100644 --- a/crates/bullet-core/src/domain/play/overlay.rs +++ b/crates/bullet-core/src/domain/play/overlay.rs @@ -1,8 +1,17 @@ use serde::{Deserialize, Serialize}; +use crate::identity::IdentityLoadout; use crate::mods::ModSelectionView; use crate::selection::{ChampionId, ChromaId, SkinId}; +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct InClientPartyView { + pub joinable_friends: usize, + pub connected_members: usize, + pub local_identity: Option, + pub peer_identities: Vec<(String, IdentityLoadout)>, +} + #[derive(Debug, Clone, PartialEq, Eq)] pub enum OverlayCommand { Select { id: u32 }, @@ -13,8 +22,14 @@ pub enum OverlayCommand { SetMods { selection: ModSelectionView }, + SetIdentity { loadout: Option }, + + JoinLobbyParty, + OpenModsFolder, + OpenPanel, + ImportMod { category: crate::mods::ModCategory }, ChromaPreview { id: u32 }, @@ -118,6 +133,8 @@ pub struct Catalog { pub classic: bool, pub lobby: Vec, + + pub party: InClientPartyView, } #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/crates/bullet-core/src/domain/play/party.rs b/crates/bullet-core/src/domain/play/party.rs index 572b294..bc1815e 100644 --- a/crates/bullet-core/src/domain/play/party.rs +++ b/crates/bullet-core/src/domain/play/party.rs @@ -1,5 +1,6 @@ use serde::{Deserialize, Serialize}; +use crate::identity::IdentityLoadout; use crate::phase::GamePhase; use crate::selection::{ChampionId, ChromaId, SkinId}; @@ -16,6 +17,8 @@ pub struct PartyPeer { pub champion_id: ChampionId, pub skin_id: SkinId, pub chroma_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub identity: Option, } impl PartyPeer { @@ -190,6 +193,7 @@ mod tests { champion_id, skin_id, chroma_id: None, + identity: None, } } diff --git a/crates/bullet-core/src/lib.rs b/crates/bullet-core/src/lib.rs index 51b1ce3..29559de 100644 --- a/crates/bullet-core/src/lib.rs +++ b/crates/bullet-core/src/lib.rs @@ -4,7 +4,7 @@ mod domain; mod runtime; -pub use domain::{historic, library, lobby, mods, overlay, party, presets}; +pub use domain::{historic, identity, library, lobby, mods, overlay, party, presets}; pub use runtime::{phase, selection, state, supervisor}; pub mod env; diff --git a/crates/bullet-core/src/runtime/state/lobby_tests.rs b/crates/bullet-core/src/runtime/state/lobby_tests.rs index 9644183..266b672 100644 --- a/crates/bullet-core/src/runtime/state/lobby_tests.rs +++ b/crates/bullet-core/src/runtime/state/lobby_tests.rs @@ -203,6 +203,7 @@ fn stopping_to_share_drops_the_friends_picks() { champion_id: 1, skin_id: 1_004, chroma_id: None, + identity: None, }], ); assert_eq!(rx.borrow().party_peers.len(), 1); diff --git a/crates/bullet-core/src/runtime/state/mod.rs b/crates/bullet-core/src/runtime/state/mod.rs index 9f788b6..20d8b5c 100644 --- a/crates/bullet-core/src/runtime/state/mod.rs +++ b/crates/bullet-core/src/runtime/state/mod.rs @@ -1,6 +1,7 @@ use serde::{Deserialize, Serialize}; use tokio::sync::watch; +use crate::identity::IdentityLoadout; use crate::lobby::{LobbyPicks, LobbySlot}; use crate::mods::ModSelection; use crate::overlay::OverlayTarget; @@ -12,17 +13,12 @@ use crate::selection::{ChampionId, SkinId}; pub enum InjectionStatus { #[default] Idle, - Pending, - Confirmed, - Unconfirmed, - Failed { error: String, }, - PatcherExited { code: i32, }, @@ -31,36 +27,22 @@ pub enum InjectionStatus { #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AppState { pub phase: GamePhase, - pub champion_id: Option, - pub selected_skin_id: Option, - pub overlay_target: Option, - pub lcu_connected: bool, - pub injection: InjectionStatus, - pub mods: ModSelection, - pub local_puuid: Option, - pub team: Vec, - pub party_status: PartyStatus, - pub party_hosting: bool, - pub party_peers: Vec, - pub party_share: bool, - pub lobby_party: Option, - pub lobby: Option, - pub queue: Option, + pub local_identity: Option, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -70,6 +52,13 @@ pub struct QueueInfo { pub map_id: u32, } +impl QueueInfo { + #[must_use] + pub fn is_tft(&self) -> bool { + self.map_id == 22 || self.game_mode.eq_ignore_ascii_case("TFT") + } +} + impl Default for AppState { fn default() -> Self { Self { @@ -89,6 +78,7 @@ impl Default for AppState { lobby_party: None, lobby: None, queue: None, + local_identity: None, } } } @@ -387,6 +377,16 @@ pub fn set_lcu_connected(tx: &StateSender, connected: bool) { }); } +pub fn set_local_identity(tx: &StateSender, loadout: Option) { + tx.send_if_modified(|state| { + if state.local_identity == loadout { + return false; + } + state.local_identity = loadout; + true + }); +} + #[cfg(test)] mod tests; diff --git a/crates/bullet-inject/Cargo.toml b/crates/bullet-inject/Cargo.toml index cc2887b..f0dfc25 100644 --- a/crates/bullet-inject/Cargo.toml +++ b/crates/bullet-inject/Cargo.toml @@ -22,3 +22,6 @@ xxhash-rust.workspace = true zip.workspace = true zstd.workspace = true base64.workspace = true + +[target.'cfg(target_os = "macos")'.dependencies] +libc.workspace = true diff --git a/crates/bullet-inject/src/injector/macos_patcher/macho.rs b/crates/bullet-inject/src/injector/macos_patcher/macho.rs new file mode 100644 index 0000000..40badbb --- /dev/null +++ b/crates/bullet-inject/src/injector/macos_patcher/macho.rs @@ -0,0 +1,321 @@ +pub const MH_MAGIC_64: u32 = 0xFEED_FACF; +pub const CPU_TYPE_X86_64: i32 = 0x0100_0007; +pub const CPU_TYPE_ARM64: i32 = 0x0100_000C; + +pub const LC_SEGMENT_64: u32 = 0x19; +pub const LC_DYLD_INFO: u32 = 0x22; +pub const LC_DYLD_INFO_ONLY: u32 = 0x8000_0022; + +pub const BIND_OPCODE_MASK: u8 = 0xF0; +pub const BIND_IMMEDIATE_MASK: u8 = 0x0F; +pub const BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: u8 = 0x40; +pub const BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: u8 = 0x70; +pub const BIND_OPCODE_DO_BIND: u8 = 0x90; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CpuArch { + X86_64, + Arm64, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MachoLayout { + pub arch: CpuArch, + pub text_addr: u64, + pub text_size: u64, + pub text_off: u64, + pub text_vmaddr: u64, + pub stubs_addr: u64, + pub stubs_size: u64, + pub stubs_off: u64, + pub la_sym_off: u64, + pub lazy_bind_off: u32, + pub lazy_bind_size: u32, +} + +fn read_u32_le(buf: &[u8], off: usize) -> Option { + let slice = buf.get(off..off.checked_add(4)?)?; + Some(u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]])) +} + +fn read_i32_le(buf: &[u8], off: usize) -> Option { + let slice = buf.get(off..off.checked_add(4)?)?; + Some(i32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]])) +} + +fn read_u64_le(buf: &[u8], off: usize) -> Option { + let slice = buf.get(off..off.checked_add(8)?)?; + Some(u64::from_le_bytes([ + slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6], slice[7], + ])) +} + +fn trim_nul(bytes: &[u8]) -> &[u8] { + let end = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len()); + &bytes[..end] +} + +pub fn parse_macho_commands(image_base: u64, buf: &[u8]) -> Result { + if buf.len() < 32 { + return Err("Mach-O header buffer truncated".into()); + } + let magic = read_u32_le(buf, 0).ok_or_else(|| "cannot read magic".to_owned())?; + if magic != MH_MAGIC_64 { + return Err(format!("invalid Mach-O 64 magic: {magic:#x}")); + } + let cputype = read_i32_le(buf, 4).ok_or_else(|| "cannot read cputype".to_owned())?; + let arch = match cputype { + CPU_TYPE_X86_64 => CpuArch::X86_64, + CPU_TYPE_ARM64 => CpuArch::Arm64, + other => return Err(format!("unsupported Mach-O CPU type: {other:#x}")), + }; + let ncmds = read_u32_le(buf, 16).ok_or_else(|| "cannot read ncmds".to_owned())?; + let sizeofcmds = + read_u32_le(buf, 20).ok_or_else(|| "cannot read sizeofcmds".to_owned())? as usize; + if buf.len() < 32usize.saturating_add(sizeofcmds) { + return Err("Mach-O load commands truncated".into()); + } + + let mut layout = MachoLayout { + arch, + text_addr: 0, + text_size: 0, + text_off: 0, + text_vmaddr: 0, + stubs_addr: 0, + stubs_size: 0, + stubs_off: 0, + la_sym_off: 0, + lazy_bind_off: 0, + lazy_bind_size: 0, + }; + + let mut off = 32usize; + for _ in 0..ncmds { + let cmd = + read_u32_le(buf, off).ok_or_else(|| "load command header truncated".to_owned())?; + let cmdsize = read_u32_le(buf, off + 4) + .ok_or_else(|| "load command size truncated".to_owned())? + as usize; + if cmdsize < 8 || off.saturating_add(cmdsize) > 32usize.saturating_add(sizeofcmds) { + return Err("invalid Mach-O load command size".into()); + } + + if cmd == LC_SEGMENT_64 && cmdsize >= 72 { + let segname = trim_nul(&buf[off + 8..off + 24]); + let vmaddr = + read_u64_le(buf, off + 24).ok_or_else(|| "segment vmaddr truncated".to_owned())?; + let nsects = read_u32_le(buf, off + 64) + .ok_or_else(|| "segment nsects truncated".to_owned())? + as usize; + if segname == b"__TEXT" { + layout.text_vmaddr = vmaddr; + } + for s in 0..nsects { + let soff = off + 72 + s * 80; + if soff + 80 > off + cmdsize { + break; + } + let sectname = trim_nul(&buf[soff..soff + 16]); + let s_addr = read_u64_le(buf, soff + 32).unwrap_or(0); + let s_size = read_u64_le(buf, soff + 40).unwrap_or(0); + let s_offset = u64::from(read_u32_le(buf, soff + 48).unwrap_or(0)); + if segname == b"__TEXT" && sectname == b"__text" { + layout.text_addr = image_base.wrapping_add(s_offset); + layout.text_size = s_size; + layout.text_off = s_offset; + } else if segname == b"__TEXT" && sectname == b"__stubs" { + layout.stubs_addr = image_base.wrapping_add(s_offset); + layout.stubs_size = s_size; + layout.stubs_off = s_offset; + } else if (segname == b"__DATA" || segname == b"__DATA_CONST") + && sectname == b"__la_symbol_ptr" + { + layout.la_sym_off = if layout.text_vmaddr > 0 && s_addr >= layout.text_vmaddr { + s_addr - layout.text_vmaddr + } else { + s_offset + }; + } + } + } else if (cmd == LC_DYLD_INFO || cmd == LC_DYLD_INFO_ONLY) && cmdsize >= 48 { + layout.lazy_bind_off = read_u32_le(buf, off + 32).unwrap_or(0); + layout.lazy_bind_size = read_u32_le(buf, off + 36).unwrap_or(0); + } + + off += cmdsize; + } + + if layout.text_size == 0 || layout.stubs_size == 0 || layout.la_sym_off == 0 { + return Err("missing required Mach-O sections (__text, __stubs, __la_symbol_ptr)".into()); + } + Ok(layout) +} + +fn read_uleb128(data: &[u8], pos: &mut usize) -> u64 { + let mut result = 0u64; + let mut shift = 0u32; + while *pos < data.len() { + let byte = data[*pos]; + *pos += 1; + result |= u64::from(byte & 0x7F) << shift; + if (byte & 0x80) == 0 { + break; + } + shift = shift.saturating_add(7); + } + result +} + +#[must_use] +pub fn find_lazy_bind_offset(lazy_bind: &[u8], la_sym_off: u64, symbol: &str) -> Option { + let mut pos = 0usize; + let mut seg_offset = 0u64; + let mut current_sym = String::new(); + while pos < lazy_bind.len() { + let byte = lazy_bind[pos]; + pos += 1; + let opcode = byte & BIND_OPCODE_MASK; + let _imm = byte & BIND_IMMEDIATE_MASK; + match opcode { + BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB => { + seg_offset = read_uleb128(lazy_bind, &mut pos); + } + BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM => { + let start = pos; + while pos < lazy_bind.len() && lazy_bind[pos] != 0 { + pos += 1; + } + current_sym = String::from_utf8_lossy(&lazy_bind[start..pos]).into_owned(); + if pos < lazy_bind.len() { + pos += 1; + } + } + BIND_OPCODE_DO_BIND if current_sym == symbol => { + return Some(la_sym_off.wrapping_add(seg_offset)); + } + _ => {} + } + } + None +} + +#[must_use] +pub fn find_stub_x86_64(stubs: &[u8], stubs_off: u64, target_ptr_off: u64) -> Option { + let mut i = 0usize; + while i + 6 <= stubs.len() { + if stubs[i] == 0xFF && stubs[i + 1] == 0x25 { + let rip_rel = + i32::from_le_bytes([stubs[i + 2], stubs[i + 3], stubs[i + 4], stubs[i + 5]]); + let stub_off = stubs_off.wrapping_add(i as u64); + let target = (stub_off.wrapping_add(6) as i64).wrapping_add(i64::from(rip_rel)) as u64; + if target == target_ptr_off { + return Some(i as u64); + } + } + i += 6; + } + None +} + +#[must_use] +pub fn find_stub_arm64( + stubs: &[u8], + stubs_off: u64, + text_vmaddr: u64, + target_ptr_off: u64, +) -> Option { + let target_vmaddr = text_vmaddr.wrapping_add(target_ptr_off); + let mut i = 0usize; + while i + 12 <= stubs.len() { + let i0 = read_u32_le(stubs, i)?; + let i1 = read_u32_le(stubs, i + 4)?; + let i2 = read_u32_le(stubs, i + 8)?; + let is_adrp_x16 = (i0 & 0x9F00_001F) == 0x9000_0010; + let is_ldr_x16 = (i1 & 0xFFC0_03FF) == 0xF940_0210; + let is_br_x16 = i2 == 0xD61F_0200; + if is_adrp_x16 && is_ldr_x16 && is_br_x16 { + let immlo = i64::from((i0 >> 29) & 0x3); + let immhi = i64::from((i0 >> 5) & 0x7FFFF); + let mut imm = (immhi << 2) | immlo; + if (imm & (1 << 20)) != 0 { + imm |= !((1 << 21) - 1); + } + let pc = text_vmaddr.wrapping_add(stubs_off).wrapping_add(i as u64); + let page = ((pc & !0xFFF) as i64).wrapping_add(imm << 12) as u64; + let ldr_off = u64::from((i1 >> 10) & 0xFFF) * 8; + if page.wrapping_add(ldr_off) == target_vmaddr { + return Some(i as u64); + } + } + i += 12; + } + None +} + +const WAD_VERIFY_PAT_X86_64: &[i16] = &[ + 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x53, 0x48, 0x81, 0xEC, -1, -1, 0x00, 0x00, + 0x49, 0x89, -1, 0x48, 0x8B, 0x05, -1, -1, -1, -1, 0x48, 0x31, 0xE0, 0x48, 0x89, 0x84, 0x24, -1, + -1, 0x00, 0x00, -1, 0x85, -1, 0x0F, 0x84, -1, -1, 0x00, 0x00, 0x4D, 0x85, +]; + +const WAD_VERIFY_PAT_ARM64: &[i16] = &[ + 0xFF, -1, -1, 0xD1, -1, -1, -1, 0xA9, -1, -1, -1, 0xA9, -1, -1, -1, 0xA9, -1, -1, -1, 0xA9, -1, + -1, -1, 0xA9, 0xFD, -1, -1, 0x91, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 0xF9, -1, -1, 0x00, 0xB4, +]; + +fn scan_pattern(haystack: &[u8], pattern: &[i16], step: usize) -> Option { + if haystack.len() < pattern.len() { + return None; + } + let limit = haystack.len() - pattern.len(); + let mut i = 0usize; + while i <= limit { + let matched = pattern + .iter() + .enumerate() + .all(|(j, &pat)| pat < 0 || i16::from(haystack[i + j]) == pat); + if matched { + return Some(i); + } + i += step; + } + None +} + +#[must_use] +pub fn scan_wad_verify_x86_64(text: &[u8]) -> Option { + let idx = scan_pattern(text, WAD_VERIFY_PAT_X86_64, 1)?; + let lookback = idx.min(16); + for back in 1..=lookback { + let pos = idx - back; + if pos + 4 <= text.len() && text[pos..pos + 4] == [0x55, 0x48, 0x89, 0xE5] { + return Some(pos); + } + } + Some(idx) +} + +#[must_use] +pub fn scan_wad_verify_arm64(text: &[u8]) -> Option { + let limit = text.len().saturating_sub(WAD_VERIFY_PAT_ARM64.len()); + let mut i = 0usize; + while i <= limit { + let matched = WAD_VERIFY_PAT_ARM64 + .iter() + .enumerate() + .all(|(j, &pat)| pat < 0 || i16::from(text[i + j]) == pat); + if matched + && (text[i + 4] & 0xF0) == 0xF0 + && (text[i + 8] & 0xF0) == 0xF0 + && (text[i + 12] & 0xF0) == 0xF0 + && (text[i + 16] & 0xF0) == 0xF0 + && (text[i + 20] & 0xF0) == 0xF0 + { + return Some(i); + } + i += 4; + } + None +} diff --git a/crates/bullet-inject/src/injector/macos_patcher/mod.rs b/crates/bullet-inject/src/injector/macos_patcher/mod.rs new file mode 100644 index 0000000..25cfc8d --- /dev/null +++ b/crates/bullet-inject/src/injector/macos_patcher/mod.rs @@ -0,0 +1,221 @@ +use std::path::Path; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::time::Duration; + +use bullet_core::state::{InjectionStatus, StateSender, set_injection_status}; +use tokio::sync::{mpsc, oneshot}; +use tracing::{info, warn}; + +use crate::error::InjectError; +use crate::overlay::OverlayManager; +use crate::overlay_process::{OverlayProcess, PatcherSignal}; + +pub mod macho; +pub mod payload; +pub mod sys; + +pub use macho::CpuArch; + +pub const MACOS_OVERLAY_SYMLINK: &str = "/tmp/bullet_ovl"; + +pub fn prepare_macos_overlay_prefix(overlay_dir: &Path) -> Result { + std::fs::create_dir_all(overlay_dir)?; + #[cfg(unix)] + { + let link_path = Path::new(MACOS_OVERLAY_SYMLINK); + if link_path.exists() || link_path.symlink_metadata().is_ok() { + let _ = std::fs::remove_file(link_path); // ignore-ok: replace previous symlink + } + if std::os::unix::fs::symlink(overlay_dir, link_path).is_ok() { + return Ok(format!("{MACOS_OVERLAY_SYMLINK}/")); + } + } + let mut raw = overlay_dir.display().to_string(); + if !raw.ends_with('/') { + raw.push('/'); + } + if raw.len() >= payload::MAX_PREFIX_BYTES { + return Err(InjectError::Overlay(format!( + "overlay prefix '{}' exceeds {} bytes", + raw, + payload::MAX_PREFIX_BYTES + ))); + } + Ok(raw) +} + +pub fn patch_game_pid(pid: u32, prefix: &str) -> Result { + sys::patch_live_process(pid, prefix).map_err(InjectError::Process) +} + +pub fn run_cli_patcher(args: &[String]) -> Result, String> { + let Some(idx) = args.iter().position(|a| a == "--macos-patcher") else { + return Ok(None); + }; + let prefix = args + .get(idx + 1) + .ok_or_else(|| "--macos-patcher requires an overlay prefix path".to_owned())?; + let pid = match args.iter().position(|a| a == "--pid") { + Some(p_idx) => args + .get(p_idx + 1) + .ok_or_else(|| "--pid requires a numeric process ID".to_owned())? + .parse::() + .map_err(|e| format!("invalid --pid value: {e}"))?, + None => bullet_platform::process::ProcessFinder::find_any_process( + &bullet_platform::game_version::GAME_EXES, + ) + .map_err(|e| e.to_string())? + .ok_or_else(|| "LeagueofLegends process not running".to_owned())?, + }; + match patch_game_pid(pid, prefix) { + Ok(arch) => { + println!("MACPATCH_HOOKED pid={pid} arch={arch:?}"); + Ok(Some(0)) + } + Err(e) => { + eprintln!("MACPATCH_FAILED pid={pid} error={e}"); + Ok(Some(1)) + } + } +} + +fn patch_pid_elevated_or_direct(pid: u32, prefix: &str) -> Result<(), String> { + if bullet_platform::elevation::is_elevated() { + patch_game_pid(pid, prefix) + .map(|_| ()) + .map_err(|e| e.to_string()) + } else { + let exe = std::env::current_exe().map_err(|e| format!("current_exe failed: {e}"))?; + let args = format!("--macos-patcher \"{prefix}\" --pid {pid}"); + match bullet_platform::elevation::run_elevated(&exe, &args) { + Ok(bullet_platform::elevation::ElevatedRun::Finished(0)) => Ok(()), + Ok(bullet_platform::elevation::ElevatedRun::Finished(code)) => { + Err(format!("elevated macOS patcher exited with code {code}")) + } + Ok(bullet_platform::elevation::ElevatedRun::Declined) => { + Err("macOS administrator authorization was declined".into()) + } + Err(e) => Err(format!("elevated macOS patcher failed: {e}")), + } + } +} + +pub async fn spawn_macos_patcher( + mods_dir: &Path, + mods: &[String], + state_tx: Option, +) -> Result { + let data_dir = + bullet_platform::paths::data_dir().unwrap_or_else(|_| std::env::temp_dir().join("Bullet")); + let overlay_dir = data_dir.join("overlay"); + let game_dir = bullet_platform::paths::discover_game_dir().ok_or_else(|| { + InjectError::Overlay("League of Legends game directory not found on macOS".into()) + })?; + + OverlayManager::prepare_overlay_dir(&overlay_dir)?; + let fresh = + crate::overlay_cache::OverlayCache::is_fresh(&game_dir, mods_dir, &overlay_dir, mods); + if fresh.is_none() { + let g_dir = game_dir.clone(); + let m_dir = mods_dir.to_path_buf(); + let o_dir = overlay_dir.clone(); + let mod_names = mods.to_vec(); + let cancel = AtomicBool::new(false); + tokio::task::spawn_blocking(move || { + crate::overlay_builder::build(&g_dir, &m_dir, &o_dir, &mod_names, &cancel) + }) + .await + .map_err(|e| InjectError::Overlay(format!("macOS overlay build task failed: {e}")))??; + let _ = crate::overlay_cache::OverlayCache::record(&game_dir, mods_dir, &overlay_dir, mods); // ignore-ok: cache recording is best-effort + } + + let prefix = prepare_macos_overlay_prefix(&overlay_dir)?; + info!( + prefix = %prefix, + overlay = %overlay_dir.display(), + mods = ?mods, + "macOS Mach-O patcher armed with native WAD overlay" + ); + + let (tx, rx) = mpsc::unbounded_channel(); + let _ = tx.send(PatcherSignal::Armed); // ignore-ok: receiver is open + let (stop_tx, mut stop_rx) = oneshot::channel::<()>(); + + let monitor = tokio::spawn(async move { + let mut last_patched_pid: Option = None; + loop { + tokio::select! { + _ = &mut stop_rx => break, + () = tokio::time::sleep(Duration::from_millis(120)) => { + let found_pid = bullet_platform::process::ProcessFinder::find_any_process( + &bullet_platform::game_version::GAME_EXES, + ) + .ok() + .flatten(); + + match found_pid { + Some(pid) if last_patched_pid != Some(pid) => { + let prefix_owned = prefix.clone(); + let res = tokio::task::spawn_blocking(move || { + patch_pid_elevated_or_direct(pid, &prefix_owned) + }) + .await; + match res { + Ok(Ok(())) => { + last_patched_pid = Some(pid); + info!(pid, "macOS Mach-O patch applied to LeagueofLegends"); + let _ = tx.send(PatcherSignal::Hooked); // ignore-ok: notify hook confirmed + if let Some(ref stx) = state_tx { + set_injection_status(stx, InjectionStatus::Confirmed); + } + } + Ok(Err(err)) => { + warn!(pid, error = %err, "macOS Mach-O patch failed"); + let _ = tx.send(PatcherSignal::Failed); // ignore-ok: notify hook failure + if let Some(ref stx) = state_tx { + set_injection_status(stx, InjectionStatus::Failed { error: err }); + } + break; + } + Err(join_err) => { + warn!(pid, error = %join_err, "macOS Mach-O patch task panicked"); + let _ = tx.send(PatcherSignal::Failed); // ignore-ok: notify hook failure + break; + } + } + } + Some(_) => {} + None => { + last_patched_pid = None; + } + } + } + } + } + }); + + let stop_slot = Arc::new(std::sync::Mutex::new(Some(stop_tx))); + let shutdown_hook: crate::overlay_process::ShutdownHook = Box::new(move || { + Box::pin(async move { + if let Ok(mut guard) = stop_slot.lock() + && let Some(s) = guard.take() + { + let _ = s.send(()); // ignore-ok: stop macOS patcher loop + } + }) + }); + + Ok(OverlayProcess { + child: None, + _stdin: None, + signals: rx, + _stdout_reader: Some(monitor), + _stderr_reader: None, + hooked: false, + shutdown_hook: Some(shutdown_hook), + }) +} + +#[cfg(test)] +mod tests; diff --git a/crates/bullet-inject/src/injector/macos_patcher/payload.rs b/crates/bullet-inject/src/injector/macos_patcher/payload.rs new file mode 100644 index 0000000..c94ed78 --- /dev/null +++ b/crates/bullet-inject/src/injector/macos_patcher/payload.rs @@ -0,0 +1,106 @@ +pub const WAD_VERIFY_RET1_X86_64: [u8; 6] = [0xB8, 0x01, 0x00, 0x00, 0x00, 0xC3]; +pub const WAD_VERIFY_RET1_ARM64: [u8; 8] = [0x20, 0x00, 0x80, 0xD2, 0xC0, 0x03, 0x5F, 0xD6]; +pub const MAX_PREFIX_BYTES: usize = 200; + +const SHELLCODE_X86_64: &[u8] = &[ + 0x55, 0x48, 0x89, 0xE5, 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x53, 0x48, 0x81, 0xEC, + 0x08, 0x04, 0x00, 0x00, 0x49, 0x89, 0xF6, 0x49, 0x89, 0xFC, 0x48, 0x85, 0xFF, 0x0F, 0x84, 0xB8, + 0x00, 0x00, 0x00, 0x48, 0x85, 0xF6, 0x0F, 0x84, 0xAF, 0x00, 0x00, 0x00, 0x80, 0x3E, 0x72, 0x0F, + 0x85, 0xA6, 0x00, 0x00, 0x00, 0x80, 0x7E, 0x01, 0x62, 0x0F, 0x85, 0x9C, 0x00, 0x00, 0x00, 0x80, + 0x7E, 0x02, 0x00, 0x0F, 0x85, 0x92, 0x00, 0x00, 0x00, 0x48, 0x8D, 0x1D, 0xA3, 0x00, 0x00, 0x00, + 0x4C, 0x8D, 0xBD, 0xD0, 0xFB, 0xFF, 0xFF, 0x4C, 0x89, 0xFF, 0x48, 0x8D, 0x8D, 0xD0, 0xFF, 0xFF, + 0xFF, 0x66, 0x2E, 0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xB6, 0x03, 0x84, 0xC0, + 0x74, 0x20, 0x48, 0xFF, 0xC3, 0x88, 0x07, 0x48, 0xFF, 0xC7, 0x48, 0x39, 0xCF, 0x75, 0xED, 0xEB, + 0x5A, 0x66, 0x2E, 0x0F, 0x1F, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x1F, 0x44, 0x00, 0x00, + 0x48, 0xFF, 0xC2, 0x88, 0x07, 0x48, 0xFF, 0xC7, 0x48, 0x39, 0xCF, 0x74, 0x42, 0x49, 0x89, 0xE5, + 0x49, 0xFF, 0xC5, 0x0F, 0xB6, 0x02, 0x84, 0xC0, 0x75, 0xE7, 0xC6, 0x07, 0x00, 0x4D, 0x29, 0xFD, + 0x49, 0x83, 0xFD, 0x08, 0x76, 0x29, 0x48, 0xB8, 0x2E, 0x63, 0x6C, 0x69, 0x65, 0x6E, 0x74, 0x00, + 0x48, 0x39, 0x47, 0xF9, 0x75, 0x19, 0x4C, 0x89, 0xFF, 0x4C, 0x89, 0xF6, 0xFF, 0x15, 0x1B, 0x00, + 0x00, 0x00, 0x48, 0x85, 0xC0, 0x74, 0x08, 0x48, 0x81, 0xC4, 0x08, 0x04, 0x00, 0x00, 0x5B, 0x41, + 0x5C, 0x41, 0x5D, 0x41, 0x5E, 0x41, 0x5F, 0x5D, 0xC3, 0x4C, 0x89, 0xE7, 0x4C, 0x89, 0xF6, 0x48, + 0x81, 0xC4, 0x08, 0x04, 0x00, 0x00, 0x5B, 0x41, 0x5C, 0x41, 0x5D, 0x41, 0x5E, 0x41, 0x5F, 0x5D, + 0xFF, 0x25, 0x00, 0x00, 0x00, 0x00, +]; + +const SHELLCODE_ARM64: &[u8] = &[ + 0xFF, 0xC3, 0x04, 0xD1, 0xF6, 0x57, 0x10, 0xA9, 0xF4, 0x4F, 0x11, 0xA9, 0xFD, 0x7B, 0x12, 0xA9, + 0xFD, 0x83, 0x04, 0x91, 0xF3, 0x03, 0x01, 0xAA, 0xF4, 0x03, 0x00, 0xAA, 0x34, 0x05, 0x00, 0xB4, + 0x13, 0x05, 0x00, 0xB4, 0x7F, 0x0E, 0x40, 0x79, 0x08, 0x9C, 0x8C, 0x52, 0x1F, 0x01, 0x1F, 0x6B, + 0xA1, 0x04, 0x00, 0x54, 0x68, 0x0A, 0x40, 0x39, 0xA8, 0x04, 0x00, 0x35, 0xEA, 0x03, 0x00, 0x91, + 0xE9, 0x03, 0x10, 0x91, 0xEB, 0x6D, 0x00, 0x10, 0x6C, 0x01, 0x40, 0x39, 0xAC, 0x00, 0x00, 0x34, + 0x4C, 0x15, 0x00, 0x38, 0x4A, 0x01, 0x10, 0xEB, 0x6B, 0x05, 0x00, 0x91, 0xF3, 0xFF, 0xFF, 0x54, + 0x1B, 0x00, 0x00, 0x14, 0xE8, 0x03, 0x14, 0xAA, 0x0B, 0x01, 0x40, 0x39, 0x8B, 0x00, 0x00, 0x34, + 0x4B, 0x15, 0x00, 0x38, 0x4A, 0x01, 0x09, 0xEB, 0x60, 0x02, 0x00, 0x54, 0x08, 0x05, 0x00, 0x91, + 0xF5, 0xFF, 0xFF, 0x17, 0x5F, 0x01, 0x00, 0x39, 0x48, 0x01, 0x00, 0xCB, 0xFF, 0x1D, 0x00, 0xF1, + 0xA3, 0x01, 0x00, 0x54, 0x48, 0x91, 0xDF, 0xF8, 0x29, 0x6C, 0x8C, 0xD2, 0x29, 0x2D, 0xAD, 0xF2, + 0xC9, 0xCC, 0xCD, 0xF2, 0x89, 0x0E, 0xE0, 0xF2, 0x1F, 0x01, 0x09, 0xEB, 0xE1, 0x00, 0x00, 0x54, + 0x48, 0x02, 0x00, 0x58, 0xE0, 0x03, 0x00, 0x91, 0xE1, 0x03, 0x13, 0xAA, 0x00, 0x01, 0x3F, 0xD6, + 0x60, 0x00, 0x00, 0xB5, 0xA8, 0x01, 0x00, 0x58, 0xE0, 0x03, 0x14, 0xAA, 0xE1, 0x03, 0x13, 0xAA, + 0x00, 0x01, 0x3F, 0xD6, 0xFD, 0x7B, 0x52, 0xA9, 0xF4, 0x4F, 0x51, 0xA9, 0xF6, 0x57, 0x50, 0xA9, + 0xFF, 0xC3, 0x04, 0x91, 0xC0, 0x03, 0x5F, 0xD6, +]; + +fn validate_prefix(prefix: &str) -> Result<&[u8], String> { + let bytes = prefix.as_bytes(); + if bytes.is_empty() || bytes.len() >= MAX_PREFIX_BYTES { + return Err(format!( + "overlay prefix length {} is outside 1..{MAX_PREFIX_BYTES}", + bytes.len() + )); + } + if bytes.contains(&0) { + return Err("overlay prefix contains NUL byte".into()); + } + Ok(bytes) +} + +pub fn build_payload_x86_64(fopen_orig_addr: u64, prefix: &str) -> Result, String> { + let prefix_bytes = validate_prefix(prefix)?; + let mut out = Vec::with_capacity(SHELLCODE_X86_64.len() + 8 + 256); + out.extend_from_slice(SHELLCODE_X86_64); + out.extend_from_slice(&fopen_orig_addr.to_le_bytes()); + let mut prefix_buf = [0u8; 256]; + prefix_buf[..prefix_bytes.len()].copy_from_slice(prefix_bytes); + out.extend_from_slice(&prefix_buf); + Ok(out) +} + +pub fn build_payload_arm64(fopen_orig_addr: u64, prefix: &str) -> Result, String> { + let prefix_bytes = validate_prefix(prefix)?; + let mut out = Vec::with_capacity(SHELLCODE_ARM64.len() + 8 + 256); + out.extend_from_slice(SHELLCODE_ARM64); + out.extend_from_slice(&fopen_orig_addr.to_le_bytes()); + let mut prefix_buf = [0u8; 256]; + prefix_buf[..prefix_bytes.len()].copy_from_slice(prefix_bytes); + out.extend_from_slice(&prefix_buf); + Ok(out) +} + +pub fn encode_x86_64_stub_jmp(stub_addr: u64, target_addr: u64) -> Result<[u8; 6], String> { + let rel = (target_addr as i64) - (stub_addr.wrapping_add(5) as i64); + let rel32 = i32::try_from(rel) + .map_err(|_| format!("x86_64 jump displacement out of i32 range: {rel}"))?; + let bytes = rel32.to_le_bytes(); + Ok([0xE9, bytes[0], bytes[1], bytes[2], bytes[3], 0x90]) +} + +pub fn encode_arm64_stub_jmp(stub_addr: u64, target_addr: u64) -> Result<[u8; 12], String> { + let page_diff = ((target_addr & !0xFFF) as i64) - ((stub_addr & !0xFFF) as i64); + let imm21 = page_diff >> 12; + if !(-1_048_576..=1_048_575).contains(&imm21) { + return Err(format!("arm64 ADRP page offset out of range: {imm21}")); + } + let immlo = ((imm21 as u32) & 0x3) << 29; + let immhi = (((imm21 as u32) >> 2) & 0x7FFFF) << 5; + let adrp = 0x9000_0010u32 | immlo | immhi; + + let page_off = (target_addr & 0xFFF) as u32; + let add = 0x9100_0210u32 | (page_off << 10); + let br = 0xD61F_0200u32; + + let mut out = [0u8; 12]; + out[0..4].copy_from_slice(&adrp.to_le_bytes()); + out[4..8].copy_from_slice(&add.to_le_bytes()); + out[8..12].copy_from_slice(&br.to_le_bytes()); + Ok(out) +} diff --git a/crates/bullet-inject/src/injector/macos_patcher/sys.rs b/crates/bullet-inject/src/injector/macos_patcher/sys.rs new file mode 100644 index 0000000..1e80456 --- /dev/null +++ b/crates/bullet-inject/src/injector/macos_patcher/sys.rs @@ -0,0 +1,318 @@ +use super::macho::CpuArch; + +#[cfg(not(target_os = "macos"))] +pub fn patch_live_process(_pid: u32, _prefix: &str) -> Result { + Err("macOS Mach-O live process patching is only supported on macOS".into()) +} + +#[cfg(target_os = "macos")] +pub fn patch_live_process(pid: u32, prefix: &str) -> Result { + imp::patch_live_process(pid, prefix) +} + +#[cfg(target_os = "macos")] +mod imp { + use super::super::macho::{ + CpuArch, MH_MAGIC_64, find_lazy_bind_offset, find_stub_arm64, find_stub_x86_64, + parse_macho_commands, scan_wad_verify_arm64, scan_wad_verify_x86_64, + }; + use super::super::payload::{ + WAD_VERIFY_RET1_ARM64, WAD_VERIFY_RET1_X86_64, build_payload_arm64, build_payload_x86_64, + encode_arm64_stub_jmp, encode_x86_64_stub_jmp, + }; + + type KernReturn = i32; + type MachPort = u32; + type MachVmAddress = u64; + type MachVmSize = u64; + type VmProt = i32; + + const KERN_SUCCESS: KernReturn = 0; + const VM_PROT_READ: VmProt = 0x01; + const VM_PROT_WRITE: VmProt = 0x02; + const VM_PROT_EXECUTE: VmProt = 0x04; + const VM_PROT_COPY: VmProt = 0x10; + const VM_REGION_BASIC_INFO_64: i32 = 9; + const VM_REGION_BASIC_INFO_COUNT_64: u32 = 9; + + #[repr(C)] + #[derive(Default)] + struct VmRegionBasicInfo64 { + protection: VmProt, + max_protection: VmProt, + inheritance: u32, + shared: i32, + reserved: i32, + offset: u64, + behavior: i32, + user_wired_count: u16, + } + + unsafe extern "C" { + fn mach_task_self() -> MachPort; + fn task_for_pid(target_tport: MachPort, pid: i32, t: *mut MachPort) -> KernReturn; + fn task_suspend(target_task: MachPort) -> KernReturn; + fn task_resume(target_task: MachPort) -> KernReturn; + fn mach_vm_region( + target_task: MachPort, + address: *mut MachVmAddress, + size: *mut MachVmSize, + flavor: i32, + info: *mut VmRegionBasicInfo64, + info_cnt: *mut u32, + object_name: *mut MachPort, + ) -> KernReturn; + fn mach_vm_read_overwrite( + target_task: MachPort, + address: MachVmAddress, + size: MachVmSize, + data: MachVmAddress, + outsize: *mut MachVmSize, + ) -> KernReturn; + fn mach_vm_write( + target_task: MachPort, + address: MachVmAddress, + data: usize, + data_cnt: u32, + ) -> KernReturn; + fn mach_vm_protect( + target_task: MachPort, + address: MachVmAddress, + size: MachVmSize, + set_maximum: i32, + new_protection: VmProt, + ) -> KernReturn; + fn sys_icache_invalidate(start: *const libc::c_void, len: usize); + } + + struct TaskSuspendGuard(MachPort); + + impl Drop for TaskSuspendGuard { + fn drop(&mut self) { + let _ = unsafe { task_resume(self.0) }; // ignore-ok: resume remote task on drop + } + } + + fn read_mem(task: MachPort, address: u64, len: usize) -> Result, String> { + let mut buf = vec![0u8; len]; + let mut out_size: MachVmSize = 0; + let kr = unsafe { + mach_vm_read_overwrite( + task, + address, + len as u64, + buf.as_mut_ptr() as u64, + &mut out_size, + ) + }; + if kr != KERN_SUCCESS || (out_size as usize) != len { + return Err(format!( + "mach_vm_read_overwrite failed at {address:#x} (len {len}, kr={kr})" + )); + } + Ok(buf) + } + + fn read_u64(task: MachPort, address: u64) -> Result { + let bytes = read_mem(task, address, 8)?; + Ok(u64::from_le_bytes([ + bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], + ])) + } + + fn read_i32(task: MachPort, address: u64) -> Result { + let bytes = read_mem(task, address, 4)?; + Ok(i32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])) + } + + fn find_image_base(task: MachPort) -> Result { + let mut address: MachVmAddress = 0; + for _ in 0..4096 { + let mut size: MachVmSize = 0; + let mut info = VmRegionBasicInfo64::default(); + let mut count = VM_REGION_BASIC_INFO_COUNT_64; + let mut object_name: MachPort = 0; + let kr = unsafe { + mach_vm_region( + task, + &mut address, + &mut size, + VM_REGION_BASIC_INFO_64, + &mut info, + &mut count, + &mut object_name, + ) + }; + if kr != KERN_SUCCESS { + break; + } + if let Ok(magic_bytes) = read_mem(task, address, 4) { + let magic = u32::from_le_bytes([ + magic_bytes[0], + magic_bytes[1], + magic_bytes[2], + magic_bytes[3], + ]); + if magic == MH_MAGIC_64 { + return Ok(address); + } + } + if size == 0 { + break; + } + address = address.saturating_add(size); + } + Err("could not locate Mach-O 64 image base in LeagueofLegends process".into()) + } + + fn write_code(task: MachPort, address: u64, data: &[u8]) -> Result<(), String> { + let page_mask = 0xFFFu64; + let page_start = address & !page_mask; + let page_end = (address + data.len() as u64 + page_mask) & !page_mask; + let page_len = page_end - page_start; + + let kr = unsafe { + mach_vm_protect( + task, + page_start, + page_len, + 0, + VM_PROT_READ | VM_PROT_WRITE | VM_PROT_COPY, + ) + }; + if kr != KERN_SUCCESS { + return Err(format!( + "mach_vm_protect(RW+COPY) failed at {page_start:#x} (kr={kr})" + )); + } + + let write_kr = + unsafe { mach_vm_write(task, address, data.as_ptr() as usize, data.len() as u32) }; + + let restore_kr = unsafe { + mach_vm_protect( + task, + page_start, + page_len, + 0, + VM_PROT_READ | VM_PROT_EXECUTE, + ) + }; + unsafe { + sys_icache_invalidate(address as *const libc::c_void, data.len()); + } + + if write_kr != KERN_SUCCESS { + return Err(format!( + "mach_vm_write failed at {address:#x} (kr={write_kr})" + )); + } + if restore_kr != KERN_SUCCESS { + return Err(format!( + "mach_vm_protect(RX) failed at {page_start:#x} (kr={restore_kr})" + )); + } + Ok(()) + } + + pub fn patch_live_process(pid: u32, prefix: &str) -> Result { + let raw_pid = i32::try_from(pid).map_err(|_| "invalid PID".to_owned())?; + let mut task: MachPort = 0; + let kr = unsafe { task_for_pid(mach_task_self(), raw_pid, &mut task) }; + if kr != KERN_SUCCESS { + return Err(format!( + "task_for_pid({pid}) failed (kr={kr}); administrator privileges are required" + )); + } + + let base = find_image_base(task)?; + let header = read_mem(task, base, 32)?; + let sizeofcmds = + u32::from_le_bytes([header[20], header[21], header[22], header[23]]) as usize; + let header_and_cmds = read_mem(task, base, 32usize.saturating_add(sizeofcmds))?; + let layout = parse_macho_commands(base, &header_and_cmds)?; + + let lazy_bind = read_mem( + task, + base.wrapping_add(u64::from(layout.lazy_bind_off)), + layout.lazy_bind_size as usize, + )?; + let fopen_ptr_off = find_lazy_bind_offset(&lazy_bind, layout.la_sym_off, "_fopen") + .ok_or_else(|| "could not find _fopen in Mach-O lazy bind table".to_owned())?; + + let stubs = read_mem(task, layout.stubs_addr, layout.stubs_size as usize)?; + let stub_rel = match layout.arch { + CpuArch::X86_64 => find_stub_x86_64(&stubs, layout.stubs_off, fopen_ptr_off), + CpuArch::Arm64 => { + find_stub_arm64(&stubs, layout.stubs_off, layout.text_vmaddr, fopen_ptr_off) + } + } + .ok_or_else(|| "could not find _fopen stub in __TEXT.__stubs".to_owned())?; + let fopen_stub_addr = layout.stubs_addr.wrapping_add(stub_rel); + + let chunk_size = 1024 * 1024usize; + let overlap = 64usize; + let mut offset = 0u64; + let mut wad_verify_addr = None; + while offset < layout.text_size { + let read_len = ((layout.text_size - offset) as usize).min(chunk_size); + if let Ok(chunk) = read_mem(task, layout.text_addr.wrapping_add(offset), read_len) { + let found = match layout.arch { + CpuArch::X86_64 => scan_wad_verify_x86_64(&chunk), + CpuArch::Arm64 => scan_wad_verify_arm64(&chunk), + }; + if let Some(rel) = found { + wad_verify_addr = Some( + layout + .text_addr + .wrapping_add(offset) + .wrapping_add(rel as u64), + ); + break; + } + } + if read_len <= overlap { + break; + } + offset = offset.saturating_add((read_len - overlap) as u64); + } + let wad_verify = wad_verify_addr + .ok_or_else(|| "could not find wad_verify signature in __TEXT.__text".to_owned())?; + + let fopen_orig_addr = match layout.arch { + CpuArch::X86_64 => { + let disp = read_i32(task, fopen_stub_addr.wrapping_add(2))?; + let ptr_addr = + (fopen_stub_addr.wrapping_add(6) as i64).wrapping_add(i64::from(disp)) as u64; + read_u64(task, ptr_addr)? + } + CpuArch::Arm64 => read_u64(task, base.wrapping_add(fopen_ptr_off))?, + }; + + let hook_fn_addr = wad_verify.wrapping_add(0x10); + let payload = match layout.arch { + CpuArch::X86_64 => build_payload_x86_64(fopen_orig_addr, prefix)?, + CpuArch::Arm64 => build_payload_arm64(fopen_orig_addr, prefix)?, + }; + + let suspend_kr = unsafe { task_suspend(task) }; + let _guard = (suspend_kr == KERN_SUCCESS).then_some(TaskSuspendGuard(task)); + + match layout.arch { + CpuArch::X86_64 => { + let jmp = encode_x86_64_stub_jmp(fopen_stub_addr, hook_fn_addr)?; + write_code(task, wad_verify, &WAD_VERIFY_RET1_X86_64)?; + write_code(task, hook_fn_addr, &payload)?; + write_code(task, fopen_stub_addr, &jmp)?; + } + CpuArch::Arm64 => { + let jmp = encode_arm64_stub_jmp(fopen_stub_addr, hook_fn_addr)?; + write_code(task, wad_verify, &WAD_VERIFY_RET1_ARM64)?; + write_code(task, hook_fn_addr, &payload)?; + write_code(task, fopen_stub_addr, &jmp)?; + } + } + + Ok(layout.arch) + } +} diff --git a/crates/bullet-inject/src/injector/macos_patcher/tests.rs b/crates/bullet-inject/src/injector/macos_patcher/tests.rs new file mode 100644 index 0000000..658cd75 --- /dev/null +++ b/crates/bullet-inject/src/injector/macos_patcher/tests.rs @@ -0,0 +1,157 @@ +use super::macho::*; +use super::payload::*; + +fn synthetic_macho64(cputype: i32) -> Vec { + let mut buf = vec![0u8; 512]; + buf[0..4].copy_from_slice(&MH_MAGIC_64.to_le_bytes()); + buf[4..8].copy_from_slice(&cputype.to_le_bytes()); + buf[16..20].copy_from_slice(&3u32.to_le_bytes()); + buf[20..24].copy_from_slice(&432u32.to_le_bytes()); + + let seg_text = 32usize; + buf[seg_text..seg_text + 4].copy_from_slice(&LC_SEGMENT_64.to_le_bytes()); + buf[seg_text + 4..seg_text + 8].copy_from_slice(&232u32.to_le_bytes()); + buf[seg_text + 8..seg_text + 14].copy_from_slice(b"__TEXT"); + buf[seg_text + 24..seg_text + 32].copy_from_slice(&0x100000000u64.to_le_bytes()); + buf[seg_text + 64..seg_text + 68].copy_from_slice(&2u32.to_le_bytes()); + + let sect_text = seg_text + 72; + buf[sect_text..sect_text + 6].copy_from_slice(b"__text"); + buf[sect_text + 16..sect_text + 22].copy_from_slice(b"__TEXT"); + buf[sect_text + 32..sect_text + 40].copy_from_slice(&0x100001000u64.to_le_bytes()); + buf[sect_text + 40..sect_text + 48].copy_from_slice(&0x50000u64.to_le_bytes()); + buf[sect_text + 48..sect_text + 52].copy_from_slice(&0x1000u32.to_le_bytes()); + + let sect_stubs = sect_text + 80; + buf[sect_stubs..sect_stubs + 7].copy_from_slice(b"__stubs"); + buf[sect_stubs + 16..sect_stubs + 22].copy_from_slice(b"__TEXT"); + buf[sect_stubs + 32..sect_stubs + 40].copy_from_slice(&0x100051000u64.to_le_bytes()); + buf[sect_stubs + 40..sect_stubs + 48].copy_from_slice(&0x300u64.to_le_bytes()); + buf[sect_stubs + 48..sect_stubs + 52].copy_from_slice(&0x51000u32.to_le_bytes()); + + let seg_data = seg_text + 232; + buf[seg_data..seg_data + 4].copy_from_slice(&LC_SEGMENT_64.to_le_bytes()); + buf[seg_data + 4..seg_data + 8].copy_from_slice(&152u32.to_le_bytes()); + buf[seg_data + 8..seg_data + 14].copy_from_slice(b"__DATA"); + buf[seg_data + 24..seg_data + 32].copy_from_slice(&0x100080000u64.to_le_bytes()); + buf[seg_data + 64..seg_data + 68].copy_from_slice(&1u32.to_le_bytes()); + + let sect_la = seg_data + 72; + buf[sect_la..sect_la + 15].copy_from_slice(b"__la_symbol_ptr"); + buf[sect_la + 16..sect_la + 22].copy_from_slice(b"__DATA"); + buf[sect_la + 32..sect_la + 40].copy_from_slice(&0x100080000u64.to_le_bytes()); + buf[sect_la + 40..sect_la + 48].copy_from_slice(&0x100u64.to_le_bytes()); + buf[sect_la + 48..sect_la + 52].copy_from_slice(&0x80000u32.to_le_bytes()); + + let dyld = seg_data + 152; + buf[dyld..dyld + 4].copy_from_slice(&LC_DYLD_INFO_ONLY.to_le_bytes()); + buf[dyld + 4..dyld + 8].copy_from_slice(&48u32.to_le_bytes()); + buf[dyld + 32..dyld + 36].copy_from_slice(&0x90000u32.to_le_bytes()); + buf[dyld + 36..dyld + 40].copy_from_slice(&64u32.to_le_bytes()); + buf +} + +#[test] +fn parses_x86_64_and_arm64_macho_headers_and_sections() { + let x86 = parse_macho_commands(0x100000000, &synthetic_macho64(CPU_TYPE_X86_64)).expect("x86"); + assert_eq!(x86.arch, CpuArch::X86_64); + assert_eq!(x86.text_off, 0x1000); + assert_eq!(x86.stubs_off, 0x51000); + assert_eq!(x86.la_sym_off, 0x80000); + assert_eq!(x86.lazy_bind_off, 0x90000); + + let arm = parse_macho_commands(0x100000000, &synthetic_macho64(CPU_TYPE_ARM64)).expect("arm64"); + assert_eq!(arm.arch, CpuArch::Arm64); +} + +#[test] +fn resolves_fopen_from_lazy_bind_and_matches_x86_64_and_arm64_stubs() { + let lazy_bind = [ + BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | 2, + 0x10, + BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM, + b'_', + b'm', + b'a', + b'l', + b'l', + b'o', + b'c', + 0, + BIND_OPCODE_DO_BIND, + BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | 2, + 0x28, + BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM, + b'_', + b'f', + b'o', + b'p', + b'e', + b'n', + 0, + BIND_OPCODE_DO_BIND, + ]; + let ptr_off = find_lazy_bind_offset(&lazy_bind, 0x80000, "_fopen").expect("lazy bind"); + assert_eq!(ptr_off, 0x80028); + + let stubs_off = 0x51000u64; + let disp = (ptr_off as i64 - (stubs_off + 6 + 6) as i64) as i32; + let mut x86_stubs = vec![0x90u8; 12]; + x86_stubs[6] = 0xFF; + x86_stubs[7] = 0x25; + x86_stubs[8..12].copy_from_slice(&disp.to_le_bytes()); + assert_eq!(find_stub_x86_64(&x86_stubs, stubs_off, ptr_off), Some(6)); + + let text_vmaddr = 0x100000000u64; + let page_diff = + (((text_vmaddr + ptr_off) & !0xFFF) as i64) - (((text_vmaddr + stubs_off) & !0xFFF) as i64); + let imm21 = (page_diff >> 12) as u32; + let adrp = 0x9000_0010u32 | ((imm21 & 0x3) << 29) | (((imm21 >> 2) & 0x7FFFF) << 5); + let ldr_off = (((text_vmaddr + ptr_off) & 0xFFF) / 8) as u32; + let ldr = 0xF940_0210u32 | (ldr_off << 10); + let br = 0xD61F_0200u32; + let mut arm_stubs = [0u8; 12]; + arm_stubs[0..4].copy_from_slice(&adrp.to_le_bytes()); + arm_stubs[4..8].copy_from_slice(&ldr.to_le_bytes()); + arm_stubs[8..12].copy_from_slice(&br.to_le_bytes()); + assert_eq!( + find_stub_arm64(&arm_stubs, stubs_off, text_vmaddr, ptr_off), + Some(0) + ); +} + +#[test] +fn scans_wad_verify_signatures_and_encodes_payloads_for_both_architectures() { + let mut x86_text = vec![0x90u8; 128]; + x86_text[16..20].copy_from_slice(&[0x55, 0x48, 0x89, 0xE5]); + let sig_x86 = [ + 0x41, 0x57, 0x41, 0x56, 0x41, 0x55, 0x41, 0x54, 0x53, 0x48, 0x81, 0xEC, 0x40, 0x02, 0x00, + 0x00, 0x49, 0x89, 0xFE, 0x48, 0x8B, 0x05, 0x11, 0x22, 0x33, 0x44, 0x48, 0x31, 0xE0, 0x48, + 0x89, 0x84, 0x24, 0x30, 0x02, 0x00, 0x00, 0x48, 0x85, 0xF6, 0x0F, 0x84, 0x80, 0x00, 0x00, + 0x00, 0x4D, 0x85, + ]; + x86_text[20..20 + sig_x86.len()].copy_from_slice(&sig_x86); + assert_eq!(scan_wad_verify_x86_64(&x86_text), Some(16)); + + let mut arm_text = vec![0u8; 128]; + let sig_arm = [ + 0xFF, 0x83, 0x02, 0xD1, 0xFA, 0x67, 0x04, 0xA9, 0xF8, 0x5F, 0x05, 0xA9, 0xF6, 0x57, 0x06, + 0xA9, 0xF4, 0x4F, 0x07, 0xA9, 0xFD, 0x7B, 0x08, 0xA9, 0xFD, 0x03, 0x02, 0x91, 0x01, 0x02, + 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0xE8, 0x1F, 0x00, 0xF9, 0x94, + 0x02, 0x00, 0xB4, + ]; + arm_text[32..32 + sig_arm.len()].copy_from_slice(&sig_arm); + assert_eq!(scan_wad_verify_arm64(&arm_text), Some(32)); + + let p_x86 = build_payload_x86_64(0x7FFF_1234_5678, "/tmp/bullet_ovl/").expect("x86 payload"); + assert!(p_x86.len() > 264); + let p_arm = build_payload_arm64(0x7FFF_1234_5678, "/tmp/bullet_ovl/").expect("arm64 payload"); + assert!(p_arm.len() > 264); + + let jmp_x86 = encode_x86_64_stub_jmp(0x100051000, 0x100002010).expect("x86 jmp"); + assert_eq!(jmp_x86[0], 0xE9); + assert_eq!(jmp_x86[5], 0x90); + + let jmp_arm = encode_arm64_stub_jmp(0x100051000, 0x100002010).expect("arm64 jmp"); + assert_eq!(&jmp_arm[8..12], &0xD61F_0200u32.to_le_bytes()); +} diff --git a/crates/bullet-inject/src/injector/mod.rs b/crates/bullet-inject/src/injector/mod.rs index f46c397..3074531 100644 --- a/crates/bullet-inject/src/injector/mod.rs +++ b/crates/bullet-inject/src/injector/mod.rs @@ -1,3 +1,4 @@ pub mod dll_validator; +pub mod macos_patcher; pub mod overlay_process; pub mod trust; diff --git a/crates/bullet-inject/src/injector/overlay_process/mod.rs b/crates/bullet-inject/src/injector/overlay_process/mod.rs index db1ca95..8c8d7cb 100644 --- a/crates/bullet-inject/src/injector/overlay_process/mod.rs +++ b/crates/bullet-inject/src/injector/overlay_process/mod.rs @@ -111,15 +111,20 @@ impl OverlayProcess { } pub fn exited(&mut self) -> Option { - let child = self.child.as_mut()?; - match child.try_wait() { - Ok(Some(status)) => Some(status.code().unwrap_or(-1)), - Ok(None) => None, - Err(e) => { - warn!(error = %e, "The patcher's exit status could not be read"); - None - } + if let Some(child) = self.child.as_mut() { + return match child.try_wait() { + Ok(Some(status)) => Some(status.code().unwrap_or(-1)), + Ok(None) => None, + Err(e) => { + warn!(error = %e, "The patcher's exit status could not be read"); + None + } + }; } + self._stdout_reader + .as_ref() + .is_some_and(tokio::task::JoinHandle::is_finished) + .then_some(0) } pub async fn exited_within(&mut self, grace: Duration) -> Option { diff --git a/crates/bullet-inject/src/lib.rs b/crates/bullet-inject/src/lib.rs index 69a424d..ee19e46 100644 --- a/crates/bullet-inject/src/lib.rs +++ b/crates/bullet-inject/src/lib.rs @@ -4,7 +4,7 @@ mod build; mod injector; pub use build::{mod_compat, overlay, overlay_builder, overlay_cache}; -pub use injector::{dll_validator, overlay_process, trust}; +pub use injector::{dll_validator, macos_patcher, overlay_process, trust}; pub mod error; pub mod ltf; diff --git a/crates/bullet-inject/src/ltf/mod.rs b/crates/bullet-inject/src/ltf/mod.rs index 6c034bb..86ba219 100644 --- a/crates/bullet-inject/src/ltf/mod.rs +++ b/crates/bullet-inject/src/ltf/mod.rs @@ -1,5 +1,6 @@ use std::path::{Path, PathBuf}; +use bullet_core::overlay::{Catalog, OverlayCommand}; use bullet_core::state::StateSender; use crate::error::InjectError; @@ -22,23 +23,67 @@ pub enum ManagerInstallState { #[must_use] pub fn check_manager_install() -> ManagerInstallState { - ManagerInstallState::Missing + #[cfg(target_os = "macos")] + { + return ManagerInstallState::Ready { + path: std::env::current_exe().unwrap_or_else(|_| { + PathBuf::from("/Applications/Bullet.app/Contents/MacOS/bullet") + }), + version: Some(MIN_MANAGER_VERSION), + }; + } + #[cfg(not(target_os = "macos"))] + { + ManagerInstallState::Missing + } } #[must_use] pub fn find_manager_manager() -> Option { - None + #[cfg(target_os = "macos")] + { + return Some( + std::env::current_exe().unwrap_or_else(|_| { + PathBuf::from("/Applications/Bullet.app/Contents/MacOS/bullet") + }), + ); + } + #[cfg(not(target_os = "macos"))] + { + None + } } pub async fn warmup_bridge(_tools_dirs: &[PathBuf]) {} +pub async fn shutdown_bridge() {} + +pub async fn deactivate_in_client_ui(_tools_dirs: &[PathBuf]) {} + +pub async fn sync_in_client_ui( + _enabled: bool, + _tools_dirs: &[PathBuf], + _catalog: Option<&Catalog>, + _selected_id: Option, +) -> (Vec, bool) { + (Vec::new(), false) +} + +#[cfg_attr(not(target_os = "macos"), allow(unused_variables))] pub async fn spawn_ltf_patcher( _tools_dirs: &[PathBuf], - _mods_dir: &Path, - _mods: &[String], - _state_tx: Option, + mods_dir: &Path, + mods: &[String], + state_tx: Option, ) -> Result { - Err(InjectError::Process( - "Private LTK bridge module is not linked in this build".into(), - )) + #[cfg(target_os = "macos")] + { + return crate::macos_patcher::spawn_macos_patcher(mods_dir, mods, state_tx).await; + } + #[cfg(not(target_os = "macos"))] + { + Err(InjectError::Process( + "Private LTK bridge module is not linked in this build".into(), + )) + } } diff --git a/crates/bullet-lcu/src/connection/lockfile.rs b/crates/bullet-lcu/src/connection/lockfile/mod.rs similarity index 66% rename from crates/bullet-lcu/src/connection/lockfile.rs rename to crates/bullet-lcu/src/connection/lockfile/mod.rs index c44aa5c..58502a9 100644 --- a/crates/bullet-lcu/src/connection/lockfile.rs +++ b/crates/bullet-lcu/src/connection/lockfile/mod.rs @@ -42,13 +42,9 @@ macro_rules! warn_once { #[derive(Clone, PartialEq, Eq)] pub struct Lockfile { pub process_name: String, - pub pid: u32, - pub port: u16, - pub auth_token: String, - pub protocol: String, } @@ -180,12 +176,10 @@ impl Lockfile { for proc_name in &bullet_platform::game_version::CLIENT_EXES { match ProcessFinder::find_process_path(proc_name) { Ok(Some(exe_path)) => { - let mut candidates = Vec::with_capacity(2); - if let Some(parent) = exe_path.parent() { - candidates.push(parent.join("lockfile")); - if let Some(grandparent) = parent.parent() { - candidates.push(grandparent.join("lockfile")); - } + let mut candidates = Vec::with_capacity(8); + for ancestor in exe_path.ancestors().skip(1).take(7) { + candidates.push(ancestor.join("lockfile")); + candidates.push(ancestor.join("Contents/LoL/lockfile")); } for candidate in &candidates { @@ -220,10 +214,12 @@ impl Lockfile { } for install in bullet_platform::paths::riot_league_installs() { - let candidate = install.join("lockfile"); - if candidate.is_file() { - debug!(path = %candidate.display(), source = "riot-client-installs", "Lockfile located"); - return Some(candidate); + for sub in ["lockfile", "Contents/LoL/lockfile"] { + let candidate = install.join(sub); + if candidate.is_file() { + debug!(path = %candidate.display(), source = "riot-client-installs", "Lockfile located"); + return Some(candidate); + } } } @@ -249,23 +245,59 @@ impl Lockfile { } } - pub fn discover(explicit_path: Option<&Path>) -> Result { - let path = Self::find_lockfile_path(explicit_path).ok_or(LcuError::LockfileNotFound)?; - let lockfile = Self::from_file(&path)?; - - if !lockfile.is_client_alive() { - warn_once!( - &format!("stale:{}:{}", path.display(), lockfile.pid), - path = %path.display(), - pid = lockfile.pid, - port = lockfile.port, - "Stale lockfile: the client process is gone. Not connecting" - ); - return Err(LcuError::LockfileNotFound); + #[must_use] + pub fn parse_ux_cmdline(cmdline: &str, pid: u32) -> Option { + let port = extract_flag(cmdline, "--app-port=")? + .parse::() + .ok() + .filter(|&p| p > 0)?; + let auth_token = extract_flag(cmdline, "--remoting-auth-token=")?; + if auth_token.is_empty() { + return None; } + Some(Self { + process_name: "LeagueClientUx".to_owned(), + pid, + port, + auth_token, + protocol: "https".to_owned(), + }) + } - clear_report(); - Ok(lockfile) + pub fn discover(explicit_path: Option<&Path>) -> Result { + if let Some(path) = Self::find_lockfile_path(explicit_path) { + if let Ok(lockfile) = Self::from_file(&path) { + if lockfile.is_client_alive() { + clear_report(); + return Ok(lockfile); + } + warn_once!( + &format!("stale:{}:{}", path.display(), lockfile.pid), + path = %path.display(), + pid = lockfile.pid, + port = lockfile.port, + "Stale lockfile: the client process is gone. Not connecting" + ); + } + } + for proc_name in &bullet_platform::game_version::CLIENT_EXES { + if let Some(pid) = ProcessFinder::find_process_by_name(proc_name) + .ok() + .flatten() + && let Some(cmd) = bullet_platform::process::query_process_cmdline(pid) + && let Some(found) = Self::parse_ux_cmdline(&cmd, pid) + { + debug!( + pid = found.pid, + port = found.port, + token_len = found.auth_token.len(), + "LCU credentials recovered from LeagueClientUx command line" + ); + clear_report(); + return Ok(found); + } + } + Err(LcuError::LockfileNotFound) } #[must_use] @@ -286,82 +318,16 @@ impl Lockfile { } } -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_parse_valid_lockfile() { - let content = "LeagueClient:12345:55667:supersecrettoken:https\n"; - let lockfile = Lockfile::parse(content).expect("valid lockfile"); - - assert_eq!(lockfile.process_name, "LeagueClient"); - assert_eq!(lockfile.pid, 12345); - assert_eq!(lockfile.port, 55667); - assert_eq!(lockfile.auth_token, "supersecrettoken"); - assert_eq!(lockfile.protocol, "https"); - - assert_eq!(lockfile.base_url(), "https://127.0.0.1:55667"); - assert_eq!(lockfile.ws_url(), "wss://127.0.0.1:55667"); - - let auth = lockfile.basic_auth_header(); - assert!(auth.starts_with("Basic ")); - let raw_b64 = &auth["Basic ".len()..]; - let decoded = String::from_utf8(BASE64.decode(raw_b64).unwrap()).unwrap(); - assert_eq!(decoded, "riot:supersecrettoken"); - } - - #[test] - fn test_rejects_missing_fields() { - let content = "LeagueClient:12345:55667:token"; - let err = Lockfile::parse(content).unwrap_err(); - match err { - LcuError::InvalidLockfile(msg) => assert!(msg.contains("expected 5")), - other => panic!("expected InvalidLockfile, got {other:?}"), - } - } - - #[test] - fn test_rejects_invalid_port() { - let content = "LeagueClient:12345:notaport:token:https"; - let err = Lockfile::parse(content).unwrap_err(); - match err { - LcuError::InvalidLockfile(msg) => assert!(msg.contains("invalid port")), - other => panic!("expected InvalidLockfile, got {other:?}"), - } - } - - #[test] - fn test_rejects_empty_token() { - let content = "LeagueClient:12345:55667::https"; - let err = Lockfile::parse(content).unwrap_err(); - match err { - LcuError::InvalidLockfile(msg) => assert!(msg.contains("token is empty")), - other => panic!("expected InvalidLockfile, got {other:?}"), - } - } - - #[test] - fn test_find_lockfile_path_explicit() { - let dir = std::env::temp_dir().join(format!("bullet_test_lock_{}", std::process::id())); - let _ = std::fs::create_dir_all(&dir); // ignore-ok: test temp dir - let lock_path = dir.join("lockfile"); - - let live_pid = std::process::id(); - std::fs::write( - &lock_path, - format!("LeagueClient:{live_pid}:456:secret:https"), - ) - .unwrap(); - - let found = Lockfile::find_lockfile_path(Some(&lock_path)); - assert_eq!(found, Some(lock_path.clone())); - - let lock = Lockfile::discover(Some(&lock_path)).unwrap(); - assert_eq!(lock.pid, live_pid); - assert_eq!(lock.port, 456); - assert_eq!(lock.auth_token, "secret"); - - let _ = std::fs::remove_dir_all(&dir); // ignore-ok: test temp dir teardown - } +fn extract_flag(cmdline: &str, prefix: &str) -> Option { + let idx = cmdline.find(prefix)?; + let rest = &cmdline[idx + prefix.len()..]; + let val = if let Some(quoted) = rest.strip_prefix('"') { + quoted.split('"').next()? + } else { + rest.split_whitespace().next()?.trim_matches('"') + }; + Some(val.to_owned()) } + +#[cfg(test)] +mod tests; diff --git a/crates/bullet-lcu/src/connection/lockfile/tests.rs b/crates/bullet-lcu/src/connection/lockfile/tests.rs new file mode 100644 index 0000000..dd54412 --- /dev/null +++ b/crates/bullet-lcu/src/connection/lockfile/tests.rs @@ -0,0 +1,78 @@ +use super::*; + +#[test] +fn test_parse_valid_lockfile() { + let lf = Lockfile::parse("LeagueClient:12345:55667:supersecrettoken:https\n").unwrap(); + assert_eq!( + (lf.process_name.as_str(), lf.pid, lf.port), + ("LeagueClient", 12345, 55667) + ); + assert_eq!( + (lf.auth_token.as_str(), lf.protocol.as_str()), + ("supersecrettoken", "https") + ); + assert_eq!( + (lf.base_url(), lf.ws_url()), + ( + "https://127.0.0.1:55667".into(), + "wss://127.0.0.1:55667".into() + ) + ); + let raw_b64 = &lf.basic_auth_header()["Basic ".len()..]; + assert_eq!( + String::from_utf8(BASE64.decode(raw_b64).unwrap()).unwrap(), + "riot:supersecrettoken" + ); +} + +#[test] +fn test_rejects_malformed_lockfiles() { + assert!( + matches!(Lockfile::parse("LeagueClient:12345:55667:token").unwrap_err(), LcuError::InvalidLockfile(m) if m.contains("expected 5")) + ); + assert!( + matches!(Lockfile::parse("LeagueClient:12345:notaport:token:https").unwrap_err(), LcuError::InvalidLockfile(m) if m.contains("invalid port")) + ); + assert!( + matches!(Lockfile::parse("LeagueClient:12345:55667::https").unwrap_err(), LcuError::InvalidLockfile(m) if m.contains("token is empty")) + ); +} + +#[test] +fn test_parse_ux_cmdline_regional() { + let cmd = r#""D:\WeGame\LeagueClientUx.exe" --app-port=54321 --remoting-auth-token="cn-token_99" --region=CN"#; + let lf = Lockfile::parse_ux_cmdline(cmd, 8888).expect("regional cmdline"); + assert_eq!( + ( + lf.pid, + lf.port, + lf.auth_token.as_str(), + lf.protocol.as_str() + ), + (8888, 54321, "cn-token_99", "https") + ); + assert!(Lockfile::parse_ux_cmdline("--app-port=0 --remoting-auth-token=x", 1).is_none()); +} + +#[test] +fn test_find_lockfile_path_explicit() { + let dir = std::env::temp_dir().join(format!("bullet_test_lock_{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); // ignore-ok: test temp dir + let lock_path = dir.join("lockfile"); + let live_pid = std::process::id(); + std::fs::write( + &lock_path, + format!("LeagueClient:{live_pid}:456:secret:https"), + ) + .unwrap(); + assert_eq!( + Lockfile::find_lockfile_path(Some(&lock_path)), + Some(lock_path.clone()) + ); + let lock = Lockfile::discover(Some(&lock_path)).unwrap(); + assert_eq!( + (lock.pid, lock.port, lock.auth_token.as_str()), + (live_pid, 456, "secret") + ); + let _ = std::fs::remove_dir_all(&dir); // ignore-ok: test temp dir teardown +} diff --git a/crates/bullet-lcu/src/connection/observer.rs b/crates/bullet-lcu/src/connection/observer.rs index 6415245..f3a410b 100644 --- a/crates/bullet-lcu/src/connection/observer.rs +++ b/crates/bullet-lcu/src/connection/observer.rs @@ -176,6 +176,16 @@ impl LcuObserver { } async fn sync_initial_state(&self, rest_client: &LcuClient) { + match rest_client.get_current_summoner().await { + Ok(summoner) if !summoner.puuid.is_empty() => { + debug!("Current summoner identified on LCU connect"); + let current_team = self.state_tx.borrow().team.clone(); + bullet_core::state::set_team(&self.state_tx, Some(summoner.puuid), current_team); + } + Ok(_) => warn!("The client returned the current summoner without an id"), + Err(e) => warn!(error = %e, "Could not read the current summoner on LCU connect"), + } + match rest_client.get_gameflow_phase().await { Ok(initial_phase) => { info!(phase = ?initial_phase, "Initial LCU gameflow phase synced"); @@ -204,20 +214,38 @@ impl LcuObserver { } } } + + if matches!( + initial_phase, + GamePhase::Reconnect | GamePhase::InProgress | GamePhase::GameStart + ) { + self.sync_live_game_selection(rest_client).await; + } } Err(e) => { warn!(error = %e, "Could not sync the initial gameflow phase; the state may be stale until the next client event"); } } + } - match rest_client.get_current_summoner().await { - Ok(summoner) if !summoner.puuid.is_empty() => { - debug!("Current summoner identified on LCU connect"); - let current_team = self.state_tx.borrow().team.clone(); - bullet_core::state::set_team(&self.state_tx, Some(summoner.puuid), current_team); + async fn sync_live_game_selection(&self, rest_client: &LcuClient) { + let known_champion = self.state_tx.borrow().champion_id; + match crate::live_selection::resolve_live_selection(rest_client, known_champion).await { + Ok(live) => { + info!( + champion_id = live.champion_id, + skin_id = live.skin_id, + source = ?live.source, + "Live match champion recovered from LCU gameflow session" + ); + bullet_core::state::set_champion(&self.state_tx, live.champion_id); + if live.skin_id != 0 { + bullet_core::state::set_selected_skin(&self.state_tx, live.skin_id); + } + } + Err(e) => { + debug!(error = %e, "Live match champion unavailable from LCU gameflow session"); } - Ok(_) => warn!("The client returned the current summoner without an id"), - Err(e) => warn!(error = %e, "Could not read the current summoner on LCU connect"), } } @@ -288,7 +316,16 @@ impl LcuObserver { msg_opt = ws_stream.next() => { match msg_opt { Some(Ok(Message::Text(text))) => match LcuEvent::parse(&text) { - Ok(Some(event)) => dispatch_event_to_state(&self.state_tx, &event), + Ok(Some(event)) => { + dispatch_event_to_state(&self.state_tx, &event); + let needs_reconnect_champ = { + let s = self.state_tx.borrow(); + s.phase == GamePhase::Reconnect && s.champion_id.is_none() + }; + if needs_reconnect_champ { + self.sync_live_game_selection(&rest_client).await; + } + } Ok(None) => {} Err(e) => { undecodable_frames += 1; diff --git a/crates/bullet-lcu/src/session/skins/skin_registration.rs b/crates/bullet-lcu/src/session/skins/skin_registration.rs index a6e1853..8242fa2 100644 --- a/crates/bullet-lcu/src/session/skins/skin_registration.rs +++ b/crates/bullet-lcu/src/session/skins/skin_registration.rs @@ -6,9 +6,7 @@ use tracing::{debug, info, warn}; use crate::client::LcuClient; -const VERIFY_ATTEMPTS: u32 = 5; - -const VERIFY_INTERVAL: Duration = Duration::from_millis(100); +const VERIFY_DELAYS_MS: [u64; 5] = [25, 50, 100, 100, 100]; #[must_use] pub fn skin_to_register( @@ -117,8 +115,8 @@ pub async fn register_skin(client: &LcuClient, skin_id: SkinId) -> RegistrationO let mut actual = None; let mut read_error = None; - for _ in 0..VERIFY_ATTEMPTS { - tokio::time::sleep(VERIFY_INTERVAL).await; + for delay_ms in VERIFY_DELAYS_MS { + tokio::time::sleep(Duration::from_millis(delay_ms)).await; actual = match client.get_champ_select_session().await { Ok(session) => session.local_player().map(|p| p.selected_skin_id), Err(e) => { diff --git a/crates/bullet-lcu/tests/rigorous_lockfile_tests.rs b/crates/bullet-lcu/tests/rigorous_lockfile_tests.rs new file mode 100644 index 0000000..c26dfc0 --- /dev/null +++ b/crates/bullet-lcu/tests/rigorous_lockfile_tests.rs @@ -0,0 +1,61 @@ +use bullet_lcu::lockfile::Lockfile; + +struct XorShift64(u64); + +impl XorShift64 { + fn next_u64(&mut self) -> u64 { + let mut x = self.0; + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + self.0 = x; + x + } +} + +#[test] +fn universal_server_lockfile_and_ux_cmdline_parsing() { + let cases = [ + ( + r#""C:\Riot Games\League of Legends\LeagueClientUx.exe" "--app-port=54321" "--remoting-auth-token=AbC_123-xyz" "--app-pid=9988""#, + 9988, + 54321, + "AbC_123-xyz", + ), + ( + r#""D:\WeGameApps\英雄联盟\LeagueClient\LeagueClientUx.exe" --region=TENCENT --locale=zh_CN --app-port=61234 --remoting-auth-token=cnToken9988 --app-pid=4411"#, + 4411, + 61234, + "cnToken9988", + ), + ( + r#""E:\Garena\LoL\LeagueClientUx.exe" --app-port=12000 --remoting-auth-token=seaTok_77"#, + 777, + 12000, + "seaTok_77", + ), + ]; + + for (cmd, fallback_pid, expected_port, expected_token) in cases { + let parsed = Lockfile::parse_ux_cmdline(cmd, fallback_pid).expect("valid cmdline"); + assert_eq!(parsed.port, expected_port); + assert_eq!(parsed.auth_token, expected_token); + assert_eq!(parsed.protocol, "https"); + assert!(parsed.pid > 0); + } +} + +#[test] +fn fuzz_lockfile_and_cmdline_parsers_never_panic() { + let mut rng = XorShift64(0xCAFE_BABE_1337_0001); + let alphabet = b"abcdefghijklmnopqrstuvwxyz0123456789:=\"'-- \t\r\n/\\_-"; + + for _ in 0..1000 { + let len = (rng.next_u64() % 180) as usize; + let s: String = (0..len) + .map(|_| alphabet[(rng.next_u64() as usize) % alphabet.len()] as char) + .collect(); + let _ = Lockfile::parse(&s); // ignore-ok: fuzz test asserts no panic + let _ = Lockfile::parse_ux_cmdline(&s, 1234); // ignore-ok: fuzz test asserts no panic + } +} diff --git a/crates/bullet-party/src/transport/client/mod.rs b/crates/bullet-party/src/transport/client/mod.rs index 2bc5324..43e449d 100644 --- a/crates/bullet-party/src/transport/client/mod.rs +++ b/crates/bullet-party/src/transport/client/mod.rs @@ -2,7 +2,7 @@ use std::collections::HashMap; use std::time::Duration; use bullet_core::party::PartyStatus; -use bullet_core::state::{AppState, StateReceiver, StateSender, set_party_peers, set_party_status}; +use bullet_core::state::{StateReceiver, StateSender, set_party_peers, set_party_status}; use chacha20poly1305::aead::Generate; use futures_util::{SinkExt, StreamExt}; use tokio_tungstenite::tungstenite::Message; @@ -13,7 +13,9 @@ use tracing::{debug, error, info, warn}; use crate::crypto::{RoomCipher, room_id}; use crate::error::PartyError; -use crate::protocol::{Announcement, ClientMessage, RelayMessage, open_member}; +use crate::protocol::{ + Announcement, ClientMessage, RelayMessage, announcement_from_state, open_member, +}; use crate::token::PartyToken; const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); @@ -198,7 +200,7 @@ impl PartyClient { let mut warned_unreadable = false; loop { - let current = announcement(&state_rx.borrow_and_update(), self.member_id); + let current = announcement_from_state(&state_rx.borrow_and_update(), self.member_id); if announced.as_ref() != Some(¤t) { let skin = match ¤t { Some(a) => Some(a.seal(cipher)?), @@ -356,29 +358,6 @@ impl PartyClient { } } -fn announcement(state: &AppState, member_id: u64) -> Option { - if !state.party_share || !(state.phase.is_champ_select() || state.phase.is_in_game()) { - return None; - } - let champion_id = state.champion_id?; - let target = state - .overlay_target - .as_ref() - .filter(|t| t.matches_champion(champion_id))?; - let puuid = state.local_puuid.clone()?; - let announcement = Announcement { - member_id, - puuid, - champion_id, - skin_id: target.skin_id, - chroma_id: target.chroma_id, - }; - if target.package_entry_id() == champion_id * 1000 || announcement.validate().is_err() { - return None; - } - Some(announcement) -} - async fn deliver(write: &mut S, message: Message, within: Duration) -> Result<(), PartyError> where S: futures_util::Sink + Unpin, diff --git a/crates/bullet-party/src/transport/client/tests.rs b/crates/bullet-party/src/transport/client/tests.rs index 75fcc4d..7dc1e8f 100644 --- a/crates/bullet-party/src/transport/client/tests.rs +++ b/crates/bullet-party/src/transport/client/tests.rs @@ -1,6 +1,8 @@ use super::*; +use crate::protocol::announcement_from_state as announcement; use bullet_core::overlay::OverlayTarget; use bullet_core::phase::GamePhase; +use bullet_core::state::AppState; fn picking_103() -> AppState { AppState { diff --git a/crates/bullet-party/src/transport/protocol.rs b/crates/bullet-party/src/transport/protocol.rs index f2bdeed..3661277 100644 --- a/crates/bullet-party/src/transport/protocol.rs +++ b/crates/bullet-party/src/transport/protocol.rs @@ -1,4 +1,6 @@ +use bullet_core::identity::IdentityLoadout; use bullet_core::party::PartyPeer; +use bullet_core::state::AppState; use serde::{Deserialize, Serialize}; use crate::crypto::{RoomCipher, SealedBlob}; @@ -41,6 +43,8 @@ pub struct Announcement { pub champion_id: u32, pub skin_id: u32, pub chroma_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub identity: Option, } const MAX_PUUID_LEN: usize = 100; @@ -57,6 +61,18 @@ impl Announcement { { return bad("puuid"); } + if let Some(identity) = self.identity.as_ref() + && let Err(why) = identity.validate() + { + return bad(why); + } + let identity_only = self.champion_id == 0 + && self.skin_id == 0 + && self.chroma_id.is_none() + && self.identity.as_ref().is_some_and(|id| !id.is_empty()); + if identity_only { + return Ok(()); + } if self.champion_id == 0 || self.champion_id >= 70_000 { return bad("champion"); @@ -78,6 +94,46 @@ impl Announcement { } } +#[must_use] +pub fn announcement_from_state(state: &AppState, member_id: u64) -> Option { + if !state.party_share { + return None; + } + let puuid = state.local_puuid.clone()?; + let identity = state + .local_identity + .clone() + .filter(|id| !id.is_empty() && id.validate().is_ok()); + if (state.phase.is_champ_select() || state.phase.is_in_game()) + && let Some(champion_id) = state.champion_id + && let Some(target) = state + .overlay_target + .as_ref() + .filter(|t| t.matches_champion(champion_id)) + && target.package_entry_id() != champion_id * 1000 + { + let announcement = Announcement { + member_id, + puuid, + champion_id, + skin_id: target.skin_id, + chroma_id: target.chroma_id, + identity, + }; + return announcement.validate().ok().map(|()| announcement); + } + let identity = identity?; + let announcement = Announcement { + member_id, + puuid, + champion_id: 0, + skin_id: 0, + chroma_id: None, + identity: Some(identity), + }; + announcement.validate().ok().map(|()| announcement) +} + pub fn open_member( member: &RelayMember, cipher: &RoomCipher, @@ -107,6 +163,7 @@ pub fn open_member( champion_id: announcement.champion_id, skin_id: announcement.skin_id, chroma_id: announcement.chroma_id, + identity: announcement.identity, })) } @@ -121,6 +178,7 @@ mod tests { champion_id: 103, skin_id: 103_015, chroma_id: Some(103_020), + identity: None, } } diff --git a/crates/bullet-party/tests/rigorous_protocol_tests.rs b/crates/bullet-party/tests/rigorous_protocol_tests.rs new file mode 100644 index 0000000..28d2cd8 --- /dev/null +++ b/crates/bullet-party/tests/rigorous_protocol_tests.rs @@ -0,0 +1,101 @@ +use bullet_core::identity::IdentityLoadout; +use bullet_party::crypto::RoomCipher; +use bullet_party::protocol::{Announcement, RelayMember, open_member}; + +#[test] +fn crypto_detects_every_single_bit_flip_and_wrong_key() { + let cipher = RoomCipher::new(&[0x5Au8; 32]); + let other_cipher = RoomCipher::new(&[0xA5u8; 32]); + + let ann = Announcement { + member_id: 42, + puuid: "player-uuid-42".into(), + champion_id: 238, + skin_id: 238_015, + chroma_id: Some(238_020), + identity: Some(IdentityLoadout { + icon_id: Some(29), + border: Some("CHALLENGER".into()), + banner: Some("/lol-game-data/assets/v1/regalia/banner.png".into()), + title: Some("Bot Diff".into()), + tokens: vec!["101000:CHALLENGER".into()], + }), + }; + + let blob = ann.seal(&cipher).expect("seal"); + assert!(other_cipher.open(&blob).is_err()); + + let mut raw_json = serde_json::to_value(&blob).expect("blob json"); + let ct_b64 = raw_json["c"].as_str().expect("ciphertext").to_owned(); + assert!(!ct_b64.is_empty()); + + let mut chars: Vec = ct_b64.into_bytes(); + for pos in 0..chars.len().min(48) { + let orig = chars[pos]; + chars[pos] = if orig == b'A' { b'B' } else { b'A' }; + raw_json["c"] = serde_json::Value::String(String::from_utf8(chars.clone()).expect("utf8")); + if let Ok(mutated) = serde_json::from_value(raw_json.clone()) { + assert!(cipher.open(&mutated).is_err()); + } + chars[pos] = orig; + } +} + +#[test] +fn lobby_identity_only_announcement_opens_and_rejects_hostile_payloads() { + let cipher = RoomCipher::new(&[7u8; 32]); + + let lobby_ann = Announcement { + member_id: 11, + puuid: "friend-11".into(), + champion_id: 0, + skin_id: 0, + chroma_id: None, + identity: Some(IdentityLoadout { + icon_id: Some(502), + border: Some("GRANDMASTER".into()), + banner: Some("/lol-game-data/assets/v1/regalia/gm.png".into()), + title: Some("Rift Legend".into()), + tokens: vec![ + "/lol-game-data/assets/assets/challenges/t1.png".into(), + "/lol-game-data/assets/assets/challenges/t2.png".into(), + ], + }), + }; + let blob = lobby_ann.seal(&cipher).expect("seal"); + let member = RelayMember { + summoner_id: serde_json::json!(11), + skin: Some(serde_json::to_value(&blob).expect("json")), + }; + let peer = open_member(&member, &cipher, 1) + .expect("valid") + .expect("peer present"); + assert_eq!(peer.champion_id, 0); + assert_eq!(peer.identity, lobby_ann.identity); + + let hostile_banners = [ + "javascript:alert(1)", + "/lol-game-data/assets/a.png);color:red", + "/lol-game-data/assets/../../etc/passwd", + "https://evil.example/a.png", + ]; + for bad_banner in hostile_banners { + let bad = Announcement { + member_id: 11, + puuid: "friend-11".into(), + champion_id: 0, + skin_id: 0, + chroma_id: None, + identity: Some(IdentityLoadout { + banner: Some(bad_banner.into()), + ..IdentityLoadout::default() + }), + }; + let bad_blob = bad.seal(&cipher).expect("seal"); + let bad_member = RelayMember { + summoner_id: serde_json::json!(11), + skin: Some(serde_json::to_value(&bad_blob).expect("json")), + }; + assert!(open_member(&bad_member, &cipher, 1).is_err()); + } +} diff --git a/crates/bullet-platform/src/league/client_window/macos.rs b/crates/bullet-platform/src/league/client_window/macos.rs index 8d7a44d..f3a5a52 100644 --- a/crates/bullet-platform/src/league/client_window/macos.rs +++ b/crates/bullet-platform/src/league/client_window/macos.rs @@ -1,8 +1,40 @@ +use std::sync::Mutex; +use std::time::{Duration, Instant}; + use super::{ClientWindowState, WindowRect, overlay_placement_on}; +const CACHE_TTL: Duration = Duration::from_millis(800); +const DEFAULT_MACOS_CLIENT_RECT: WindowRect = WindowRect { + left: 120, + top: 120, + right: 1400, + bottom: 840, +}; + +static CACHED_STATE: Mutex> = Mutex::new(None); + #[must_use] pub fn client_window_state() -> ClientWindowState { - ClientWindowState::Absent + if let Ok(guard) = CACHED_STATE.lock() + && let Some((at, state)) = *guard + && at.elapsed() < CACHE_TTL + { + return state; + } + let running = + crate::process::ProcessFinder::find_any_process(&crate::game_version::CLIENT_EXES) + .ok() + .flatten() + .is_some(); + let state = if running { + ClientWindowState::Visible(DEFAULT_MACOS_CLIENT_RECT) + } else { + ClientWindowState::Absent + }; + if let Ok(mut guard) = CACHED_STATE.lock() { + *guard = Some((Instant::now(), state)); + } + state } pub(crate) fn take_foreground(_window: isize) {} diff --git a/crates/bullet-platform/src/league/game_version.rs b/crates/bullet-platform/src/league/game_version.rs index 4d738d8..36f6c19 100644 --- a/crates/bullet-platform/src/league/game_version.rs +++ b/crates/bullet-platform/src/league/game_version.rs @@ -7,15 +7,38 @@ use tracing::warn; pub const GAME_PATCH_FILE: &str = "game_patch.json"; +#[cfg(not(target_os = "macos"))] pub const GAME_EXES: [&str; 2] = ["League of Legends.exe", "League of Legends (TM) Client.exe"]; +#[cfg(target_os = "macos")] +pub const GAME_EXES: [&str; 3] = [ + "LeagueofLegends", + "League of Legends.exe", + "League of Legends (TM) Client.exe", +]; + +#[cfg(not(target_os = "macos"))] pub const CLIENT_EXES: [&str; 2] = ["LeagueClientUx.exe", "LeagueClient.exe"]; +#[cfg(target_os = "macos")] +pub const CLIENT_EXES: [&str; 4] = [ + "LeagueClientUx", + "LeagueClient", + "LeagueClientUx.exe", + "LeagueClient.exe", +]; + +const MACOS_BUNDLE_GAME_EXE: &str = "LeagueofLegends.app/Contents/MacOS/LeagueofLegends"; + #[must_use] pub fn game_exe(game_dir: &Path) -> PathBuf { GAME_EXES .iter() .map(|name| game_dir.join(name)) + .chain([ + game_dir.join(MACOS_BUNDLE_GAME_EXE), + game_dir.join("LeagueofLegends"), + ]) .find(|path| path.is_file()) .unwrap_or_else(|| game_dir.join(GAME_EXES[0])) } @@ -72,7 +95,47 @@ pub fn read_time_date_stamp(path: &Path) -> Result { context: format!("could not open {}", path.display()), source: e, })?; - time_date_stamp_from(&mut file) + match time_date_stamp_from(&mut file) { + Ok(stamp) => Ok(stamp), + Err(GameVersionError::BadDosSignature) => { + if let Some(stamp) = macho_stamp_from(&mut file) { + Ok(stamp) + } else { + Err(GameVersionError::BadDosSignature) + } + } + Err(e) => Err(e), + } +} + +fn macho_stamp_from(reader: &mut R) -> Option { + reader.seek(SeekFrom::Start(0)).ok()?; + let mut buf = [0u8; 4096]; + let mut read = 0usize; + while read < buf.len() { + match reader.read(&mut buf[read..]) { + Ok(0) => break, + Ok(n) => read += n, + Err(_) => return None, + } + } + if read < 32 { + return None; + } + let magic = u32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]); + let is_macho = matches!( + magic, + 0xFEED_FACF | 0xCFFA_EDFE | 0xFEED_FACE | 0xCEFA_EDFE | 0xCAFE_BABE | 0xBEBA_FECA + ); + if !is_macho { + return None; + } + let mut hash: u32 = 0x811C_9DC5; + for &b in &buf[..read] { + hash ^= u32::from(b); + hash = hash.wrapping_mul(0x0100_0193); + } + Some(if hash == 0 { 1 } else { hash }) } pub fn time_date_stamp_from(reader: &mut R) -> Result { diff --git a/crates/bullet-platform/src/league/paths.rs b/crates/bullet-platform/src/league/paths.rs index 6bac8ac..fbc60b0 100644 --- a/crates/bullet-platform/src/league/paths.rs +++ b/crates/bullet-platform/src/league/paths.rs @@ -6,9 +6,17 @@ use tracing::debug; use crate::error::PlatformError; pub fn install_dir() -> Result { - let base = std::env::var("PROGRAMFILES") - .map_err(|_| PlatformError::Path("PROGRAMFILES not set".into()))?; - Ok(PathBuf::from(base).join("Bullet")) + if let Ok(base) = std::env::var("PROGRAMFILES") { + return Ok(PathBuf::from(base).join("Bullet")); + } + #[cfg(target_os = "macos")] + { + return Ok(PathBuf::from("/Applications/Bullet.app/Contents/MacOS")); + } + #[cfg(not(target_os = "macos"))] + { + Err(PlatformError::Path("PROGRAMFILES not set".into())) + } } pub fn data_dir() -> Result { @@ -58,26 +66,65 @@ pub fn riot_league_installs() -> Vec { riot_installs(&mut Vec::new()) } +fn riot_metadata_dir(notes: &mut Vec) -> Option { + if let Ok(program_data) = std::env::var("ProgramData") { + return Some( + PathBuf::from(program_data) + .join("Riot Games") + .join("Metadata"), + ); + } + #[cfg(target_os = "macos")] + { + let shared = PathBuf::from("/Users/Shared/Riot Games/Metadata"); + if shared.exists() { + return Some(shared); + } + } + notes.push("ProgramData is not set".into()); + None +} + +#[cfg_attr(not(target_os = "macos"), allow(unused_variables, clippy::ptr_arg))] +fn append_macos_default_installs(installs: &mut Vec) { + #[cfg(target_os = "macos")] + { + let mut defaults = vec![ + PathBuf::from("/Applications/League of Legends.app/Contents/LoL"), + PathBuf::from("/Applications/League of Legends.app"), + ]; + if let Some(home) = std::env::home_dir() { + defaults.push(home.join("Applications/League of Legends.app/Contents/LoL")); + defaults.push(home.join("Applications/League of Legends.app")); + } + for candidate in defaults { + if candidate.exists() && !installs.contains(&candidate) { + installs.push(candidate); + } + } + } +} + fn riot_installs(notes: &mut Vec) -> Vec { - let Ok(program_data) = std::env::var("ProgramData") else { - notes.push("ProgramData is not set".into()); - return Vec::new(); + let mut installs = Vec::new(); + let Some(metadata) = riot_metadata_dir(notes) else { + append_macos_default_installs(&mut installs); + return installs; }; - let metadata = PathBuf::from(program_data) - .join("Riot Games") - .join("Metadata"); let entries = match std::fs::read_dir(&metadata) { Ok(entries) => entries, Err(e) if e.kind() == std::io::ErrorKind::NotFound => { notes.push(format!("no Riot metadata folder at {}", metadata.display())); - return Vec::new(); + append_macos_default_installs(&mut installs); + return installs; } Err(e) => { notes.push(format!( "Riot metadata folder {} unreadable: {e}", metadata.display() )); - return Vec::new(); + append_macos_default_installs(&mut installs); + return installs; } }; let mut patchlines: Vec = Vec::new(); @@ -99,7 +146,6 @@ fn riot_installs(notes: &mut Vec) -> Vec { patchlines.sort_by_key(|name| (name != "league_of_legends.live", name.clone())); - let mut installs = Vec::new(); for name in &patchlines { let settings = metadata .join(name) @@ -112,6 +158,7 @@ fn riot_installs(notes: &mut Vec) -> Vec { Err(e) => notes.push(format!("{} unreadable: {e}", settings.display())), } } + append_macos_default_installs(&mut installs); installs } @@ -188,9 +235,28 @@ pub fn normalize_game_dir(path: &Path) -> Option { if is_valid_game_dir(path) { return Some(path.to_path_buf()); } - [path.join("Game"), path.with_file_name("Game")] - .into_iter() - .find(|candidate| is_valid_game_dir(candidate)) + for candidate in [ + path.join("Game"), + path.with_file_name("Game"), + path.join("Contents/LoL/Game"), + path.join("LoL/Game"), + ] { + if is_valid_game_dir(&candidate) { + return Some(candidate); + } + } + for ancestor in path.ancestors().skip(1).take(7) { + if is_valid_game_dir(ancestor) { + return Some(ancestor.to_path_buf()); + } + for sub in ["Game", "Contents/LoL/Game"] { + let candidate = ancestor.join(sub); + if is_valid_game_dir(&candidate) { + return Some(candidate); + } + } + } + None } #[cfg(test)] @@ -276,6 +342,21 @@ mod tests { assert_eq!(normalize_game_dir(&game_dir), Some(game_dir)); + let mac_app = temp.join("League of Legends.app"); + let mac_game = mac_app.join("Contents/LoL/Game"); + let mac_exe_dir = mac_game.join("LeagueofLegends.app/Contents/MacOS"); + let mac_client_dir = mac_app.join( + "Contents/LoL/LeagueClient.app/Contents/Helpers/LeagueClientUx.app/Contents/MacOS", + ); + std::fs::create_dir_all(mac_game.join("DATA")).expect("mac DATA"); + std::fs::create_dir_all(&mac_exe_dir).expect("mac exe dir"); + std::fs::create_dir_all(&mac_client_dir).expect("mac client dir"); + std::fs::write(mac_exe_dir.join("LeagueofLegends"), b"macho").expect("mac exe"); + assert!(is_valid_game_dir(&mac_game)); + assert_eq!(normalize_game_dir(&mac_app), Some(mac_game.clone())); + assert_eq!(normalize_game_dir(&mac_exe_dir), Some(mac_game.clone())); + assert_eq!(normalize_game_dir(&mac_client_dir), Some(mac_game)); + let _ = std::fs::remove_dir_all(&temp); // ignore-ok: cleanup fixture after test } diff --git a/crates/bullet-platform/src/os/storage/preferences.rs b/crates/bullet-platform/src/os/storage/preferences.rs index 78baa41..01b7eca 100644 --- a/crates/bullet-platform/src/os/storage/preferences.rs +++ b/crates/bullet-platform/src/os/storage/preferences.rs @@ -24,6 +24,12 @@ pub static INJECTION: Preference = Preference::new("injection.json", "skin injec pub static LIGHT_LOADING: Preference = Preference::new("light_loading.json", "light game loading", true); +pub static IN_CLIENT_UI: Preference = Preference::new( + "in_client_ui.json", + "pick skins inside the League client", + false, +); + pub static HOOK_LOADING_GAME: Preference = Preference::new( "hook_loading_game.json", "hook a game that is already loading", @@ -218,5 +224,9 @@ mod tests { !HOOK_LOADING_GAME.default, "a late pick must not hook a game that is already loading by default" ); + assert!( + !IN_CLIENT_UI.default, + "the native Bullet window is the default until the user opts into the in-client carousel" + ); } } diff --git a/crates/bullet-platform/src/os/system/identity/version.rs b/crates/bullet-platform/src/os/system/identity/version.rs index faf593c..1ec589b 100644 --- a/crates/bullet-platform/src/os/system/identity/version.rs +++ b/crates/bullet-platform/src/os/system/identity/version.rs @@ -1,4 +1,4 @@ -use std::path::Path; +use std::path::{Path, PathBuf}; #[must_use] pub fn display_version() -> &'static str { @@ -63,23 +63,264 @@ pub fn read_pe_version(path: &Path) -> Option<(u16, u16, u16)> { &raw mut info_len, ) }; - if !found.as_bool() - || info_ptr.is_null() - || (info_len as usize) < std::mem::size_of::() - { + let base = buffer.as_ptr() as usize; + let ptr = info_ptr as usize; + let needed = std::mem::size_of::(); + if !found.as_bool() || info_ptr.is_null() || (info_len as usize) < needed || ptr < base { return None; } + let offset = ptr - base; + let slice = buffer.get(offset..offset.checked_add(needed)?)?; + let sig = u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]); + if sig != 0xFEEF_04BD { + return None; + } + let ms = u32::from_le_bytes([slice[8], slice[9], slice[10], slice[11]]); + let ls = u32::from_le_bytes([slice[12], slice[13], slice[14], slice[15]]); + let major = ((ms >> 16) & 0xFFFF) as u16; + let minor = (ms & 0xFFFF) as u16; + let patch = ((ls >> 16) & 0xFFFF) as u16; + Some((major, minor, patch)) +} + +#[cfg(not(windows))] +#[must_use] +pub fn read_pe_version(path: &Path) -> Option<(u16, u16, u16)> { + read_macos_bundle_version(path) +} + +#[must_use] +pub fn read_macos_bundle_version(path: &Path) -> Option<(u16, u16, u16)> { + for ancestor in path.ancestors().take(4) { + let plist = if ancestor.ends_with("Contents") { + ancestor.join("Info.plist") + } else { + ancestor.join("Contents").join("Info.plist") + }; + if let Ok(text) = std::fs::read_to_string(&plist) + && let Some(ver) = parse_plist_short_version(&text) + { + return Some(ver); + } + } + None +} - let fixed = unsafe { &*(info_ptr.cast::()) }; - let major = ((fixed.dwFileVersionMS >> 16) & 0xFFFF) as u16; - let minor = (fixed.dwFileVersionMS & 0xFFFF) as u16; - let patch = ((fixed.dwFileVersionLS >> 16) & 0xFFFF) as u16; +#[must_use] +pub fn parse_plist_short_version(plist_xml: &str) -> Option<(u16, u16, u16)> { + let key_idx = plist_xml.find("CFBundleShortVersionString")?; + let after_key = &plist_xml[key_idx..]; + let start_tag = after_key.find("")?; + let after_start = &after_key[start_tag + "".len()..]; + let end_tag = after_start.find("")?; + let raw = after_start[..end_tag].trim().trim_start_matches('v'); + let mut parts = raw.split('.'); + let major = parts.next()?.parse::().ok()?; + let minor = parts.next().unwrap_or("0").parse::().ok()?; + let patch = parts + .next() + .unwrap_or("0") + .split(|c: char| !c.is_ascii_digit()) + .next() + .unwrap_or("0") + .parse::() + .ok()?; Some((major, minor, patch)) } +#[must_use] +pub fn parse_registry_path_value(raw: &str) -> Option { + let trimmed = raw.trim(); + if trimmed.is_empty() { + return None; + } + let without_quotes = if let Some(rest) = trimmed.strip_prefix('"') { + rest.split('"').next().unwrap_or(rest) + } else { + trimmed + }; + let clean = match without_quotes.rfind(',') { + Some(idx) + if !without_quotes[idx + 1..].is_empty() + && without_quotes[idx + 1..] + .trim() + .chars() + .all(|c| c.is_ascii_digit() || c == '-') => + { + &without_quotes[..idx] + } + _ => without_quotes, + }; + let clean = clean.trim().trim_matches('"'); + (!clean.is_empty()).then(|| PathBuf::from(clean)) +} + +#[cfg(windows)] +#[must_use] +pub fn discover_installed_exe(keywords: &[&str], exe_names: &[&str]) -> Option { + use windows::Win32::Foundation::ERROR_NO_MORE_ITEMS; + use windows::Win32::System::Registry::{ + HKEY, HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_READ, RRF_RT_REG_EXPAND_SZ, RRF_RT_REG_SZ, + RegCloseKey, RegEnumKeyExW, RegGetValueW, RegOpenKeyExW, + }; + use windows::core::PCWSTR; + + unsafe fn read_reg_str(hkey: HKEY, name: &str) -> Option { + let wide_name: Vec = name.encode_utf16().chain(std::iter::once(0)).collect(); + let mut buf = vec![0u16; 512]; + let mut bytes = (buf.len() * 2) as u32; + let status = unsafe { + RegGetValueW( + hkey, + PCWSTR::null(), + PCWSTR(wide_name.as_ptr()), + RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ, + None, + Some(buf.as_mut_ptr().cast()), + Some(&mut bytes), + ) + }; + if status.is_err() { + return None; + } + let chars = (bytes as usize / 2).min(buf.len()); + let slice = &buf[..chars]; + let end = slice.iter().position(|&c| c == 0).unwrap_or(slice.len()); + Some(String::from_utf16_lossy(&slice[..end])) + } + + let roots = [ + ( + HKEY_CURRENT_USER, + r"Software\Microsoft\Windows\CurrentVersion\Uninstall", + ), + ( + HKEY_LOCAL_MACHINE, + r"Software\Microsoft\Windows\CurrentVersion\Uninstall", + ), + ( + HKEY_LOCAL_MACHINE, + r"Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall", + ), + ]; + + for (hive, subkey_path) in roots { + let subkey_wide: Vec = subkey_path + .encode_utf16() + .chain(std::iter::once(0)) + .collect(); + let mut root_key = HKEY::default(); + if unsafe { + RegOpenKeyExW( + hive, + PCWSTR(subkey_wide.as_ptr()), + Some(0), + KEY_READ, + &mut root_key, + ) + } + .is_err() + { + continue; + } + + let mut index = 0u32; + let mut name_buf = [0u16; 256]; + loop { + let mut name_len = name_buf.len() as u32; + let status = unsafe { + RegEnumKeyExW( + root_key, + index, + Some(windows::core::PWSTR(name_buf.as_mut_ptr())), + &mut name_len, + None, + None, + None, + None, + ) + }; + if status == ERROR_NO_MORE_ITEMS || status.is_err() { + break; + } + index += 1; + + let child_name = String::from_utf16_lossy(&name_buf[..name_len as usize]); + let child_wide: Vec = child_name + .encode_utf16() + .chain(std::iter::once(0)) + .collect(); + let mut app_key = HKEY::default(); + if unsafe { + RegOpenKeyExW( + root_key, + PCWSTR(child_wide.as_ptr()), + Some(0), + KEY_READ, + &mut app_key, + ) + } + .is_err() + { + continue; + } + + let display_name = unsafe { read_reg_str(app_key, "DisplayName") } + .unwrap_or_default() + .to_ascii_lowercase(); + let key_lower = child_name.to_ascii_lowercase(); + let matched = keywords + .iter() + .any(|kw| display_name.contains(kw) || key_lower.contains(kw)); + if matched { + if let Some(icon) = unsafe { read_reg_str(app_key, "DisplayIcon") } + .and_then(|v| parse_registry_path_value(&v)) + && icon.is_file() + && exe_names.iter().any(|e| { + icon.file_name() + .and_then(|n| n.to_str()) + .is_some_and(|n| n.eq_ignore_ascii_case(e)) + }) + { + let _ = unsafe { RegCloseKey(app_key) }; // ignore-ok: close app uninstall key + let _ = unsafe { RegCloseKey(root_key) }; // ignore-ok: close uninstall root key + return Some(icon); + } + + for field in ["InstallLocation", "UninstallString"] { + let Some(raw) = (unsafe { read_reg_str(app_key, field) }) else { + continue; + }; + let Some(parsed) = parse_registry_path_value(&raw) else { + continue; + }; + let dir = if field == "UninstallString" { + parsed.parent().map(Path::to_path_buf) + } else { + Some(parsed) + }; + if let Some(dir) = dir { + for exe in exe_names { + let candidate = dir.join(exe); + if candidate.is_file() { + let _ = unsafe { RegCloseKey(app_key) }; // ignore-ok: close app uninstall key + let _ = unsafe { RegCloseKey(root_key) }; // ignore-ok: close uninstall root key + return Some(candidate); + } + } + } + } + } + let _ = unsafe { RegCloseKey(app_key) }; // ignore-ok: close app uninstall key + } + let _ = unsafe { RegCloseKey(root_key) }; // ignore-ok: close uninstall root key + } + None +} + #[cfg(not(windows))] #[must_use] -pub fn read_pe_version(_path: &Path) -> Option<(u16, u16, u16)> { +pub fn discover_installed_exe(_keywords: &[&str], _exe_names: &[&str]) -> Option { None } @@ -111,4 +352,25 @@ mod tests { assert!(ver.is_some()); } } + + #[test] + fn parses_quoted_install_location_and_icon_suffixes() { + assert_eq!( + parse_registry_path_value(r#""D:\Apps\LTK Manager""#), + Some(PathBuf::from(r"D:\Apps\LTK Manager")) + ); + assert_eq!( + parse_registry_path_value(r#""D:\Apps\LTK Manager\ltk-manager.exe",0"#), + Some(PathBuf::from(r"D:\Apps\LTK Manager\ltk-manager.exe")) + ); + assert_eq!( + parse_registry_path_value(r"C:\Program Files\LTK Manager\ltk-manager.exe"), + Some(PathBuf::from( + r"C:\Program Files\LTK Manager\ltk-manager.exe" + )) + ); + assert_eq!(parse_registry_path_value(" "), None); + let plist = "CFBundleShortVersionString1.34.2"; + assert_eq!(parse_plist_short_version(plist), Some((1, 34, 2))); + } } diff --git a/crates/bullet-platform/src/os/system/launch/desktop.rs b/crates/bullet-platform/src/os/system/launch/desktop.rs index 5f321d5..ef9ba4b 100644 --- a/crates/bullet-platform/src/os/system/launch/desktop.rs +++ b/crates/bullet-platform/src/os/system/launch/desktop.rs @@ -63,6 +63,74 @@ pub fn terminate_process(pid: u32) -> bool { ok } +#[must_use] +#[cfg_attr(not(target_arch = "x86_64"), allow(unused_variables))] +pub fn query_process_cmdline(pid: u32) -> Option { + #[cfg(target_arch = "x86_64")] + unsafe { + if pid == 0 { + return None; + } + let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid).ok()?; + let result = read_cmdline_query_only(handle); + let _ = CloseHandle(handle); // ignore-ok: process handle released after cmdline query + result + } + #[cfg(not(target_arch = "x86_64"))] + None +} + +#[cfg(target_arch = "x86_64")] +unsafe fn read_cmdline_query_only(handle: HANDLE) -> Option { + #[repr(C)] + struct UnicodeStr { + length: u16, + maximum_length: u16, + buffer: *const u16, + } + + const PROCESS_COMMAND_LINE_INFORMATION: u32 = 60; + let mut needed = 0u32; + let probe = unsafe { + NtQueryInformationProcess( + handle, + PROCESS_COMMAND_LINE_INFORMATION, + core::ptr::null_mut(), + 0, + &mut needed, + ) + }; + let _ = probe; // ignore-ok: initial query populates required buffer size in needed + for _ in 0..3 { + let cap = (needed as usize).max(std::mem::size_of::()); + let mut buf = vec![0u8; cap]; + let status = unsafe { + NtQueryInformationProcess( + handle, + PROCESS_COMMAND_LINE_INFORMATION, + buf.as_mut_ptr().cast(), + cap as u32, + &mut needed, + ) + }; + if status >= 0 { + let ustr = unsafe { &*(buf.as_ptr().cast::()) }; + if ustr.buffer.is_null() || ustr.length == 0 { + return Some(String::new()); + } + let units = usize::from(ustr.length) / 2; + let base = buf.as_ptr() as usize; + let ptr = ustr.buffer as usize; + if ptr < base || ptr.saturating_add(units * 2) > base.saturating_add(buf.len()) { + return None; + } + let slice = unsafe { std::slice::from_raw_parts(ustr.buffer, units) }; + return Some(String::from_utf16_lossy(slice)); + } + } + None +} + #[cfg(target_arch = "x86_64")] unsafe fn read_peb_desktop_info(handle: HANDLE) -> Option { #[repr(C)] diff --git a/crates/bullet-platform/src/os/system/launch/macos/process.rs b/crates/bullet-platform/src/os/system/launch/macos/process.rs index 80b2da9..047fbd2 100644 --- a/crates/bullet-platform/src/os/system/launch/macos/process.rs +++ b/crates/bullet-platform/src/os/system/launch/macos/process.rs @@ -30,6 +30,29 @@ impl Drop for BackgroundThread { } } +pub fn query_process_cmdline(pid: u32) -> Option { + let output = std::process::Command::new("/bin/ps") + .args(["-p", &pid.to_string(), "-o", "command="]) + .output() + .ok()?; + if !output.status.success() { + return None; + } + let cmd = String::from_utf8_lossy(&output.stdout).trim().to_owned(); + (!cmd.is_empty()).then_some(cmd) +} + +#[must_use] +pub fn terminate_process(pid: u32) -> bool { + let Ok(raw_pid) = libc::c_int::try_from(pid) else { + return false; + }; + if raw_pid <= 0 { + return false; + } + unsafe { libc::kill(raw_pid, libc::SIGTERM) == 0 } +} + pub struct ProcessFinder; impl ProcessFinder { diff --git a/crates/bullet-platform/src/os/system/launch/process.rs b/crates/bullet-platform/src/os/system/launch/process.rs index 7630393..db9a7bd 100644 --- a/crates/bullet-platform/src/os/system/launch/process.rs +++ b/crates/bullet-platform/src/os/system/launch/process.rs @@ -14,7 +14,9 @@ use windows::Win32::System::Threading::{ }; use windows::core::{HRESULT, PWSTR}; -pub use super::desktop::{is_default_desktop, process_desktop, terminate_process}; +pub use super::desktop::{ + is_default_desktop, process_desktop, query_process_cmdline, terminate_process, +}; use tracing::debug; diff --git a/crates/bullet-platform/src/ui/desktop/macos/shell.rs b/crates/bullet-platform/src/ui/desktop/macos/shell.rs index 1956d42..b91139b 100644 --- a/crates/bullet-platform/src/ui/desktop/macos/shell.rs +++ b/crates/bullet-platform/src/ui/desktop/macos/shell.rs @@ -91,6 +91,20 @@ pub fn message_box_question(title: &str, text: &str) -> bool { } } +pub fn run_elevated_wait(exe: &Path, args: &str) -> Result { + match crate::elevation::run_elevated(exe, args)? { + crate::elevation::ElevatedRun::Finished(0) => Ok(true), + crate::elevation::ElevatedRun::Finished(_) | crate::elevation::ElevatedRun::Declined => { + Ok(false) + } + } +} + +#[must_use] +pub fn read_hklm_string(_subkey: &str, _value_name: &str) -> Option { + None +} + pub fn dismiss_question(_title: &str) -> bool { false } diff --git a/crates/bullet-platform/src/ui/desktop/shell.rs b/crates/bullet-platform/src/ui/desktop/shell.rs index 52ec81d..42dc989 100644 --- a/crates/bullet-platform/src/ui/desktop/shell.rs +++ b/crates/bullet-platform/src/ui/desktop/shell.rs @@ -124,6 +124,94 @@ pub fn message_box_question(title: &str, text: &str) -> bool { note_if_not_shown(answer.0, title) && answer == IDYES } +pub fn run_elevated_wait(exe: &Path, args: &str) -> Result { + use windows::Win32::Foundation::{CloseHandle, ERROR_CANCELLED}; + use windows::Win32::System::Threading::{GetExitCodeProcess, INFINITE, WaitForSingleObject}; + use windows::Win32::UI::Shell::{SEE_MASK_NOCLOSEPROCESS, SHELLEXECUTEINFOW, ShellExecuteExW}; + use windows::Win32::UI::WindowsAndMessaging::SW_HIDE; + use windows::core::PCWSTR; + + let file_h = HSTRING::from(exe.as_os_str()); + let params_h = HSTRING::from(args); + let mut info = SHELLEXECUTEINFOW { + cbSize: std::mem::size_of::() as u32, + fMask: SEE_MASK_NOCLOSEPROCESS, + lpVerb: w!("runas"), + lpFile: PCWSTR(file_h.as_ptr()), + lpParameters: PCWSTR(params_h.as_ptr()), + nShow: SW_HIDE.0, + ..Default::default() + }; + let res = unsafe { ShellExecuteExW(&mut info) }; + if let Err(e) = res { + if e.code() == ERROR_CANCELLED.to_hresult() { + return Ok(false); + } + return Err(PlatformError::Window(format!( + "ShellExecuteExW(runas) failed for '{}': {e}", + exe.display() + ))); + } + if info.hProcess.is_invalid() { + return Ok(false); + } + unsafe { + let _ = WaitForSingleObject(info.hProcess, INFINITE); // ignore-ok: wait for elevated helper exit + let mut code = 1u32; + let _ = GetExitCodeProcess(info.hProcess, &mut code); // ignore-ok: read helper exit code + let _ = CloseHandle(info.hProcess); // ignore-ok: release process handle + Ok(code == 0) + } +} + +#[must_use] +pub fn read_hklm_string(subkey: &str, value_name: &str) -> Option { + use windows::Win32::System::Registry::{ + HKEY, HKEY_LOCAL_MACHINE, KEY_READ, KEY_WOW64_64KEY, RRF_RT_REG_EXPAND_SZ, RRF_RT_REG_SZ, + RegCloseKey, RegGetValueW, RegOpenKeyExW, + }; + use windows::core::PCWSTR; + + let sub_h = HSTRING::from(subkey); + let val_h = HSTRING::from(value_name); + let mut key = HKEY::default(); + if unsafe { + RegOpenKeyExW( + HKEY_LOCAL_MACHINE, + PCWSTR(sub_h.as_ptr()), + Some(0), + KEY_READ | KEY_WOW64_64KEY, + &mut key, + ) + } + .is_err() + { + return None; + } + let mut buf = vec![0u16; 512]; + let mut bytes = (buf.len() * 2) as u32; + let ok = unsafe { + RegGetValueW( + key, + PCWSTR::null(), + PCWSTR(val_h.as_ptr()), + RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ, + None, + Some(buf.as_mut_ptr().cast()), + Some(&mut bytes), + ) + } + .is_ok(); + let _ = unsafe { RegCloseKey(key) }; // ignore-ok: close registry key + if !ok { + return None; + } + let chars = (bytes as usize / 2).min(buf.len()); + let slice = &buf[..chars]; + let end = slice.iter().position(|&c| c == 0).unwrap_or(slice.len()); + Some(String::from_utf16_lossy(&slice[..end])) +} + pub fn dismiss_question(title: &str) -> bool { use windows::Win32::Foundation::{LPARAM, WPARAM}; use windows::Win32::System::Threading::GetCurrentProcessId; diff --git a/crates/bullet-platform/src/ui/desktop/tray/mod.rs b/crates/bullet-platform/src/ui/desktop/tray/mod.rs index b59e512..162b71a 100644 --- a/crates/bullet-platform/src/ui/desktop/tray/mod.rs +++ b/crates/bullet-platform/src/ui/desktop/tray/mod.rs @@ -28,6 +28,7 @@ pub enum TrayEvent { ToggleRandomSkin, ToggleLightLoading, + ToggleInClientUi, Quit, @@ -41,7 +42,13 @@ pub enum TrayEvent { OpenRelease, + OpenProject, + MarkProblem, ExportDiagnostics, + + RepairSkins, + + RepairClient, } diff --git a/crates/bullet-platform/src/ui/locale/i18n/en.rs b/crates/bullet-platform/src/ui/locale/i18n/en.rs index 2e70079..35ab500 100644 --- a/crates/bullet-platform/src/ui/locale/i18n/en.rs +++ b/crates/bullet-platform/src/ui/locale/i18n/en.rs @@ -38,27 +38,35 @@ pub(super) static ENGLISH: Text = Text { menu_auto_accept: "Accept matches automatically", menu_quit: "Quit Bullet", menu_open_panel: "Open Bullet", - menu_random_skin: "Random skin if none is chosen", - panel_section_options: "Options", - panel_section_diagnostics: "Diagnostics", + menu_random_skin: "Automatic random skin", + panel_section_options: "Skins", + panel_section_diagnostics: "Pending items", panel_tab_home: "Home", panel_tab_party: "Party", - panel_tab_help: "Help", - panel_all_clear: "All set. Pick your skin in Bullet's window during champion select.", - panel_attention: "Checks needing attention:", - panel_see_diagnostics: "See diagnostics", - panel_party_hint: "Create a room and share the code with friends: in the match, each of you sees the skins the others picked.", - panel_random_skin_hint: "When your champion locks in with no skin chosen in Bullet, one is rolled so the match never starts without a skin.", + panel_tab_help: "Support", + panel_all_clear: "All set. Pick your skin in champion select.", + panel_attention: "Pending items:", + panel_see_diagnostics: "View pending items", + panel_party_hint: "Create a room and share the code to see each other's skins.", + panel_random_skin_hint: "Rolls a skin automatically when none is chosen.", menu_injection: "Inject skins", - panel_injection_hint: "Turn off to play with the game's own files, without any skin or mod; use it when a mod breaks the match loading: Bullet stops the injector, so reconnecting loads without mods.", - menu_light_loading: "Light match loading", - panel_light_loading_hint: "Turns off the League client's crash reports (Config\\LeagueClientSettings.yaml) so the injector checks each file only when the game loads it, instead of all of them as the match starts.", + panel_injection_hint: "Applies skins and mods when a match starts.", + menu_light_loading: "Light loading", + panel_light_loading_hint: "Loads files on demand for faster match entry.", + menu_in_client_ui: "Pick inside the League client", + panel_in_client_ui_hint: "Unlocks skins and chromas right inside the client carousel.", + panel_mode_title: "Skin picker mode", + panel_mode_window: "Bullet interface", + panel_mode_client: "Native in client", check_injector: "Injector (tools folder)", + check_manager: "Mod Manager (LTK)", check_game: "Installed game", check_client: "League client", check_privileges: "Bullet privileges", detail_ok: "OK", detail_injector_missing: "bullet_launcher.exe or bullet_bridge.dll is missing", + detail_manager_missing: "not found on this PC (install LTK Manager 1.33.0+)", + detail_manager_outdated: "version {found} is outdated (requires {required}+)", detail_game_missing: "game folder not found", detail_client_connected: "connected", detail_client_waiting: "waiting for the client to open", @@ -85,9 +93,11 @@ No: keep this version; you can update later from the download page.", custom_mods_restored_title: "Originals restored", custom_mods_restored_body: "{n} custom mod(s) are back to their original file in the folder and will not be rewritten again. In a match, only a broken link that would crash the game is still fixed.", custom_mods_restore_failed: "The originals could not be restored: {error}", - panel_mark_problem: "Mark a problem now", - panel_mark_problem_hint: "Without leaving the game: during a match, Ctrl+Shift+B marks the moment something looks wrong and F12 takes a screenshot. When the match ends the diagnostics are saved to the logs folder on their own.", + panel_mark_problem: "Mark problem", + panel_mark_problem_hint: "In-game: Ctrl+Shift+B marks a problem and F12 takes a screenshot.", panel_export_diagnostics: "Export diagnostics", + panel_open_project: "GitHub project", + panel_project_star_hint: "GitHub project: support Bullet with a star on the official repository.", missing_tools_title: "Bullet — Injection tools missing", missing_tools_body: "Bullet's injection tools (bullet_launcher.exe and bullet_bridge.dll) are missing from the 'tools' folder.\n\nReinstall Bullet to restore them.", @@ -225,4 +235,12 @@ No: keep this version; you can update later from the download page.", manager_missing_body: "Mod Manager was not found on this PC. Install the latest version (1.33.0 or newer) so Bullet can work properly.", manager_outdated_title: "Mod Manager outdated", manager_outdated_body: "The installed Mod Manager version ({found}) is outdated for this Bullet version ({bullet}). Please update Mod Manager on your PC to version {required}+ so everything works properly.", + + panel_repair_skins: "Repair skins and mods", + panel_repair_client: "Repair client", + panel_stats_title: "Skin performance", + panel_stats_empty: "Play a match to track wins, losses, and win rate per skin.", + panel_stats_games: "games", + panel_stats_wins_short: "W", + panel_stats_losses_short: "L", }; diff --git a/crates/bullet-platform/src/ui/locale/i18n/es.rs b/crates/bullet-platform/src/ui/locale/i18n/es.rs index d91ed4f..fd5f8e4 100644 --- a/crates/bullet-platform/src/ui/locale/i18n/es.rs +++ b/crates/bullet-platform/src/ui/locale/i18n/es.rs @@ -38,27 +38,35 @@ pub(super) static SPANISH: Text = Text { menu_auto_accept: "Aceptar partida automáticamente", menu_quit: "Salir de Bullet", menu_open_panel: "Abrir Bullet", - menu_random_skin: "Skin aleatoria si no eliges ninguna", - panel_section_options: "Opciones", - panel_section_diagnostics: "Diagnóstico", + menu_random_skin: "Skin aleatoria automática", + panel_section_options: "Skins", + panel_section_diagnostics: "Pendientes", panel_tab_home: "Inicio", - panel_tab_party: "Grupo", - panel_tab_help: "Ayuda", - panel_all_clear: "Todo listo. Elige tu skin en la ventana de Bullet durante la selección de campeones.", - panel_attention: "Comprobaciones con aviso:", - panel_see_diagnostics: "Ver diagnóstico", - panel_party_hint: "Crea una sala y comparte el código con tus amigos: en la partida, cada uno ve las skins que eligieron los demás.", - panel_random_skin_hint: "Cuando el campeón se bloquea sin skin elegida en Bullet, se sortea una para que la partida no empiece sin skin.", + panel_tab_party: "Party", + panel_tab_help: "Soporte", + panel_all_clear: "Todo listo. Elige tu skin en la selección de campeones.", + panel_attention: "Pendientes:", + panel_see_diagnostics: "Ver pendientes", + panel_party_hint: "Crea una sala y comparte el código para ver las skins de todos.", + panel_random_skin_hint: "Sortea una skin automáticamente si no eliges ninguna.", menu_injection: "Inyectar aspectos", - panel_injection_hint: "Desactívalo para jugar con los archivos del propio juego, sin aspectos ni mods; úsalo cuando un mod rompa la carga de la partida: Bullet cierra el inyector y al reconectar carga sin mods.", - menu_light_loading: "Carga ligera de la partida", - panel_light_loading_hint: "Desactiva el envío de informes de fallos del cliente de League (Config\\LeagueClientSettings.yaml) para que el inyector verifique cada archivo solo cuando el juego lo carga, en vez de todos al entrar a la partida.", + panel_injection_hint: "Aplica skins y mods al iniciar la partida.", + menu_light_loading: "Carga ligera", + panel_light_loading_hint: "Carga archivos bajo demanda al entrar en la partida.", + menu_in_client_ui: "Elegir en el cliente de League", + panel_in_client_ui_hint: "Desbloquea skins y chromas directo en el carrusel del cliente.", + panel_mode_title: "Modo de selección de skins", + panel_mode_window: "Interfaz de Bullet", + panel_mode_client: "Nativo en el cliente", check_injector: "Inyector (carpeta tools)", + check_manager: "Mod Manager (LTK)", check_game: "Juego instalado", check_client: "Cliente de League", check_privileges: "Privilegios de Bullet", detail_ok: "OK", detail_injector_missing: "falta bullet_launcher.exe o bullet_bridge.dll", + detail_manager_missing: "no encontrado en este PC (instala LTK Manager 1.33.0+)", + detail_manager_outdated: "versión {found} desactualizada (requiere {required}+)", detail_game_missing: "carpeta del juego no encontrada", detail_client_connected: "conectado", detail_client_waiting: "esperando a que se abra el cliente", @@ -85,9 +93,11 @@ No: sigues con esta versión; puedes actualizar después desde la página de des custom_mods_restored_title: "Originales restaurados", custom_mods_restored_body: "{n} mod(s) personalizados volvieron a su archivo original en la carpeta y no se volverán a reescribir. En la partida solo se sigue corrigiendo un enlace roto que haría caer el juego.", custom_mods_restore_failed: "No se pudieron restaurar los originales: {error}", - panel_mark_problem: "Marcar problema ahora", - panel_mark_problem_hint: "Sin salir del juego: durante la partida, Ctrl+Shift+B marca el momento en que algo se ve mal y F12 toma una captura. Al terminar la partida el diagnóstico se guarda solo en la carpeta de logs.", + panel_mark_problem: "Marcar problema", + panel_mark_problem_hint: "En partida: Ctrl+Shift+B marca un problema y F12 toma captura.", panel_export_diagnostics: "Exportar diagnóstico", + panel_open_project: "Proyecto en GitHub", + panel_project_star_hint: "Proyecto en GitHub: apoya a Bullet con una estrella en el repositorio oficial.", missing_tools_title: "Bullet — Faltan las herramientas de inyección", missing_tools_body: "Las herramientas de inyección de Bullet (bullet_launcher.exe y bullet_bridge.dll) no están en la carpeta 'tools'.\n\nReinstale Bullet para restaurarlas.", @@ -226,4 +236,12 @@ No: sigues con esta versión; puedes actualizar después desde la página de des manager_missing_body: "No se encontró Mod Manager en este PC. Instala la última versión (1.33.0 o superior) para que Bullet funcione correctamente.", manager_outdated_title: "Mod Manager desactualizado", manager_outdated_body: "La versión instalada de Mod Manager ({found}) está desactualizada para esta versión de Bullet ({bullet}). Actualiza Mod Manager en tu PC a la versión {required}+ para que todo funcione correctamente.", + + panel_repair_skins: "Reparar skins y mods", + panel_repair_client: "Reparar cliente", + panel_stats_title: "Rendimiento con skins", + panel_stats_empty: "Juega una partida para registrar victorias, derrotas y tasa de victoria por skin.", + panel_stats_games: "partidas", + panel_stats_wins_short: "V", + panel_stats_losses_short: "D", }; diff --git a/crates/bullet-platform/src/ui/locale/i18n/mod.rs b/crates/bullet-platform/src/ui/locale/i18n/mod.rs index d0aaa89..cef98ff 100644 --- a/crates/bullet-platform/src/ui/locale/i18n/mod.rs +++ b/crates/bullet-platform/src/ui/locale/i18n/mod.rs @@ -150,12 +150,20 @@ pub struct Text { pub panel_injection_hint: &'static str, pub menu_light_loading: &'static str, pub panel_light_loading_hint: &'static str, + pub menu_in_client_ui: &'static str, + pub panel_in_client_ui_hint: &'static str, + pub panel_mode_title: &'static str, + pub panel_mode_window: &'static str, + pub panel_mode_client: &'static str, pub check_injector: &'static str, + pub check_manager: &'static str, pub check_game: &'static str, pub check_client: &'static str, pub check_privileges: &'static str, pub detail_ok: &'static str, pub detail_injector_missing: &'static str, + pub detail_manager_missing: &'static str, + pub detail_manager_outdated: &'static str, pub detail_game_missing: &'static str, pub detail_client_connected: &'static str, pub detail_client_waiting: &'static str, @@ -182,6 +190,8 @@ pub struct Text { pub panel_mark_problem: &'static str, pub panel_mark_problem_hint: &'static str, pub panel_export_diagnostics: &'static str, + pub panel_open_project: &'static str, + pub panel_project_star_hint: &'static str, pub missing_tools_title: &'static str, pub missing_tools_body: &'static str, @@ -316,6 +326,14 @@ pub struct Text { pub manager_missing_body: &'static str, pub manager_outdated_title: &'static str, pub manager_outdated_body: &'static str, + + pub panel_repair_skins: &'static str, + pub panel_repair_client: &'static str, + pub panel_stats_title: &'static str, + pub panel_stats_empty: &'static str, + pub panel_stats_games: &'static str, + pub panel_stats_wins_short: &'static str, + pub panel_stats_losses_short: &'static str, } #[must_use] diff --git a/crates/bullet-platform/src/ui/locale/i18n/pt.rs b/crates/bullet-platform/src/ui/locale/i18n/pt.rs index 68605ad..7ca1e3f 100644 --- a/crates/bullet-platform/src/ui/locale/i18n/pt.rs +++ b/crates/bullet-platform/src/ui/locale/i18n/pt.rs @@ -38,27 +38,35 @@ pub(super) static PORTUGUESE: Text = Text { menu_auto_accept: "Aceitar partida automaticamente", menu_quit: "Sair do Bullet", menu_open_panel: "Abrir o Bullet", - menu_random_skin: "Sortear skin se nenhuma for escolhida", - panel_section_options: "Opções", - panel_section_diagnostics: "Diagnóstico", + menu_random_skin: "Skin aleatória automática", + panel_section_options: "Skins", + panel_section_diagnostics: "Pendências", panel_tab_home: "Início", panel_tab_party: "Party", - panel_tab_help: "Ajuda", - panel_all_clear: "Tudo pronto. Escolha a skin na janela do Bullet durante a seleção de campeões.", - panel_attention: "Verificações com aviso:", - panel_see_diagnostics: "Ver diagnóstico", - panel_party_hint: "Crie uma sala e passe o código para os amigos: cada um vê na partida as skins que os outros escolheram.", - panel_random_skin_hint: "Quando o campeão trava sem skin escolhida no Bullet, uma skin é sorteada para a partida não começar sem skin.", + panel_tab_help: "Suporte", + panel_all_clear: "Tudo pronto. Escolha sua skin na seleção de campeões.", + panel_attention: "Pendências:", + panel_see_diagnostics: "Ver pendências", + panel_party_hint: "Crie uma sala e envie o código para verem as skins uns dos outros.", + panel_random_skin_hint: "Sorteia uma skin quando nenhuma for escolhida.", menu_injection: "Injetar skins", - panel_injection_hint: "Desligue para jogar com os arquivos do próprio jogo, sem skin nem mod; use quando um mod travar o carregamento da partida: o Bullet encerra o injetor e a reconexão carrega sem mods.", - menu_light_loading: "Carregamento leve da partida", - panel_light_loading_hint: "Desliga o envio de relatórios de crash do cliente do League (Config\\LeagueClientSettings.yaml) para o injetor verificar cada arquivo só quando o jogo o carrega, em vez de todos ao entrar na partida.", + panel_injection_hint: "Aplica skins e mods ao iniciar a partida.", + menu_light_loading: "Carregamento leve", + panel_light_loading_hint: "Carrega arquivos sob demanda ao entrar na partida.", + menu_in_client_ui: "Escolher no cliente do League", + panel_in_client_ui_hint: "Destrava skins e chromas direto no carrossel do cliente.", + panel_mode_title: "Modo de escolha de skins", + panel_mode_window: "Interface do Bullet", + panel_mode_client: "Nativo no cliente", check_injector: "Injetor (pasta tools)", + check_manager: "Mod Manager (LTK)", check_game: "Jogo instalado", check_client: "Cliente do League", check_privileges: "Privilégios do Bullet", detail_ok: "OK", detail_injector_missing: "bullet_launcher.exe ou bullet_bridge.dll ausente", + detail_manager_missing: "não encontrado no PC (instale o LTK Manager 1.33.0+)", + detail_manager_outdated: "versão {found} desatualizada (requer {required}+)", detail_game_missing: "pasta do jogo não encontrada", detail_client_connected: "conectado", detail_client_waiting: "aguardando o cliente abrir", @@ -85,9 +93,11 @@ Não: continua nesta versão; dá para atualizar depois pela página de download custom_mods_restored_title: "Originais restaurados", custom_mods_restored_body: "{n} mod(s) custom voltaram ao arquivo original na pasta e não serão regravados de novo. Na partida, só um link quebrado que derrubaria o jogo continua sendo corrigido.", custom_mods_restore_failed: "Não foi possível restaurar os originais: {error}", - panel_mark_problem: "Marcar problema agora", - panel_mark_problem_hint: "Sem sair do jogo: durante a partida, Ctrl+Shift+B marca o momento em que algo aparece errado e F12 tira um print. No fim da partida o diagnóstico é salvo sozinho na pasta de logs.", + panel_mark_problem: "Marcar problema", + panel_mark_problem_hint: "Em partida: Ctrl+Shift+B marca um problema e F12 captura a tela.", panel_export_diagnostics: "Exportar diagnóstico", + panel_open_project: "Projeto no GitHub", + panel_project_star_hint: "Projeto no GitHub: apoie o Bullet com uma estrela no repositório oficial.", missing_tools_title: "Bullet — Ferramentas de injeção ausentes", missing_tools_body: "As ferramentas de injeção do Bullet (bullet_launcher.exe e bullet_bridge.dll) não estão na pasta 'tools'.\n\nReinstale o Bullet para restaurá-las.", @@ -226,4 +236,12 @@ Não: continua nesta versão; dá para atualizar depois pela página de download manager_missing_body: "O Mod Manager não foi encontrado neste PC. Instale a versão mais recente (1.33.0 ou superior) para que o Bullet funcione corretamente.", manager_outdated_title: "Mod Manager desatualizado", manager_outdated_body: "A versão instalada do Mod Manager ({found}) está desatualizada para esta versão do Bullet ({bullet}). Atualize o Mod Manager no seu PC para a versão {required}+ para que tudo funcione corretamente.", + + panel_repair_skins: "Reparar skins e mods", + panel_repair_client: "Reparar cliente", + panel_stats_title: "Desempenho com skins", + panel_stats_empty: "Jogue uma partida para registrar vitórias, derrotas e taxa de vitória por skin.", + panel_stats_games: "jogos", + panel_stats_wins_short: "V", + panel_stats_losses_short: "D", }; diff --git a/crates/bullet-platform/src/ui/locale/i18n/tests.rs b/crates/bullet-platform/src/ui/locale/i18n/tests.rs index 9ffdae5..01836cb 100644 --- a/crates/bullet-platform/src/ui/locale/i18n/tests.rs +++ b/crates/bullet-platform/src/ui/locale/i18n/tests.rs @@ -51,6 +51,8 @@ fn templates_are_filled_and_every_dictionary_keeps_its_placeholders() { (text.manager_outdated_body, "found"), (text.manager_outdated_body, "bullet"), (text.manager_outdated_body, "required"), + (text.detail_manager_outdated, "found"), + (text.detail_manager_outdated, "required"), ] { assert!( template.contains(&format!("{{{key}}}")), diff --git a/crates/bullet-platform/src/ui/pages/overlay_model/tests.rs b/crates/bullet-platform/src/ui/pages/overlay_model/tests.rs index 9516724..dd4a6ed 100644 --- a/crates/bullet-platform/src/ui/pages/overlay_model/tests.rs +++ b/crates/bullet-platform/src/ui/pages/overlay_model/tests.rs @@ -36,6 +36,7 @@ fn catalog(skins: Vec) -> Catalog { notice: None, classic: false, lobby: Vec::new(), + party: Default::default(), } } diff --git a/crates/bullet-platform/src/ui/pages/overlay_window/mod.rs b/crates/bullet-platform/src/ui/pages/overlay_window/mod.rs index 271a314..9210ad2 100644 --- a/crates/bullet-platform/src/ui/pages/overlay_window/mod.rs +++ b/crates/bullet-platform/src/ui/pages/overlay_window/mod.rs @@ -58,6 +58,7 @@ struct Overlay { origin: Option, columns: usize, tiles: HashMap, + raw_previews: HashMap>, previews: HashMap, preview_for: Option, presets: PresetsView, @@ -151,7 +152,7 @@ impl OverlayController { } pub fn set_chroma_preview(&self, chroma_id: u32, image: Arc<[u8]>) { - self.post(move |overlay| overlay.deliver_preview(chroma_id, &image)); + self.post(move |overlay| overlay.deliver_raw_preview(chroma_id, image)); } pub fn click(&self, entry_id: u32) { diff --git a/crates/bullet-platform/src/ui/pages/overlay_window/render.rs b/crates/bullet-platform/src/ui/pages/overlay_window/render.rs index 43f6fe6..afcccee 100644 --- a/crates/bullet-platform/src/ui/pages/overlay_window/render.rs +++ b/crates/bullet-platform/src/ui/pages/overlay_window/render.rs @@ -18,6 +18,7 @@ impl Overlay { origin: None, columns: 1, tiles: HashMap::new(), + raw_previews: HashMap::new(), previews: HashMap::new(), preview_for: None, presets: PresetsView::default(), @@ -310,9 +311,15 @@ impl Overlay { self.view.set_preview_name(gem.name.clone()); self.view.set_preview_anchor_x(x); self.view.set_preview_anchor_y(y); - match self.previews.get(&id) { + let cached = self.previews.get(&id).cloned().or_else(|| { + let bytes = self.raw_previews.get(&id)?; + let image = runtime::image(bytes)?; + self.previews.insert(id, image.clone()); + Some(image) + }); + match cached { Some(image) => { - self.view.set_preview_image(image.clone()); + self.view.set_preview_image(image); self.view.set_preview_loading(false); } None => { @@ -329,7 +336,25 @@ impl Overlay { self.view.set_preview_visible(false); } + pub(super) fn deliver_raw_preview(&mut self, chroma_id: u32, bytes: Arc<[u8]>) { + if self.raw_previews.len() >= 512 && !self.raw_previews.contains_key(&chroma_id) { + if let Some(&evict) = self.raw_previews.keys().next() { + self.raw_previews.remove(&evict); + self.previews.remove(&evict); + } + } + self.raw_previews.insert(chroma_id, Arc::clone(&bytes)); + if self.preview_for == Some(chroma_id) { + self.decode_and_show_preview(chroma_id, &bytes); + } + } + + #[cfg(test)] pub(super) fn deliver_preview(&mut self, chroma_id: u32, bytes: &[u8]) { + self.deliver_raw_preview(chroma_id, Arc::from(bytes)); + } + + fn decode_and_show_preview(&mut self, chroma_id: u32, bytes: &[u8]) { let Some(image) = runtime::image(bytes) else { warn!( chroma_id, diff --git a/crates/bullet-platform/src/ui/pages/overlay_window/tests.rs b/crates/bullet-platform/src/ui/pages/overlay_window/tests.rs index 8819d5b..40889d1 100644 --- a/crates/bullet-platform/src/ui/pages/overlay_window/tests.rs +++ b/crates/bullet-platform/src/ui/pages/overlay_window/tests.rs @@ -104,6 +104,7 @@ pub(super) fn catalog() -> Catalog { notice: None, classic: false, lobby: Vec::new(), + party: Default::default(), } } @@ -241,3 +242,36 @@ fn the_party_line_shows_the_room_and_teammate_skins_and_goes_away_outside_a_part }); assert_eq!(view.get_party_line(), ""); } + +#[test] +fn chroma_previews_store_raw_bytes_across_catalogs_and_decode_lazily_on_hover() { + let (view, _commands) = open_overlay(); + let png_bytes: std::sync::Arc<[u8]> = + std::sync::Arc::from(include_bytes!("../../../../ui/assets/logo-56.png").as_slice()); + with_overlay(|overlay| { + overlay.deliver_raw_preview(238_070, png_bytes.clone()); + assert!(overlay.raw_previews.contains_key(&238_070)); + assert!( + !overlay.previews.contains_key(&238_070), + "raw bytes are not decoded eagerly when the chroma is not hovered" + ); + let gem = views::ChromaGem { + id: 238_070, + name: "Esmeralda".into(), + color: slint::Color::from_rgb_u8(0x40, 0xc0, 0xff), + form: false, + has_preview: true, + }; + overlay.show_preview(&gem, 100.0, 100.0); + assert!( + overlay.previews.contains_key(&238_070), + "hovering decodes and caches the image" + ); + overlay.set_catalog(catalog()); + assert!( + overlay.raw_previews.contains_key(&238_070), + "cached previews survive a catalog refresh" + ); + }); + assert!(view.get_preview_image().size().width > 0); +} diff --git a/crates/bullet-platform/src/ui/pages/panel/mod.rs b/crates/bullet-platform/src/ui/pages/panel/mod.rs index 3657278..838ad54 100644 --- a/crates/bullet-platform/src/ui/pages/panel/mod.rs +++ b/crates/bullet-platform/src/ui/pages/panel/mod.rs @@ -7,7 +7,7 @@ use slint::{ComponentHandle, ModelRc, VecModel}; use tracing::{debug, warn}; use super::runtime; -use super::views::{ControlPanel, PanelAction, PanelCheckRow, PanelLabels}; +use super::views::{ControlPanel, PanelAction, PanelCheckRow, PanelLabels, PanelSkinStatRow}; use crate::tray::TrayEvent; const REFRESH: Duration = Duration::from_millis(700); @@ -19,6 +19,22 @@ pub struct PanelCheck { pub detail: String, } +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PanelSkinStat { + pub name: String, + pub wins: u32, + pub losses: u32, + pub winrate: u8, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct PanelStats { + pub wins: u32, + pub losses: u32, + pub winrate: u8, + pub top: Vec, +} + #[derive(Debug, Clone, PartialEq, Eq)] pub struct PanelSnapshot { pub status: String, @@ -28,9 +44,11 @@ pub struct PanelSnapshot { pub injection: bool, pub random_skin: bool, pub light_loading: bool, + pub in_client_ui: bool, pub autostart: bool, pub update_line: Option, pub checks: Vec, + pub stats: PanelStats, } pub type SnapshotSource = Arc PanelSnapshot + Send + Sync>; @@ -56,6 +74,7 @@ pub(crate) fn event_for(action: PanelAction) -> TrayEvent { PanelAction::ToggleInjection => TrayEvent::ToggleInjection, PanelAction::ToggleRandomSkin => TrayEvent::ToggleRandomSkin, PanelAction::ToggleLightLoading => TrayEvent::ToggleLightLoading, + PanelAction::ToggleInClientUi => TrayEvent::ToggleInClientUi, PanelAction::ToggleAutoAccept => TrayEvent::ToggleAutoAccept, PanelAction::ToggleAutostart => TrayEvent::ToggleAutostart, PanelAction::PartyCreate => TrayEvent::PartyCreate, @@ -68,6 +87,9 @@ pub(crate) fn event_for(action: PanelAction) -> TrayEvent { PanelAction::OpenRelease => TrayEvent::OpenRelease, PanelAction::MarkProblem => TrayEvent::MarkProblem, PanelAction::ExportDiagnostics => TrayEvent::ExportDiagnostics, + PanelAction::RepairSkins => TrayEvent::RepairSkins, + PanelAction::RepairClient => TrayEvent::RepairClient, + PanelAction::OpenProject => TrayEvent::OpenProject, PanelAction::About => TrayEvent::About, PanelAction::Quit => TrayEvent::Quit, } @@ -92,6 +114,11 @@ pub(crate) fn labels(text: &crate::i18n::Text) -> PanelLabels { random_skin_hint: text.panel_random_skin_hint.into(), light_loading: text.menu_light_loading.into(), light_loading_hint: text.panel_light_loading_hint.into(), + in_client_ui: text.menu_in_client_ui.into(), + in_client_ui_hint: text.panel_in_client_ui_hint.into(), + mode_title: text.panel_mode_title.into(), + mode_window: text.panel_mode_window.into(), + mode_client: text.panel_mode_client.into(), auto_accept: text.menu_auto_accept.into(), autostart: text.menu_autostart.into(), party_create: text.menu_party_create.into(), @@ -102,11 +129,20 @@ pub(crate) fn labels(text: &crate::i18n::Text) -> PanelLabels { open_tools: text.folder_tools.into(), open_logs: text.folder_logs.into(), about: text.menu_about.into(), + open_project: text.panel_open_project.into(), + project_star_hint: text.panel_project_star_hint.into(), quit: text.menu_quit.into(), update_download: text.panel_update_download.into(), mark_problem: text.panel_mark_problem.into(), mark_problem_hint: text.panel_mark_problem_hint.into(), export_diagnostics: text.panel_export_diagnostics.into(), + repair_skins: text.panel_repair_skins.into(), + repair_client: text.panel_repair_client.into(), + stats_title: text.panel_stats_title.into(), + stats_empty: text.panel_stats_empty.into(), + stats_games: text.panel_stats_games.into(), + stats_wins_short: text.panel_stats_wins_short.into(), + stats_losses_short: text.panel_stats_losses_short.into(), } } @@ -127,6 +163,7 @@ pub(crate) fn render(window: &ControlPanel, state: &PanelSnapshot) { window.set_injection(state.injection); window.set_random_skin(state.random_skin); window.set_light_loading(state.light_loading); + window.set_in_client_ui(state.in_client_ui); window.set_auto_accept(state.auto_accept); window.set_autostart(state.autostart); window.set_update_line(state.update_line.as_deref().unwrap_or_default().into()); @@ -142,6 +179,25 @@ pub(crate) fn render(window: &ControlPanel, state: &PanelSnapshot) { }) .collect(); window.set_checks(ModelRc::new(VecModel::from(checks))); + window.set_stats_wins(i32::try_from(state.stats.wins).unwrap_or(i32::MAX)); + window.set_stats_losses(i32::try_from(state.stats.losses).unwrap_or(i32::MAX)); + window.set_stats_winrate(i32::from(state.stats.winrate)); + let t = crate::i18n::text(); + let rows: Vec = state + .stats + .top + .iter() + .map(|s| PanelSkinStatRow { + name: s.name.as_str().into(), + record: format!( + "{}{} / {}{}", + s.wins, t.panel_stats_wins_short, s.losses, t.panel_stats_losses_short + ) + .into(), + winrate: i32::from(s.winrate), + }) + .collect(); + window.set_stats_rows(ModelRc::new(VecModel::from(rows))); } pub fn show_panel(links: PanelLinks) { diff --git a/crates/bullet-platform/src/ui/pages/panel/tests.rs b/crates/bullet-platform/src/ui/pages/panel/tests.rs index 78e6404..83a041f 100644 --- a/crates/bullet-platform/src/ui/pages/panel/tests.rs +++ b/crates/bullet-platform/src/ui/pages/panel/tests.rs @@ -3,10 +3,11 @@ use crate::i18n::Language; use i_slint_backend_testing::ElementHandle; use slint::Model; -const ACTIONS: [PanelAction; 17] = [ +const ACTIONS: [PanelAction; 21] = [ PanelAction::ToggleInjection, PanelAction::ToggleRandomSkin, PanelAction::ToggleLightLoading, + PanelAction::ToggleInClientUi, PanelAction::ToggleAutoAccept, PanelAction::ToggleAutostart, PanelAction::PartyCreate, @@ -19,6 +20,9 @@ const ACTIONS: [PanelAction; 17] = [ PanelAction::OpenRelease, PanelAction::MarkProblem, PanelAction::ExportDiagnostics, + PanelAction::RepairSkins, + PanelAction::RepairClient, + PanelAction::OpenProject, PanelAction::About, PanelAction::Quit, ]; @@ -41,6 +45,7 @@ fn snapshot() -> PanelSnapshot { injection: true, random_skin: false, light_loading: true, + in_client_ui: false, autostart: false, update_line: Some("Bullet 1.3 is available".into()), checks: vec![ @@ -55,6 +60,7 @@ fn snapshot() -> PanelSnapshot { detail: "refused".into(), }, ], + stats: PanelStats::default(), } } @@ -88,12 +94,18 @@ fn every_language_fills_every_label() { ("injection", &labels.injection), ("random", &labels.random_skin), ("light", &labels.light_loading), + ("in client", &labels.in_client_ui), + ("mode title", &labels.mode_title), + ("mode window", &labels.mode_window), + ("mode client", &labels.mode_client), ("accept", &labels.auto_accept), ("autostart", &labels.autostart), ("create", &labels.party_create), ("join", &labels.party_join), ("leave", &labels.party_leave), ("about", &labels.about), + ("open project", &labels.open_project), + ("project star hint", &labels.project_star_hint), ("quit", &labels.quit), ("mark", &labels.mark_problem), ("export", &labels.export_diagnostics), @@ -201,6 +213,8 @@ fn every_button_and_toggle_of_the_panel_sends_its_own_action() { let clicks = [ (0, text.panel_update_download, PanelAction::OpenRelease), (0, text.menu_injection, PanelAction::ToggleInjection), + (0, text.panel_mode_client, PanelAction::ToggleInClientUi), + (0, text.panel_open_project, PanelAction::OpenProject), (1, text.menu_random_skin, PanelAction::ToggleRandomSkin), (1, text.menu_light_loading, PanelAction::ToggleLightLoading), (1, text.menu_auto_accept, PanelAction::ToggleAutoAccept), diff --git a/crates/bullet-platform/src/ui/pages/welcome/mod.rs b/crates/bullet-platform/src/ui/pages/welcome/mod.rs index a05a426..0d1d31f 100644 --- a/crates/bullet-platform/src/ui/pages/welcome/mod.rs +++ b/crates/bullet-platform/src/ui/pages/welcome/mod.rs @@ -13,6 +13,7 @@ pub(crate) struct WelcomeContent { pub pill: &'static str, pub items: Vec<&'static str>, pub dismiss: &'static str, + pub project: &'static str, } pub(crate) fn welcome_content(text: &crate::i18n::Text) -> WelcomeContent { @@ -25,6 +26,7 @@ pub(crate) fn welcome_content(text: &crate::i18n::Text) -> WelcomeContent { text.welcome_quote, ]), dismiss: text.welcome_dismiss, + project: text.panel_open_project, } } @@ -37,6 +39,7 @@ pub(crate) fn about_content(text: &crate::i18n::Text) -> WelcomeContent { text.about_quote, ]), dismiss: text.about_dismiss, + project: text.panel_open_project, } } @@ -64,6 +67,7 @@ pub(crate) fn fill(window: &WelcomeWindow, content: &WelcomeContent) { let items: Vec = content.items.iter().map(|item| (*item).into()).collect(); window.set_items(ModelRc::new(VecModel::from(items))); window.set_dismiss_label(content.dismiss.into()); + window.set_project_label(content.project.into()); } fn open(content: &WelcomeContent, auto_dismiss: Option) { @@ -82,6 +86,11 @@ fn open(content: &WelcomeContent, auto_dismiss: Option) { close(&window); } }); + window.on_open_project(|| { + if let Err(e) = crate::shell::open_web_page(crate::star_gate::REPOSITORY_URL) { + warn!(error = %e, "Could not open the GitHub repository page"); + } + }); if let Err(e) = window.show() { warn!(error = %e, "The welcome window could not be shown"); return; diff --git a/crates/bullet-platform/ui/panel/panel.slint b/crates/bullet-platform/ui/panel/panel.slint index aea8e18..9e25e6e 100644 --- a/crates/bullet-platform/ui/panel/panel.slint +++ b/crates/bullet-platform/ui/panel/panel.slint @@ -1,7 +1,9 @@ import { Theme, ExposeLayer, GoldButton, Wordmark, StatusDot, Halo } from "../theme.slint"; import { ScrollView } from "std-widgets.slint"; -import { PanelLabels, PanelCheckRow, PanelAction } from "panel_types.slint"; -import { Section, PanelTab, CheckRow, Toggle, Notice, PowerCard } from "panel_parts.slint"; +import { PanelLabels, PanelCheckRow, PanelSkinStatRow, PanelAction } from "panel_types.slint"; +import { Section, PanelTab, CheckRow, Toggle, Notice, PowerCard, AllClearBanner } from "panel_parts.slint"; +import { ModeCard } from "panel_mode.slint"; +import { StatsCard } from "panel_stats.slint"; export component ControlPanel inherits Window { in property expose-flip; @@ -11,62 +13,68 @@ export component ControlPanel inherits Window { in property in-room; in property random-skin; in property light-loading; + in property in-client-ui; in property injection; in property auto-accept; in property autostart; in property update-line; in property attention; in property <[PanelCheckRow]> checks; + in property stats-wins; + in property stats-losses; + in property stats-winrate; + in property <[PanelSkinStatRow]> stats-rows; in-out property tab; callback action(PanelAction); title: "Bullet"; icon: @image-url("../assets/logo.png"); - preferred-width: 460px; - preferred-height: 640px; - min-width: 380px; - min-height: 420px; + preferred-width: 480px; + preferred-height: 600px; + min-width: 400px; + min-height: 440px; background: Theme.backdrop; default-font-family: Theme.sans; VerticalLayout { Rectangle { vertical-stretch: 0; - min-height: 96px; + min-height: 92px; Halo { - x: -50px; - y: -54px; + x: -44px; + y: -52px; } HorizontalLayout { padding-left: 22px; padding-right: 22px; - padding-top: 22px; - padding-bottom: 18px; + padding-top: 20px; + padding-bottom: 16px; spacing: 16px; Image { source: @image-url("../assets/logo-56.png"); - width: 56px; - height: 56px; + width: 52px; + height: 52px; } VerticalLayout { alignment: center; - spacing: 5px; + spacing: 4px; Wordmark { version: root.labels.version; - size: 11px; + size: 12px; } HorizontalLayout { - spacing: 9px; + spacing: 8px; alignment: start; VerticalLayout { - alignment: start; - padding-top: 9px; - StatusDot { } + alignment: center; + StatusDot { + online: root.injection && root.attention == 0; + } } Text { text: root.status; color: Theme.gold-bright; font-family: Theme.serif; - font-size: 18px; + font-size: 17px; font-weight: 700; wrap: word-wrap; horizontal-stretch: 1; @@ -80,43 +88,48 @@ export component ControlPanel inherits Window { padding-left: 20px; padding-right: 20px; track := Rectangle { - height: 42px; - border-radius: 11px; + height: 44px; + border-radius: 12px; border-width: 1px; border-color: Theme.surface-line; - background: #0a111c; + background: #09101b; Rectangle { y: 4px; height: parent.height - 8px; - border-radius: 8px; + border-radius: 9px; border-width: 1px; border-color: Theme.gold-dim; - background: @linear-gradient(180deg, #2a3850 0%, #1c2839 100%); - x: root.tab == 0 ? home.x : root.tab == 1 ? options.x : root.tab == 2 ? party.x : help.x; - width: root.tab == 0 ? home.width : root.tab == 1 ? options.width : root.tab == 2 ? party.width : help.width; - animate x, width { duration: 260ms; easing: ease-out-quart; } + background: @linear-gradient(180deg, #273750 0%, #192538 100%); + x: root.tab == 0 ? home.x : root.tab == 1 ? skins.x : root.tab == 2 ? party.x : support.x; + width: root.tab == 0 ? home.width : root.tab == 1 ? skins.width : root.tab == 2 ? party.width : support.width; + animate x, width { duration: 240ms; easing: ease-out-quart; } } - tabs := HorizontalLayout { + HorizontalLayout { padding: 4px; spacing: 2px; home := PanelTab { text: root.labels.tab-home; + icon: "M 2 7.5 L 8 2.5 L 14 7.5 M 4 6.5 L 4 13.5 L 12 13.5 L 12 6.5"; active: root.tab == 0; clicked => { root.tab = 0; } } - options := PanelTab { + skins := PanelTab { text: root.labels.tab-options; + icon: "M 8 2 L 14 5.5 L 8 9 L 2 5.5 Z M 2 9 L 8 12.5 L 14 9"; active: root.tab == 1; clicked => { root.tab = 1; } } party := PanelTab { text: root.labels.tab-party; + icon: "M 6 7 A 2.5 2.5 0 1 1 5.99 7 Z M 11.5 7.5 A 2 2 0 1 1 11.49 7.5 Z M 2 13.5 C 2 11 3.8 9.8 6 9.8 C 8.2 9.8 10 11 10 13.5 M 10 10.5 C 12 10.5 14 11.4 14 13.5"; active: root.tab == 2; clicked => { root.tab = 2; } } - help := PanelTab { + support := PanelTab { text: root.labels.tab-help; + icon: "M 8 2 L 13.5 4.2 L 13.5 8.5 C 13.5 11.4 11.1 13.2 8 14.2 C 4.9 13.2 2.5 11.4 2.5 8.5 L 2.5 4.2 Z"; active: root.tab == 3; + badge: root.attention; clicked => { root.tab = 3; } } } @@ -146,18 +159,33 @@ export component ControlPanel inherits Window { action: root.labels.see-diagnostics; activated => { root.tab = 3; } } - if root.update-line == "" && root.attention == 0: Text { - text: root.labels.all-clear; - color: Theme.muted; - font-size: Theme.text-base; - wrap: word-wrap; - } PowerCard { label: root.labels.injection; hint: root.labels.injection-hint; checked: root.injection; toggled => { root.action(PanelAction.toggle-injection); } } + ModeCard { + heading: root.labels.mode-title; + window-label: root.labels.mode-window; + client-label: root.labels.mode-client; + in-client: root.in-client-ui; + toggled => { root.action(PanelAction.toggle-in-client-ui); } + } + StatsCard { + heading: root.labels.stats-title; + empty-text: root.labels.stats-empty; + games-suffix: root.labels.stats-games; + wins-short: root.labels.stats-wins-short; + losses-short: root.labels.stats-losses-short; + wins: root.stats-wins; + losses: root.stats-losses; + winrate: root.stats-winrate; + rows: root.stats-rows; + } + if root.update-line == "" && root.attention == 0: AllClearBanner { + text: root.labels.all-clear; + } } if root.tab == 1: Section { Toggle { @@ -185,23 +213,39 @@ export component ControlPanel inherits Window { } } if root.tab == 2: Section { - Text { - text: root.party-line != "" ? root.party-line : root.labels.party-hint; - color: root.party-line != "" ? Theme.gold-bright : Theme.muted; - font-size: Theme.text-base; + HorizontalLayout { + spacing: 10px; + alignment: start; + VerticalLayout { + alignment: center; + StatusDot { + online: root.in-room; + } + } + Text { + text: root.party-line != "" ? root.party-line : root.labels.party-hint; + color: root.party-line != "" ? Theme.gold-bright : Theme.muted; + font-size: Theme.text-base; + font-weight: root.party-line != "" ? 600 : 400; + wrap: word-wrap; + horizontal-stretch: 1; + } + } + if root.party-line != "": Text { + text: root.labels.party-hint; + color: Theme.muted; + font-size: Theme.text-sm; wrap: word-wrap; } if !root.in-room: HorizontalLayout { spacing: 8px; GoldButton { text: root.labels.party-create; - hug: true; primary: true; clicked => { root.action(PanelAction.party-create); } } GoldButton { text: root.labels.party-join; - hug: true; clicked => { root.action(PanelAction.party-join); } } } @@ -216,7 +260,7 @@ export component ControlPanel inherits Window { Section { heading: root.labels.section-diagnostics; VerticalLayout { - spacing: 10px; + spacing: 8px; for check in root.checks: CheckRow { check: check; } @@ -231,6 +275,17 @@ export component ControlPanel inherits Window { font-size: Theme.text-sm; wrap: word-wrap; } + HorizontalLayout { + spacing: 8px; + GoldButton { + text: root.labels.repair-skins; + clicked => { root.action(PanelAction.repair-skins); } + } + GoldButton { + text: root.labels.repair-client; + clicked => { root.action(PanelAction.repair-client); } + } + } HorizontalLayout { spacing: 8px; GoldButton { @@ -239,6 +294,7 @@ export component ControlPanel inherits Window { } GoldButton { text: root.labels.export-diagnostics; + primary: true; clicked => { root.action(PanelAction.export-diagnostics); } } } @@ -273,8 +329,8 @@ export component ControlPanel inherits Window { } if -scroll.content-y + scroll.visible-height < scroll.content-height - 2px: Rectangle { y: parent.height - self.height; - height: 36px; - background: @linear-gradient(180deg, #060a1200 0%, #060a12f2 100%); + height: 32px; + background: @linear-gradient(180deg, #060a1000 0%, #060a10f2 100%); } } Rectangle { @@ -295,6 +351,12 @@ export component ControlPanel inherits Window { horizontal-stretch: 0; clicked => { root.action(PanelAction.about); } } + GoldButton { + text: root.labels.open-project; + hug: true; + horizontal-stretch: 0; + clicked => { root.action(PanelAction.open-project); } + } Rectangle { horizontal-stretch: 1; } diff --git a/crates/bullet-platform/ui/panel/panel_mode.slint b/crates/bullet-platform/ui/panel/panel_mode.slint new file mode 100644 index 0000000..35f3b6b --- /dev/null +++ b/crates/bullet-platform/ui/panel/panel_mode.slint @@ -0,0 +1,109 @@ +import { Theme, Surface } from "../theme.slint"; + +component ModeOption inherits Rectangle { + in property label; + in property icon; + in property selected; + callback picked(); + property hot: touch.has-hover; + property focused: keys.has-focus; + horizontal-stretch: 1; + min-height: 54px; + border-radius: 10px; + border-width: root.focused ? 2px : 1px; + border-color: root.focused ? Theme.gold-bright : root.selected ? Theme.gold : root.hot ? Theme.control-line : Theme.surface-line; + background: root.selected ? @linear-gradient(180deg, #2a2417 0%, #172233 100%) : root.hot ? #192436 : #0e1623; + drop-shadow-blur: root.selected ? 10px : 0px; + drop-shadow-color: Theme.gold.with-alpha(0.22); + animate border-color, background, drop-shadow-blur { duration: 160ms; } + HorizontalLayout { + padding-left: 12px; + padding-right: 12px; + spacing: 10px; + alignment: center; + VerticalLayout { + alignment: center; + Path { + width: 16px; + height: 16px; + viewbox-width: 16; + viewbox-height: 16; + stroke: root.selected ? Theme.gold-bright : root.hot ? Theme.text : Theme.muted; + stroke-width: 1.5px; + fill: transparent; + commands: root.icon; + animate stroke { duration: 150ms; } + } + } + Text { + text: root.label; + color: root.selected ? Theme.gold-bright : root.hot ? Theme.text : Theme.muted; + font-size: Theme.text-md; + font-weight: root.selected ? 700 : 500; + vertical-alignment: center; + wrap: word-wrap; + animate color { duration: 150ms; } + } + } + keys := FocusScope { + key-pressed(event) => { + if event.text == " " || event.text == Key.Return { + root.picked(); + return accept; + } + reject + } + } + touch := TouchArea { + mouse-cursor: pointer; + clicked => { root.picked(); } + } + accessible-role: button; + accessible-label: root.label; + accessible-checkable: true; + accessible-checked: root.selected; + accessible-action-default => { root.picked(); } +} + +export component ModeCard inherits Surface { + in property heading; + in property window-label; + in property client-label; + in property in-client; + callback toggled(); + border-radius: 14px; + VerticalLayout { + padding: 14px; + spacing: 10px; + Text { + text: root.heading; + color: Theme.gold; + font-size: Theme.text-sm; + font-weight: 700; + letter-spacing: 0.6px; + } + HorizontalLayout { + spacing: 8px; + ModeOption { + label: root.window-label; + icon: "M 2 3 L 14 3 L 14 13 L 2 13 Z M 2 6 L 14 6"; + selected: !root.in-client; + picked => { + if root.in-client { + root.toggled(); + } + } + } + ModeOption { + label: root.client-label; + icon: "M 5 3.5 L 11 3.5 L 11 12.5 L 5 12.5 Z M 1.5 5.5 L 3.5 5.5 L 3.5 10.5 L 1.5 10.5 Z M 12.5 5.5 L 14.5 5.5 L 14.5 10.5 L 12.5 10.5 Z"; + selected: root.in-client; + picked => { + if !root.in-client { + root.toggled(); + } + } + } + } + } +} diff --git a/crates/bullet-platform/ui/panel/panel_parts.slint b/crates/bullet-platform/ui/panel/panel_parts.slint index 671c8f7..8129ea2 100644 --- a/crates/bullet-platform/ui/panel/panel_parts.slint +++ b/crates/bullet-platform/ui/panel/panel_parts.slint @@ -1,8 +1,9 @@ -import { Theme, GoldButton, Switch, Surface } from "../theme.slint"; +import { Theme, GoldButton, Switch, Surface, CheckGlyph } from "../theme.slint"; import { PanelCheckRow } from "panel_types.slint"; export component Section inherits Surface { in property heading; + border-radius: 14px; VerticalLayout { padding-top: 14px; padding-bottom: 14px; @@ -11,9 +12,10 @@ export component Section inherits Surface { spacing: 10px; if root.heading != "": Text { text: root.heading; - color: Theme.gold-bright; - font-size: Theme.text-base; - font-weight: 600; + color: Theme.gold; + font-size: Theme.text-sm; + font-weight: 700; + letter-spacing: 0.6px; } @children } @@ -21,19 +23,70 @@ export component Section inherits Surface { export component PanelTab inherits Rectangle { in property text; + in property icon; in property active; + in property badge; callback clicked(); - min-width: label.preferred-width + 16px; + property focused: keys.has-focus; + min-width: row.preferred-width + 16px; horizontal-stretch: 1; - height: 32px; - label := Text { - text: root.text; - color: root.active ? Theme.gold-bright : touch.has-hover ? Theme.text : Theme.muted; - font-size: Theme.text-base; - font-weight: root.active ? 600 : 400; - horizontal-alignment: center; - vertical-alignment: center; - animate color { duration: 160ms; } + height: 36px; + border-radius: 9px; + border-width: root.focused ? 2px : 0px; + border-color: Theme.gold-bright; + row := HorizontalLayout { + alignment: center; + spacing: 6px; + padding-left: 8px; + padding-right: 8px; + if root.icon != "": VerticalLayout { + alignment: center; + Path { + width: 13px; + height: 13px; + viewbox-width: 16; + viewbox-height: 16; + stroke: root.active ? Theme.gold-bright : touch.has-hover ? Theme.text : Theme.muted; + stroke-width: 1.5px; + fill: transparent; + commands: root.icon; + animate stroke { duration: 150ms; } + } + } + Text { + text: root.text; + color: root.active ? Theme.gold-bright : touch.has-hover ? Theme.text : Theme.muted; + font-size: Theme.text-md; + font-weight: root.active ? 700 : 500; + vertical-alignment: center; + animate color { duration: 150ms; } + } + if root.badge > 0: VerticalLayout { + alignment: center; + Rectangle { + min-width: 16px; + height: 16px; + border-radius: 8px; + background: Theme.danger; + Text { + text: root.badge; + color: #ffffff; + font-size: 10px; + font-weight: 700; + horizontal-alignment: center; + vertical-alignment: center; + } + } + } + } + keys := FocusScope { + key-pressed(event) => { + if event.text == " " || event.text == Key.Return { + root.clicked(); + return accept; + } + reject + } } touch := TouchArea { mouse-cursor: pointer; @@ -46,7 +99,15 @@ export component PanelTab inherits Rectangle { export component CheckRow inherits Rectangle { in property check; + border-radius: 9px; + background: root.check.ok ? #0f1927 : #24151a; + border-width: 1px; + border-color: root.check.ok ? #1f2e42 : #5a2a30; HorizontalLayout { + padding-top: 9px; + padding-bottom: 9px; + padding-left: 12px; + padding-right: 12px; spacing: 10px; VerticalLayout { alignment: start; @@ -56,15 +117,18 @@ export component CheckRow inherits Rectangle { height: 8px; border-radius: 4px; background: root.check.ok ? Theme.cyan : Theme.danger; + drop-shadow-blur: 4px; + drop-shadow-color: root.check.ok ? Theme.cyan.with-alpha(0.55) : Theme.danger.with-alpha(0.55); } } VerticalLayout { alignment: start; - spacing: 1px; + spacing: 2px; Text { text: root.check.label; color: Theme.text; font-size: Theme.text-base; + font-weight: 600; wrap: word-wrap; } Text { @@ -83,21 +147,26 @@ export component Toggle inherits Rectangle { in property checked; in property divider: true; callback toggled(); - border-radius: 8px; - background: touch.has-hover ? #ffffff07 : #ffffff00; - animate background { duration: 120ms; } + property focused: keys.has-focus; + border-radius: 10px; + border-width: root.focused ? 2px : 0px; + border-color: Theme.gold-bright; + background: touch.has-hover ? #ffffff09 : #ffffff00; + animate background { duration: 130ms; } VerticalLayout { if root.divider: Rectangle { height: 1px; background: Theme.surface-line; } HorizontalLayout { - padding-top: 10px; - padding-bottom: 10px; + padding-top: 11px; + padding-bottom: 11px; + padding-left: 6px; + padding-right: 6px; spacing: 14px; VerticalLayout { - alignment: start; - spacing: 3px; + alignment: center; + spacing: 2px; Text { text: root.label; color: Theme.text; @@ -113,19 +182,29 @@ export component Toggle inherits Rectangle { } } VerticalLayout { - alignment: start; + alignment: center; Switch { checked: root.checked; } } } } + keys := FocusScope { + key-pressed(event) => { + if event.text == " " || event.text == Key.Return { + root.toggled(); + return accept; + } + reject + } + } touch := TouchArea { mouse-cursor: pointer; clicked => { root.toggled(); } } accessible-role: switch; accessible-label: root.label; + accessible-description: root.hint; accessible-checkable: true; accessible-checked: root.checked; accessible-action-default => { root.toggled(); } @@ -136,27 +215,32 @@ export component PowerCard inherits Rectangle { in property hint; in property checked; callback toggled(); - border-radius: 14px; - border-width: 1px; - border-color: root.checked ? Theme.gold-dim : Theme.surface-line; - background: root.checked ? @linear-gradient(180deg, #2a2619 0%, #18202b 60%, #131b27 100%) : @linear-gradient(180deg, #161f2d 0%, #111925 100%); - animate border-color { duration: 200ms; } + property focused: keys.has-focus; + border-radius: 16px; + border-width: root.focused ? 2px : 1px; + border-color: root.focused ? Theme.gold-bright : root.checked ? Theme.gold-dim : Theme.surface-line; + background: root.checked ? @linear-gradient(135deg, #272216 0%, #152132 58%, #101926 100%) : @linear-gradient(180deg, #161f2e 0%, #101824 100%); + drop-shadow-blur: root.checked ? 14px : 0px; + drop-shadow-color: Theme.gold.with-alpha(0.16); + animate border-color, drop-shadow-blur { duration: 180ms; } Rectangle { x: 0; - y: 14px; - width: 3px; - height: parent.height - 28px; - border-radius: 1.5px; + y: 16px; + width: 3.5px; + height: parent.height - 32px; + border-radius: 2px; background: root.checked ? Theme.gold : Theme.control-line; - animate background { duration: 200ms; } + animate background { duration: 180ms; } } HorizontalLayout { - padding: 18px; + padding-top: 18px; + padding-bottom: 18px; padding-left: 20px; + padding-right: 18px; spacing: 16px; VerticalLayout { alignment: center; - spacing: 5px; + spacing: 4px; Text { text: root.label; color: Theme.gold-bright; @@ -180,46 +264,96 @@ export component PowerCard inherits Rectangle { } } } + keys := FocusScope { + key-pressed(event) => { + if event.text == " " || event.text == Key.Return { + root.toggled(); + return accept; + } + reject + } + } TouchArea { mouse-cursor: pointer; clicked => { root.toggled(); } } accessible-role: switch; accessible-label: root.label; + accessible-description: root.hint; accessible-checkable: true; accessible-checked: root.checked; accessible-action-default => { root.toggled(); } } +export component AllClearBanner inherits Rectangle { + in property text; + border-radius: 12px; + border-width: 1px; + border-color: #194545; + background: #0d1e24; + HorizontalLayout { + padding-top: 11px; + padding-bottom: 11px; + padding-left: 14px; + padding-right: 14px; + spacing: 10px; + VerticalLayout { + alignment: center; + Rectangle { + width: 20px; + height: 20px; + border-radius: 10px; + background: Theme.cyan.with-alpha(0.18); + CheckGlyph { + x: 5px; + y: 5px; + stroke: Theme.cyan; + } + } + } + Text { + text: root.text; + color: Theme.text; + font-size: Theme.text-base; + wrap: word-wrap; + vertical-alignment: center; + } + } +} + export component Notice inherits Rectangle { in property line; in property action; in property warning; callback activated(); - border-radius: 10px; + border-radius: 12px; border-width: 1px; - border-color: root.warning ? Theme.danger : Theme.gold-dim; - background: root.warning ? #22161a : #1a1912; + border-color: root.warning ? #7c3037 : Theme.gold-dim; + background: root.warning ? #241419 : #1c1910; Rectangle { x: 0; + y: 10px; width: 3px; + height: parent.height - 20px; border-radius: 1.5px; background: root.warning ? Theme.danger : Theme.gold; } - VerticalLayout { + HorizontalLayout { padding-top: 12px; padding-bottom: 12px; padding-left: 16px; padding-right: 14px; - spacing: 10px; + spacing: 12px; Text { text: root.line; color: Theme.gold-bright; font-size: Theme.text-base; wrap: word-wrap; + vertical-alignment: center; + horizontal-stretch: 1; } - if root.action != "": HorizontalLayout { - alignment: start; + if root.action != "": VerticalLayout { + alignment: center; GoldButton { text: root.action; primary: !root.warning; diff --git a/crates/bullet-platform/ui/panel/panel_stats.slint b/crates/bullet-platform/ui/panel/panel_stats.slint new file mode 100644 index 0000000..b480142 --- /dev/null +++ b/crates/bullet-platform/ui/panel/panel_stats.slint @@ -0,0 +1,141 @@ +import { Theme } from "../theme.slint"; +import { PanelSkinStatRow } from "panel_types.slint"; + +export component StatsCard inherits Rectangle { + in property heading; + in property empty-text; + in property games-suffix; + in property wins-short; + in property losses-short; + in property wins: 0; + in property losses: 0; + in property winrate: 0; + in property <[PanelSkinStatRow]> rows: []; + + property total: root.wins + root.losses; + property positive: root.winrate >= 50; + + border-radius: 12px; + background: Theme.surface; + border-width: 1px; + border-color: Theme.surface-line; + + VerticalLayout { + padding: 14px; + spacing: 10px; + + HorizontalLayout { + alignment: space-between; + Text { + text: root.heading; + color: Theme.gold-bright; + font-size: Theme.text-xs; + font-weight: 700; + letter-spacing: 0.9px; + vertical-alignment: center; + } + if root.total > 0: Text { + text: root.total + " " + root.games-suffix; + color: Theme.muted; + font-size: Theme.text-xs; + vertical-alignment: center; + } + } + + if root.total == 0: Text { + text: root.empty-text; + color: Theme.muted; + font-size: Theme.text-sm; + wrap: word-wrap; + } + + if root.total > 0: VerticalLayout { + spacing: 8px; + + HorizontalLayout { + spacing: 12px; + alignment: start; + Text { + text: root.winrate + "%"; + color: root.positive ? Theme.cyan : Theme.danger-text; + font-size: Theme.text-xl; + font-weight: 700; + vertical-alignment: center; + } + VerticalLayout { + alignment: center; + spacing: 2px; + HorizontalLayout { + spacing: 6px; + Text { + text: root.wins + root.wins-short; + color: Theme.cyan; + font-size: Theme.text-sm; + font-weight: 700; + } + Text { + text: "/"; + color: Theme.muted; + font-size: Theme.text-sm; + } + Text { + text: root.losses + root.losses-short; + color: Theme.danger-text; + font-size: Theme.text-sm; + font-weight: 700; + } + } + } + } + + Rectangle { + height: 6px; + border-radius: 3px; + background: #3b1e24; + clip: true; + + Rectangle { + x: 0; + y: 0; + height: parent.height; + width: parent.width * clamp(root.winrate, 0, 100) / 100; + border-radius: 3px; + background: Theme.cyan; + } + } + + if root.rows.length > 0: Rectangle { + height: 1px; + background: Theme.surface-line; + } + + for row in root.rows: HorizontalLayout { + spacing: 8px; + Text { + text: row.name; + color: Theme.text; + font-size: Theme.text-sm; + font-weight: 500; + overflow: elide; + horizontal-stretch: 1; + vertical-alignment: center; + } + Text { + text: row.record; + color: Theme.muted; + font-size: Theme.text-xs; + vertical-alignment: center; + } + Text { + text: row.winrate + "%"; + color: row.winrate >= 50 ? Theme.cyan : Theme.danger-text; + font-size: Theme.text-xs; + font-weight: 700; + min-width: 32px; + horizontal-alignment: right; + vertical-alignment: center; + } + } + } + } +} diff --git a/crates/bullet-platform/ui/panel/panel_types.slint b/crates/bullet-platform/ui/panel/panel_types.slint index 491ded7..7bda5a1 100644 --- a/crates/bullet-platform/ui/panel/panel_types.slint +++ b/crates/bullet-platform/ui/panel/panel_types.slint @@ -16,6 +16,11 @@ export struct PanelLabels { random-skin-hint: string, light-loading: string, light-loading-hint: string, + in-client-ui: string, + in-client-ui-hint: string, + mode-title: string, + mode-window: string, + mode-client: string, auto-accept: string, autostart: string, party-create: string, @@ -26,11 +31,26 @@ export struct PanelLabels { open-tools: string, open-logs: string, about: string, + open-project: string, + project-star-hint: string, quit: string, update-download: string, mark-problem: string, mark-problem-hint: string, export-diagnostics: string, + repair-skins: string, + repair-client: string, + stats-title: string, + stats-empty: string, + stats-games: string, + stats-wins-short: string, + stats-losses-short: string, +} + +export struct PanelSkinStatRow { + name: string, + record: string, + winrate: int, } export struct PanelCheckRow { @@ -43,6 +63,7 @@ export enum PanelAction { toggle-injection, toggle-random-skin, toggle-light-loading, + toggle-in-client-ui, toggle-auto-accept, toggle-autostart, party-create, @@ -55,6 +76,9 @@ export enum PanelAction { open-release, mark-problem, export-diagnostics, + repair-skins, + repair-client, + open-project, about, quit, } diff --git a/crates/bullet-platform/ui/theme.slint b/crates/bullet-platform/ui/theme.slint index e839918..9322215 100644 --- a/crates/bullet-platform/ui/theme.slint +++ b/crates/bullet-platform/ui/theme.slint @@ -1,33 +1,33 @@ export global Theme { - out property bg-0: #05080c; - out property bg-1: #0a1428; - out property bg-2: #0e1c2e; - out property panel: #10161f; - out property card: #1a2230; - out property card-hover: #202a3b; - out property line: #2a3542; - out property line-gold: #4a3d22; - out property gold: #c8aa6e; - out property gold-bright: #f0e6d2; - out property gold-dim: #785a28; - out property cyan: #0ac8b9; - out property text: #f0e6d2; - out property muted: #a09b8c; - out property muted-dim: #85817a; - out property control-line: #5a6a82; - out property button-line: #9b7b45; - out property danger: #c24b4b; - out property danger-text: #e8a0a0; - out property surface: #141c28; - out property surface-hover: #1a2436; - out property surface-line: #243040; - out property button: #0f1622; - out property input: #09121d; - out property backdrop: @linear-gradient(180deg, #0a1428 0%, #070d18 45%, #05080c 100%); - out property header: @linear-gradient(180deg, #0e1c2e 0%, #10161f 100%); - out property card-fill: @linear-gradient(180deg, #1a2230 0%, #10161f 100%); - out property card-fill-hover: @linear-gradient(180deg, #202a3b 0%, #10161f 100%); - out property card-fill-selected: @linear-gradient(180deg, #2c2a25 0%, #1a2230 100%); + out property bg-0: #060a10; + out property bg-1: #0b1320; + out property bg-2: #101b2d; + out property panel: #0e1520; + out property card: #172131; + out property card-hover: #1e2b40; + out property line: #263448; + out property line-gold: #4d3f23; + out property gold: #d2b26e; + out property gold-bright: #f5ecd8; + out property gold-dim: #8a6a30; + out property cyan: #18d4c4; + out property text: #f2ead8; + out property muted: #b4afa1; + out property muted-dim: #929089; + out property control-line: #52647d; + out property button-line: #7a6337; + out property danger: #d65454; + out property danger-text: #f3b1b1; + out property surface: #121b29; + out property surface-hover: #192538; + out property surface-line: #233146; + out property button: #121b2a; + out property input: #08101a; + out property backdrop: @linear-gradient(180deg, #0b1424 0%, #080f1a 52%, #060a10 100%); + out property header: @linear-gradient(180deg, #101c2f 0%, #0d1522 100%); + out property card-fill: @linear-gradient(180deg, #182334 0%, #101824 100%); + out property card-fill-hover: @linear-gradient(180deg, #202d42 0%, #131c2b 100%); + out property card-fill-selected: @linear-gradient(180deg, #2d2920 0%, #182231 100%); out property sans: "Segoe UI"; out property serif: "Georgia"; out property text-xs: 10px; diff --git a/crates/bullet-platform/ui/welcome.slint b/crates/bullet-platform/ui/welcome.slint index 5ba071a..884c627 100644 --- a/crates/bullet-platform/ui/welcome.slint +++ b/crates/bullet-platform/ui/welcome.slint @@ -6,7 +6,9 @@ export component WelcomeWindow inherits Window { in property pill; in property <[string]> items; in property dismiss-label; + in property project-label; callback dismiss(); + callback open-project(); property shown; title: "Bullet — League of Legends Skin Changer"; icon: @image-url("assets/logo.png"); @@ -131,8 +133,9 @@ export component WelcomeWindow inherits Window { } HorizontalLayout { alignment: center; + spacing: 12px; GoldButton { - width: 230px; + width: 190px; min-height: 40px; horizontal-stretch: 0; primary: true; @@ -140,6 +143,14 @@ export component WelcomeWindow inherits Window { text: root.dismiss-label; clicked => { root.dismiss(); } } + if root.project-label != "": GoldButton { + hug: true; + min-height: 40px; + horizontal-stretch: 0; + font-size: Theme.text-base; + text: root.project-label; + clicked => { root.open-project(); } + } } } diff --git a/crates/bullet-wad/tests/property_fuzz_tests.rs b/crates/bullet-wad/tests/property_fuzz_tests.rs new file mode 100644 index 0000000..e095fa3 --- /dev/null +++ b/crates/bullet-wad/tests/property_fuzz_tests.rs @@ -0,0 +1,174 @@ +use std::path::PathBuf; +use std::time::Instant; + +use bullet_wad::hash::{prop_key_hash, wad_path_hash}; +use bullet_wad::prop::{ + PropEntry, PropFile, parse_prop_file, parse_prop_header, parse_prop_links, serialize_prop_file, +}; +use bullet_wad::wad::WadFile; +use bullet_wad::writer::{WadWriter, optimal_raw}; + +struct TempDir(PathBuf); + +impl TempDir { + fn new(tag: &str) -> Self { + let dir = std::env::temp_dir().join(format!( + "bullet_wad_fuzz_{tag}_{}_{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()) + )); + std::fs::create_dir_all(&dir).expect("create temp dir"); + Self(dir) + } + + fn path(&self) -> &std::path::Path { + &self.0 + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); // ignore-ok: best-effort test cleanup + } +} + +struct XorShift64(u64); + +impl XorShift64 { + fn next_u64(&mut self) -> u64 { + let mut x = self.0; + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + self.0 = x; + x + } + + fn next_bytes(&mut self, len: usize) -> Vec { + let mut out = Vec::with_capacity(len); + for _ in 0..len { + out.push((self.next_u64() & 0xFF) as u8); + } + out + } +} + +#[test] +fn property_wad_roundtrip_preserves_every_payload_verbatim() { + let mut rng = XorShift64(0x9E37_79B9_7F4A_7C15); + let dir = TempDir::new("roundtrip"); + + for case in 0..25u32 { + let count = ((rng.next_u64() % 24) + 1) as usize; + let mut entries = Vec::with_capacity(count); + let mut writer = WadWriter::default(); + for i in 0..count { + let path = format!("data/test/case_{case}/entry_{i}.bin"); + let size = (rng.next_u64() % 2048) as usize; + let data = if i % 3 == 0 { + vec![(i as u8).wrapping_mul(17); size] + } else { + rng.next_bytes(size) + }; + let hash = wad_path_hash(&path); + writer.insert(hash, optimal_raw(data.clone()).expect("encode")); + entries.push((hash, data)); + } + + let wad_path = dir.path().join(format!("case_{case}.wad.client")); + writer + .write_to_file(&wad_path, &|| false) + .expect("write wad"); + + let opened = WadFile::open(&wad_path).expect("open wad"); + for (hash, expected) in &entries { + let actual = opened.read(*hash).expect("read ok").expect("entry present"); + assert_eq!(&actual, expected); + } + } +} + +#[test] +fn fuzz_malformed_wad_and_prop_buffers_never_panic() { + let mut rng = XorShift64(0xD1B5_4A32_D192_ED03); + let dir = TempDir::new("fuzz"); + let scratch = dir.path().join("fuzz.wad.client"); + + let valid_prop = serialize_prop_file(&PropFile { + version: 2, + links: vec!["characters/zed/skins/skin0.bin".into()], + entries: vec![PropEntry { + class_hash: prop_key_hash("SkinCharacterDataProperties"), + key_hash: prop_key_hash("Characters/Zed/Skins/Skin0"), + body: vec![0, 0, 0, 0], + }], + }) + .expect("valid prop"); + + for iter in 0..1000u32 { + let mut buf = if iter % 4 == 0 { + let mut copy = valid_prop.clone(); + let flips = ((rng.next_u64() % 6) + 1) as usize; + for _ in 0..flips { + let idx = (rng.next_u64() as usize) % copy.len().max(1); + copy[idx] ^= ((rng.next_u64() % 255) + 1) as u8; + } + if iter % 8 == 0 && copy.len() > 2 { + copy.truncate((rng.next_u64() as usize) % copy.len()); + } + copy + } else { + let len = (rng.next_u64() % 512) as usize; + rng.next_bytes(len) + }; + + let _ = parse_prop_header(&buf); // ignore-ok: fuzz test asserts no panic + let _ = parse_prop_links(&buf); // ignore-ok: fuzz test asserts no panic + let _ = parse_prop_file(&buf); // ignore-ok: fuzz test asserts no panic + + if iter % 5 == 0 { + if buf.len() >= 3 && iter % 10 == 0 { + buf[0] = b'R'; + buf[1] = b'W'; + buf[2] = 3; + } + std::fs::write(&scratch, &buf).expect("write scratch"); + if let Ok(wad) = WadFile::open(&scratch) { + let _ = wad.read(rng.next_u64()); // ignore-ok: fuzz test asserts no panic + } + } + } +} + +#[test] +fn performance_256_entry_wad_write_and_read_stays_fast() { + let dir = TempDir::new("perf"); + let wad_path = dir.path().join("perf.wad.client"); + let mut writer = WadWriter::default(); + let mut hashes = Vec::with_capacity(256); + for i in 0..256u32 { + let hash = wad_path_hash(&format!("data/perf/item_{i}.bin")); + writer.insert( + hash, + optimal_raw(vec![(i % 251) as u8; 1024]).expect("encode"), + ); + hashes.push(hash); + } + + let start = Instant::now(); + writer + .write_to_file(&wad_path, &|| false) + .expect("write perf wad"); + let wad = WadFile::open(&wad_path).expect("open perf wad"); + for hash in hashes { + let got = wad.read(hash).expect("read").expect("present"); + assert_eq!(got.len(), 1024); + } + assert!( + start.elapsed().as_millis() < 2000, + "256-entry WAD roundtrip took {:?}", + start.elapsed() + ); +} diff --git a/deny.toml b/deny.toml index c55a5bf..b3abd81 100644 --- a/deny.toml +++ b/deny.toml @@ -70,12 +70,8 @@ allow-wildcard-paths = true [advisories] unmaintained = "workspace" yanked = "warn" -ignore = [ - { id = "RUSTSEC-2026-0367", reason = "zip extract() keeps Unix SUID/SGID bits; Bullet never calls extract(), its own Windows extractor writes plain files" }, - { id = "RUSTSEC-2026-0368", reason = "zip extract() follows symlink targets; Bullet never calls extract() and its extractor refuses symlink entries" }, - { id = "RUSTSEC-2026-0369", reason = "zip extract() applies Unix permissions through symlinks; Bullet never calls extract() and runs on Windows only" }, - { id = "RUSTSEC-2026-0381", reason = "webpki-roots 0.26.11 is the semver shim re-exporting webpki-roots 1.x, locked at the fixed 1.0.10" }, -] +unused-ignored-advisory = "deny" +ignore = [] [sources] unknown-registry = "deny" diff --git a/installer/bullet.iss b/installer/bullet.iss index 6658eba..1eaa37c 100644 --- a/installer/bullet.iss +++ b/installer/bullet.iss @@ -8,7 +8,7 @@ #define MyAppNumericVersion MyAppVersion #endif #define MyAppPublisher "Isllan Toso" -#define MyAppDescription "League of Legends skin changer for Windows" +#define MyAppDescription "League of Legends skin changer, chroma selector, and custom mod manager for Windows" #define MyAppCopyright "Copyright (c) 2026 Isllan Toso. MIT License." #define MyAppURL "https://github.com/Isllanrx/Bullet" #define MyPublisherURL "https://isllan.dev/" diff --git a/xtask/src/audit/skin_audit/asset_checks.rs b/xtask/src/audit/skin_audit/asset_checks.rs new file mode 100644 index 0000000..7b7d5aa --- /dev/null +++ b/xtask/src/audit/skin_audit/asset_checks.rs @@ -0,0 +1,367 @@ +use std::collections::BTreeSet; +use std::path::Path; + +use bullet_classic::generator::StandardChampion; +use bullet_classic::loading_name::rst; +use bullet_wad::hash::prop_key_hash as h; +use bullet_wad::prop::parse_prop_file; +use bullet_wad::prop::tree::{self, Value}; + +use super::SkinFinding; +use super::checks::{has_skin_numbered_ref, valid_texture_bytes}; + +const VFX_SYSTEM_CLASS: u32 = 0x45cd_8998; +const STATIC_MATERIAL_CLASS: u32 = 0xff9d_3409; + +fn raw_text(value: &Value) -> Option { + match value { + Value::Raw { kind: 16, bytes } if bytes.len() >= 2 => { + Some(String::from_utf8_lossy(&bytes[2..]).into_owned()) + } + _ => None, + } +} + +fn check_anm_magic(bytes: &[u8]) -> bool { + bytes.len() >= 12 && (bytes.starts_with(b"r3d2anmd") || bytes.starts_with(b"r3d2canm")) +} + +fn check_audio_magic(path: &str, bytes: &[u8]) -> bool { + if path.ends_with(".bnk") { + bytes.starts_with(b"BKHD") && bullet_classic::sound_bank::parse(bytes).is_ok() + } else if path.ends_with(".wpk") { + bytes.len() >= 12 && bytes.starts_with(b"r3d2") + } else if path.ends_with(".wem") { + bytes.len() >= 12 && bytes.starts_with(b"RIFF") + } else { + !bytes.is_empty() + } +} + +fn collect_defined_keys( + champion: &StandardChampion, + wad_root: &Path, + gen_bytes: &[u8], +) -> BTreeSet { + let mut keys = BTreeSet::new(); + let Ok(file) = parse_prop_file(gen_bytes) else { + return keys; + }; + keys.extend(file.entries.iter().map(|e| e.key_hash)); + for link in &file.links { + let lower = link.to_ascii_lowercase(); + let bytes = std::fs::read(wad_root.join(&lower)) + .ok() + .or_else(|| champion.read_path(&lower).ok().flatten()); + if let Some(b) = bytes + && let Ok(linked) = parse_prop_file(&b) + { + keys.extend(linked.entries.into_iter().map(|e| e.key_hash)); + } + } + keys +} + +fn check_audio_banks_and_rebase( + champion: &StandardChampion, + main: &str, + skin: u32, + wad_root: &Path, + gen_fields: &[tree::Field], + finding: &mut SkinFinding, +) { + if let Some(name) = tree::field(gen_fields, h("championSkinName")).and_then(raw_text) + && has_skin_numbered_ref(&name, main) + { + finding.stale_references.push(format!( + "{main} skin{skin}: un-rebased championSkinName '{name}'" + )); + } + let Some(audio) = tree::field(gen_fields, h("skinAudioProperties")).and_then(Value::fields) + else { + return; + }; + if let Some(tags) = tree::field(audio, h("tagEventList")).and_then(Value::items) { + for tag in tags.iter().filter_map(raw_text) { + if has_skin_numbered_ref(&tag, main) { + finding.stale_references.push(format!( + "{main} skin{skin}: un-rebased tagEventList '{tag}'" + )); + } + } + } + let Some(units) = tree::field(audio, h("bankUnits")).and_then(Value::items) else { + return; + }; + for uf in units.iter().filter_map(Value::fields) { + if let Some(uname) = tree::field(uf, h("name")).and_then(raw_text) + && has_skin_numbered_ref(&uname, main) + { + finding.stale_references.push(format!( + "{main} skin{skin}: un-rebased bankUnits.name '{uname}'" + )); + } + if let Some(events) = tree::field(uf, h("events")).and_then(Value::items) + && let Some(ev) = events + .iter() + .filter_map(raw_text) + .find(|ev| has_skin_numbered_ref(ev, main)) + { + finding.stale_references.push(format!( + "{main} skin{skin}: un-rebased bankUnits.events '{ev}'" + )); + } + let Some(paths) = tree::field(uf, h("bankPath")).and_then(Value::items) else { + continue; + }; + for p in paths.iter().filter_map(raw_text) { + let lower = p.to_ascii_lowercase(); + let local = wad_root.join(&lower); + if local.is_file() { + if let Ok(bytes) = std::fs::read(&local) + && !check_audio_magic(&lower, &bytes) + { + finding.stale_references.push(format!( + "{main} skin{skin}: generated audio bank '{lower}' has invalid header magic" + )); + } + } else if !lower.contains("/en_us/") + && !lower.contains("/vo/") + && !champion.contains_path(&lower) + { + finding.missing_links.push(format!( + "{main} skin{skin}: missing audio bank '{lower}' in WAD" + )); + } + } + } +} + +fn check_animation_clips_and_anm( + champion: &StandardChampion, + main: &str, + skin: u32, + wad_root: &Path, + graph_bytes: &[u8], + graph_key: u32, + finding: &mut SkinFinding, +) { + let Ok(file) = parse_prop_file(graph_bytes) else { + finding.stale_references.push(format!( + "{main} skin{skin}: generated animation graph is not a valid PROP" + )); + return; + }; + let Some(entry) = file.entries.iter().find(|e| e.key_hash == graph_key) else { + return; + }; + let Ok(fields) = tree::parse_fields(&entry.body) else { + return; + }; + let map_keys = |name: &str| -> BTreeSet { + match tree::field(&fields, h(name)) { + Some(Value::Map { entries, .. }) => { + entries.iter().filter_map(|(k, _)| k.as_u32()).collect() + } + _ => BTreeSet::new(), + } + }; + let (tracks, masks) = (map_keys("mTrackDataMap"), map_keys("mMaskDataMap")); + let Some(Value::Map { entries: clips, .. }) = tree::field(&fields, h("mClipDataMap")) else { + return; + }; + let clip_keys: BTreeSet = clips.iter().filter_map(|(k, _)| k.as_u32()).collect(); + for cf in clips.iter().filter_map(|(_, c)| c.fields()) { + if let Some(tk) = tree::field(cf, h("mTrackDataName")).and_then(Value::as_u32) + && !tracks.is_empty() + && !tracks.contains(&tk) + { + finding.stale_references.push(format!( + "{main} skin{skin}: clip references undefined track {tk:08x}" + )); + } + if let Some(mk) = tree::field(cf, h("mMaskDataName")).and_then(Value::as_u32) + && !masks.is_empty() + && !masks.contains(&mk) + { + finding.stale_references.push(format!( + "{main} skin{skin}: clip references undefined mask {mk:08x}" + )); + } + for ref_field in [ + "mTrueConditionClipName", + "mFalseConditionClipName", + "mClipName", + ] { + if let Some(target) = tree::field(cf, h(ref_field)).and_then(Value::as_u32) + && target != 0 + && !clip_keys.contains(&target) + { + finding.stale_references.push(format!( + "{main} skin{skin}: clip field {ref_field} points to missing clip {target:08x}" + )); + } + } + if let Some(anm) = tree::field(cf, h("mAnimationResourceData")) + .and_then(Value::fields) + .and_then(|r| tree::field(r, h("mAnimationFilePath"))) + .and_then(raw_text) + { + let lower = anm.to_ascii_lowercase(); + if let Some(b) = std::fs::read(wad_root.join(&lower)) + .ok() + .or_else(|| champion.read_path(&lower).ok().flatten()) + && !check_anm_magic(&b) + { + finding.stale_references.push(format!( + "{main} skin{skin}: animation '{lower}' has invalid .anm header" + )); + } + } + } +} + +fn check_vfx_materials_and_character_record( + champion: &StandardChampion, + main: &str, + skin: u32, + wad_root: &Path, + gen_bytes: &[u8], + finding: &mut SkinFinding, +) { + if let Ok(file) = parse_prop_file(gen_bytes) { + for entry in &file.entries { + if entry.class_hash == VFX_SYSTEM_CLASS && tree::parse_fields(&entry.body).is_err() { + finding.stale_references.push(format!( + "{main} skin{skin}: VfxSystemDefinitionData {:08x} body corrupted", + entry.key_hash + )); + } else if entry.class_hash == STATIC_MATERIAL_CLASS { + let Ok(mfields) = tree::parse_fields(&entry.body) else { + finding.stale_references.push(format!( + "{main} skin{skin}: StaticMaterialDef {:08x} body corrupted", + entry.key_hash + )); + continue; + }; + if let Some(samplers) = + tree::field(&mfields, h("samplerValues")).and_then(Value::items) + { + for s in samplers.iter().filter_map(Value::fields) { + if let Some(t) = tree::field(s, h("textureName")) + .or_else(|| tree::field(s, h("texturePath"))) + .and_then(raw_text) + { + check_texture_ref(champion, main, skin, wad_root, &t, finding); + } + } + } + } + } + } + let record_path = format!("data/characters/{main}/{main}.bin"); + if let Ok(Some(record_bytes)) = champion.read_path(&record_path) + && let Some(patched) = rst::patch_record_key(&record_bytes, &champion.alias) + && parse_prop_file(&patched).is_err() + { + finding.stale_references.push(format!( + "{main} skin{skin}: loading_name CharacterRecord patch corrupted PROP layout" + )); + } +} + +fn check_texture_ref( + champion: &StandardChampion, + main: &str, + skin: u32, + wad_root: &Path, + rel: &str, + finding: &mut SkinFinding, +) { + let lower = rel.to_ascii_lowercase(); + if let Some(bytes) = std::fs::read(wad_root.join(&lower)) + .ok() + .or_else(|| champion.read_path(&lower).ok().flatten()) + && !valid_texture_bytes(&bytes) + { + finding.stale_references.push(format!( + "{main} skin{skin}: invalid texture header in '{lower}'" + )); + } +} + +#[allow(clippy::too_many_arguments)] +pub(super) fn check_deep_assets( + champion: &StandardChampion, + main: &str, + skin: u32, + wad_root: &Path, + gen_bytes: &[u8], + gen_fields: &[tree::Field], + gen_graph: Option, + finding: &mut SkinFinding, +) { + let defined_keys = collect_defined_keys(champion, wad_root, gen_bytes); + if let Some(resolver) = tree::field(gen_fields, h("mResourceResolver")).and_then(Value::as_u32) + && resolver != 0 + && !defined_keys.contains(&resolver) + { + finding.stale_references.push(format!( + "{main} skin{skin}: mResourceResolver {resolver:08x} missing from skin and linked bins" + )); + } + for ui_field in [ + "iconAvatar", + "iconCircle", + "iconSquare", + "loadscreen", + "loadscreenVintage", + ] { + if let Some(tex) = tree::field(gen_fields, h(ui_field)).and_then(raw_text) { + check_texture_ref(champion, main, skin, wad_root, &tex, finding); + } + } + if let Some(mesh) = tree::field(gen_fields, h("skinMeshProperties")).and_then(Value::fields) { + if let Some(skl) = tree::field(mesh, h("skeleton")).and_then(raw_text) { + let lower = skl.to_ascii_lowercase(); + if let Some(bytes) = std::fs::read(wad_root.join(&lower)) + .ok() + .or_else(|| champion.read_path(&lower).ok().flatten()) + && let Ok(ps) = bullet_classic::skeleton::parse(&bytes) + { + let len = ps.joints.len() as i16; + if ps.joints.is_empty() + || ps.joints.iter().any(|j| j.parent < -1 || j.parent >= len) + { + finding.stale_references.push(format!( + "{main} skin{skin}: invalid skeleton joint hierarchy in '{lower}'" + )); + } + } + } + if let Some(tex) = tree::field(mesh, h("texture")).and_then(raw_text) { + check_texture_ref(champion, main, skin, wad_root, &tex, finding); + } + if let Some(items) = tree::field(mesh, h("materialOverride")).and_then(Value::items) { + for f in items.iter().filter_map(Value::fields) { + if let Some(tex) = tree::field(f, h("texture")).and_then(raw_text) { + check_texture_ref(champion, main, skin, wad_root, &tex, finding); + } + } + } + } + check_audio_banks_and_rebase(champion, main, skin, wad_root, gen_fields, finding); + check_vfx_materials_and_character_record(champion, main, skin, wad_root, gen_bytes, finding); + if let Some(gk) = gen_graph + && let Ok(parsed) = parse_prop_file(gen_bytes) + { + for link in &parsed.links { + let lower = link.to_ascii_lowercase(); + if lower.contains("/animations/") + && let Ok(bytes) = std::fs::read(wad_root.join(&lower)) + { + check_animation_clips_and_anm(champion, main, skin, wad_root, &bytes, gk, finding); + } + } + } +} diff --git a/xtask/src/audit/skin_audit/checks.rs b/xtask/src/audit/skin_audit/checks.rs index 5a1a154..58fdfea 100644 --- a/xtask/src/audit/skin_audit/checks.rs +++ b/xtask/src/audit/skin_audit/checks.rs @@ -59,6 +59,23 @@ pub(super) fn source_keys(character: &str, links: &[String]) -> HashSet { .collect() } +pub(super) fn check_mod_metadata(mod_root: &Path, finding: &mut SkinFinding) { + for rel in ["META/info.json", "META/manifest.json"] { + let path = mod_root.join(rel); + let Ok(bytes) = std::fs::read(&path) else { + finding + .stale_references + .push(format!("missing metadata file '{rel}'")); + continue; + }; + if serde_json::from_slice::(&bytes).is_err() { + finding + .stale_references + .push(format!("invalid JSON in metadata file '{rel}'")); + } + } +} + pub(super) fn check_generated_bins( champion: &StandardChampion, maps: &MapIndex, @@ -80,6 +97,14 @@ pub(super) fn check_generated_bins( .push(format!("{character}: generated bin unreadable")); continue; }; + for prop_entry in &bin.entries { + if bullet_wad::prop::tree::parse_fields(&prop_entry.body).is_err() { + finding.stale_references.push(format!( + "{character}: entry {:08x} failed field parse", + prop_entry.key_hash + )); + } + } let stale = source_keys(&character, &bin.links); let stuck = bin .entries @@ -105,23 +130,189 @@ pub(super) fn check_generated_bins( } } +pub(super) fn valid_texture_bytes(bytes: &[u8]) -> bool { + (bytes.len() >= 12 + && bytes.starts_with(b"TEX\0") + && u16::from_le_bytes([bytes[4], bytes[5]]) > 0 + && u16::from_le_bytes([bytes[6], bytes[7]]) > 0) + || (bytes.len() >= 128 && bytes.starts_with(b"DDS ")) + || bytes.starts_with(b"\x89PNG\r\n\x1a\n") + || bytes.starts_with(b"\xFF\xD8\xFF") + || (bytes.len() >= 12 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WEBP") +} + +pub(super) fn has_skin_numbered_ref(value: &str, character: &str) -> bool { + for segment in value.split('_') { + let low = segment.to_ascii_lowercase(); + if let Some(at) = low.rfind("skin") { + let after = &low[at + 4..]; + let digit_len = after.bytes().take_while(u8::is_ascii_digit).count(); + let (digits, tail, head) = (&after[..digit_len], &after[digit_len..], &low[..at]); + if !digits.is_empty() + && digits.bytes().any(|b| b != b'0') + && head.bytes().all(|b| b.is_ascii_alphabetic()) + && tail.bytes().all(|b| b.is_ascii_alphabetic()) + { + return true; + } + } + } + let lower = value.to_ascii_lowercase(); + let char_low = character.to_ascii_lowercase(); + let plain = char_low.strip_prefix("jade_").unwrap_or(&char_low); + let needle = format!("{plain}skin"); + let mut from = 0; + while let Some(pos) = lower[from..].find(&needle) { + let after = from + pos + needle.len(); + if lower + .as_bytes() + .get(after) + .is_some_and(|b| b.is_ascii_digit() && *b != b'0') + { + return true; + } + from = after; + } + false +} + +fn check_single_generated_file(path: &str, bytes: &[u8], finding: &mut SkinFinding) { + if path.ends_with(".skn") { + if bytes.get(0..4) != Some(&0x0011_2233u32.to_le_bytes()) { + finding + .stale_references + .push(format!("{path}: invalid .skn magic")); + return; + } + let major = bytes + .get(4..6) + .map(|b| u16::from_le_bytes([b[0], b[1]])) + .unwrap_or(0); + if !(1..=4).contains(&major) { + finding + .stale_references + .push(format!("{path}: unsupported .skn major {major}")); + return; + } + if major == 4 { + match bullet_classic::skinned_mesh::parse(bytes) { + Ok(mesh) => { + if let Err(e) = mesh.validate_submesh_indices() { + finding.stale_references.push(format!("{path}: {e}")); + } + if mesh.submeshes.is_empty() + || mesh.vertices.is_empty() + || mesh.indices.is_empty() + || !(52..=72).contains(&mesh.vertex_size) + { + finding + .stale_references + .push(format!("{path}: degenerate .skn geometry")); + } + } + Err(e) => finding.stale_references.push(format!("{path}: {e}")), + } + } + } else if path.ends_with(".skl") { + if let Ok(skl) = bullet_classic::skeleton::parse(bytes) { + let len = skl.joints.len() as i16; + if skl.joints.is_empty() || skl.joints.iter().any(|j| j.parent < -1 || j.parent >= len) + { + finding + .stale_references + .push(format!("{path}: invalid skeleton joint hierarchy")); + } + } + } else if path.ends_with(".anm") { + if bytes.len() < 12 || (!bytes.starts_with(b"r3d2anmd") && !bytes.starts_with(b"r3d2canm")) + { + finding + .stale_references + .push(format!("{path}: invalid .anm header")); + } + } else if path.ends_with(".tex") + || path.ends_with(".dds") + || path.ends_with(".png") + || path.ends_with(".jpg") + || path.ends_with(".jpeg") + || path.ends_with(".webp") + { + if !valid_texture_bytes(bytes) { + finding + .stale_references + .push(format!("{path}: invalid texture header")); + } + } else if path.ends_with(".bnk") { + if !bytes.starts_with(b"BKHD") || bullet_classic::sound_bank::parse(bytes).is_err() { + finding + .stale_references + .push(format!("{path}: invalid .bnk soundbank")); + } + } else if path.ends_with(".wpk") { + if bytes.len() < 12 || !bytes.starts_with(b"r3d2") { + finding + .stale_references + .push(format!("{path}: invalid .wpk header")); + } + } else if path.ends_with(".wem") { + if bytes.len() < 12 || !bytes.starts_with(b"RIFF") { + finding + .stale_references + .push(format!("{path}: invalid .wem header")); + } + } else if path.ends_with(".bin") { + match bullet_wad::prop::parse_prop_file(bytes) { + Ok(prop) => { + for entry in &prop.entries { + if bullet_wad::prop::tree::parse_fields(&entry.body).is_err() { + finding.stale_references.push(format!( + "{path}: entry {:08x} failed field parse", + entry.key_hash + )); + } + } + } + Err(e) => finding + .stale_references + .push(format!("{path}: invalid PROP bin: {e}")), + } + } else if (path.ends_with(".scb") && !bytes.starts_with(b"r3d2Mesh")) + || (path.ends_with(".sco") && !bytes.starts_with(b"[ObjectBegin]")) + || (path.ends_with(".mapgeo") && !bytes.starts_with(b"OEGM")) + || (path.ends_with(".nvr") && !bytes.starts_with(b"NVR\0")) + || (path.ends_with(".wgeo") && !bytes.starts_with(b"WGEO")) + || (path.ends_with(".stringtable") && !bytes.starts_with(b"RST")) + || ((path.ends_with(".gmesh") + || path.ends_with(".tmesh") + || path.ends_with(".troybin") + || path.ends_with(".aimesh_ngrid") + || path.ends_with(".ngrid_overlay") + || path.ends_with(".rg_overlay")) + && bytes.is_empty()) + { + finding + .stale_references + .push(format!("{path}: invalid format header or empty payload")); + } +} + pub(super) fn check_generated_meshes( wad_root: &Path, written: &HashSet, finding: &mut SkinFinding, ) { - for path in written.iter().filter(|path| path.ends_with(".skn")) { + let mut seen_hashes = HashSet::with_capacity(written.len()); + for path in written { + let hash = wad_path_hash(path); + if hash == 0 || !seen_hashes.insert(hash) { + finding.stale_references.push(format!( + "{path}: invalid or colliding WAD path hash {hash:016x}" + )); + } let Ok(bytes) = std::fs::read(wad_root.join(path)) else { continue; }; - if bytes.get(4..6) != Some(&4u16.to_le_bytes()) { - continue; - } - let check = bullet_classic::skinned_mesh::parse(&bytes) - .and_then(|mesh| mesh.validate_submesh_indices()); - if let Err(error) = check { - finding.stale_references.push(format!("{path}: {error}")); - } + check_single_generated_file(path, &bytes, finding); } } diff --git a/xtask/src/audit/skin_audit/form_checks.rs b/xtask/src/audit/skin_audit/form_checks.rs new file mode 100644 index 0000000..9e0df6d --- /dev/null +++ b/xtask/src/audit/skin_audit/form_checks.rs @@ -0,0 +1,367 @@ +use std::collections::BTreeSet; +use std::path::Path; + +use bullet_classic::forms::skn_submesh_names; +use bullet_classic::gear_toggle::gear_swap; +use bullet_classic::generator::StandardChampion; +use bullet_wad::hash::prop_key_hash as h; +use bullet_wad::prop::parse_prop_file; +use bullet_wad::prop::tree::{self, Value}; + +use super::SkinFinding; + +const SKIN_DATA_CLASS: u32 = 0x9b67_e9f6; + +fn split_submesh_list(raw: &str) -> BTreeSet { + raw.split(|c: char| c.is_whitespace() || matches!(c, ',' | '|' | ':')) + .filter(|s| !s.is_empty()) + .map(h) + .collect() +} + +fn is_bullet_form_copy(sub: &str) -> bool { + let Some((_, tail)) = sub.rsplit_once("_F") else { + return false; + }; + !tail.is_empty() && tail.bytes().all(|b| b.is_ascii_digit()) +} + +fn raw_text(value: &Value) -> Option { + match value { + Value::Raw { kind: 16, bytes } if bytes.len() >= 2 => { + Some(String::from_utf8_lossy(&bytes[2..]).into_owned()) + } + _ => None, + } +} + +fn hashes_of(fields: &[tree::Field], name: &str) -> Vec { + tree::field(fields, h(name)) + .and_then(Value::items) + .map(|items| items.iter().filter_map(Value::as_u32).collect()) + .unwrap_or_default() +} + +fn skin_fields_of(bytes: &[u8]) -> Option> { + let file = parse_prop_file(bytes).ok()?; + let entry = file + .entries + .iter() + .find(|e| e.class_hash == SKIN_DATA_CLASS)?; + tree::parse_fields(&entry.body).ok() +} + +fn anim_graph_key(fields: &[tree::Field]) -> Option { + tree::field(fields, h("skinAnimationProperties")) + .and_then(Value::fields) + .and_then(|a| tree::field(a, h("animationGraphData"))) + .and_then(Value::as_u32) +} + +fn mesh_field_text(fields: &[tree::Field], name: &str) -> Option { + tree::field(fields, h("skinMeshProperties")) + .and_then(Value::fields) + .and_then(|m| tree::field(m, h(name))) + .and_then(raw_text) +} + +fn material_override_submeshes(fields: &[tree::Field]) -> Vec { + tree::field(fields, h("skinMeshProperties")) + .and_then(Value::fields) + .and_then(|m| tree::field(m, h("materialOverride"))) + .and_then(Value::items) + .unwrap_or_default() + .iter() + .filter_map(|item| item.fields().and_then(|f| tree::field(f, h("submesh")))) + .filter_map(raw_text) + .collect() +} + +fn form0_hidden_in_conditions(fields: &[tree::Field]) -> BTreeSet { + let mut hidden = BTreeSet::new(); + let Some(items) = tree::field(fields, h("PersistentEffectConditions")).and_then(Value::items) + else { + return hidden; + }; + for cond in items { + let Some(cf) = cond.fields() else { + continue; + }; + let is_form0 = tree::field(cf, h("OwnerCondition")) + .and_then(Value::class) + .is_some_and(|c| c == h("NotMaterialDriver")); + if is_form0 { + hidden.extend(hashes_of(cf, "SubmeshesToHide")); + } + } + hidden +} + +fn form0_hidden_in_graph(graph_bytes: &[u8], graph_key: u32) -> BTreeSet { + let mut hidden = BTreeSet::new(); + let Ok(file) = parse_prop_file(graph_bytes) else { + return hidden; + }; + let Some(entry) = file.entries.iter().find(|e| e.key_hash == graph_key) else { + return hidden; + }; + let Ok(fields) = tree::parse_fields(&entry.body) else { + return hidden; + }; + let Some(Value::Map { entries, .. }) = tree::field(&fields, h("mClipDataMap")) else { + return hidden; + }; + let swap0 = bullet_classic::form_state::swap_key(0); + let state0 = bullet_classic::form_state::state_key(0); + for (k, clip) in entries { + let Some(key) = k.as_u32() else { + continue; + }; + if key != state0 && key != swap0 { + continue; + } + let Some(Value::Map { + entries: events, .. + }) = clip + .fields() + .and_then(|f| tree::field(f, h("mEventDataMap"))) + else { + continue; + }; + for (_, ev) in events { + if ev.class() == Some(h("SubmeshVisibilityEventData")) + && let Some(ef) = ev.fields() + { + hidden.extend(hashes_of(ef, "mHideSubmeshList")); + } + } + } + hidden +} + +pub(super) fn check_skin_fidelity( + champion: &StandardChampion, + main: &str, + skin: u32, + wad_root: &Path, + finding: &mut SkinFinding, +) { + let Ok(Some(source_bytes)) = champion.read_skin_bin(main, skin) else { + return; + }; + let gen_path = wad_root + .join("data") + .join("characters") + .join(main) + .join("skins") + .join("skin0.bin"); + let Ok(gen_bytes) = std::fs::read(&gen_path) else { + return; + }; + let (Some(src_fields), Some(gen_fields)) = + (skin_fields_of(&source_bytes), skin_fields_of(&gen_bytes)) + else { + return; + }; + + let src_graph = anim_graph_key(&src_fields); + let gen_graph = anim_graph_key(&gen_fields); + if src_graph.is_some() && src_graph != gen_graph { + finding.stale_references.push(format!( + "{main} skin{skin}: animationGraphData drifted from {src_graph:?} to {gen_graph:?}" + )); + } + + super::asset_checks::check_deep_assets( + champion, + main, + skin, + wad_root, + &gen_bytes, + &gen_fields, + gen_graph, + finding, + ); + + let src_skn_rel = mesh_field_text(&src_fields, "simpleSkin").map(|s| s.to_ascii_lowercase()); + let src_skn_parts: Vec = src_skn_rel + .as_deref() + .and_then(|rel| champion.read_path(rel).ok().flatten()) + .and_then(|b| skn_submesh_names(&b).ok()) + .unwrap_or_default(); + + let gen_skn_rel = mesh_field_text(&gen_fields, "simpleSkin").map(|s| s.to_ascii_lowercase()); + let skn_bytes = gen_skn_rel.as_deref().and_then(|rel| { + let local = wad_root.join(rel); + std::fs::read(local) + .ok() + .or_else(|| champion.read_path(rel).ok().flatten()) + }); + let skn_parts: Vec = skn_bytes + .as_deref() + .and_then(|b| skn_submesh_names(b).ok()) + .unwrap_or_default(); + let skn_hashes: BTreeSet = skn_parts.iter().map(|n| h(n)).collect(); + + if !skn_parts.is_empty() { + for sub in material_override_submeshes(&gen_fields) { + if is_bullet_form_copy(&sub) && !skn_hashes.contains(&h(&sub)) { + finding.stale_references.push(format!( + "{main} skin{skin}: materialOverride references missing form copy '{sub}'" + )); + } + } + } + + if let Some(skl_rel) = mesh_field_text(&gen_fields, "skeleton") { + let local = wad_root.join(skl_rel.to_ascii_lowercase()); + if local.is_file() + && let Ok(bytes) = std::fs::read(&local) + && let Err(e) = bullet_classic::skeleton::parse(&bytes) + { + finding + .stale_references + .push(format!("{main} skin{skin}: rebuilt skeleton invalid: {e}")); + } + } + + let Ok(gear_keys) = bullet_classic::forms::gear_keys(&source_bytes) else { + return; + }; + if gear_keys.len() < 2 || champion.gear_count(0) > 0 || skn_parts.is_empty() { + return; + } + + let src_init_hide = mesh_field_text(&src_fields, "initialSubmeshToHide") + .map(|s| split_submesh_list(&s)) + .unwrap_or_default(); + let gear0_hide: BTreeSet = champion + .gear_body(&source_bytes, gear_keys[0]) + .ok() + .and_then(|body| gear_swap(&body).ok()) + .map(|swap| swap.hide.into_iter().collect()) + .unwrap_or_default(); + + let src_cond_hide: BTreeSet = tree::field(&src_fields, h("PersistentEffectConditions")) + .and_then(Value::items) + .unwrap_or_default() + .iter() + .filter_map(Value::fields) + .flat_map(|cf| hashes_of(cf, "SubmeshesToHide")) + .collect(); + let gen_init_hide = mesh_field_text(&gen_fields, "initialSubmeshToHide") + .map(|s| split_submesh_list(&s)) + .unwrap_or_default(); + let cond_hide = form0_hidden_in_conditions(&gen_fields); + + let mut graph_hide = BTreeSet::new(); + if let Some(gk) = gen_graph + && let Ok(parsed) = parse_prop_file(&gen_bytes) + { + for link in &parsed.links { + let lower = link.to_ascii_lowercase(); + if lower.contains("/animations/") { + let local = wad_root.join(&lower); + if local.is_file() + && let Ok(bytes) = std::fs::read(&local) + { + graph_hide.extend(form0_hidden_in_graph(&bytes, gk)); + } + } + } + } + + for part in &src_skn_parts { + let lower = part.to_ascii_lowercase(); + if lower.starts_with("bulletform") || is_bullet_form_copy(part) { + continue; + } + let ph = h(part); + let default_visible = !src_init_hide.contains(&ph) + && !gear0_hide.contains(&ph) + && !src_cond_hide.contains(&ph); + if !default_visible { + continue; + } + if gen_init_hide.contains(&ph) || cond_hide.contains(&ph) || graph_hide.contains(&ph) { + finding.stale_references.push(format!( + "{main} skin{skin}: default-visible submesh '{part}' is wrongly hidden in Form 0 (init={}, cond={}, graph={})", + gen_init_hide.contains(&ph), + cond_hide.contains(&ph), + graph_hide.contains(&ph), + )); + } + } +} + +pub(super) fn check_baked_form_fidelity( + champion: &StandardChampion, + main: &str, + skin: u32, + form: u32, + wad_root: &Path, + finding: &mut SkinFinding, +) { + let gen_path = wad_root + .join("data") + .join("characters") + .join(main) + .join("skins") + .join("skin0.bin"); + let Ok(gen_bytes) = std::fs::read(&gen_path) else { + finding + .stale_references + .push(format!("{main} skin{skin} form{form}: missing skin0.bin")); + return; + }; + let Some(gen_fields) = skin_fields_of(&gen_bytes) else { + finding.stale_references.push(format!( + "{main} skin{skin} form{form}: unreadable SkinCharacterDataProperties" + )); + return; + }; + let gen_graph = anim_graph_key(&gen_fields); + super::asset_checks::check_deep_assets( + champion, + main, + skin, + wad_root, + &gen_bytes, + &gen_fields, + gen_graph, + finding, + ); + if let Some(skn_rel) = mesh_field_text(&gen_fields, "simpleSkin") { + let lower = skn_rel.to_ascii_lowercase(); + let bytes = std::fs::read(wad_root.join(&lower)) + .ok() + .or_else(|| champion.read_path(&lower).ok().flatten()); + if let Some(b) = bytes { + if let Ok(parts) = skn_submesh_names(&b) { + let part_hashes: BTreeSet = parts.iter().map(|n| h(n)).collect(); + for sub in material_override_submeshes(&gen_fields) { + if is_bullet_form_copy(&sub) && !part_hashes.contains(&h(&sub)) { + finding.stale_references.push(format!( + "{main} skin{skin} form{form}: materialOverride submesh '{sub}' not in mesh" + )); + } + } + } + } else { + finding.missing_links.push(format!( + "{main} skin{skin} form{form}: missing simpleSkin '{lower}'" + )); + } + } + if let Some(skl_rel) = mesh_field_text(&gen_fields, "skeleton") { + let lower = skl_rel.to_ascii_lowercase(); + let bytes = std::fs::read(wad_root.join(&lower)) + .ok() + .or_else(|| champion.read_path(&lower).ok().flatten()); + if bytes.is_none() { + finding.missing_links.push(format!( + "{main} skin{skin} form{form}: missing skeleton '{lower}'" + )); + } + } +} diff --git a/xtask/src/audit/skin_audit/mod.rs b/xtask/src/audit/skin_audit/mod.rs index f576509..7a2e573 100644 --- a/xtask/src/audit/skin_audit/mod.rs +++ b/xtask/src/audit/skin_audit/mod.rs @@ -156,8 +156,10 @@ pub fn audit_champion( finding.source_links_dropped = !keeps_source_links(&champion, &main, skin, &characters.join(&main)); let written: HashSet = generated_paths(&wad_root).into_iter().collect(); + checks::check_mod_metadata(&staging.join(&folder), &mut finding); check_generated_bins(&champion, maps, &characters, &written, &mut finding); checks::check_generated_meshes(&wad_root, &written, &mut finding); + form_checks::check_skin_fidelity(&champion, &main, skin, &wad_root, &mut finding); finding.shared_with_map = generated_paths(&wad_root) .into_iter() .filter_map(|path| { @@ -187,8 +189,17 @@ pub fn audit_champion( let written: HashSet = generated_paths(&wad_root).into_iter().collect(); let characters = wad_root.join("data").join("characters"); + checks::check_mod_metadata(&staging.join(&folder), &mut finding); check_generated_bins(&champion, maps, &characters, &written, &mut finding); checks::check_generated_meshes(&wad_root, &written, &mut finding); + form_checks::check_baked_form_fidelity( + &champion, + &main, + skin, + form, + &wad_root, + &mut finding, + ); if !settings.keep { let _ = std::fs::remove_dir_all(staging.join(&folder)); // ignore-ok: probe scratch folder } @@ -347,7 +358,9 @@ relatorio: {} ({} s)", } } +mod asset_checks; mod checks; +mod form_checks; mod report; use checks::{check_generated_bins, generated_paths, keeps_source_links, maps_holding, skin_bin}; diff --git a/xtask/src/build/package/mod.rs b/xtask/src/build/package/mod.rs index 0b93c7d..39c06cf 100644 --- a/xtask/src/build/package/mod.rs +++ b/xtask/src/build/package/mod.rs @@ -141,12 +141,18 @@ pub(crate) fn run_package() { }; let dest = tools_dest_dir.join(tool); if let Err(e) = std::fs::copy(src, &dest) { - eprintln!( - "[ERROR] copying {} to {}: {e}", - src.display(), - dest.display() - ); - std::process::exit(1); + let same_bytes = std::fs::read(src) + .ok() + .zip(std::fs::read(&dest).ok()) + .is_some_and(|(a, b)| a == b); + if !same_bytes { + eprintln!( + "[ERROR] copying {} to {}: {e}", + src.display(), + dest.display() + ); + std::process::exit(1); + } } let bytes_tool = std::fs::read(&dest).unwrap_or_else(|e| { eprintln!("[ERROR] reading {}: {e}", dest.display());