diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..082c07a --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +github: objz diff --git a/.github/ISSUE_TEMPLATE/crash_report.yml b/.github/ISSUE_TEMPLATE/crash_report.yml index f37e41e..59d7ee3 100644 --- a/.github/ISSUE_TEMPLATE/crash_report.yml +++ b/.github/ISSUE_TEMPLATE/crash_report.yml @@ -18,7 +18,7 @@ body: paste relevant log output here. you can find logs at: - **rmcl logs**: `~/.cache/rmcl/` (per-session files like `rmcl_2026-04-20_12-34-56.log`) - - **launch logs**: `~/.local/share/rmcl/instances/{instance}/.minecraft/logs/launches/` + - **launch logs**: `~/.local/share/rmcl/instances/{instance}/minecraft/logs/launches/` you can also view logs in the TUI via the log overlay or use `rmcl log` from the CLI. render: text diff --git a/.github/workflows/build-release.yml b/.github/workflows/build-release.yml index bea0f88..bf7a286 100644 --- a/.github/workflows/build-release.yml +++ b/.github/workflows/build-release.yml @@ -1,4 +1,3 @@ -# cargo-dist artifact building and publishing, called by release.yml. # Based on cargo-dist's generated GitHub workflow. name: build release @@ -13,7 +12,6 @@ on: type: string jobs: - # Run 'dist plan' (or host) to determine what tasks we need to do plan: runs-on: "ubuntu-22.04" outputs: @@ -39,11 +37,6 @@ jobs: with: name: cargo-dist-cache path: ~/.cargo/bin/dist - # sure would be cool if github gave us proper conditionals... - # so here's a doubly-nested ternary-via-truthiness to try to provide the best possible - # functionality based on whether this is a pull_request, and whether it's from a fork. - # (PRs run on the *source* but secrets are usually on the *target* -- that's *good* - # but also really annoying to build CI around when it needs secrets to work right.) - id: plan run: | dist host --steps=create --tag=${{ inputs.tag }} --output-format=json > plan-dist-manifest.json @@ -56,25 +49,13 @@ jobs: name: artifacts-plan-dist-manifest path: plan-dist-manifest.json - # Build and packages all the platform-specific things build-local-artifacts: name: build-local-artifacts (${{ join(matrix.targets, ', ') }}) - # Let the initial task tell us to not run (currently very blunt) needs: - plan if: ${{ fromJson(needs.plan.outputs.val).ci.github.artifacts_matrix.include != null && (needs.plan.outputs.publishing == 'true' || fromJson(needs.plan.outputs.val).ci.github.pr_run_mode == 'upload') }} strategy: fail-fast: false - # Target platforms/runners are computed by dist in create-release. - # Each member of the matrix has the following arguments: - # - # - runner: the github runner - # - dist-args: cli flags to pass to dist - # - install-dist: expression to run to install dist on the runner - # - # Typically there will be: - # - 1 "global" task that builds universal installers - # - N "local" tasks that build each platform's binaries and platform-specific installers matrix: ${{ fromJson(needs.plan.outputs.val || '{"ci":{"github":{"artifacts_matrix":{"include":[]}}}}').ci.github.artifacts_matrix }} runs-on: ${{ matrix.runner }} container: ${{ matrix.container && matrix.container.image || null }} @@ -108,7 +89,6 @@ jobs: run: sudo apt-get update && sudo apt-get install --yes libxcb1-dev - name: Install dist run: ${{ matrix.install_dist.run }} - # Get the dist-manifest - name: Fetch local artifacts uses: actions/download-artifact@v7 with: @@ -120,7 +100,6 @@ jobs: ${{ matrix.packages_install }} - name: Build artifacts run: | - # Actually do builds and make zips and whatnot dist build ${{ needs.plan.outputs.tag-flag }} --print=linkage --output-format=json ${{ matrix.dist_args }} > dist-manifest.json echo "dist ran successfully" - id: cargo-dist @@ -130,7 +109,6 @@ jobs: # inconsistent syntax between shell and powershell. shell: bash run: | - # Parse out what we just built and upload it to scratch storage echo "paths<> "$GITHUB_OUTPUT" dist print-upload-files-from-manifest --manifest dist-manifest.json >> "$GITHUB_OUTPUT" echo "EOF" >> "$GITHUB_OUTPUT" @@ -144,7 +122,6 @@ jobs: ${{ steps.cargo-dist.outputs.paths }} ${{ env.BUILD_MANIFEST_NAME }} - # Build and package all the platform-agnostic(ish) things build-global-artifacts: needs: - plan @@ -165,7 +142,6 @@ jobs: name: cargo-dist-cache path: ~/.cargo/bin/ - run: chmod +x ~/.cargo/bin/dist - # Get all the local artifacts for the global tasks to use (for e.g. checksums) - name: Fetch local artifacts uses: actions/download-artifact@v7 with: @@ -178,7 +154,6 @@ jobs: dist build ${{ needs.plan.outputs.tag-flag }} --output-format=json "--artifacts=global" > dist-manifest.json echo "dist ran successfully" - # Parse out what we just built and upload it to scratch storage echo "paths<> "$GITHUB_OUTPUT" jq --raw-output ".upload_files[]" dist-manifest.json >> "$GITHUB_OUTPUT" echo "EOF" >> "$GITHUB_OUTPUT" @@ -191,13 +166,11 @@ jobs: path: | ${{ steps.cargo-dist.outputs.paths }} ${{ env.BUILD_MANIFEST_NAME }} - # Determines if we should publish/announce host: needs: - plan - build-local-artifacts - build-global-artifacts - # Only run if we're "publishing", and only if plan, local and global didn't fail (skipped is fine) if: ${{ always() && needs.plan.result == 'success' && needs.plan.outputs.publishing == 'true' && (needs.build-global-artifacts.result == 'skipped' || needs.build-global-artifacts.result == 'success') && (needs.build-local-artifacts.result == 'skipped' || needs.build-local-artifacts.result == 'success') }} env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -218,7 +191,6 @@ jobs: name: cargo-dist-cache path: ~/.cargo/bin/ - run: chmod +x ~/.cargo/bin/dist - # Fetch artifacts from scratch-storage - name: Fetch artifacts uses: actions/download-artifact@v7 with: @@ -235,10 +207,8 @@ jobs: - name: "Upload dist-manifest.json" uses: actions/upload-artifact@v6 with: - # Overwrite the previous copy name: artifacts-dist-manifest path: dist-manifest.json - # Create a GitHub Release while uploading all files to it - name: "Download GitHub Artifacts" uses: actions/download-artifact@v7 with: @@ -260,12 +230,17 @@ jobs: env: PRERELEASE_FLAG: "${{ fromJson(steps.host.outputs.manifest).announcement_is_prerelease && '--prerelease' || '' }}" ANNOUNCEMENT_TITLE: "${{ fromJson(steps.host.outputs.manifest).announcement_title }}" - RELEASE_COMMIT: "${{ github.sha }}" CHANGELOG: "${{ steps.changelog.outputs.content }}" RELEASE_TAG: "${{ needs.plan.outputs.tag }}" APP_VERSION: "${{ fromJson(steps.host.outputs.manifest).releases[0].app_version }}" + PUBLISH_WINGET: "${{ !fromJson(needs.plan.outputs.val).announcement_is_prerelease || fromJson(needs.plan.outputs.val).publish_prereleases }}" run: | + RELEASE_COMMIT="$(git rev-parse HEAD)" echo "$CHANGELOG" > $RUNNER_TEMP/notes.txt + WINGET_MANIFEST_NOTE="" + if [[ "$PUBLISH_WINGET" == true ]]; then + WINGET_MANIFEST_NOTE="The generated WinGet manifest is attached as \`winget-manifest-${APP_VERSION}.zip\` for local validation." + fi cat >> $RUNNER_TEMP/notes.txt <> "$GITHUB_OUTPUT" - echo "tag=$tag" >> "$GITHUB_OUTPUT" - - if [[ "$release" == true ]]; then - echo "releasing $tag (latest release: ${latest:-none})" - else - echo "Cargo.toml version $version is not newer than latest release v$latest; nothing to release" - fi + python3 scripts/release-version.py --check + python3 scripts/release-version.py "$version" - name: create tag if: steps.version.outputs.release == 'true' diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 14e0662..0f0a769 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,55 +1,99 @@ -# contributing +# Contributing to rmcl -thanks for wanting to contribute. here's how we/I do things around here. +Bug reports, fixes, documentation, and themes are welcome. For a larger feature or +architectural change, open an issue first so we can agree on the approach before +you spend time implementing it. -## code style +## Reporting bugs -### comments +Search the [existing issues](https://github.com/objz/rmcl/issues) before opening a +new one. Include your rmcl version, operating system, steps to reproduce, and what +you expected to happen. For game-launch problems, include the Minecraft version +and mod loader; for TUI problems, include your terminal and a screenshot if useful. -preferred are `//` comments with a lowercase, casual tone. try to explain **why** something is done rather than restating what the code does. file-level comments are nice for describing what a file is responsible for, and function-level comments help when the behavior isn't obvious. enum variants and struct fields usually don't need comments if the names are clear enough. basically just look at how existing comments are written and match that vibe. +Relevant logs help, but remove tokens, account details, and other private +information before posting them. See the [README](README.md#logs) for log locations. -### visibility and naming +## Development setup -try to keep visibility as narrow as makes sense. `pub` when something is actually used outside the crate, `pub(crate)` across modules, `pub(super)` within a module. don't leave things `pub` just because they might be useful someday. function names should ideally be clear enough that you don't need a comment to explain what they do. +You need a stable Rust toolchain and a JDK with `javac` and `jar` on `PATH`. +CI uses JDK 21. On Linux, install the libxcb development package (`libxcb1-dev` on +Debian/Ubuntu, `libxcb` on Arch). -### modules and file organization +Fork the repository and create a branch for your change. The +[source build instructions](README.md#from-source) cover cloning and building. +Run the development version with `cargo run --locked`, or use +`cargo run --locked -- --help` to see the CLI commands. -each file should have one clear responsibility. if a file starts doing two unrelated things, split it up. when a module gets big enough, convert `foo.rs` into `foo/mod.rs` with submodules. keep format-specific or protocol-specific code in its own file (e.g. `mrpack.rs` for modrinth, `mmc.rs` for multimc) and put shared types and dispatching in `mod.rs`. the general idea is that you shouldn't find multimc logic in the modrinth file or vice versa. +The main parts of the codebase are: -### tests +- `src/cli/`: command-line commands and output. +- `src/config/`: settings, paths, and themes. +- `src/instance/`: instance management, content, modpack imports, loaders, and launches. +- `src/net/`: HTTP requests, downloads, and service API clients. +- `src/tui/`: the terminal interface. +- `tests/`: integration tests; unit tests are under `src/`. -every test should cover a distinct code path. don't test the same branch twice with just different inputs. test names should describe the scenario, not just the function name. no need to test trivially correct code. +## Making changes -### general advice +Keep each pull request focused on one fix or feature. Follow the style of nearby +code and reuse existing helpers where they fit. Keep public APIs and new +dependencies limited to what the change needs. -- avoid "obvious" comments like `// save the profile` right above `save_profile()` -- avoid unnecessary abstractions or wrappers for things that only happen once -- avoid speculative features or "just in case" parameters -- prefer iterating directly over collecting into a vec when you only need one pass -- match existing error handling patterns, usually `map_err` with `format!` +Comments should explain a decision, constraint, or non-obvious behavior. There is +no need to describe what a clearly named function already does. Keep modules +organized by responsibility without splitting files just to meet a size target. -## architecture +For a bug fix, add a regression test that fails without the fix. For new behavior, +cover the cases that could break. Use test names that describe the scenario and +avoid repeating coverage unless the inputs exercise different behavior. -the codebase is split roughly like this: +## Testing -- `src/cli/` handles command line interface -- `src/config/` has settings, paths, theme config -- `src/instance/` is the core. `content/` scans mods, resource packs, shaders, worlds. `import/` handles modpack importing with `mod.rs` dispatching to format-specific modules like `mrpack.rs` and `mmc.rs`. `loader/` installs mod loaders (fabric, forge, neoforge, quilt). `launch/` builds the java command and spawns minecraft, with `patches.rs` handling lwjgl3ify classpath patches. `manager.rs` does instance CRUD -- `src/net/` is the networking layer. http client, file downloads, and API clients per service -- `src/tui/` is the terminal UI built with ratatui +Run the same checks as CI before submitting code changes: -### adding a new import format +```sh +cargo fmt --all -- --check +cargo build --locked +cargo clippy --all-targets --locked -- -D warnings +cargo test --locked --all-targets +``` -create a new file in `src/instance/import/`, add the variant to `PackFormat` in `mod.rs`, add detection logic in `detect_format()`, and add the dispatch arms in `build_summary()` and `execute_import()`. +Live-service tests are ignored by default. If you run them, note that in the PR, +along with any failures caused by network access or provider credentials. -### adding a new mod loader +Check visual and input changes in a real terminal as well as the automated TUI +tests. CI covers Linux, macOS, and Windows; say which platforms you tested locally +and mention anything you could not verify. -create a new file in `src/instance/loader/` implementing `ModLoaderInstaller`, add the variant to `ModLoader` in `models.rs`, and register it in `get_installer()`. +## Pull requests -## commits +Open your PR against `master`. Explain the problem, summarize the change, link any +related issue, and list the checks you ran. Screenshots or a short recording are +useful for visible TUI changes. Use descriptive commit messages and keep unrelated +changes in separate commits or PRs. -start with what you did: `added`, `fixed`, `refactored`, etc. lowercase. separate logical changes into separate commits. don't bundle unrelated things into one commit. +Be available to answer review questions and make follow-up changes. Passing CI +is required before merging, but maintainers may still request changes to the +implementation or scope. -## before submitting +## AI and LLM assistance -make sure `cargo build`, `cargo clippy`, and `cargo test` all pass. you'll need a JDK (`javac` and `jar` on PATH) for the build script that compiles the java shim. +AI-assisted contributions are welcome. You are responsible for the code, tests, +and documentation you submit, including anything generated by a tool. Review the +changes yourself, verify the behavior, and be prepared to explain the implementation. + +If an LLM helped produce your contribution, disclose it in the PR description. +Name the tool or model, describe which parts it helped with, and say how you +reviewed and tested the result. A short note is enough, for example: + +> AI assistance: ChatGPT helped draft the tests. I reviewed the assertions and ran +> the relevant tests locally. + +Use your own words in issue reports, PR summaries, and review replies. Maintainers +may close contributions that have not been reviewed or that the author cannot explain. + +## License + +Contributions are covered by the project's [GPL-3.0-only license](LICENSE). +Only submit code and assets you have the right to contribute under those terms. diff --git a/Cargo.lock b/Cargo.lock index c975ea2..0f83cfc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1001,16 +1001,6 @@ dependencies = [ "dirs-sys", ] -[[package]] -name = "dirs-next" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b98cf8ebf19c3d1b223e151f99a4f9f0690dca41414773390fc824184ac833e1" -dependencies = [ - "cfg-if", - "dirs-sys-next", -] - [[package]] name = "dirs-sys" version = "0.5.0" @@ -1019,21 +1009,10 @@ checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" dependencies = [ "libc", "option-ext", - "redox_users 0.5.2", + "redox_users", "windows-sys 0.61.2", ] -[[package]] -name = "dirs-sys-next" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ebda144c4fe02d1f7ea1a7d9641b6fc6b580adcfa024ae48797ecdeb6825b4d" -dependencies = [ - "libc", - "redox_users 0.4.6", - "winapi", -] - [[package]] name = "dispatch2" version = "0.3.1" @@ -1100,6 +1079,12 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + [[package]] name = "either" version = "1.15.0" @@ -2879,6 +2864,7 @@ version = "5.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f3bab717c29a857abf75fcef718d441ec7cb2725f937343c734740a985d37fd" dependencies = [ + "dunce", "is-wsl", "libc", "pathdiff", @@ -3721,17 +3707,6 @@ dependencies = [ "bitflags 2.13.1", ] -[[package]] -name = "redox_users" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" -dependencies = [ - "getrandom 0.2.17", - "libredox", - "thiserror 1.0.69", -] - [[package]] name = "redox_users" version = "0.5.2" @@ -3884,13 +3859,13 @@ name = "rmcl" version = "0.5.1" dependencies = [ "async-trait", + "base64", "chrono", "clap", "color-eyre", "config", "crossterm 0.29.0", "dirs", - "dirs-next", "display-info", "fast-strip-ansi", "fastnbt", @@ -3899,6 +3874,7 @@ dependencies = [ "html-to-markdown-rs", "image", "insta", + "libc", "libcasr", "log", "minecraft-msa-auth", @@ -3918,6 +3894,7 @@ dependencies = [ "serde_json", "sha1 0.10.7", "sha2", + "shlex", "tachyonfx", "tempfile", "thiserror 2.0.18", @@ -3936,6 +3913,7 @@ dependencies = [ "tui-widget-list", "unicode-segmentation", "which", + "windows-sys 0.61.2", "wiremock", "zip", ] diff --git a/Cargo.toml b/Cargo.toml index 2431ec6..fadfbb8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,13 +24,13 @@ path = "src/main.rs" [dependencies] async-trait = "0.1" +base64 = "0.22" chrono = { version = "0.4.39", features = ["serde"] } clap = "4.5.27" color-eyre = "0.6.3" config = "0.15.6" crossterm = "0.29.0" display-info = "0.5.9" -dirs-next = "2.0.0" log = "0.4" ratatui = { version = "0.30.0", features = ["serde", "unstable-rendered-line-info"] } ratatui-themekit = { version = "0.6", features = ["serde"] } @@ -64,7 +64,7 @@ image = { version = "0.25", default-features = false, features = ["gif", "jpeg", zip = "8.5.1" minecraft-msa-auth = "0.4.0" oauth2 = "5.0.0" -open = "5" +open = { version = "5", features = ["shellexecute-on-windows"] } which = "8.0.2" dirs = "6.0.0" notify = "8" @@ -74,7 +74,14 @@ libcasr = "2.13" fs2 = "0.4" fastnbt = "2.6.2" flate2 = "1.1.9" +tempfile = "3" +[target.'cfg(unix)'.dependencies] +libc = "0.2" +shlex = "1.3" + +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_System_JobObjects", "Win32_System_Threading", "Win32_System_Diagnostics_ToolHelp", "Win32_UI_Shell"] } [profile.release] codegen-units = 1 @@ -87,8 +94,6 @@ inherits = "release" lto = "thin" [dev-dependencies] -tempfile = "3" insta = "1" wiremock = "0.6" rstest = "0.23" -image = { version = "0.25", default-features = false, features = ["png", "webp"] } diff --git a/README.md b/README.md index 567e80c..4cfc36d 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ it does everything you'd expect from a launcher. ### modpacks and accounts -Browse Modrinth and CurseForge modpacks or import Modrinth, CurseForge, MultiMC, Prism, and GTNH packs directly. Direct imports accept a file, Modrinth URL, or project slug. Source builds enable CurseForge when `CURSEFORGE_API_KEY` is set at compile time. Able to use multiple Microsoft accounts and offline accounts aswell. +Browse Modrinth and CurseForge modpacks or import Modrinth, CurseForge, and MultiMC/Prism archives (including GTNH packs in that format). Direct imports accept a local archive, Modrinth URL, or Modrinth project slug. CurseForge requires a build-time [API key](#curseforge-api). Multiple Microsoft accounts and offline accounts are supported. --- @@ -53,6 +53,14 @@ rmcl uses its own Microsoft client ID for Minecraft account authentication. Authentication is performed through Microsoft’s official services. +## CurseForge API + +Git, source, and Cargo builds use rmcl's dedicated API key unless `CURSEFORGE_API_KEY` is set at compile time. An empty or whitespace-only override disables CurseForge. +Use of the API is subject to the [CurseForge 3rd Party API Terms and Conditions](https://support.curseforge.com/en/support/solutions/articles/9000207405-curse-forge-3rd-party-api-terms-and-conditions). +Keys supplied for rmcl are for rmcl builds only. Forks, rebranded applications, +and unrelated projects must use their own key. Keys included in source or compiled +binaries are extractable; do not publish a private key. + ## installation [![GitHub release](https://img.shields.io/github/v/release/objz/rmcl?style=for-the-badge&logo=github)](https://github.com/objz/rmcl/releases) @@ -68,6 +76,13 @@ prebuilt archives are attached to each GitHub release. brew install objz/tap/rmcl ``` +Linux archives and Homebrew installations require the system `libxcb` runtime +package (`libxcb1` on Debian/Ubuntu, `libxcb` on Arch). + +An ARM64 launcher build still needs Minecraft natives for that platform. For +example, Minecraft 1.20.1 supplies macOS ARM64 natives but no Linux ARM64 natives; +using a custom GLFW library alone does not provide the other required libraries. + ### Windows release builds include a `.zip` archive and an `.msi`. WinGet packages are @@ -106,6 +121,7 @@ cargo install rmcl ### from source requires a Rust toolchain and a JDK (`javac` and `jar` on `PATH`). +Linux builds also require the libxcb development package (`libxcb1-dev` on Debian/Ubuntu, `libxcb` on Arch). ```sh git clone https://github.com/objz/rmcl.git @@ -124,17 +140,22 @@ settings, accounts, instances, and cached game metadata. | what | Linux | macOS | Windows | |---|---|---|---| | config (`config.toml`, `theme.toml`, `accounts.json`) | `~/.config/rmcl/` | `~/Library/Application Support/rmcl/` | `%APPDATA%\rmcl\` | -| instances | `~/.local/share/rmcl/instances/` | `~/Library/Application Support/rmcl/instances/` | `%LOCALAPPDATA%\rmcl\instances\` | -| metadata (versions, libraries, assets, loader profiles) | `~/.local/share/rmcl/meta/` | `~/Library/Application Support/rmcl/meta/` | `%LOCALAPPDATA%\rmcl\meta\` | +| instances | `~/.local/share/rmcl/instances/` | `~/Library/Application Support/rmcl/instances/` | `%APPDATA%\rmcl\instances\` | +| metadata (versions, libraries, assets, loader profiles) | `~/.local/share/rmcl/meta/` | `~/Library/Application Support/rmcl/meta/` | `%APPDATA%\rmcl\meta\` | -each instance has an `instance.json` for its config and a `.minecraft/` directory with the actual game files. +These are default locations. On Linux, `XDG_CONFIG_HOME`, `XDG_DATA_HOME`, and +`XDG_CACHE_HOME` override the corresponding base directories. Instance and metadata +paths can also be changed in `config.toml`. -Launcher settings can be edited from the TUI or in `config.toml`. Changes to -`instances_dir`, `meta_dir`, and `image_protocol` apply after restarting rmcl; -other launcher settings apply immediately. Omitting `java_path` enables automatic -Java selection. Global JVM arguments and environment variables are applied before -per-instance values. Instances can explicitly inherit the launcher window mode -and resolution defaults. +each instance has an `instance.json` for its config and a `minecraft/` directory with the actual game files. + +Launcher settings saved through the TUI apply immediately, except changes to +`instances_dir`, `meta_dir`, and `image_protocol`, which require a restart. +Settings files opened through rmcl's editor shortcut are reloaded after saves; +otherwise, restart rmcl after editing `config.toml` externally. When neither global nor instance +`java_path` is set, rmcl selects Java automatically. Global JVM arguments and +environment variables are applied before per-instance values. Instances can +explicitly inherit the launcher window mode and resolution defaults. ```toml [general] @@ -169,7 +190,7 @@ launcher logs are per-session and contain rmcl's own output. instance launch log | what | Linux | macOS | Windows | |---|---|---|---| | launcher logs | `~/.cache/rmcl/` | `~/Library/Caches/rmcl/` | `%LOCALAPPDATA%\rmcl\` | -| instance launch logs | `//.minecraft/logs/launches/` | same | same | +| instance launch logs | `//minecraft/logs/launches/` | same | same | --- @@ -236,7 +257,7 @@ then set `theme = "my-theme"` in `theme.toml`. colors accept `"#f97316"`, ANSI names (`"Red"`, `"LightBlue"`), `{ Rgb = [r, g, b] }` or `{ Indexed = n }`. -note that `[custom]` in `theme.toml` is only for overriding single values of a builtin, it doesn't define a new theme. same for `border_style`, that one lives in `theme.toml`, not in a theme file. +note that `[custom]` in `theme.toml` overrides colors of the selected theme, whether built-in or loaded from a file; it doesn't define a standalone theme. `border_style` belongs at the top level of `theme.toml`, not in a custom theme file. --- diff --git a/assets/icon.svg b/assets/icon.svg index d24fa6a..9c819fd 100644 --- a/assets/icon.svg +++ b/assets/icon.svg @@ -1,5 +1,4 @@ - for StatusLayer { fn on_event(&self, event: &tracing::Event<'_>, _ctx: Context<'_, S>) { let level = *event.metadata().level(); @@ -150,12 +139,7 @@ impl Layer for StatusLayer { } if level <= Level::WARN && should_record_app_log(target, level) { - error_buffer::push_error(ErrorEvent { - id: 0, - level, - message: visitor.message, - pushed_at: std::time::Instant::now(), - }); + error_buffer::push_message(level, visitor.message); } } } diff --git a/src/tui/mod.rs b/src/tui/mod.rs index f79d343..52fd44a 100644 --- a/src/tui/mod.rs +++ b/src/tui/mod.rs @@ -1,8 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// tui entrypoint: sets up the terminal, runs the app, cleans up on exit. - pub mod app; mod event; mod input; diff --git a/src/tui/render.rs b/src/tui/render.rs index 6aff581..8a211d1 100644 --- a/src/tui/render.rs +++ b/src/tui/render.rs @@ -1,11 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// layout and rendering. the main frame is split into: -// left 20%: instance sidebar -// right 80%: title bar + content area + bottom bar (account / details / status) -// popups and error toasts render on top of everything. - use ratatui::{ Frame, layout::{Constraint, Direction, Layout}, @@ -34,6 +29,9 @@ impl App { use ratatui::style::Style; use ratatui::widgets::Block; + if load_content { + self.sync_instance_content(); + } let theme = THEME.as_ref(); frame.render_widget( Block::default().style(Style::default().bg(theme.background())), @@ -149,6 +147,23 @@ impl App { if self.focused == FocusedArea::OverviewExpanded { self.render_log_overlay(frame); + if self.log_filter_open { + widgets::logs_viewer::render_level_filter( + frame, + self.log_filter_selected, + &self.log_level_filters, + ); + } + } else if load_content + && self.content_tab == widgets::content::ContentTab::Logs + && self.instances_state.selected_instance().is_some() + && self.logs_state.filter_open + { + widgets::logs_viewer::render_level_filter( + frame, + self.logs_state.filter_selected, + &self.logs_state.level_filters, + ); } if self.focused == FocusedArea::InstanceSettings @@ -165,7 +180,6 @@ impl App { widgets::popups::global_settings::render(frame, area, state); } - // error toasts stack from the top, each one below the previous let all_errors = error_buffer::peek_all_errors(); self.sync_error_effects(&all_errors); let mut next_y: u16 = 1; @@ -220,16 +234,26 @@ impl App { } } - // full-screen log viewer with search highlighting and auto-scroll. - // auto-sticks to the bottom unless the user scrolled up manually + pub(super) fn overlay_filtered_lines(&self) -> Vec { + crate::tui::logging::get_app_logs() + .into_iter() + .filter(|line| self.log_overlay_search.matches(line)) + .filter(|line| { + widgets::logs_viewer::level_matches( + &self.log_level_filters, + widgets::logs_viewer::level_of_line(line), + ) + }) + .collect() + } + fn render_log_overlay(&mut self, frame: &mut Frame) { use crate::config::theme::{BORDER_STYLE, THEME}; - use crate::tui::logging::get_app_logs; use ratatui::{ layout::{Alignment, Margin}, style::{Modifier, Style}, text::Line, - widgets::{Block, Clear, Paragraph, Scrollbar, ScrollbarOrientation}, + widgets::{Block, Clear, Paragraph}, }; let theme = THEME.as_ref(); @@ -238,34 +262,47 @@ impl App { frame.render_widget(Clear, overlay); - let all_lines = get_app_logs(); - let filtered: Vec<&String> = all_lines - .iter() - .filter(|l| self.log_overlay_search.matches(l)) - .collect(); + let filtered = self.overlay_filtered_lines(); let visible_height = overlay.height.saturating_sub(2) as usize; - let was_at_bottom = - self.log_overlay_scroll >= self.log_overlay_max_scroll.saturating_sub(1); + // Only follow new lines when pinned to the very bottom; being even + // one line up means the user is reading history. + let was_at_bottom = self.log_overlay_scroll >= self.log_overlay_max_scroll; self.log_overlay_max_scroll = filtered.len().saturating_sub(visible_height); - if was_at_bottom || self.log_overlay_scroll > self.log_overlay_max_scroll { + if (was_at_bottom && self.log_selection.range.is_none()) + || self.log_overlay_scroll > self.log_overlay_max_scroll + { self.log_overlay_scroll = self.log_overlay_max_scroll; } self.log_overlay_scrollbar = ratatui::widgets::ScrollbarState::new(self.log_overlay_max_scroll) .position(self.log_overlay_scroll); + let active_filters = self.log_level_filters.iter().flatten().count(); + let title = if active_filters == 0 { + " Logs ".to_owned() + } else { + format!(" Logs · {active_filters} filter(s) ") + }; + let mut keybinds = vec![ + ("Esc", " close"), + ("f", " filter"), + ("g/G", " top/bottom"), + ("/", " search"), + ]; + if self.log_selection.range.is_some() { + keybinds.insert(1, ("y", " yank")); + } let mut block = Block::bordered() .title_top( - Line::from(" Logs ").style( + Line::from(title).style( Style::default() .fg(theme.text()) .add_modifier(Modifier::BOLD), ), ) .title_bottom( - crate::tui::widgets::popups::keybind_line(&[("O", " close"), ("/", " search")]) - .alignment(Alignment::Right), + crate::tui::widgets::popups::keybind_line(&keybinds).alignment(Alignment::Right), ) .border_type(BORDER_STYLE.to_border_type()) .border_style(Style::default().fg(theme.accent())) @@ -277,23 +314,21 @@ impl App { let inner = block.inner(overlay); frame.render_widget(block, overlay); + self.log_overlay_inner = inner; let search = &self.log_overlay_search; let styled: Vec = filtered .iter() + .enumerate() .skip(self.log_overlay_scroll) .take(visible_height) - .map(|line| { - let style = if line.contains("ERROR") || line.contains("FATAL") { - Style::default().fg(theme.error()) - } else if line.contains("WARN") { - Style::default().fg(theme.warning()) - } else if line.contains("DEBUG") || line.contains("TRACE") { - Style::default().fg(theme.text_dim()) - } else { - Style::default().fg(theme.text()) - }; - search.highlight_line(line, style) + .map(|(index, line)| { + self.log_selection.highlight_line( + index, + line, + search, + widgets::logs_viewer::line_level_style(line), + ) }) .collect(); @@ -306,24 +341,12 @@ impl App { height: overlay.height.saturating_sub(2), }; frame.render_stateful_widget( - Scrollbar::default() - .orientation(ScrollbarOrientation::VerticalRight) - .begin_symbol(Some("\u{25b2}")) - .style( - Style::default() - .fg(theme.text_dim()) - .add_modifier(Modifier::BOLD), - ) - .thumb_symbol("\u{2551}") - .track_symbol(Some("")) - .end_symbol(Some("\u{25bc}")), + widgets::scrollbar(theme.text_dim()), scrollbar_area, &mut self.log_overlay_scrollbar, ); } - // keeps the effect map in sync with current errors: removes effects for - // dismissed errors and creates slide-in effects for new ones fn sync_error_effects(&mut self, events: &[error_buffer::ErrorEvent]) { use crate::config::theme::THEME; let theme = THEME.as_ref(); @@ -348,8 +371,6 @@ impl App { } } - // drives the slide-in / idle / slide-out state machine for each error toast. - // transitions to FadingOut at the configured slide-start time fn render_error_effect( &mut self, frame: &mut Frame, diff --git a/src/tui/tests/event.rs b/src/tui/tests/event.rs index 3465d3b..f0aa413 100644 --- a/src/tui/tests/event.rs +++ b/src/tui/tests/event.rs @@ -4,6 +4,1114 @@ use super::*; use crate::tui::tests::harness::UiHarness; +#[test] +fn instance_switches_keep_scans_empty_lists_selections_and_reconciliation_cached() { + let mut ui = UiHarness::new(); + ui.add_instance("Cached A"); + ui.add_instance("Cached B"); + ui.app.instances_state.list_state.selected = Some(0); + ui.app.sync_instance_content(); + let instance = ui.app.instances_state.selected_instance().unwrap().clone(); + let mods = crate::storage::InstancePaths::new(ui.instance_path(&instance.name)) + .minecraft() + .join("mods"); + let entry = + |name: &str| crate::instance::scan_one_mod(&mods.join(format!("{name}.jar")), name, true); + let stream = ui.app.mods_state.start_stream(&instance.name); + assert!(stream.send(entry("alpha"))); + assert!(stream.send(entry("bravo"))); + ui.app.mods_state.drain_pending(); + ui.app.mods_state.list_state.selected = Some(1); + drop(ui.app.resource_packs_state.start_stream(&instance.name)); + ui.app.resource_packs_state.drain_pending(); + ui.app.reconciliation_for = Some((instance.name.clone(), instance.created)); + ui.app.content_manifest = Some(( + instance.name.clone(), + crate::instance::ContentManifest::default(), + )); + ui.app.content_update_snapshot = Some(( + instance.name.clone(), + crate::instance::content::updates::UpdateSnapshot { + game_version: instance.game_version.clone(), + loader: instance.loader, + inventory: Vec::new(), + checked_at: 123, + updates: Vec::new(), + failures: Vec::new(), + }, + )); + ui.app.content_update_check_pending = true; + + ui.app.instances_state.list_state.selected = Some(1); + ui.draw(); + assert!(ui.app.mods_state.entries.is_empty()); + assert!(ui.app.content_manifest.is_none()); + assert!(stream.send(entry("charlie"))); + ui.app.instances_state.list_state.selected = Some(0); + ui.draw(); + ui.app.ensure_content_reconciliation(false); + + assert_eq!(ui.app.mods_state.entries.len(), 2); + assert_eq!(ui.app.mods_state.list_state.selected, Some(1)); + assert!(ui.app.mods_state.drain_pending()); + assert_eq!(ui.app.mods_state.entries.len(), 3); + assert_eq!( + ui.app.resource_packs_state.loaded_for.as_deref(), + Some("Cached A") + ); + assert!(ui.app.resource_packs_state.entries.is_empty()); + assert!(!ui.app.resource_packs_state.is_scanning()); + assert!(!ui.app.resource_packs_state.loading); + assert_eq!( + ui.app + .content_update_snapshot + .as_ref() + .unwrap() + .1 + .checked_at, + 123 + ); + assert!(ui.app.content_update_check_pending); + + ui.app.forget_instance_content("Cached B"); + assert!(stream.send(entry("delta"))); + assert!(ui.app.content_manifest.is_some()); + ui.app.instances_state.list_state.selected = Some(1); + ui.app.sync_instance_content(); + ui.app.forget_instance_content("Cached A"); + assert!(!stream.send(entry("discarded"))); + ui.app.instances_state.list_state.selected = Some(0); + ui.app.sync_instance_content(); + assert!(ui.app.mods_state.entries.is_empty()); + assert!(ui.app.mods_state.loaded_for.is_none()); + assert!(ui.app.reconciliation_for.is_none()); +} + +#[test] +fn content_cache_does_not_survive_a_recreated_instance_or_runtime_change() { + let mut ui = UiHarness::new(); + ui.add_instance("Changed"); + ui.app.sync_instance_content(); + for recreate in [true, false] { + let stream = ui.app.mods_state.start_stream("Changed"); + if recreate { + ui.app.instances_state.instances[0].created += chrono::TimeDelta::seconds(1); + } else { + ui.app.instances_state.instances[0].game_version = "1.21.2".to_owned(); + } + ui.app.sync_instance_content(); + assert!(!stream.send(crate::instance::scan_one_mod( + std::path::Path::new("stale.jar"), + "stale", + true + ))); + assert!(ui.app.mods_state.loaded_for.is_none()); + assert!(ui.app.cached_instance_content.is_empty()); + } +} + +#[test] +fn partial_update_snapshots_label_rows_immediately_and_keep_inactive_results() { + use crate::instance::content::updates::{ + AvailableUpdate, PENDING_UPDATE_SNAPSHOTS, PendingUpdateSnapshot, UpdateSnapshot, + }; + let mut ui = UiHarness::new(); + for name in ["Streaming A", "Streaming B"] { + ui.add_instance(name); + } + ui.app.instances_state.list_state.selected = Some(0); + ui.app.sync_instance_content(); + let installed = crate::instance::ProviderProject { + provider: "modrinth".to_owned(), + project_id: "project".to_owned(), + version_id: "old".to_owned(), + }; + let mut entry = + crate::instance::scan_one_mod(std::path::Path::new("example.jar"), "example", true); + entry.provider_project = Some(installed.clone()); + ui.app.mods_state.set_entries(vec![entry]); + let snapshot = UpdateSnapshot { + game_version: "1.21.1".to_owned(), loader: crate::instance::ModLoader::Fabric, + inventory: vec![installed.clone()], checked_at: 0, + updates: vec![AvailableUpdate { + installed, current: None, kind: crate::instance::ContentKind::Mod, + target: serde_json::from_value(serde_json::json!({ + "id": "new", "name": "New", "version_number": "2", "game_versions": [], "loaders": [], "files": [] + })).unwrap(), + }], failures: Vec::new(), + }; + { + let mut pending = PENDING_UPDATE_SNAPSHOTS.lock().unwrap(); + pending.clear(); + for instance in &ui.app.instances_state.instances { + pending.push(PendingUpdateSnapshot { + instance_name: instance.name.clone(), + instance_created: instance.created, + snapshot: snapshot.clone(), + }); + } + } + ui.app.drain_content_update_snapshots(); + assert_eq!( + ui.app.mods_state.entries[0].title_suffix.as_deref(), + Some("Update") + ); + assert_eq!( + ui.app + .content_update_snapshot + .as_ref() + .unwrap() + .1 + .checked_at, + 0 + ); + assert_eq!(PENDING_UPDATE_SNAPSHOTS.lock().unwrap().len(), 1); + ui.app.instances_state.list_state.selected = Some(1); + ui.app.sync_instance_content(); + ui.app.drain_content_update_snapshots(); + assert_eq!( + ui.app.content_update_snapshot.as_ref().unwrap().0, + "Streaming B" + ); + assert!(PENDING_UPDATE_SNAPSHOTS.lock().unwrap().is_empty()); +} + +#[test] +fn update_badges_stream_while_the_content_index_is_still_being_saved() { + use crate::instance::content::{manifest, reconcile, updates}; + use std::{collections::HashMap, sync::Arc}; + + fn wait_for(mut ready: impl FnMut() -> bool) { + let deadline = std::time::Instant::now() + Duration::from_secs(5); + while !ready() { + assert!( + std::time::Instant::now() < deadline, + "content work timed out" + ); + std::thread::sleep(Duration::from_millis(5)); + } + } + + let mut ui = UiHarness::new(); + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .enable_all() + .build() + .unwrap(); + let _runtime = runtime.enter(); + ui.add_instance("Streaming index"); + ui.app.sync_instance_content(); + let instance = ui.app.instances_state.selected_instance().unwrap().clone(); + let paths = crate::storage::InstancePaths::new(ui.instance_path(&instance.name)); + let minecraft = paths.minecraft(); + let mut saved = crate::instance::ContentManifest::default(); + let mut entries = Vec::new(); + let mut versions = Vec::new(); + let mut pauses = HashMap::new(); + for name in ["alpha", "bravo"] { + let relative_path = std::path::PathBuf::from("mods").join(format!("{name}.jar")); + let path = minecraft.join(&relative_path); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, name).unwrap(); + saved.files.push(crate::instance::ContentFileRecord { + relative_path, + kind: crate::instance::ContentKind::Mod, + enabled: true, + fingerprint: manifest::fingerprint(&path).unwrap(), + resolution: crate::instance::Resolution::Resolved { + project: crate::instance::ProviderProject { + provider: "modrinth".to_owned(), + project_id: name.to_owned(), + version_id: format!("{name}-old"), + }, + }, + provider_aliases: Vec::new(), + provider_checks: vec!["modrinth".to_owned(), "curseforge".to_owned()], + required_dependencies: Vec::new(), + automatic_dependency: false, + cleanup_eligible: false, + }); + entries.push(crate::instance::scan_one_mod(&path, name, true)); + for (suffix, date) in [ + ("old", "2026-01-01T00:00:00Z"), + ("new", "2026-02-01T00:00:00Z"), + ] { + versions.push( + serde_json::from_value(serde_json::json!({ + "id": format!("{name}-{suffix}"), "project_id": name, + "name": name, "version_number": suffix, + "date_published": date, "game_versions": ["1.21.1"], + "loaders": ["fabric"], "files": [] + })) + .unwrap(), + ); + } + pauses.insert(name.to_owned(), Arc::new(tokio::sync::Semaphore::new(0))); + } + let mut removed = saved.files[0].clone(); + removed.relative_path = std::path::PathBuf::from("mods").join("removed.jar"); + saved.files.push(removed); + saved.save(&paths.content_manifest()).unwrap(); + let stream = ui.app.mods_state.start_stream(&instance.name); + let _shader_stream = ui.app.shaders_state.start_stream(&instance.name); + updates::PENDING_UPDATE_SNAPSHOTS.lock().unwrap().clear(); + reconcile::PENDING_RECONCILIATIONS.lock().unwrap().clear(); + let instances_dir = ui.app.instance_manager.instances_dir.clone(); + let indexing_instance = instance.clone(); + let (resume_save, saving) = std::sync::mpsc::channel(); + let indexing = runtime.spawn(async move { + let task = crate::feedback::progress::ProgressTask::start("Preparing content index"); + let result = reconcile::reconcile( + indexing_instance, + instances_dir, + crate::net::HttpClient::new(), + &task, + move |result| { + reconcile::publish_reconciliation(result); + saving.recv().unwrap(); + }, + ) + .await; + reconcile::publish_reconciliation(result); + }); + wait_for(|| { + !reconcile::PENDING_RECONCILIATIONS + .lock() + .unwrap() + .is_empty() + }); + assert!(!reconcile::PENDING_RECONCILIATIONS.lock().unwrap()[0].complete); + ui.app.drain_content_reconciliation(); + assert_eq!( + ui.app.content_update_check_pending, + crate::config::SETTINGS.read().general.check_content_updates + ); + assert!(!ui.app.content_update_check_ready()); + for entry in entries { + assert!(stream.send(entry)); + } + ui.app.mods_state.drain_pending(); + ui.app.apply_cached_content_manifest(); + assert!(ui.app.content_update_check_ready()); + assert!(ui.app.mods_state.is_scanning()); + assert!(ui.app.shaders_state.is_scanning()); + let priority = ui.app.content_update_priority(); + let manifest = ui.app.content_manifest.as_ref().unwrap().1.clone(); + ui.app.content_update_check_pending = false; + let (started, mut requests) = tokio::sync::mpsc::unbounded_channel(); + let registry = Arc::new( + crate::instance::content::dependencies::tests::controlled_update_registry( + versions, + started, + pauses.clone(), + ), + ); + let start_check = |manifest: &crate::instance::ContentManifest, previous| { + updates::spawn_with_registry( + instance.clone(), + manifest.clone(), + paths.content_updates(), + priority.clone(), + previous, + registry.clone(), + ) + }; + let mut wait_for_requests = || { + runtime.block_on(async { + for _ in 0..2 { + tokio::time::timeout(Duration::from_secs(5), requests.recv()) + .await + .unwrap() + .unwrap(); + } + }) + }; + assert!(start_check(&manifest, None)); + assert!(!start_check(&manifest, None)); + wait_for_requests(); + pauses["alpha"].add_permits(1); + wait_for(|| !updates::PENDING_UPDATE_SNAPSHOTS.lock().unwrap().is_empty()); + ui.app.drain_content_update_snapshots(); + assert_eq!( + ui.app.mods_state.entries[0].title_suffix.as_deref(), + Some("Update") + ); + assert_eq!(ui.app.mods_state.entries[1].title_suffix, None); + assert!(updates::is_running( + &instance, + &manifest, + &paths.content_updates() + )); + assert_eq!( + crate::instance::ContentManifest::load(&paths.content_manifest()) + .unwrap() + .files + .len(), + 3 + ); + assert!( + reconcile::PENDING_RECONCILIATIONS + .lock() + .unwrap() + .is_empty() + ); + ui.draw(); + assert!(ui.screen().contains("Update")); + assert_eq!( + crate::feedback::progress::PROGRESS.lock().unwrap().progress, + Some((1, 2)) + ); + + resume_save.send(()).unwrap(); + runtime.block_on(indexing).unwrap(); + wait_for(|| { + !reconcile::PENDING_RECONCILIATIONS + .lock() + .unwrap() + .is_empty() + }); + assert!(reconcile::PENDING_RECONCILIATIONS.lock().unwrap()[0].complete); + assert_eq!( + crate::instance::ContentManifest::load(&paths.content_manifest()) + .unwrap() + .files + .len(), + 2 + ); + ui.app.drain_content_reconciliation(); + assert!(!ui.app.content_update_check_pending); + assert_eq!( + ui.app.mods_state.entries[0].title_suffix.as_deref(), + Some("Update") + ); + assert_eq!(ui.app.mods_state.entries[1].title_suffix, None); + assert_eq!( + ui.app + .content_update_snapshot + .as_ref() + .unwrap() + .1 + .checked_at, + 0 + ); + pauses["bravo"].add_permits(1); + wait_for(|| !updates::is_running(&instance, &manifest, &paths.content_updates())); + ui.app.content_update_check_pending = true; + ui.app.drain_content_update_snapshots(); + assert!(!ui.app.content_update_check_pending); + assert!( + ui.app + .mods_state + .entries + .iter() + .all(|entry| entry.title_suffix.as_deref() == Some("Update")) + ); + + ui.app + .content_update_snapshot + .as_mut() + .unwrap() + .1 + .checked_at = 0; + reconcile::publish_reconciliation(reconcile::ReconcileResult { + instance_name: instance.name.clone(), + instance_created: instance.created, + manifest: manifest.clone(), + complete: true, + error: None, + }); + ui.app.drain_content_reconciliation(); + assert!(ui.app.content_update_check_pending); + let previous = ui.app.content_update_snapshot.as_ref().unwrap().1.clone(); + assert!(start_check(&manifest, Some(previous))); + wait_for_requests(); + + let mut changed = manifest.clone(); + changed.files[1].resolution = crate::instance::Resolution::Resolved { + project: crate::instance::ProviderProject { + provider: "modrinth".to_owned(), + project_id: "bravo".to_owned(), + version_id: "bravo-new".to_owned(), + }, + }; + changed.save(&paths.content_manifest()).unwrap(); + reconcile::publish_reconciliation(reconcile::ReconcileResult { + instance_name: instance.name.clone(), + instance_created: instance.created, + manifest: changed.clone(), + complete: true, + error: None, + }); + ui.app.drain_content_reconciliation(); + assert!(ui.app.content_update_check_ready()); + let previous = ui.app.content_update_snapshot.as_ref().unwrap().1.clone(); + assert!(start_check(&changed, Some(previous))); + wait_for_requests(); + pauses["bravo"].add_permits(1); + wait_for(|| !updates::PENDING_UPDATE_SNAPSHOTS.lock().unwrap().is_empty()); + ui.app.drain_content_update_snapshots(); + assert_eq!( + ui.app.mods_state.entries[0].title_suffix.as_deref(), + Some("Update") + ); + assert_eq!(ui.app.mods_state.entries[1].title_suffix, None); + assert!(updates::is_running( + &instance, + &changed, + &paths.content_updates() + )); + assert_eq!( + ui.app + .content_update_snapshot + .as_ref() + .unwrap() + .1 + .checked_at, + 0 + ); + pauses["alpha"].add_permits(1); + wait_for(|| !updates::is_running(&instance, &changed, &paths.content_updates())); + ui.app.drain_content_update_snapshots(); + assert!( + ui.app + .content_update_snapshot + .as_ref() + .unwrap() + .1 + .matches_manifest(&changed) + ); + assert!( + updates::UpdateSnapshot::load(&paths.content_updates()) + .unwrap() + .matches_manifest(&changed) + ); + assert!(!ui.app.content_update_check_pending); + let previous = ui.app.content_update_snapshot.as_ref().unwrap().1.clone(); + assert!(start_check(&changed, Some(previous))); + wait_for_requests(); + assert!(updates::is_running( + &instance, + &changed, + &paths.content_updates() + )); + ui.app.forget_instance_content(&instance.name); + assert!(!updates::is_running( + &instance, + &changed, + &paths.content_updates() + )); + assert!(updates::PENDING_UPDATE_SNAPSHOTS.lock().unwrap().is_empty()); + assert!(requests.try_recv().is_err()); +} + +fn key_kind(code: KeyCode, kind: KeyEventKind) -> KeyEvent { + KeyEvent::new_with_kind(code, KeyModifiers::NONE, kind) +} + +#[test] +fn dispatch_repeats_navigation_but_not_launch_delete_or_confirmation() { + let mut ui = UiHarness::new(); + for name in ["First", "Second", "Third"] { + ui.add_instance(name); + } + ui.app.instances_state.list_state.selected = Some(0); + ui.draw(); + + assert!(ui.key_event(key_kind(KeyCode::Down, KeyEventKind::Press))); + assert_eq!(ui.app.instances_state.list_state.selected, Some(1)); + assert!(ui.key_event(key_kind(KeyCode::Down, KeyEventKind::Repeat))); + assert_eq!(ui.app.instances_state.list_state.selected, Some(2)); + assert!(!ui.key_event(key_kind(KeyCode::Up, KeyEventKind::Release))); + assert_eq!(ui.app.instances_state.list_state.selected, Some(2)); + + for code in [ + KeyCode::Char('l'), + KeyCode::Char('d'), + KeyCode::Char('u'), + KeyCode::Enter, + ] { + assert!(!ui.key_event(key_kind(code, KeyEventKind::Repeat))); + } + assert_eq!(ui.app.focused, FocusedArea::Instances); + assert!(crate::instance::runtime::get("Third").is_none()); + assert!(widgets::popups::confirm::pending_target().is_none()); + + ui.key(KeyCode::Char('d')); + assert_eq!(ui.app.focused, FocusedArea::ConfirmDelete); + // A search behind the confirmation cannot turn its 'y' into repeatable text. + ui.app.instances_state.search.active = true; + for kind in [KeyEventKind::Repeat, KeyEventKind::Release] { + for code in [KeyCode::Enter, KeyCode::Char('y'), KeyCode::Char('n')] { + assert!(!ui.key_event(key_kind(code, kind))); + } + } + assert!(ui.instance_path("Third").exists()); + assert_eq!(ui.app.focused, FocusedArea::ConfirmDelete); + ui.app.instances_state.search.active = false; + ui.key(KeyCode::Char('y')); + assert!(!ui.instance_path("Third").exists()); + assert!(!ui.key_event(key_kind(KeyCode::Char('y'), KeyEventKind::Repeat))); + assert_eq!(ui.app.instances_state.instances.len(), 2); +} + +#[test] +fn dispatch_repeats_text_and_backspace_in_search_rename_account_and_profile_inputs() { + let mut ui = UiHarness::new(); + ui.add_instance("Text Fields"); + + ui.app.instances_state.search.activate(); + ui.key_event(key_kind(KeyCode::Char('d'), KeyEventKind::Press)); + ui.key_event(key_kind(KeyCode::Char('d'), KeyEventKind::Repeat)); + assert!(!ui.key_event(key_kind(KeyCode::Char('d'), KeyEventKind::Release))); + assert_eq!(ui.app.instances_state.search.query, "dd"); + assert!(ui.key_event(key_kind(KeyCode::Backspace, KeyEventKind::Repeat))); + assert_eq!(ui.app.instances_state.search.query, "d"); + assert!(!ui.key_event(key_kind(KeyCode::Enter, KeyEventKind::Repeat))); + assert!(ui.app.instances_state.search.active); + ui.app.instances_state.search.deactivate(); + + ui.app.instances_state.renaming = Some(String::new()); + assert!(ui.key_event(key_kind(KeyCode::Char('l'), KeyEventKind::Repeat))); + assert_eq!(ui.app.instances_state.renaming.as_deref(), Some("l")); + assert!(!ui.key_event(key_kind(KeyCode::Enter, KeyEventKind::Repeat))); + assert!(ui.instance_path("Text Fields").exists()); + ui.app.instances_state.renaming = None; + + ui.app.focused = FocusedArea::Account; + ui.app.account_state.add_mode = widgets::account::AddMode::OfflineNameInput(String::new()); + assert!(ui.key_event(key_kind(KeyCode::Char('d'), KeyEventKind::Repeat))); + assert!( + matches!(&ui.app.account_state.add_mode, widgets::account::AddMode::OfflineNameInput(name) if name == "d") + ); + assert!(!ui.key_event(key_kind(KeyCode::Enter, KeyEventKind::Repeat))); + assert_eq!(ui.app.focused, FocusedArea::Account); + + ui.app.focused = FocusedArea::Settings; + ui.app.settings_state.add_mode = widgets::settings::AddMode::ProfileName(String::new()); + assert!(ui.key_event(key_kind(KeyCode::Char('q'), KeyEventKind::Repeat))); + assert!( + matches!(&ui.app.settings_state.add_mode, widgets::settings::AddMode::ProfileName(name) if name == "q") + ); + assert!(!ui.key_event(key_kind(KeyCode::Enter, KeyEventKind::Repeat))); + assert!(!ui.app.exit); +} + +#[test] +fn dispatch_does_not_repeat_content_toggles_or_install_confirmation() { + let mut ui = UiHarness::new(); + ui.add_instance("One Shot Content"); + let path = ui + .instance_path("One Shot Content") + .join(crate::storage::MINECRAFT_DIR_NAME) + .join("mods/test.jar"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, b"mod").unwrap(); + ui.app.focused = FocusedArea::Content; + ui.app + .mods_state + .set_entries(vec![crate::instance::content::entry::ContentEntry { + file_stem: "test".to_owned(), + name: "Test Mod".to_owned(), + source_slug: None, + installed_path: None, + provider_project: None, + world_details: None, + title_suffix: None, + footer_label: None, + footer_change: None, + description: String::new(), + enabled: true, + icon_bytes: None, + provider_icon: false, + provider_description: false, + path: path.clone(), + icon_lines: None, + }]); + ui.app.mods_state.list_state.selected = Some(0); + assert!(!ui.key_event(key_kind(KeyCode::Enter, KeyEventKind::Repeat))); + assert!(path.exists()); + ui.key(KeyCode::Enter); + assert!(!path.exists()); + assert!(path.with_extension("jar.disabled").exists()); + assert!(!ui.key_event(key_kind(KeyCode::Enter, KeyEventKind::Repeat))); + assert!(!path.exists()); + + ui.app + .mods_discovery_state + .begin_managed_modpack_versions( + "Install", + crate::instance::ProviderProject { + provider: "modrinth".to_owned(), + project_id: "test".to_owned(), + version_id: "installed".to_owned(), + }, + ) + .unwrap(); + let popup = ui.app.mods_discovery_state.version_popup.as_mut().unwrap(); + popup.loading = false; + popup.confirming = true; + ui.app.mods_discovery_state.search.activate(); + for code in [KeyCode::Enter, KeyCode::Char('s'), KeyCode::Tab] { + assert!(!ui.key_event(key_kind(code, KeyEventKind::Repeat))); + } + let popup = ui.app.mods_discovery_state.version_popup.as_ref().unwrap(); + assert!(!popup.installing); + assert!(!popup.skip_dependencies); + + let popup = ui.app.mods_discovery_state.version_popup.as_mut().unwrap(); + popup.confirming = false; + popup.selecting_world = true; + popup.worlds.search.activate(); + assert!(ui.key_event(key_kind(KeyCode::Char('d'), KeyEventKind::Repeat))); + assert_eq!( + ui.app + .mods_discovery_state + .version_popup + .as_ref() + .unwrap() + .worlds + .search + .query, + "d" + ); + assert!(!ui.key_event(key_kind(KeyCode::Enter, KeyEventKind::Repeat))); +} + +#[test] +fn dispatch_repeats_only_the_visible_content_search() { + use widgets::content::{ContentMode, ContentTab}; + + let mut ui = UiHarness::new(); + ui.app.focused = FocusedArea::Content; + for tab in [ + ContentTab::Mods, + ContentTab::ResourcePacks, + ContentTab::Shaders, + ContentTab::Worlds, + ContentTab::Screenshots, + ContentTab::Logs, + ] { + ui.app.content_tab = tab; + ui.key(KeyCode::Char('/')); + assert!( + ui.key_event(key_kind(KeyCode::Char('d'), KeyEventKind::Repeat)), + "{tab:?}" + ); + let query = match tab { + ContentTab::Mods => &ui.app.mods_state.search.query, + ContentTab::ResourcePacks => &ui.app.resource_packs_state.search.query, + ContentTab::Shaders => &ui.app.shaders_state.search.query, + ContentTab::Worlds => &ui.app.worlds_state.search.query, + ContentTab::Screenshots => &ui.app.screenshots_state.search.query, + ContentTab::Logs => &ui.app.logs_state.search.query, + _ => unreachable!(), + }; + assert_eq!(query, "d"); + assert!(!ui.key_event(key_kind(KeyCode::Tab, KeyEventKind::Repeat))); + ui.key(KeyCode::Esc); + } + ui.app.content_tab = ContentTab::Worlds; + ui.app.open_world_datapacks = Some(("World".to_owned(), std::path::PathBuf::from("World"))); + ui.app.world_datapacks_state.search.activate(); + assert!(ui.key_event(key_kind(KeyCode::Char('u'), KeyEventKind::Repeat))); + assert_eq!(ui.app.world_datapacks_state.search.query, "u"); + ui.app.open_world_datapacks = None; + + ui.app.content_tab = ContentTab::Logs; + ui.app.logs_state.viewer_focused = true; + ui.app.logs_state.viewer_search.activate(); + assert!(ui.key_event(key_kind(KeyCode::Char('G'), KeyEventKind::Repeat))); + assert_eq!(ui.app.logs_state.viewer_search.query, "G"); + + ui.app.content_tab = ContentTab::Mods; + ui.app.content_mode = ContentMode::Discover; + ui.app.mods_discovery_state.search.activate(); + assert!(ui.key_event(key_kind(KeyCode::Char('v'), KeyEventKind::Repeat))); + assert_eq!(ui.app.mods_discovery_state.search.query, "v"); + assert!(ui.app.mods_discovery_state.version_popup.is_none()); + ui.app.mods_discovery_state.search.deactivate(); + ui.app.mods_discovery_state.sort_panel_open = true; + ui.app.mods_discovery_state.sort_panel_focused = true; + ui.app.mods_discovery_state.filter_version_picker_open = true; + ui.app.mods_discovery_state.filter_version_search.activate(); + assert!(ui.key_event(key_kind(KeyCode::Char('s'), KeyEventKind::Repeat))); + assert_eq!(ui.app.mods_discovery_state.filter_version_search.query, "s"); + assert!(!ui.app.mods_discovery_state.filter_show_snapshots); +} + +#[test] +fn dispatch_repeats_instance_setting_text_but_not_picker_selection_or_toggles() { + let mut ui = UiHarness::new(); + ui.add_instance("Settings Text"); + ui.key(KeyCode::Char('E')); + for _ in 0..4 { + ui.key_event(key_kind(KeyCode::Down, KeyEventKind::Repeat)); + } + ui.key(KeyCode::Char('c')); + assert!( + ui.app + .instance_settings + .as_ref() + .unwrap() + .text_input_active() + ); + ui.key(KeyCode::Char('d')); + assert!(ui.key_event(key_kind(KeyCode::Char('d'), KeyEventKind::Repeat))); + assert!(!ui.key_event(key_kind(KeyCode::Char('d'), KeyEventKind::Release))); + assert!(!ui.key_event(key_kind(KeyCode::Enter, KeyEventKind::Repeat))); + ui.key(KeyCode::Enter); + assert_eq!( + ui.app + .instances_state + .selected_instance() + .unwrap() + .java_path + .as_deref(), + Some("dd") + ); + assert!(!ui.key_event(key_kind(KeyCode::Right, KeyEventKind::Repeat))); + assert!(!ui.key_event(key_kind(KeyCode::Char('a'), KeyEventKind::Repeat))); + + ui.key(KeyCode::Esc); + ui.key(KeyCode::Char('E')); + ui.key(KeyCode::Down); + ui.key(KeyCode::Enter); + let loader = ui.app.instance_settings.as_ref().unwrap().draft.loader; + assert!(!ui.key_event(key_kind(KeyCode::Right, KeyEventKind::Repeat))); + assert_eq!( + ui.app.instance_settings.as_ref().unwrap().draft.loader, + loader + ); +} + +#[test] +fn dispatch_repeats_wizard_name_import_input_and_discovery_search() { + let mut ui = UiHarness::new(); + ui.key(KeyCode::Char('a')); + ui.key(KeyCode::Char('q')); + assert!(ui.key_event(key_kind(KeyCode::Char('q'), KeyEventKind::Repeat))); + assert!(!ui.key_event(key_kind(KeyCode::Char('q'), KeyEventKind::Release))); + assert!(!ui.key_event(key_kind(KeyCode::Enter, KeyEventKind::Repeat))); + ui.draw(); + assert!(ui.screen().contains("qq")); + assert!(!ui.app.exit); + ui.key(KeyCode::Esc); + + ui.key(KeyCode::Char('m')); + ui.key(KeyCode::Char('i')); + ui.key(KeyCode::Char('q')); + assert!(ui.key_event(key_kind(KeyCode::Char('q'), KeyEventKind::Repeat))); + assert!(!ui.key_event(key_kind(KeyCode::Enter, KeyEventKind::Repeat))); + ui.draw(); + assert!(ui.screen().contains("qq")); + ui.key(KeyCode::Esc); + ui.key(KeyCode::Char('/')); + assert!(ui.key_event(key_kind(KeyCode::Char('v'), KeyEventKind::Repeat))); + assert!(!ui.key_event(key_kind(KeyCode::Enter, KeyEventKind::Repeat))); + ui.draw(); + assert!(ui.screen().contains("/ v")); +} + +#[test] +fn gui_editor_handoff_process() {} + +#[test] +fn unrelated_directory_events_do_not_postpone_an_edited_file_save() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("instance.json"); + std::fs::write(&path, b"old").unwrap(); + let mut watch = EditedConfigWatch::new(path.clone()).unwrap(); + let (sender, events) = std::sync::mpsc::channel(); + watch.events = events; + watch.pending = Some(std::time::Instant::now() - Duration::from_secs(1)); + std::fs::write(path, b"new").unwrap(); + sender + .send(Ok(notify::Event::new(notify::EventKind::Modify( + notify::event::ModifyKind::Any, + )) + .add_path(temp.path().join("other.json")))) + .unwrap(); + assert!(watch.changed()); + std::fs::write(temp.path().join("instance.json"), b"changed again").unwrap(); + sender + .send(Ok(notify::Event::new(notify::EventKind::Modify( + notify::event::ModifyKind::Any, + )) + .add_path(temp.path().join("INSTANCE.JSON")))) + .unwrap(); + assert!(!watch.changed()); + assert!(watch.pending.is_some()); + watch.pending = Some(std::time::Instant::now() - Duration::from_secs(1)); + assert!(watch.changed()); +} + +fn wait_for_edited_config(ui: &mut UiHarness, changed: bool) { + let deadline = std::time::Instant::now() + Duration::from_secs(5); + let mut observed = false; + loop { + let reloaded = ui.app.drain_edited_configs(); + observed |= ui + .app + .edited_config_watches + .iter() + .any(|watch| watch.pending.is_some()); + if changed && reloaded { + return; + } + assert!(!reloaded, "unchanged bytes must not reload"); + if !changed + && observed + && ui + .app + .edited_config_watches + .iter() + .all(|watch| watch.pending.is_none()) + { + return; + } + assert!( + std::time::Instant::now() < deadline, + "edited file notification timed out" + ); + std::thread::sleep(Duration::from_millis(20)); + } +} + +#[test] +fn gui_editor_saves_reload_after_handoff_and_atomic_replacement_only_when_bytes_change() { + let mut ui = UiHarness::new(); + ui.add_instance("GUI Edited"); + let path = ui.instance_path("GUI Edited").join("instance.json"); + let mut config = ui.app.instances_state.selected_instance().unwrap().clone(); + config.memory_max = Some("4G".to_owned()); + ui.app.instance_manager.save(&config).unwrap(); + let original = std::fs::read(&path).unwrap(); + + let reaper = ui + .app + .launch_gui_editor( + std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "tui::event::tests::gui_editor_handoff_process"]), + &path, + ) + .unwrap(); + assert!(!ui.app.drain_edited_configs()); + reaper.join().unwrap(); + assert!(!ui.app.drain_edited_configs()); + assert_eq!( + ui.app + .instances_state + .selected_instance() + .unwrap() + .memory_max, + None + ); + ui.app.watch_edited_config(&path).unwrap(); + assert_eq!(ui.app.edited_config_watches.len(), 1); + + std::fs::write(&path, &original).unwrap(); + wait_for_edited_config(&mut ui, false); + assert_eq!( + ui.app + .instances_state + .selected_instance() + .unwrap() + .memory_max, + None + ); + + config.memory_max = Some("8G".to_owned()); + std::fs::write(&path, serde_json::to_vec(&config).unwrap()).unwrap(); + wait_for_edited_config(&mut ui, true); + assert_eq!( + ui.app + .instances_state + .selected_instance() + .unwrap() + .memory_max + .as_deref(), + Some("8G") + ); + + config.memory_max = Some("12G".to_owned()); + crate::storage::write_atomic(&path, &serde_json::to_vec(&config).unwrap()).unwrap(); + wait_for_edited_config(&mut ui, true); + assert_eq!( + ui.app + .instances_state + .selected_instance() + .unwrap() + .memory_max + .as_deref(), + Some("12G") + ); + + config.memory_max = Some("16G".to_owned()); + std::fs::write(&path, serde_json::to_vec(&config).unwrap()).unwrap(); + wait_for_edited_config(&mut ui, true); + assert_eq!( + ui.app + .instances_state + .selected_instance() + .unwrap() + .memory_max + .as_deref(), + Some("16G") + ); + + std::fs::write(&path, b"invalid instance config").unwrap(); + wait_for_edited_config(&mut ui, true); + assert_eq!( + ui.app + .instances_state + .selected_instance() + .unwrap() + .memory_max + .as_deref(), + Some("16G") + ); + assert!( + error_buffer::peek_error() + .unwrap() + .message + .contains("Failed to reload edited instance") + ); + config.memory_max = Some("20G".to_owned()); + crate::storage::write_atomic(&path, &serde_json::to_vec(&config).unwrap()).unwrap(); + wait_for_edited_config(&mut ui, true); + assert_eq!( + ui.app + .instances_state + .selected_instance() + .unwrap() + .memory_max + .as_deref(), + Some("20G") + ); +} + +#[cfg(unix)] +#[test] +fn launcher_config_save_process() { + use std::os::unix::fs::PermissionsExt; + + if std::env::var_os("RMCL_EDITOR_CONFIG_TEST").is_none() { + return; + } + let mut ui = UiHarness::new(); + let config_path = crate::config::get_config_path().join("config.toml"); + let theme_path = crate::config::get_config_path().join("theme.toml"); + let mut theme = crate::config::theme::ThemeConfig::default(); + std::fs::write(&theme_path, toml::to_string(&theme).unwrap()).unwrap(); + ui.app.watch_edited_config(&config_path).unwrap(); + ui.app.watch_edited_config(&theme_path).unwrap(); + assert!(!ui.app.drain_edited_configs()); + + let mut config = crate::config::SETTINGS.read().clone(); + ui.add_instance("Inherited Java"); + std::fs::create_dir_all(ui.instance_path("Inherited Java").join("minecraft")).unwrap(); + let java = ui + .app + .instance_manager + .instances_dir + .parent() + .unwrap() + .join("selected-java"); + std::fs::write( + &java, + b"#!/bin/sh\nprintf 'java.version = %s\\n' \"$RMCL_TEST_JAVA_VERSION\"\n", + ) + .unwrap(); + std::fs::set_permissions(&java, std::fs::Permissions::from_mode(0o755)).unwrap(); + config.paths.java_path = Some(java.to_string_lossy().into_owned()); + config + .defaults + .environment + .insert("RMCL_TEST_JAVA_VERSION".to_owned(), "21".to_owned()); + config.defaults.memory_max = "6G".to_owned(); + crate::config::SETTINGS + .save_launcher_settings(config.clone()) + .unwrap(); + ui.app.settings_state.pane = widgets::settings::SettingsPane::Info; + fn wait_for_java(ui: &mut UiHarness, java: &str, memory: &str) { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + loop { + ui.draw(); + let screen = ui.screen(); + if screen.contains(java) { + assert!(screen.contains(memory), "{screen}"); + return; + } + assert!(std::time::Instant::now() < deadline, "{screen}"); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + } + wait_for_java(&mut ui, "jdk21", "6G"); + wait_for_edited_config(&mut ui, true); + + config.ui.error_auto_dismiss_ms += 1; + let timeout = config.ui.error_auto_dismiss_ms; + config + .defaults + .environment + .insert("RMCL_TEST_JAVA_VERSION".to_owned(), "25".to_owned()); + config.defaults.memory_max = "10G".to_owned(); + std::fs::write(&config_path, toml::to_string(&config).unwrap()).unwrap(); + wait_for_edited_config(&mut ui, true); + assert_eq!( + crate::config::SETTINGS.read().ui.error_auto_dismiss_ms, + timeout + ); + wait_for_java(&mut ui, "jdk25", "10G"); + + let other_java = java.with_file_name("other-java"); + std::fs::write(&other_java, b"#!/bin/sh\nprintf 'java.version = 17\\n'\n").unwrap(); + std::fs::set_permissions(&other_java, std::fs::Permissions::from_mode(0o755)).unwrap(); + config.paths.java_path = Some(other_java.to_string_lossy().into_owned()); + crate::config::SETTINGS + .save_launcher_settings(config) + .unwrap(); + wait_for_java(&mut ui, "jdk17", "10G"); + wait_for_edited_config(&mut ui, true); + + theme.theme = "dracula".to_owned(); + theme.border_style = crate::config::theme::BorderStyle::Thick; + crate::storage::write_atomic(&theme_path, toml::to_string(&theme).unwrap().as_bytes()).unwrap(); + wait_for_edited_config(&mut ui, true); + assert_eq!( + crate::config::theme::current_theme_config().theme, + "dracula" + ); + assert_eq!( + crate::config::theme::BORDER_STYLE.current(), + crate::config::theme::BorderStyle::Thick + ); +} + +#[cfg(unix)] +#[test] +fn watched_launcher_config_and_theme_saves_update_cached_settings() { + let ui = UiHarness::new(); + let root = ui.app.instance_manager.instances_dir.parent().unwrap(); + let result = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "tui::event::tests::launcher_config_save_process", + "--nocapture", + ]) + .env("RMCL_EDITOR_CONFIG_TEST", "1") + .env("HOME", root) + .env("XDG_CONFIG_HOME", root) + .output() + .unwrap(); + assert!( + result.status.success(), + "{}{}", + String::from_utf8_lossy(&result.stdout), + String::from_utf8_lossy(&result.stderr) + ); +} + #[test] fn edited_instance_config_reloads_into_the_ui() { let mut ui = UiHarness::new(); @@ -200,11 +1308,10 @@ fn structural_settings_update_repairs_runtime_before_persisting() { .mount(&server) .await; } + let asset_index = serde_json::to_vec(&serde_json::json!({"objects": {}})).unwrap(); Mock::given(method("GET")) .and(path("/assets.json")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "objects": {} - }))) + .respond_with(ResponseTemplate::new(200).set_body_bytes(asset_index.clone())) .expect(1) .mount(&server) .await; @@ -252,7 +1359,7 @@ fn structural_settings_update_repairs_runtime_before_persisting() { "assetIndex": { "id": "1.21.2", "url": format!("{}/assets.json", server.uri()), - "sha1": "unused" + "sha1": sha1(&asset_index) }, "downloads": { "client": { @@ -364,6 +1471,37 @@ fn editor_kind_is_detected_from_the_executable_name() { assert!(editor_runs_in_terminal("/usr/bin/nvim")); assert!(editor_runs_in_terminal("nano")); assert!(!editor_runs_in_terminal("/usr/bin/code")); + assert_eq!( + editor_parts("nvim -u NONE").unwrap(), + ["nvim", "-u", "NONE"] + ); +} + +#[test] +fn editor_commands_preserve_quoted_paths_arguments_and_empty_arguments() { + assert_eq!( + editor_parts(r#""/path with spaces/editor" --wait "two words" """#).unwrap(), + ["/path with spaces/editor", "--wait", "two words", ""] + ); + let temp = tempfile::tempdir().unwrap(); + let executable = temp.path().join("editor with spaces"); + std::fs::write(&executable, b"executable").unwrap(); + assert_eq!( + editor_parts(executable.to_str().unwrap()).unwrap(), + [executable.to_string_lossy().into_owned()] + ); + #[cfg(unix)] + assert!(editor_parts("editor 'unterminated").is_err()); + #[cfg(windows)] + assert_eq!( + editor_parts(r#""C:\Program Files\editor.exe" --wait "C:\folder with spaces\file.txt""#) + .unwrap(), + [ + r"C:\Program Files\editor.exe", + "--wait", + r"C:\folder with spaces\file.txt" + ] + ); } #[test] diff --git a/src/tui/tests/flows.rs b/src/tui/tests/flows.rs index a3560af..b9ed533 100644 --- a/src/tui/tests/flows.rs +++ b/src/tui/tests/flows.rs @@ -1,13 +1,13 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -use crossterm::event::{KeyCode, MouseEventKind}; +use crossterm::event::{KeyCode, MouseButton, MouseEvent, MouseEventKind}; use std::path::{Path, PathBuf}; use super::harness::UiHarness; use crate::instance::content::entry::ContentEntry; use crate::instance::{ - ContentFileRecord, ContentKind, ContentManifest, FileFingerprint, ProviderProject, Resolution, + ContentFileRecord, ContentKind, ContentManifest, ProviderProject, Resolution, }; use crate::net::modrinth::DiscoveryProject; use crate::tui::{ @@ -18,6 +18,22 @@ use crate::tui::{ }, }; +#[test] +fn remote_project_links_use_http_urls_and_encode_shell_metacharacters() { + let url = + crate::tui::input::project_link_url(r#"https://example.com/"&%USERNAME%?q=a b"#).unwrap(); + assert_eq!(url.as_str(), "https://example.com/%22&%USERNAME%?q=a%20b"); + for link in [ + "file:///C:/Windows/notepad.exe", + "javascript:alert(1)", + "shell:AppsFolder", + r"C:\folder\file", + "not a url", + ] { + assert!(crate::tui::input::project_link_url(link).is_err(), "{link}"); + } +} + #[test] fn global_navigation_returns_from_log_overlay() { let mut ui = UiHarness::new(); @@ -72,13 +88,13 @@ fn installed_version_action_requires_selected_provider_match() { ui.add_instance("Unmatched"); ui.app.focused = FocusedArea::Content; ui.app.content_tab = ContentTab::Mods; - let path = ui - .instance_path("Unmatched") - .join(crate::storage::MINECRAFT_DIR_NAME) - .join("mods/unknown.jar"); + let minecraft = crate::storage::InstancePaths::new(ui.instance_path("Unmatched")).minecraft(); + let path = minecraft.join("mods/unknown.jar"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, b"unknown").unwrap(); ui.app.mods_state.entries = vec![content_entry("Unknown mod", path)]; ui.app.mods_state.list_state.selected = Some(0); - let record = managed_mod_record("mods/unknown.jar", "known", false, Vec::new()); + let record = managed_mod_record(&minecraft, "mods/unknown.jar", "known", false, Vec::new()); let project = record.resolved_project().unwrap().clone(); ui.app.content_manifest = Some(( "Unmatched".to_owned(), @@ -102,13 +118,13 @@ fn installed_popup_navigation_preserves_local_filters() { ui.add_instance("Popup"); ui.app.focused = FocusedArea::Content; ui.app.content_tab = ContentTab::Mods; - let path = ui - .instance_path("Popup") - .join(crate::storage::MINECRAFT_DIR_NAME) - .join("mods/known.jar"); + let minecraft = crate::storage::InstancePaths::new(ui.instance_path("Popup")).minecraft(); + let path = minecraft.join("mods/known.jar"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, b"known").unwrap(); ui.app.mods_state.entries = vec![content_entry("Known mod", path)]; ui.app.mods_state.list_state.selected = Some(0); - let record = managed_mod_record("mods/known.jar", "known", false, Vec::new()); + let record = managed_mod_record(&minecraft, "mods/known.jar", "known", false, Vec::new()); let project = record.resolved_project().unwrap().clone(); ui.app.content_manifest = Some(( "Popup".to_owned(), @@ -282,15 +298,16 @@ fn world_datapack_version_action_requires_selected_provider_match() { ui.add_instance("Datapacks"); ui.app.focused = FocusedArea::Content; ui.app.content_tab = ContentTab::Worlds; - let world = ui - .instance_path("Datapacks") - .join(crate::storage::MINECRAFT_DIR_NAME) - .join("saves/World"); + let minecraft = crate::storage::InstancePaths::new(ui.instance_path("Datapacks")).minecraft(); + let world = minecraft.join("saves/World"); let path = world.join("datapacks/unknown.zip"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, b"pack").unwrap(); ui.app.world_datapacks_state.entries = vec![content_entry("Unknown datapack", path)]; ui.app.world_datapacks_state.list_state.selected = Some(0); ui.app.open_world_datapacks = Some(("World".to_owned(), world)); let mut record = managed_mod_record( + &minecraft, "saves/World/datapacks/unknown.zip", "known", false, @@ -482,6 +499,7 @@ fn confirmed_screenshot_delete_removes_state_and_file() { } fn managed_mod_record( + minecraft: &Path, path: &str, project_id: &str, automatic_dependency: bool, @@ -491,11 +509,8 @@ fn managed_mod_record( relative_path: PathBuf::from(path), kind: ContentKind::Mod, enabled: true, - fingerprint: FileFingerprint { - size: 1, - modified_ns: 1, - hashes: Default::default(), - }, + fingerprint: crate::instance::content::manifest::fingerprint(&minecraft.join(path)) + .unwrap(), resolution: Resolution::Resolved { project: ProviderProject { provider: "modrinth".to_owned(), @@ -552,8 +567,8 @@ fn deleting_a_mod_offers_its_unused_dependency_chain() { ContentManifest { version: 1, files: vec![ - managed_mod_record("mods/root.jar", "root", false, vec![dependency]), - managed_mod_record("mods/library.jar", "library", true, Vec::new()), + managed_mod_record(&minecraft, "mods/root.jar", "root", false, vec![dependency]), + managed_mod_record(&minecraft, "mods/library.jar", "library", true, Vec::new()), ], } .save(&crate::storage::InstancePaths::new(ui.instance_path("Dependencies")).content_manifest()) @@ -596,10 +611,12 @@ fn deleting_a_required_library_warns_but_can_continue() { let library_path = minecraft.join("mods/library.jar"); std::fs::create_dir_all(library_path.parent().unwrap()).unwrap(); std::fs::write(&library_path, b"l").unwrap(); + std::fs::write(minecraft.join("mods/root.jar"), b"r").unwrap(); ContentManifest { version: 1, files: vec![ managed_mod_record( + &minecraft, "mods/root.jar", "root", false, @@ -609,7 +626,7 @@ fn deleting_a_required_library_warns_but_can_continue() { version_id: "library-version".to_owned(), }], ), - managed_mod_record("mods/library.jar", "library", true, Vec::new()), + managed_mod_record(&minecraft, "mods/library.jar", "library", true, Vec::new()), ], } .save(&crate::storage::InstancePaths::new(ui.instance_path("Required")).content_manifest()) @@ -630,6 +647,58 @@ fn deleting_a_required_library_warns_but_can_continue() { assert!(!Path::new(&library_path).exists()); } +#[test] +fn content_delete_rejects_ownership_changed_after_confirmation_opened() { + let mut ui = UiHarness::new(); + ui.add_instance("ChangedOwner"); + let paths = crate::storage::InstancePaths::new(ui.instance_path("ChangedOwner")); + let minecraft = paths.minecraft(); + let path = minecraft.join("mods/root.jar"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, b"original").unwrap(); + let manifest = ContentManifest { + version: 1, + files: vec![managed_mod_record( + &minecraft, + "mods/root.jar", + "root", + false, + Vec::new(), + )], + }; + manifest.save(&paths.content_manifest()).unwrap(); + ui.app.content_manifest = Some(("ChangedOwner".to_owned(), manifest)); + ui.app.mods_state.entries = vec![content_entry("Root", path.clone())]; + ui.app.mods_state.list_state.selected = Some(0); + ui.app.focused = FocusedArea::Content; + ui.app.content_tab = ContentTab::Mods; + ui.key(KeyCode::Char('d')); + + let new_owner = ProviderProject { + provider: "curseforge".to_owned(), + project_id: "new-owner".to_owned(), + version_id: "new".to_owned(), + }; + ContentManifest::update(&paths.content_manifest(), |manifest| { + manifest.files[0].resolution = Resolution::Resolved { + project: new_owner.clone(), + }; + Ok(()) + }) + .unwrap(); + ui.key(KeyCode::Enter); + + assert_eq!(std::fs::read(&path).unwrap(), b"original"); + assert_eq!(ui.app.mods_state.entries[0].path, path); + assert_eq!( + ContentManifest::load(&paths.content_manifest()) + .unwrap() + .files[0] + .resolved_project(), + Some(&new_owner) + ); +} + #[test] fn confirmed_account_delete_updates_the_account_panel() { let mut ui = UiHarness::new(); @@ -666,6 +735,336 @@ fn confirmed_account_delete_updates_the_account_panel() { ); } +#[test] +fn typing_d_in_offline_account_name_does_not_open_delete_confirmation() { + let mut ui = UiHarness::new(); + ui.add_account("MicrosoftPlayer"); + ui.app.focused = FocusedArea::Account; + + ui.key(KeyCode::Char('a')); + ui.key(KeyCode::Char('o')); + ui.key(KeyCode::Char('d')); + + assert_eq!(ui.app.focused, FocusedArea::Account); + assert!(matches!( + &ui.app.account_state.add_mode, + crate::tui::widgets::account::AddMode::OfflineNameInput(name) if name == "d" + )); +} + +#[test] +fn switching_instances_discards_another_instances_update_review() { + let mut ui = UiHarness::new(); + ui.add_instance("A"); + ui.add_instance("B"); + let mut update = crate::tui::widgets::content::update::State::checking( + "A".to_owned(), + ContentKind::Mod, + None, + Vec::new(), + ); + update.phase = crate::tui::widgets::content::update::Phase::Review; + ui.app.content_update_popup = Some(update); + ui.app.instances_state.list_state.selected = Some(1); + + ui.key(KeyCode::Enter); + + assert!(ui.app.content_update_popup.is_none()); +} + +#[test] +fn checking_popup_locks_input_until_cancelled() { + let mut ui = UiHarness::new(); + ui.add_instance("A"); + ui.app.content_update_popup = Some(crate::tui::widgets::content::update::State::checking( + "A".to_owned(), + ContentKind::Mod, + None, + Vec::new(), + )); + ui.app.focused = FocusedArea::Content; + + ui.key(KeyCode::Tab); + assert!(ui.app.content_update_popup.is_some()); + assert_eq!(ui.app.content_tab, ContentTab::Mods); + ui.draw(); + assert!(ui.screen().contains("Preparing updates")); + + ui.key(KeyCode::Esc); + assert!(ui.app.content_update_popup.is_none()); +} + +#[test] +fn log_overlay_ignores_page_keys_and_stays_put_while_reading_history() { + use crate::tui::logging::{clear_app_logs, push_app_log}; + let mut ui = UiHarness::new(); + clear_app_logs(); + for index in 0..40 { + push_app_log(format!("12:00:{index:02}:INFO:rmcl: line {index}")); + } + ui.app.focused = FocusedArea::OverviewExpanded; + ui.draw(); + // 30-row terminal: overlay 28 rows, minus border = 26 visible lines. + assert_eq!(ui.app.log_overlay_max_scroll, 14); + assert_eq!(ui.app.log_overlay_scroll, 14); + + ui.key(KeyCode::PageUp); + assert_eq!(ui.app.log_overlay_scroll, 14); + ui.key(KeyCode::PageDown); + assert_eq!(ui.app.log_overlay_scroll, 14); + assert!(ui.screen().contains("[g/G] top/bottom")); + assert!(ui.screen().contains("[Esc] close")); + assert!(!ui.screen().contains("PgUp")); + assert!(!ui.screen().contains("[y]")); + for _ in 0..5 { + ui.key(KeyCode::Char('k')); + } + assert_eq!(ui.app.log_overlay_scroll, 9); + for index in 40..45 { + push_app_log(format!("12:01:{index:02}:INFO:rmcl: line {index}")); + } + ui.draw(); + assert_eq!(ui.app.log_overlay_max_scroll, 19); + assert_eq!(ui.app.log_overlay_scroll, 9); + + ui.key(KeyCode::End); + ui.draw(); + assert_eq!(ui.app.log_overlay_scroll, 19); + push_app_log("12:02:00:INFO:rmcl: latest".to_owned()); + ui.draw(); + assert_eq!(ui.app.log_overlay_scroll, 20); + clear_app_logs(); +} + +#[test] +fn log_overlay_level_filter_opens_cycles_and_closes() { + use crate::tui::logging::{clear_app_logs, push_app_log}; + use crate::tui::widgets::content::discovery::CategoryFilter; + let mut ui = UiHarness::new(); + clear_app_logs(); + push_app_log("12:00:00:ERROR:rmcl: failed".to_owned()); + push_app_log("12:00:00:INFO:rmcl: done".to_owned()); + ui.app.focused = FocusedArea::OverviewExpanded; + + ui.key(KeyCode::Char('f')); + assert!(ui.app.log_filter_open); + ui.draw(); + assert!(ui.screen().contains("Log levels")); + assert!(ui.screen().contains("· Error")); + ui.key(KeyCode::Enter); + assert_eq!(ui.app.log_level_filters[0], Some(CategoryFilter::Include)); + ui.draw(); + assert!(ui.screen().contains("+ Error")); + assert!(ui.screen().contains("1 filter(s)")); + ui.key(KeyCode::Esc); + ui.draw(); + assert!(ui.screen().contains("failed")); + assert!(!ui.screen().contains("done")); + ui.key(KeyCode::Char('f')); + ui.key(KeyCode::Enter); + ui.draw(); + assert!(ui.screen().contains("− Error")); + ui.key(KeyCode::Esc); + assert!(!ui.app.log_filter_open); + assert_eq!(ui.app.log_level_filters[0], Some(CategoryFilter::Exclude)); + ui.draw(); + assert!(!ui.screen().contains("failed")); + assert!(ui.screen().contains("done")); + clear_app_logs(); +} + +#[test] +fn mouse_drag_selects_viewer_characters_and_click_clears_yank_hint() { + use crate::instance::logs::files::LogFileEntry; + use crossterm::event::KeyModifiers; + let mut ui = UiHarness::new(); + ui.add_instance("A"); + ui.app.focused = FocusedArea::Content; + ui.app.content_tab = ContentTab::Logs; + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("a.log"); + std::fs::write(&path, "alpha\nbeta\ngamma").unwrap(); + ui.app.logs_state.entries = vec![LogFileEntry { + name: "a.log".to_owned(), + path, + }]; + ui.app.logs_state.list_state.selected = Some(0); + ui.app.logs_state.loaded_for = Some("A".to_owned()); + ui.app.logs_state.viewer_lines = + vec!["alpha".to_owned(), "beta".to_owned(), "gamma".to_owned()]; + ui.draw(); + assert!(!ui.screen().contains("[y]")); + let area = ui.app.logs_state.viewer_area; + assert!(area.height >= 3); + let click = |kind, row| MouseEvent { + kind, + column: area.x + 2, + row, + modifiers: KeyModifiers::NONE, + }; + ui.app + .handle_mouse_event(click(MouseEventKind::Down(MouseButton::Left), area.y)); + assert!(ui.app.logs_state.selection.range.is_none()); + ui.app + .handle_mouse_event(click(MouseEventKind::Drag(MouseButton::Left), area.y + 1)); + ui.app + .handle_mouse_event(click(MouseEventKind::Up(MouseButton::Left), area.y + 1)); + assert_eq!(ui.app.logs_state.selection.range, Some(((0, 2), (1, 2)))); + assert_eq!( + ui.app + .logs_state + .selection + .text(&["alpha", "beta", "gamma"]) + .as_deref(), + Some("pha\nbe") + ); + assert!(ui.app.logs_state.viewer_focused); + ui.draw(); + assert!(ui.screen().contains("[y] yank")); + assert!(ui.screen().contains("[g/G] top/bottom")); + assert!(!ui.screen().contains("PgUp")); + ui.app + .handle_mouse_event(click(MouseEventKind::Down(MouseButton::Left), area.y)); + ui.app + .handle_mouse_event(click(MouseEventKind::Up(MouseButton::Left), area.y)); + ui.draw(); + assert!(ui.app.logs_state.selection.range.is_none()); + assert!(!ui.screen().contains("[y]")); +} + +#[test] +fn mouse_drag_selects_overlay_characters_for_yank_and_escape_closes() { + use crate::tui::logging::{clear_app_logs, push_app_log}; + use crossterm::event::KeyModifiers; + let mut ui = UiHarness::new(); + clear_app_logs(); + for index in 0..10 { + push_app_log(format!("12:00:{index:02}:INFO:rmcl: line {index}")); + } + ui.app.focused = FocusedArea::OverviewExpanded; + ui.draw(); + let area = ui.app.log_overlay_inner; + assert!(area.height >= 3); + let click = |kind, row| MouseEvent { + kind, + column: area.x + 2, + row, + modifiers: KeyModifiers::NONE, + }; + ui.app + .handle_mouse_event(click(MouseEventKind::Down(MouseButton::Left), area.y)); + ui.app + .handle_mouse_event(click(MouseEventKind::Drag(MouseButton::Left), area.y + 2)); + ui.app + .handle_mouse_event(click(MouseEventKind::Up(MouseButton::Left), area.y + 2)); + assert_eq!(ui.app.log_selection.range, Some(((0, 2), (2, 2)))); + ui.draw(); + assert!(ui.screen().contains("[y] yank")); + ui.key(KeyCode::Char('y')); + assert!( + crate::feedback::errors::peek_all_errors() + .iter() + .any(|event| event.message.contains("Yanked 3 line(s)")) + ); + ui.app + .handle_mouse_event(click(MouseEventKind::Down(MouseButton::Left), area.y)); + ui.app + .handle_mouse_event(click(MouseEventKind::Up(MouseButton::Left), area.y)); + ui.draw(); + assert!(!ui.screen().contains("[y]")); + ui.app + .handle_mouse_event(click(MouseEventKind::Down(MouseButton::Left), area.y)); + ui.app + .handle_mouse_event(click(MouseEventKind::Drag(MouseButton::Left), area.y + 1)); + ui.key(KeyCode::Esc); + assert_ne!(ui.app.focused, FocusedArea::OverviewExpanded); + assert!(ui.app.log_selection.range.is_none()); + clear_app_logs(); +} + +#[test] +fn log_level_popup_does_not_delete_logs_or_leave_on_tab() { + use crate::instance::logs::files::LogFileEntry; + use ratatui::layout::{Constraint, Rect}; + let mut ui = UiHarness::new(); + ui.add_instance("A"); + ui.app.focused = FocusedArea::Content; + ui.app.content_tab = ContentTab::Logs; + ui.app.logs_state.loaded_for = Some("A".to_owned()); + ui.app.logs_state.entries.push(LogFileEntry { + name: "a.log".to_owned(), + path: ui.instance_path("A").join("a.log"), + }); + ui.app.logs_state.list_state.selected = Some(0); + ui.app.logs_state.viewer_lines = vec!["12:00:00:INFO:rmcl: hello".to_owned()]; + ui.key(KeyCode::Char('f')); + ui.key(KeyCode::Char('d')); + assert_eq!(ui.app.focused, FocusedArea::Content); + assert!(ui.app.logs_state.filter_open); + ui.key(KeyCode::Tab); + assert_eq!(ui.app.content_mode, ContentMode::Installed); + ui.draw(); + assert!(ui.screen().contains("· Error")); + assert!(ui.screen().contains("[Esc] close")); + let popup = Rect::new(0, 0, 100, 30).centered(Constraint::Length(26), Constraint::Length(7)); + assert_eq!( + ui.screen() + .lines() + .nth(popup.y as usize) + .unwrap() + .chars() + .skip(popup.x as usize + 2) + .take(12) + .collect::(), + " Log levels " + ); + ui.key(KeyCode::Esc); + assert!(!ui.app.logs_state.filter_open); +} + +#[test] +fn selected_unlinked_content_shows_only_the_badge() { + let mut ui = UiHarness::new(); + ui.add_instance("A"); + let minecraft = ui + .instance_path("A") + .join(crate::storage::MINECRAFT_DIR_NAME); + let path = minecraft.join("mods/local.jar"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, "local mod").unwrap(); + let mut record = managed_mod_record(&minecraft, "mods/local.jar", "local", false, Vec::new()); + record.resolution = Resolution::Unmatched { + checked_at: 1, + providers: vec!["modrinth".to_owned()], + }; + let mut manifest = ContentManifest::default(); + manifest.upsert(record); + ui.app + .mods_state + .entries + .push(content_entry("scoreboardinternal", path)); + ui.app.mods_state.loaded_for = Some("A".to_owned()); + ui.app.mods_state.list_state.selected = Some(0); + ui.app + .mods_state + .apply_manifest(&manifest, &minecraft, ContentKind::Mod); + ui.app.focused = FocusedArea::Content; + ui.draw(); + assert!(ui.screen().contains("Unlinked")); + assert!(!ui.screen().contains("No online source linked")); + assert!(!ui.screen().contains("version switching unavailable")); + ui.key(KeyCode::Char('v')); + assert!(ui.app.mods_discovery_state.version_popup.is_none()); + + manifest.files[0].resolution = Resolution::Pending; + ui.app + .mods_state + .apply_manifest(&manifest, &minecraft, ContentKind::Mod); + ui.draw(); + assert!(!ui.screen().contains("Unlinked")); + assert!(!ui.screen().contains("No online source linked")); +} + #[test] fn settings_panel_routes_legacy_edit_keys_to_tui_popups() { let mut ui = UiHarness::new(); @@ -1127,6 +1526,7 @@ fn instance_launch_options_autosave_through_the_editor() { fn settings_panel_keeps_direct_profile_management() { let mut ui = UiHarness::new(); ui.add_instance("profile-test"); + std::fs::create_dir_all(ui.instance_path("profile-test").join("minecraft")).unwrap(); ui.app.focused = FocusedArea::Settings; ui.key(KeyCode::Char('a')); @@ -1212,6 +1612,11 @@ fn provider_conflict_selection_is_persisted() { let mut ui = UiHarness::new(); ui.add_instance("Conflict"); let relative_path = std::path::PathBuf::from("mods/example.jar"); + let file = crate::storage::InstancePaths::new(ui.instance_path("Conflict")) + .minecraft() + .join(&relative_path); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(&file, b"example").unwrap(); let candidates = vec![ ProviderProject { provider: "modrinth".to_owned(), @@ -1230,11 +1635,7 @@ fn provider_conflict_selection_is_persisted() { relative_path: relative_path.clone(), kind: crate::instance::ContentKind::Mod, enabled: true, - fingerprint: crate::instance::FileFingerprint { - size: 1, - modified_ns: 0, - hashes: Default::default(), - }, + fingerprint: crate::instance::content::manifest::fingerprint(&file).unwrap(), resolution: crate::instance::Resolution::Ambiguous { candidates: candidates.clone(), }, @@ -1256,6 +1657,16 @@ fn provider_conflict_selection_is_persisted() { }); ui.key(KeyCode::Down); + std::fs::write(&manifest_path, b"invalid").unwrap(); + ui.key(KeyCode::Enter); + assert_eq!(ui.app.provider_conflict.as_ref().unwrap().selected, 1); + ui.app + .content_manifest + .as_ref() + .unwrap() + .1 + .save(&manifest_path) + .unwrap(); ui.key(KeyCode::Enter); assert!(ui.app.provider_conflict.is_none()); diff --git a/src/tui/tests/harness.rs b/src/tui/tests/harness.rs index 3f3753a..d29cce8 100644 --- a/src/tui/tests/harness.rs +++ b/src/tui/tests/harness.rs @@ -3,7 +3,7 @@ use std::collections::{HashMap, HashSet}; -use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseEvent, MouseEventKind}; +use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers, MouseEvent, MouseEventKind}; use ratatui::{Terminal, backend::TestBackend}; use crate::auth::{Account, AccountStore, AccountType}; @@ -94,7 +94,10 @@ impl UiHarness { }, logs_state: widgets::logs_viewer::LogsState::default(), account_state, - settings_state: widgets::settings::SettingsState::new(meta_dir), + settings_state: widgets::settings::SettingsState::new( + meta_dir, + instance_manager.instances_dir.clone(), + ), instance_settings: None, pending_instance_settings_updates: Default::default(), global_settings: None, @@ -103,15 +106,24 @@ impl UiHarness { instance_manager, log_overlay_scroll: 0, log_overlay_max_scroll: 0, + log_filter_open: false, + log_filter_selected: 0, + log_level_filters: [None; 5], + log_selection: widgets::log_selection::LogSelection::default(), + log_overlay_inner: ratatui::layout::Rect::default(), log_overlay_search: widgets::search::SearchState::default(), log_overlay_scrollbar: ratatui::widgets::ScrollbarState::default(), throbber_state: throbber_widgets_tui::ThrobberState::default(), throbber_tick: 0, error_effects: HashMap::new(), pending_editor: None, + edited_config_watches: Vec::new(), + content_for: None, + cached_instance_content: HashMap::new(), reconciliation_for: None, content_manifest: None, content_update_snapshot: None, + content_update_check_pending: false, content_update_popup: None, modpack_versions_state: None, modpack_update_popup: None, @@ -164,15 +176,19 @@ impl UiHarness { } pub fn add_account(&mut self, username: &str) { - self.app.account_state.store.accounts.push(Account { - uuid: username.to_owned(), - username: username.to_owned(), - account_type: AccountType::Microsoft, - active: true, - refresh_token: Some("refresh".to_owned()), - cached_mc_token: None, - cached_mc_token_expires_at: None, - }); + self.app + .account_state + .store + .add(Account { + uuid: username.to_owned(), + username: username.to_owned(), + account_type: AccountType::Microsoft, + active: true, + refresh_token: Some("refresh".to_owned()), + cached_mc_token: None, + cached_mc_token_expires_at: None, + }) + .expect("persist test account"); self.app.account_state.list_state.selected = Some(0); } @@ -185,10 +201,14 @@ impl UiHarness { } pub fn key_with(&mut self, code: KeyCode, modifiers: KeyModifiers) { + self.key_event(KeyEvent::new(code, modifiers)); + } + + pub fn key_event(&mut self, key: KeyEvent) -> bool { let _runtime = self.runtime.enter(); self.app - .handle_key_event(KeyEvent::new(code, modifiers)) - .expect("handle key"); + .dispatch_event(Event::Key(key)) + .expect("handle key") } pub fn mouse(&mut self, kind: MouseEventKind) { diff --git a/src/tui/tests/widgets/account.rs b/src/tui/tests/widgets/account.rs index aeee22e..5a22367 100644 --- a/src/tui/tests/widgets/account.rs +++ b/src/tui/tests/widgets/account.rs @@ -29,6 +29,46 @@ fn offline_account_requires_a_microsoft_account_and_can_be_dismissed() { assert!(matches!(state.add_mode, AddMode::None)); } +#[test] +fn a_cancelled_login_cannot_publish_the_next_attempts_device_code() { + let temp = tempfile::tempdir().unwrap(); + let first = auth::MicrosoftAuth::default(); + let stale_display = first.device_code.clone(); + let mut state = AccountState { + store: AccountStore::empty_for_test(temp.path().join("accounts.json")), + list_state: Default::default(), + add_mode: AddMode::DeviceCodeWaiting { + info: DeviceCodeInfo { + user_code: String::new(), + verification_uri: String::new(), + }, + pending: first, + }, + }; + handle_key(&key(KeyCode::Esc), &mut state); + let second = auth::MicrosoftAuth::default(); + *second.device_code.lock().unwrap() = Some(DeviceCodeInfo { + user_code: "current".to_owned(), + verification_uri: "current-uri".to_owned(), + }); + state.add_mode = AddMode::DeviceCodeWaiting { + info: DeviceCodeInfo { + user_code: String::new(), + verification_uri: String::new(), + }, + pending: second, + }; + *stale_display.lock().unwrap() = Some(DeviceCodeInfo { + user_code: "stale".to_owned(), + verification_uri: "stale-uri".to_owned(), + }); + drain_device_code(&mut state); + let AddMode::DeviceCodeWaiting { info, .. } = &state.add_mode else { + panic!("login must still be pending") + }; + assert_eq!(info.user_code, "current"); +} + #[test] fn account_type_popup_uses_the_theme_surface() { let temp = tempfile::tempdir().unwrap(); diff --git a/src/tui/tests/widgets/content/discovery.rs b/src/tui/tests/widgets/content/discovery.rs index c7c4d14..5e28b2d 100644 --- a/src/tui/tests/widgets/content/discovery.rs +++ b/src/tui/tests/widgets/content/discovery.rs @@ -2,6 +2,18 @@ // SPDX-License-Identifier: GPL-3.0-only use super::*; + +#[test] +fn changing_loader_isolates_pending_filter_versions() { + let mut state = DiscoveryState::new(ContentKind::Mod); + let previous = state.filter_game_versions.clone(); + state.set_filter_loader(ModLoader::Fabric); + *previous.lock().unwrap() = crate::tui::widgets::popups::LoadState::Error("stale".to_owned()); + assert!(matches!( + *state.filter_game_versions.lock().unwrap(), + crate::tui::widgets::popups::LoadState::Idle + )); +} use crate::tests::TEST_LOCK; use chrono::Utc; use crossterm::event::KeyModifiers; @@ -411,6 +423,68 @@ fn any_version_filter_requests_all_project_versions() { assert!(state.begin_versions().unwrap().all_game_versions); } +#[test] +fn empty_filtered_versions_fall_back_to_the_version_picker() { + let mut state = DiscoveryState::new(ContentKind::Mod); + state.filters.game_version = GameVersionFilter::Current; + state + .list + .entries + .push(project_entry(project("project"), None)); + state.list.list_state.selected = Some(0); + let request = state.begin_versions().unwrap(); + assert!(!request.all_game_versions); + + let mut fallback = version("new"); + fallback.game_versions = vec!["1.21.4".to_owned()]; + DiscoveryState::push_action_result( + &request.pending, + DiscoveryActionResult::VersionsUnfiltered { + request_id: request.request_id, + project_id: request.project_id, + result: Ok(vec![fallback]), + }, + ); + state.drain_pending(); + + let popup = state.version_popup.as_ref().unwrap(); + assert!(!popup.loading); + assert!(popup.selecting_minecraft_version); + assert_eq!(popup.minecraft_versions, ["1.21.4"]); + assert_eq!(popup.versions.len(), 1); + assert!(state.select_minecraft_version()); + let popup = state.version_popup.as_ref().unwrap(); + assert_eq!(popup.selected_minecraft_version.as_deref(), Some("1.21.4")); + assert_eq!(popup.visible_versions().count(), 1); +} + +#[test] +fn unfiltered_fallback_without_any_versions_keeps_the_empty_state() { + let mut state = DiscoveryState::new(ContentKind::Mod); + state.filters.game_version = GameVersionFilter::Current; + state + .list + .entries + .push(project_entry(project("project"), None)); + state.list.list_state.selected = Some(0); + let request = state.begin_versions().unwrap(); + + DiscoveryState::push_action_result( + &request.pending, + DiscoveryActionResult::VersionsUnfiltered { + request_id: request.request_id, + project_id: request.project_id, + result: Ok(Vec::new()), + }, + ); + state.drain_pending(); + + let popup = state.version_popup.as_ref().unwrap(); + assert!(!popup.loading); + assert!(!popup.selecting_minecraft_version); + assert!(popup.versions.is_empty()); +} + #[test] fn specific_version_filter_is_kept_for_project_versions() { let mut state = DiscoveryState::new(ContentKind::Mod); @@ -1332,6 +1406,7 @@ fn dependency_resolution_opens_the_existing_confirmation() { title: "Project".to_owned(), version: root_version, installed_path: None, + expected_record: None, kind: crate::instance::ContentKind::Mod, destination: std::path::PathBuf::from("mods"), provider_aliases: Vec::new(), @@ -1389,6 +1464,7 @@ fn confirming_state_with_plan() -> DiscoveryState { title: title.to_owned(), version, installed_path: None, + expected_record: None, kind: crate::instance::ContentKind::Mod, destination: std::path::PathBuf::from("mods"), provider_aliases: Vec::new(), @@ -1428,7 +1504,6 @@ fn confirming_popup_toggles_skip_dependencies_with_s() { assert!(handle_key(&KeyEvent::from(KeyCode::Char('s')), &mut state)); assert!(!state.version_popup.as_ref().unwrap().skip_dependencies); - // Toggling is blocked while loading or installing. state.version_popup.as_mut().unwrap().loading = true; assert!(handle_key(&KeyEvent::from(KeyCode::Char('s')), &mut state)); assert!(!state.version_popup.as_ref().unwrap().skip_dependencies); @@ -1505,7 +1580,6 @@ fn installed_mode_defaults_to_any_game_version() { assert_eq!(state.filters.game_version, GameVersionFilter::Any); assert_eq!(state.active_filter_count(), 0); - // The same Any filter counts as active in discovery mode. state.set_local_mode(false); state.filters.game_version = GameVersionFilter::Any; assert_eq!(state.active_filter_count(), 1); diff --git a/src/tui/tests/widgets/content/list.rs b/src/tui/tests/widgets/content/list.rs index 4711e06..1de4e35 100644 --- a/src/tui/tests/widgets/content/list.rs +++ b/src/tui/tests/widgets/content/list.rs @@ -8,6 +8,30 @@ use std::{ }; use crate::instance::content::entry::{ContentEntry, WorldDetails, WorldGameMode}; + +#[tokio::test] +async fn pending_version_metadata_does_not_queue_another_request_each_redraw() { + let temp = tempfile::tempdir().unwrap(); + let mut state = ContentListState { + provider_icon_meta_dir: Some(temp.path().to_owned()), + provider_icon_client: Some(crate::net::HttpClient::new()), + local_game_version: "1.21".to_owned(), + ..ContentListState::default() + }; + let mut entry = entry("project"); + entry.provider_project = Some(crate::instance::ProviderProject { + provider: "modrinth".to_owned(), + project_id: "project".to_owned(), + version_id: "version".to_owned(), + }); + state.entries.push(entry); + state.request_visible_provider_icons(&[0], 10); + let pending = Arc::strong_count(&state.pending_provider_icons); + for _ in 0..10 { + state.request_visible_provider_icons(&[0], 10); + } + assert_eq!(Arc::strong_count(&state.pending_provider_icons), pending); +} use ratatui::{ buffer::Buffer, layout::Rect, @@ -967,7 +991,7 @@ fn streamed_entries_without_icons_are_visible_immediately() { } #[tokio::test] -async fn installed_icon_decode_survives_manifest_binding_and_cache_restore() { +async fn installed_icon_decode_survives_manifest_binding() { let mut state = ContentListState::default(); state.set_installed_options( &crate::tui::widgets::content::discovery::DiscoveryFilters::default(), @@ -1003,30 +1027,62 @@ async fn installed_icon_decode_survives_manifest_binding_and_cache_restore() { }) .await .expect("installed icon decoded after manifest binding"); +} - let directory = tempfile::tempdir().unwrap(); - state.start_load( - directory.path(), - "other", - crate::instance::content::mods::scan_one_mod, - "jar", - ); - state.start_load( - directory.path(), - "main", - crate::instance::content::mods::scan_one_mod, - "jar", - ); - assert!(state.filtered_indices().is_empty()); - state.request_image_loads(&picker); +#[tokio::test] +async fn switching_back_rescans_content_changed_while_inactive() { + let temp = tempfile::tempdir().unwrap(); + let first = temp.path().join("first"); + let second = temp.path().join("second"); + std::fs::create_dir_all(&first).unwrap(); + std::fs::create_dir_all(&second).unwrap(); + std::fs::write(first.join("old.jar"), b"old").unwrap(); + let mut state = ContentListState::default(); + let scanner = crate::instance::content::mods::scan_one_mod; + state.start_load(&first, "first", scanner, ".jar"); tokio::time::timeout(std::time::Duration::from_secs(5), async { - while state.filtered_indices().is_empty() { - state.drain_image_loads(&picker); + while state.loading { + state.drain_pending(); tokio::task::yield_now().await; } }) .await - .expect("cached installed icon decoded"); + .unwrap(); + assert_eq!(state.entries.len(), 1); + + state.start_load(&second, "second", scanner, ".jar"); + std::fs::remove_file(first.join("old.jar")).unwrap(); + std::fs::write(first.join("new.jar"), b"new").unwrap(); + state.start_load(&first, "first", scanner, ".jar"); + tokio::time::timeout(std::time::Duration::from_secs(5), async { + while state.loading { + state.drain_pending(); + tokio::task::yield_now().await; + } + }) + .await + .unwrap(); + assert_eq!(state.entries.len(), 1); + assert_eq!(state.entries[0].path, first.join("new.jar")); +} + +#[test] +fn old_watcher_results_cannot_update_a_new_instance() { + let temp = tempfile::tempdir().unwrap(); + let mut state = ContentListState::default(); + let old_slot = state.watcher_diff.clone(); + state.watch_dir(temp.path().to_owned()); + *old_slot.lock().unwrap() = Some(super::WatcherDiff { + toggled: vec![( + "test".to_owned(), + false, + temp.path().join("test.jar.disabled"), + )], + removed: Vec::new(), + added: Vec::new(), + }); + + assert!(state.drain_watcher().toggles.is_empty()); } #[test] @@ -1148,6 +1204,47 @@ fn incompatible_installed_version_renders_red_footer() { assert_eq!(footer_color("0.9.0+mc1.20.1"), Some(theme.error())); } +#[test] +fn warning_descriptions_render_in_warning_color() { + let mut conflict = entry("Voxy"); + conflict.description = + "Other selected updates require different versions of Sodium.".to_owned(); + let mut state = ContentListState { + entries: vec![conflict], + warning_descriptions: true, + ..ContentListState::default() + }; + state.rebuild_display_metadata(); + let picker = ratatui_image::picker::Picker::halfblocks(); + let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(70, 5)).unwrap(); + terminal + .draw(|frame| { + super::render( + frame, + frame.area(), + &mut state, + true, + "Loading...", + "Empty", + &picker, + false, + true, + ); + }) + .unwrap(); + + let theme = crate::config::theme::THEME.as_ref(); + let buffer = terminal.backend().buffer().clone(); + let description_color = (0..buffer.area.height).find_map(|y| { + let row = (0..buffer.area.width) + .map(|x| buffer[(x, y)].symbol().to_owned()) + .collect::(); + row.find("Other selected") + .map(|start| buffer[(u16::try_from(start).unwrap(), y)].fg) + }); + assert_eq!(description_color, Some(theme.warning())); +} + #[test] fn multiline_rendering_uses_the_space_beside_large_icons() { let mut world = entry("World"); @@ -1294,6 +1391,92 @@ fn manifest_metadata_keeps_an_embedded_icon_renderer() { assert!(state.image_protocols.contains_key("installed")); } +#[test] +fn unlinked_badge_is_subdued_and_requires_a_completed_unmatched_lookup() { + use crate::instance::{ + ContentFileRecord, ContentKind, ContentManifest, FileFingerprint, Resolution, + }; + let minecraft = PathBuf::from("instance/minecraft"); + let mut installed = entry("scoreboardinternal"); + installed.path = minecraft.join("mods/local.jar"); + installed.footer_label = Some("1.0.0".to_owned()); + let mut state = ContentListState::default(); + state.set_entries(vec![installed]); + let mut manifest = ContentManifest::default(); + manifest.upsert(ContentFileRecord { + relative_path: PathBuf::from("mods/local.jar"), + kind: ContentKind::Mod, + enabled: true, + fingerprint: FileFingerprint { + size: 0, + modified_ns: 0, + hashes: Default::default(), + }, + resolution: Resolution::Unmatched { + checked_at: 1, + providers: vec!["modrinth".to_owned()], + }, + provider_aliases: Vec::new(), + provider_checks: vec!["modrinth".to_owned()], + required_dependencies: Vec::new(), + automatic_dependency: false, + cleanup_eligible: false, + }); + state.apply_manifest(&manifest, &minecraft, ContentKind::Mod); + state.apply_update_snapshot(None); + assert!(state.unlinked_paths.contains(&state.entries[0].path)); + let picker = ratatui_image::picker::Picker::halfblocks(); + let theme = crate::config::theme::THEME.as_ref(); + let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(50, 4)).unwrap(); + for focused in [false, true] { + terminal + .draw(|frame| { + super::render( + frame, + frame.area(), + &mut state, + focused, + "Loading...", + "Empty", + &picker, + false, + false, + ) + }) + .unwrap(); + let buffer = terminal.backend().buffer(); + let row = (0..50).map(|x| buffer[(x, 0)].symbol()).collect::(); + let x = row.find("Unlinked").expect("unlinked badge") as u16; + assert_eq!(buffer[(x, 0)].fg, theme.background()); + assert_eq!(buffer[(x, 0)].bg, theme.text_dim()); + assert!(buffer[(x, 0)].modifier.contains(Modifier::BOLD)); + assert!(terminal.backend().to_string().contains("1.0.0")); + } + for resolution in [ + Resolution::Pending, + Resolution::Unmatched { + checked_at: 1, + providers: Vec::new(), + }, + Resolution::Ambiguous { + candidates: Vec::new(), + }, + Resolution::Resolved { + project: crate::instance::ProviderProject { + provider: "modrinth".to_owned(), + project_id: "project".to_owned(), + version_id: "version".to_owned(), + }, + }, + ] { + manifest.files[0].resolution = resolution; + state.apply_manifest(&manifest, &minecraft, ContentKind::Mod); + assert!(state.unlinked_paths.is_empty()); + } + state.apply_manifest(&ContentManifest::default(), &minecraft, ContentKind::Mod); + assert!(state.unlinked_paths.is_empty()); +} + #[test] fn provider_metadata_fills_a_missing_installed_description() { let mut state = ContentListState::default(); diff --git a/src/tui/tests/widgets/content/snapshots/rmcl__tui__widgets__content__update__tests__update_review_reuses_content_rows.snap b/src/tui/tests/widgets/content/snapshots/rmcl__tui__widgets__content__update__tests__update_review_reuses_content_rows.snap index f0f3bab..d74ae4e 100644 --- a/src/tui/tests/widgets/content/snapshots/rmcl__tui__widgets__content__update__tests__update_review_reuses_content_rows.snap +++ b/src/tui/tests/widgets/content/snapshots/rmcl__tui__widgets__content__update__tests__update_review_reuses_content_rows.snap @@ -13,7 +13,7 @@ expression: terminal.backend() " " " " " ╭Update installed content──────────────────────────────────╮ " -" │▌▄▄▄▄▄▄ Example Mod Update │ " +" │▌▄▄▄▄▄▄ Example Mod │ " " │▌▄▄▄▄▄▄ Existing project description 1.0 ➜ 2.0 │ " " │▌▄▄▄▄▄▄ │ " " ╰───────────[j/k] navigate [Enter] update all [Esc] close╯ " diff --git a/src/tui/tests/widgets/content/tabs.rs b/src/tui/tests/widgets/content/tabs.rs index d4a0a12..0b7df30 100644 --- a/src/tui/tests/widgets/content/tabs.rs +++ b/src/tui/tests/widgets/content/tabs.rs @@ -185,6 +185,7 @@ fn skipped_dependencies_render_as_skipped_in_confirmation() { title: title.to_owned(), version, installed_path: None, + expected_record: None, kind: ContentKind::Mod, destination: std::path::PathBuf::from("mods"), provider_aliases: Vec::new(), diff --git a/src/tui/tests/widgets/content/update.rs b/src/tui/tests/widgets/content/update.rs index 960c8b8..7aa35c2 100644 --- a/src/tui/tests/widgets/content/update.rs +++ b/src/tui/tests/widgets/content/update.rs @@ -74,6 +74,7 @@ fn snapshot() -> UpdateSnapshot { #[test] fn update_review_reuses_content_rows() { let mut state = State::checking( + "Instance".to_owned(), ContentKind::Mod, None, vec![entry("Example Mod", "mods/example.jar")], @@ -88,6 +89,8 @@ fn update_review_reuses_content_rows() { .unwrap(); insta::assert_snapshot!(terminal.backend()); + assert_eq!(state.list.entries[0].title_suffix, None); + assert!(!state.list.warning_descriptions); } #[test] @@ -101,6 +104,7 @@ fn update_conflicts_explain_why_the_item_was_not_updated() { .to_owned(), }); let mut state = State::checking( + "Instance".to_owned(), ContentKind::Mod, None, vec![entry("Example Mod", "mods/example.jar")], @@ -116,4 +120,5 @@ fn update_conflicts_explain_why_the_item_was_not_updated() { state.list.entries[0].description, "Other selected updates require different versions of Library.\nThis mod was left unchanged; update it separately with v." ); + assert!(state.list.warning_descriptions); } diff --git a/src/tui/tests/widgets/instances.rs b/src/tui/tests/widgets/instances.rs index 29253a1..55db4c5 100644 --- a/src/tui/tests/widgets/instances.rs +++ b/src/tui/tests/widgets/instances.rs @@ -8,9 +8,6 @@ fn format_relative_time_none_returns_never_played() { assert_eq!(format_relative_time(None), "Never played"); } -// each #[case] picks a "seconds ago" value that lands in exactly one -// bucket of the match. mutating any bucket boundary (e.g. 3600 to 3601, -// or "minutes" to "seconds") makes one of these cases fail. #[rstest::rstest] #[case::just_now(0, "Just now")] #[case::just_now_upper(59, "Just now")] @@ -33,9 +30,7 @@ use ratatui::Terminal; use ratatui::backend::TestBackend; fn synthetic_instance(name: &str) -> InstanceConfig { - // last_played intentionally None so the rendered text is the - // deterministic "Never played" string. anything else would make the - // snapshot drift relative to chrono::Utc::now(). + // Avoid clock-dependent snapshot text. InstanceConfig { name: name.to_string(), game_version: "1.20.1".to_string(), diff --git a/src/tui/tests/widgets/log_selection.rs b/src/tui/tests/widgets/log_selection.rs new file mode 100644 index 0000000..35ea277 --- /dev/null +++ b/src/tui/tests/widgets/log_selection.rs @@ -0,0 +1,157 @@ +// SPDX-FileCopyrightText: 2026 Constantin Bauer +// SPDX-License-Identifier: GPL-3.0-only + +use crossterm::event::KeyModifiers; + +use super::*; + +fn mouse(kind: MouseEventKind, column: u16, row: u16) -> MouseEvent { + MouseEvent { + kind, + column, + row, + modifiers: KeyModifiers::NONE, + } +} + +#[test] +fn clicks_clear_selection_and_only_dragging_selects_characters() { + let mut selection = LogSelection::default(); + let area = Rect::new(0, 0, 20, 4); + let lines = ["alpha", "beta"]; + assert!(!selection.handle_mouse( + mouse(MouseEventKind::Drag(MouseButton::Left), 4, 0), + area, + 0, + &lines + )); + assert!(selection.handle_mouse( + mouse(MouseEventKind::Down(MouseButton::Left), 1, 0), + area, + 0, + &lines + )); + assert!(selection.range.is_none()); + assert!(selection.handle_mouse( + mouse(MouseEventKind::Drag(MouseButton::Left), 4, 0), + area, + 0, + &lines + )); + assert_eq!(selection.text(&lines).as_deref(), Some("lph")); + assert!(selection.handle_mouse( + mouse(MouseEventKind::Up(MouseButton::Left), 4, 0), + area, + 0, + &lines + )); + assert!(!selection.handle_mouse( + mouse(MouseEventKind::Drag(MouseButton::Left), 5, 0), + area, + 0, + &lines + )); + + let search = SearchState { + query: "alpha".to_owned(), + ..Default::default() + }; + let highlighted = selection.highlight_line(0, "alpha", &search, Style::default()); + assert_eq!( + highlighted + .spans + .iter() + .filter(|span| span.style.add_modifier.contains(Modifier::REVERSED)) + .map(|span| span.content.as_ref()) + .collect::(), + "lph" + ); + assert!( + highlighted + .spans + .iter() + .all(|span| span.style.add_modifier.contains(Modifier::UNDERLINED)) + ); + + selection.handle_mouse( + mouse(MouseEventKind::Down(MouseButton::Left), 2, 0), + area, + 0, + &lines, + ); + selection.handle_mouse( + mouse(MouseEventKind::Up(MouseButton::Left), 2, 0), + area, + 0, + &lines, + ); + assert!(selection.range.is_none()); + assert!(selection.text(&lines).is_none()); + + selection.handle_mouse( + mouse(MouseEventKind::Down(MouseButton::Left), 2, 0), + area, + 0, + &lines, + ); + selection.handle_mouse( + mouse(MouseEventKind::Drag(MouseButton::Left), 0, 1), + area, + 0, + &lines, + ); + assert_eq!(selection.text(&lines).as_deref(), Some("pha\n")); + selection.handle_mouse( + mouse(MouseEventKind::Drag(MouseButton::Left), 0, 3), + area, + 0, + &lines, + ); + assert_eq!(selection.text(&lines).as_deref(), Some("pha\nbeta")); +} + +#[test] +fn selection_handles_reverse_multiline_drags_scroll_and_unicode_cells() { + let mut selection = LogSelection::default(); + let area = Rect::new(10, 5, 20, 4); + let lines = ["hidden", "alpha", "beta"]; + selection.handle_mouse( + mouse(MouseEventKind::Down(MouseButton::Left), 12, 6), + area, + 1, + &lines, + ); + selection.handle_mouse( + mouse(MouseEventKind::Drag(MouseButton::Left), 11, 5), + area, + 1, + &lines, + ); + assert_eq!(selection.text(&lines).as_deref(), Some("lpha\nbe")); + + let lines = ["a界e\u{0301}🙂z"]; + selection.handle_mouse( + mouse(MouseEventKind::Down(MouseButton::Left), 12, 5), + area, + 0, + &lines, + ); + selection.handle_mouse( + mouse(MouseEventKind::Drag(MouseButton::Left), 16, 5), + area, + 0, + &lines, + ); + assert_eq!(selection.text(&lines).as_deref(), Some("界e\u{0301}🙂")); + let highlighted = + selection.highlight_line(0, lines[0], &SearchState::default(), Style::default()); + assert_eq!( + highlighted + .spans + .iter() + .filter(|span| span.style.add_modifier.contains(Modifier::REVERSED)) + .map(|span| span.content.as_ref()) + .collect::(), + "界e\u{0301}🙂" + ); +} diff --git a/src/tui/tests/widgets/logs_viewer.rs b/src/tui/tests/widgets/logs_viewer.rs index 179c39a..fb40706 100644 --- a/src/tui/tests/widgets/logs_viewer.rs +++ b/src/tui/tests/widgets/logs_viewer.rs @@ -48,3 +48,248 @@ fn list_and_viewer_navigation_loads_and_scrolls_the_selected_log() { assert!(handle_key(&key(KeyCode::Esc), &mut state)); assert!(!state.viewer_focused); } + +#[test] +fn shift_enter_without_a_selected_log_is_swallowed_without_opening() { + let mut state = LogsState::default(); + let shift_enter = KeyEvent::new(KeyCode::Enter, KeyModifiers::SHIFT); + assert!(handle_key(&shift_enter, &mut state)); + assert!(!state.viewer_focused); +} + +#[test] +fn viewer_ignores_page_keys_and_keeps_top_bottom_navigation() { + let mut state = LogsState { + viewer_focused: true, + viewer_max_scroll: 30, + ..Default::default() + }; + let page = |code| KeyEvent::new(code, KeyModifiers::NONE); + assert!(!handle_key(&page(KeyCode::PageDown), &mut state)); + assert!(!handle_key(&page(KeyCode::PageUp), &mut state)); + assert_eq!(state.viewer_scroll, 0); + assert!(handle_key(&page(KeyCode::Home), &mut state)); + assert_eq!(state.viewer_scroll, 0); + assert!(handle_key(&page(KeyCode::End), &mut state)); + assert_eq!(state.viewer_scroll, 30); +} + +#[test] +fn yank_copies_only_the_selected_viewer_characters() { + let mut state = LogsState { + viewer_lines: vec!["first".to_owned(), "second".to_owned(), "third".to_owned()], + selection: { + let mut selection = LogSelection::default(); + selection.range = Some(((2, 3), (0, 2))); + selection + }, + ..Default::default() + }; + let yank = KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE); + assert!(handle_key(&yank, &mut state)); + assert!( + crate::feedback::errors::peek_all_errors() + .iter() + .any(|event| event.message.contains("Yanked 3 line(s)")) + ); +} + +#[test] +fn log_levels_share_one_color_mapping_in_viewer_and_overlay() { + let theme = crate::config::theme::THEME.as_ref(); + for line in [ + "12:17:29:ERROR:rmcl::net: boom", + "something failed with error", + "[20:10:44] [Render thread/ERROR]: boom", + "[STDERR] boom", + ] { + assert_eq!(line_level_style(line).fg, Some(theme.error()), "{line}"); + } + for line in [ + "12:17:29:WARN:rmcl: careful", + "[20:10:44] [Server thread/WARN]: careful", + ] { + assert_eq!(line_level_style(line).fg, Some(theme.warning()), "{line}"); + } + assert_eq!( + line_level_style("12:17:28:DEBUG:rmcl::net: fetching").fg, + Some(theme.text_dim()) + ); + assert_eq!( + line_level_style("12:17:28:TRACE:rmcl::net: fetching").fg, + Some(theme.border()) + ); + assert_ne!( + log_level_style(LogLevel::Debug).fg, + log_level_style(LogLevel::Trace).fg + ); + assert_eq!( + line_level_style("[20:10:46] [Render thread/INFO]: done").fg, + Some(theme.text()) + ); +} + +#[test] +fn rescans_and_runtime_changes_keep_the_selected_log_and_viewer_in_sync() { + let temp = tempfile::tempdir().unwrap(); + let older = LogFileEntry { + name: "older.log".to_owned(), + path: temp.path().join("older.log"), + }; + let newer = LogFileEntry { + name: "newer.log".to_owned(), + path: temp.path().join("newer.log"), + }; + std::fs::write(&older.path, "older content").unwrap(); + std::fs::write(&newer.path, "newer content").unwrap(); + let name = "logs-rescan-identity"; + let mut state = LogsState { + loaded_for: Some(name.to_owned()), + entries: vec![older.clone()], + ..Default::default() + }; + state.list_state.selected = Some(0); + state.load_selected_content(); + *state.pending.lock().unwrap() = Some((name.to_owned(), vec![newer.clone(), older.clone()])); + state.drain_pending(); + assert_eq!(state.list_state.selected, Some(1)); + assert_eq!(state.viewer_lines, ["older content"]); + + crate::instance::runtime::set_state(name, crate::instance::runtime::RunState::Running); + state.drain_pending(); + assert_eq!(state.list_state.selected, Some(2)); + state.search.query = "older".to_owned(); + state.list_state.selected = Some(0); + state.load_selected_content(); + assert!(!state.is_live_selected()); + let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(60, 4)).unwrap(); + terminal + .draw(|frame| render_viewer(frame, frame.area(), &mut state)) + .unwrap(); + let rendered = terminal + .backend() + .buffer() + .content + .iter() + .map(|cell| cell.symbol()) + .collect::(); + assert!(rendered.contains("older content")); + + state.search.query.clear(); + state.list_state.selected = Some(0); + state.load_selected_content(); + crate::instance::runtime::remove(name); + state.drain_pending(); + assert_eq!(state.viewer_lines, ["newer content"]); + assert_eq!(state.selected_path, Some(newer.path)); +} + +#[test] +fn unclassified_lines_have_no_level_and_follow_category_filter_rules() { + use crate::instance::launch::parser::LogLevel; + assert_eq!(level_of_line("just some output"), None); + assert_eq!( + level_of_line("[20:10:44] [Render thread/INFO]: hello"), + Some(LogLevel::Info) + ); + assert_eq!( + level_of_line("tracing trace message"), + Some(LogLevel::Trace) + ); + let mut filters = [None; 5]; + filters[3] = Some(CategoryFilter::Exclude); + assert!(level_matches(&filters, None)); + filters[0] = Some(CategoryFilter::Include); + assert!(!level_matches(&filters, None)); + assert!(level_matches(&filters, Some(LogLevel::Error))); + assert!(!level_matches(&filters, Some(LogLevel::Debug))); +} + +#[test] +fn level_filter_panel_cycles_neutral_include_exclude_resets_and_closes() { + let mut state = LogsState::default(); + let press = |code| KeyEvent::new(code, KeyModifiers::NONE); + assert!(handle_key(&press(KeyCode::Char('f')), &mut state)); + assert!(state.filter_open); + assert!(handle_key(&press(KeyCode::Enter), &mut state)); + assert_eq!(state.level_filters[0], Some(CategoryFilter::Include)); + assert!(handle_key(&press(KeyCode::Enter), &mut state)); + assert_eq!(state.level_filters[0], Some(CategoryFilter::Exclude)); + assert!(handle_key(&press(KeyCode::Enter), &mut state)); + assert_eq!(state.level_filters[0], None); + assert!(handle_key(&press(KeyCode::Char('j')), &mut state)); + assert!(handle_key(&press(KeyCode::Enter), &mut state)); + assert_eq!(state.level_filters[1], Some(CategoryFilter::Include)); + assert!(handle_key(&press(KeyCode::Enter), &mut state)); + assert_eq!(state.level_filters[1], Some(CategoryFilter::Exclude)); + assert!(handle_key(&press(KeyCode::Char('r')), &mut state)); + assert_eq!(state.level_filters, [None; 5]); + assert!(handle_key(&press(KeyCode::Esc), &mut state)); + assert!(!state.filter_open); +} + +#[test] +fn level_filter_highlight_reaches_the_popup_right_edge() { + use ratatui::layout::Constraint; + let _guard = crate::tests::TEST_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(80, 20)).unwrap(); + let popup = Rect::new(0, 0, 80, 20).centered(Constraint::Length(26), Constraint::Length(7)); + terminal + .draw(|frame| render_level_filter(frame, 0, &[None; 5])) + .unwrap(); + let buffer = terminal.backend().buffer(); + let theme = THEME.as_ref(); + assert_eq!(buffer[(popup.right() - 2, popup.y + 1)].bg, theme.stripe()); + assert_eq!(buffer[(popup.right() - 2, popup.y + 2)].bg, theme.surface()); +} + +#[test] +fn level_filter_hides_matching_lines_but_keeps_unclassified_ones() { + fn rendered(state: &mut LogsState) -> String { + let mut terminal = + ratatui::Terminal::new(ratatui::backend::TestBackend::new(70, 6)).unwrap(); + terminal + .draw(|frame| render_viewer(frame, frame.area(), state)) + .unwrap(); + terminal + .backend() + .buffer() + .content + .iter() + .map(|cell| cell.symbol()) + .collect::() + } + let mut state = LogsState { + viewer_lines: vec![ + "12:17:28:DEBUG:rmcl::net: fetching versions".to_owned(), + "[20:10:46] [Render thread/INFO]: done".to_owned(), + "plain line without a level".to_owned(), + ], + ..Default::default() + }; + assert!(rendered(&mut state).contains("fetching versions")); + state.level_filters[3] = Some(CategoryFilter::Exclude); + let shown = rendered(&mut state); + assert!(!shown.contains("fetching versions")); + assert!(shown.contains("done")); + assert!(shown.contains("plain line")); + state.level_filters[2] = Some(CategoryFilter::Include); + let shown = rendered(&mut state); + assert!(shown.contains("done")); + assert!(!shown.contains("plain line")); +} + +#[test] +fn included_levels_form_a_union_and_excluded_levels_stay_hidden() { + let mut filters = [None; 5]; + filters[0] = Some(CategoryFilter::Include); + filters[1] = Some(CategoryFilter::Include); + filters[3] = Some(CategoryFilter::Exclude); + assert!(level_matches(&filters, Some(LogLevel::Error))); + assert!(level_matches(&filters, Some(LogLevel::Warn))); + assert!(!level_matches(&filters, Some(LogLevel::Info))); + assert!(!level_matches(&filters, Some(LogLevel::Debug))); + assert!(!level_matches(&filters, None)); +} diff --git a/src/tui/tests/widgets/markdown.rs b/src/tui/tests/widgets/markdown.rs index ac13d31..9ecd9dc 100644 --- a/src/tui/tests/widgets/markdown.rs +++ b/src/tui/tests/widgets/markdown.rs @@ -435,6 +435,18 @@ fn emphasis_next_to_html_tag_boundaries_does_not_leak_markers() { assert!(!rendered.contains('*'), "{rendered}"); } +#[test] +fn literal_stars_and_code_operators_are_preserved() { + let text = formatted_text("`*` and `2 ** 3` and \\*", 80); + assert_eq!( + text.lines + .iter() + .map(ToString::to_string) + .collect::(), + "* and 2 ** 3 and *" + ); +} + #[test] fn fenced_code_blocks_are_rendered_without_fences() { let text = formatted_text("```json5\n{\n \"enabled\": true\n}\n```", 24); diff --git a/src/tui/tests/widgets/popups/error/render.rs b/src/tui/tests/widgets/popups/error/render.rs index c32878a..334023e 100644 --- a/src/tui/tests/widgets/popups/error/render.rs +++ b/src/tui/tests/widgets/popups/error/render.rs @@ -42,8 +42,6 @@ fn error_level_renders() { insta::assert_snapshot!(term.backend()); } -// info-level events hit the catch-all `_` arm in the label match; previously -// there was no test covering it. #[test] fn info_level_renders() { let term = render(event(Level::INFO, "Reloaded config"), 40, 5); diff --git a/src/tui/tests/widgets/popups/import_modpack/render.rs b/src/tui/tests/widgets/popups/import_modpack/render.rs index f169726..0a3316b 100644 --- a/src/tui/tests/widgets/popups/import_modpack/render.rs +++ b/src/tui/tests/widgets/popups/import_modpack/render.rs @@ -84,9 +84,7 @@ fn import_modpack_renders_fetching_step() { insta::assert_snapshot!(terminal.backend()); } -// Version step: pre-populate versions as LoadState::Loaded with synthetic -// VersionInfo entries so render walks the list path without triggering -// any network helpers. +// Loaded fixtures keep rendering from spawning network tasks. #[test] fn import_modpack_renders_version_step() { use crate::net::modrinth::VersionInfo; @@ -133,9 +131,6 @@ fn import_modpack_renders_version_step() { insta::assert_snapshot!(terminal.backend()); } -// Confirm step: needs a populated ImportSummary so the render path -// doesn't bail. ImportSummary is constructed manually with synthetic -// values; archive_path is a fake tempdir-ish path that never gets read. #[test] fn import_modpack_renders_confirm_step() { use crate::instance::import::{ImportSummary, PackFormat}; @@ -177,9 +172,6 @@ fn modpack_confirmation_area_fits_its_summary() { assert_eq!(popup_rect(Rect::new(0, 0, 100, 30)).height, 8); } -// Confirm step with loader_version=None: covers the branch where the -// pack didn't declare a loader version (rare upstream, but happens for -// older mmc packs). render_confirm_step has to handle the Option. #[test] fn import_modpack_renders_confirm_step_without_loader_version() { use crate::instance::import::{ImportSummary, PackFormat}; diff --git a/src/tui/tests/widgets/popups/import_modpack/state.rs b/src/tui/tests/widgets/popups/import_modpack/state.rs index 654c5a7..01b48ae 100644 --- a/src/tui/tests/widgets/popups/import_modpack/state.rs +++ b/src/tui/tests/widgets/popups/import_modpack/state.rs @@ -16,6 +16,43 @@ fn key(code: KeyCode) -> KeyEvent { KeyEvent::new(code, KeyModifiers::NONE) } +#[test] +fn dispatch_repeats_import_version_search_but_not_import_confirmation() { + use crate::tui::{app::FocusedArea, tests::harness::UiHarness}; + use crossterm::event::KeyEventKind; + + let mut ui = UiHarness::new(); + ui.app.focused = FocusedArea::ImportPopup; + ui.app.instances_state.show_import_popup = true; + IMPORT_STATE.lock().unwrap().step = ImportStep::Version; + IMPORT_STATE.lock().unwrap().version_search.activate(); + assert!(ui.key_event(KeyEvent::new_with_kind( + KeyCode::Char('i'), + KeyModifiers::NONE, + KeyEventKind::Repeat + ))); + assert_eq!(IMPORT_STATE.lock().unwrap().version_search.query, "i"); + assert!(!ui.key_event(KeyEvent::new_with_kind( + KeyCode::Enter, + KeyModifiers::NONE, + KeyEventKind::Repeat + ))); + { + let mut state = IMPORT_STATE.lock().unwrap(); + state.step = ImportStep::Confirm; + state.summary = Some(summary()); + } + assert!(!ui.key_event(KeyEvent::new_with_kind( + KeyCode::Enter, + KeyModifiers::NONE, + KeyEventKind::Repeat + ))); + assert!(take_result().is_none()); + assert!(ui.app.instances_state.show_import_popup); + ui.key(KeyCode::Enter); + assert_eq!(take_result().unwrap().summary.name, "Test Pack"); +} + fn summary() -> ImportSummary { ImportSummary { name: "Test Pack".to_owned(), diff --git a/src/tui/tests/widgets/popups/new_instance/render.rs b/src/tui/tests/widgets/popups/new_instance/render.rs index c27225f..03ee517 100644 --- a/src/tui/tests/widgets/popups/new_instance/render.rs +++ b/src/tui/tests/widgets/popups/new_instance/render.rs @@ -6,10 +6,7 @@ use crate::tests::TEST_LOCK; use ratatui::Terminal; use ratatui::backend::TestBackend; -// WIZARD_STATE is a process-global static; without serialisation, parallel -// tests would race when each test sets the step and then renders, since -// render re-acquires the WIZARD_STATE mutex internally. this guard mutex -// ensures only one wizard snapshot test runs at a time. +// Render re-acquires WIZARD_STATE, so TEST_LOCK guards setup and rendering together. fn reset_wizard_state(step: WizardStep) { let mut guard = WIZARD_STATE.lock().expect("WIZARD_STATE lock"); *guard = WizardState::default(); @@ -19,7 +16,6 @@ fn reset_wizard_state(step: WizardStep) { #[test] fn new_instance_renders_name_step() { let _serial = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); - // Name is the default step; render touches no network helpers. reset_wizard_state(WizardStep::Name); let backend = TestBackend::new(60, 12); @@ -33,8 +29,6 @@ fn new_instance_renders_name_step() { #[test] fn new_instance_renders_loader_step() { let _serial = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); - // Loader step is reached after Name; render just paints the hardcoded - // loader list, no network. reset_wizard_state(WizardStep::Loader); let backend = TestBackend::new(60, 12); @@ -45,10 +39,7 @@ fn new_instance_renders_loader_step() { insta::assert_snapshot!(terminal.backend()); } -// Version step: pre-populate versions as LoadState::Loaded so -// ensure_versions_loaded short-circuits and never spawns a network task. -// the three synthetic versions are marked stable=true so they show with -// show_snapshots=false (the default). +// Loaded fixtures keep rendering from spawning network tasks. #[test] fn new_instance_renders_version_step() { use crate::instance::loader::GameVersion; @@ -82,9 +73,6 @@ fn new_instance_renders_version_step() { insta::assert_snapshot!(terminal.backend()); } -// LoaderVersion step: needs both versions and loader_versions pre-loaded. -// pick a non-Vanilla loader (loader_idx=2 = Forge) so the step doesn't -// skip itself to Confirm. #[test] fn new_instance_renders_loader_version_step() { use crate::instance::loader::GameVersion; @@ -111,8 +99,6 @@ fn new_instance_renders_loader_version_step() { insta::assert_snapshot!(terminal.backend()); } -// Confirm step: paints a summary, no network, no list. requires -// versions + loader_versions Loaded so selected_*() return Some. #[test] fn new_instance_renders_confirm_step() { use crate::instance::loader::GameVersion; @@ -129,8 +115,6 @@ fn new_instance_renders_confirm_step() { stable: true, }]); guard.loader_versions = LoadState::Loaded(vec!["0.15.0".into()]); - // TextState exposes only constructors; rebuilding with the - // desired initial value is the supported path. guard.name_state = TextState::new().with_value("MyPack"); } diff --git a/src/tui/tests/widgets/popups/new_instance/state.rs b/src/tui/tests/widgets/popups/new_instance/state.rs index 71e415e..42d73f3 100644 --- a/src/tui/tests/widgets/popups/new_instance/state.rs +++ b/src/tui/tests/widgets/popups/new_instance/state.rs @@ -12,7 +12,62 @@ fn key(code: KeyCode) -> KeyEvent { } #[test] -fn vanilla_wizard_reaches_confirm_and_returns_parameters() { +fn dispatch_repeats_version_search_but_not_snapshot_toggle_or_creation() { + use crate::tui::{app::FocusedArea, tests::harness::UiHarness}; + use crossterm::event::KeyEventKind; + + let mut ui = UiHarness::new(); + ui.app.focused = FocusedArea::Popup; + ui.app.instances_state.show_popup = true; + { + let mut state = WIZARD_STATE.lock().unwrap(); + state.step = WizardStep::Version; + state.versions = LoadState::Loaded(vec![GameVersion { + id: "1.21.1".to_owned(), + stable: true, + }]); + state.version_search.activate(); + } + assert!(ui.key_event(KeyEvent::new_with_kind( + KeyCode::Char('s'), + KeyModifiers::NONE, + KeyEventKind::Repeat + ))); + { + let state = WIZARD_STATE.lock().unwrap(); + assert_eq!(state.version_search.query, "s"); + assert!(!state.show_snapshots); + } + assert!(!ui.key_event(KeyEvent::new_with_kind( + KeyCode::Enter, + KeyModifiers::NONE, + KeyEventKind::Repeat + ))); + { + let mut state = WIZARD_STATE.lock().unwrap(); + state.step = WizardStep::Confirm; + state.name_state = TextState::new().with_value("Held Confirm"); + state.version_search.deactivate(); + } + assert!(!ui.key_event(KeyEvent::new_with_kind( + KeyCode::Enter, + KeyModifiers::NONE, + KeyEventKind::Repeat + ))); + assert!(take_result().is_none()); + assert!(ui.app.instances_state.show_popup); + ui.key(KeyCode::Enter); + assert_eq!(take_result().unwrap().name, "Held Confirm"); + assert!(!ui.key_event(KeyEvent::new_with_kind( + KeyCode::Enter, + KeyModifiers::NONE, + KeyEventKind::Repeat + ))); + assert_eq!(ui.app.focused, FocusedArea::Instances); +} + +#[test] +fn filtered_vanilla_wizard_returns_the_displayed_version() { let _guard = TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner()); let mut instances = instances::State { show_popup: true, @@ -32,10 +87,17 @@ fn vanilla_wizard_reaches_confirm_and_returns_parameters() { { let mut state = WIZARD_STATE.lock().unwrap(); state.step = WizardStep::Version; - state.versions = LoadState::Loaded(vec![GameVersion { - id: "1.21.1".to_owned(), - stable: true, - }]); + state.versions = LoadState::Loaded(vec![ + GameVersion { + id: "1.20.1".to_owned(), + stable: true, + }, + GameVersion { + id: "1.21.1".to_owned(), + stable: true, + }, + ]); + state.version_search.query = "1.21.1".to_owned(); } handle_key(&key(KeyCode::Enter), &mut instances); assert_eq!(WIZARD_STATE.lock().unwrap().step, WizardStep::Confirm); @@ -68,10 +130,12 @@ fn version_filter_clamps_a_stale_selection() { clamp_version_index(&mut state); assert_eq!(state.version_idx, 0); - assert_eq!(visible_versions(&state).len(), 1); + assert_eq!(visible_versions(&state).count(), 1); state.show_snapshots = true; - assert_eq!(visible_versions(&state).len(), 2); + assert_eq!(visible_versions(&state).count(), 2); + state.version_search.query = "missing".to_owned(); + assert!(state.selected_version().is_none()); } #[test] diff --git a/src/tui/tests/widgets/search.rs b/src/tui/tests/widgets/search.rs index eea224b..77774f3 100644 --- a/src/tui/tests/widgets/search.rs +++ b/src/tui/tests/widgets/search.rs @@ -13,7 +13,6 @@ fn confirm_keeps_query_but_deactivates() { s.confirm(); assert!(!s.active); assert_eq!(s.query, "ab"); - // filter should still match assert!(s.matches("abc")); assert!(!s.matches("xyz")); s.activate(); @@ -29,7 +28,6 @@ fn deactivate_clears_query() { s.deactivate(); assert!(!s.active); assert!(s.query.is_empty()); - // with empty query, everything matches assert!(s.matches("anything")); } @@ -55,6 +53,32 @@ fn highlight_spans_marks_each_case_insensitive_match() { assert!(spans[2].style.add_modifier.contains(Modifier::UNDERLINED)); } +#[test] +fn highlighting_maps_expanding_lowercase_back_to_the_original_character() { + for (query, expected) in [("a", "a"), ("i", "İ"), ("\u{307}", "İ")] { + let search = SearchState { + query: query.to_owned(), + ..Default::default() + }; + let spans = search.highlight_spans("İab", Style::default()); + assert_eq!( + spans + .iter() + .map(|span| span.content.as_ref()) + .collect::(), + "İab" + ); + assert_eq!( + spans + .iter() + .filter(|span| span.style.add_modifier.contains(Modifier::UNDERLINED)) + .map(|span| span.content.as_ref()) + .collect::(), + expected + ); + } +} + #[test] fn ctrl_backspace_deletes_the_previous_word() { let mut search = SearchState { diff --git a/src/tui/tests/widgets/settings.rs b/src/tui/tests/widgets/settings.rs index 519faed..05f32be 100644 --- a/src/tui/tests/widgets/settings.rs +++ b/src/tui/tests/widgets/settings.rs @@ -3,10 +3,162 @@ use super::*; +fn cache_java_result( + state: &mut SettingsState, + instance: &InstanceConfig, + label: Option<&str>, +) -> Arc>> { + let settings = SETTINGS.read(); + let environment = crate::instance::java::merge_environment( + &settings.defaults.environment, + &instance.environment, + ); + let cwd = state + .instances_dir + .join(&instance.name) + .join(crate::storage::MINECRAFT_DIR_NAME); + let java = crate::instance::java::resolve_java_path_in( + instance.java_path.as_deref(), + &cwd, + &environment, + ); + let result = Arc::new(Mutex::new(label.map(str::to_owned))); + state.java_cache.insert( + instance.name.clone(), + CachedJavaLabel { + key: Some((instance.created, java_path_key(&java, &cwd, &environment))), + result: result.clone(), + }, + ); + result +} + +#[test] +fn narrow_settings_shows_the_selected_pane() { + let _guard = crate::tests::TEST_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + let tmp = tempfile::tempdir().unwrap(); + let mut state = SettingsState::new(tmp.path().to_path_buf(), tmp.path().join("instances")); + let instance: InstanceConfig = serde_json::from_value(serde_json::json!({ + "name": "Test", "game_version": "1.21", "loader": "vanilla", + "loader_version": null, "created": "2026-01-01T00:00:00Z", "java_path": "test-java" + })) + .unwrap(); + cache_java_result(&mut state, &instance, Some("jdk17")); + let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(35, 8)).unwrap(); + + terminal + .draw(|frame| { + render( + frame, + frame.area(), + FocusedArea::Settings, + &mut state, + Some(&instance), + ) + }) + .unwrap(); + let text = terminal + .backend() + .buffer() + .content() + .iter() + .map(|cell| cell.symbol()) + .collect::(); + assert!(text.contains(LOCAL_PROFILE_LABEL)); + + state.pane = SettingsPane::Info; + terminal + .draw(|frame| { + render( + frame, + frame.area(), + FocusedArea::Settings, + &mut state, + Some(&instance), + ) + }) + .unwrap(); + let text = terminal + .backend() + .buffer() + .content() + .iter() + .map(|cell| cell.symbol()) + .collect::(); + assert!(text.contains("Memory")); + assert!(text.contains("jdk17")); +} + +#[test] +fn cached_settings_render_immediately_and_keep_configuration_values_current() { + let _guard = crate::tests::TEST_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + let temp = tempfile::tempdir().unwrap(); + let mut state = SettingsState::new(temp.path().join("meta"), temp.path().join("instances")); + state.profiles = vec!["shared".to_owned()]; + let mut first: InstanceConfig = serde_json::from_value(serde_json::json!({ + "name": "first", "game_version": "1.21", "loader": "vanilla", + "created": "2026-01-01T00:00:00Z", "java_path": "test-java", + "memory_max": "4G", "config_sync_profile": "shared" + })) + .unwrap(); + let mut second = first.clone(); + second.name = "second".to_owned(); + second.memory_max = Some("8G".to_owned()); + second.config_sync_profile = None; + cache_java_result(&mut state, &first, Some("jdk21")); + let pending = cache_java_result(&mut state, &second, None); + let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(60, 5)).unwrap(); + let mut draw = |state: &mut SettingsState, instance: &InstanceConfig| { + terminal + .draw(|frame| { + render( + frame, + frame.area(), + FocusedArea::Settings, + state, + Some(instance), + ) + }) + .unwrap(); + terminal.backend().to_string() + }; + + assert!(draw(&mut state, &second).contains("unknown")); + assert!(draw(&mut state, &first).contains("jdk21")); + *pending.lock().unwrap() = Some("jdk25".to_owned()); + for (instance, java, memory) in [ + (&second, "jdk25", "8G"), + (&first, "jdk21", "4G"), + (&second, "jdk25", "8G"), + ] { + let screen = draw(&mut state, instance); + assert!(screen.contains(java), "{screen}"); + assert!(screen.contains(memory), "{screen}"); + assert!(!screen.contains("unknown"), "{screen}"); + assert_eq!(state.active_profile, instance.config_sync_profile); + } + first.memory_max = Some("12G".to_owned()); + first.config_sync_profile = None; + let screen = draw(&mut state, &first); + assert!(screen.contains("jdk21")); + assert!(screen.contains("12G")); + assert_eq!(state.active_profile, None); + + state.invalidate_java_cache(Some(&first.name)); + assert!(!state.java_cache.contains_key(&first.name)); + assert!(draw(&mut state, &second).contains("jdk25")); + state.invalidate_java_cache(None); + assert!(state.java_cache.is_empty()); +} + #[test] fn removing_selected_last_profile_clamps_selection() { let tmp = tempfile::tempdir().unwrap(); - let mut state = SettingsState::new(tmp.path().to_path_buf()); + let mut state = SettingsState::new(tmp.path().to_path_buf(), tmp.path().join("instances")); state.profiles = vec!["first".to_string(), "second".to_string()]; state.active_profile = Some("second".to_string()); state.list_state.selected = Some(2); @@ -21,7 +173,7 @@ fn removing_selected_last_profile_clamps_selection() { #[test] fn info_pane_does_not_bind_desktop_toggle() { let tmp = tempfile::tempdir().unwrap(); - let mut state = SettingsState::new(tmp.path().to_path_buf()); + let mut state = SettingsState::new(tmp.path().to_path_buf(), tmp.path().join("instances")); state.pane = SettingsPane::Info; assert!(matches!( @@ -29,3 +181,87 @@ fn info_pane_does_not_bind_desktop_toggle() { SettingsAction::None )); } + +#[cfg(unix)] +#[test] +fn instance_java_labels_are_cached_and_refresh_when_probe_inputs_change() { + use std::os::unix::fs::PermissionsExt; + let _guard = crate::tests::TEST_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + let temp = tempfile::tempdir().unwrap(); + let instances = temp.path().join("instances"); + let java = temp.path().join("selected-java"); + std::fs::write(&java, b"#!/bin/sh\nprintf 'probe\\n' >> probes\nread -r expected < marker || exit 1\n[ \"$RMCL_TEST_JAVA_VERSION\" = \"$expected\" ] || exit 1\nprintf 'java.version = %s\\n' \"$expected\"\n").unwrap(); + std::fs::set_permissions(&java, std::fs::Permissions::from_mode(0o755)).unwrap(); + let mut state = SettingsState::new(temp.path().join("meta"), instances.clone()); + let instance = |name: &str, version: &str| -> InstanceConfig { + let minecraft = instances.join(name).join("minecraft"); + std::fs::create_dir_all(&minecraft).unwrap(); + std::fs::write(minecraft.join("marker"), format!("{version}\n")).unwrap(); + serde_json::from_value(serde_json::json!({ + "name": name, "game_version": "1.21", "loader": "vanilla", "created": "2026-01-01T00:00:00Z", + "java_path": java, "environment": {"RMCL_TEST_JAVA_VERSION": version} + })).unwrap() + }; + fn wait_for_label(state: &mut SettingsState, instance: &InstanceConfig, expected: &str) { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while std::time::Instant::now() < deadline { + state.update_for_instance(Some(instance)); + if state.java_label == expected { + return; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + panic!("Expected {expected}, found {}", state.java_label); + } + let mut first = instance("first", "21"); + wait_for_label(&mut state, &first, "jdk21"); + let second = instance("second", "25"); + state.update_for_instance(Some(&second)); + wait_for_label(&mut state, &second, "jdk25"); + state.update_for_instance(Some(&first)); + assert_eq!(state.java_label, "jdk21"); + state.update_for_instance(None); + state.update_for_instance(Some(&second)); + assert_eq!(state.java_label, "jdk25"); + let probes = |name: &str| { + std::fs::read_to_string(instances.join(name).join("minecraft/probes")) + .unwrap() + .lines() + .count() + }; + assert_eq!(probes("first"), 1); + assert_eq!(probes("second"), 1); + + let stale = state.java_cache[&first.name].result.clone(); + first = instance("first", "17"); + state.update_for_instance(Some(&first)); + *stale.lock().unwrap() = Some("stale label".to_owned()); + wait_for_label(&mut state, &first, "jdk17"); + assert_eq!(probes("first"), 2); + state.update_for_instance(Some(&second)); + assert_eq!(state.java_label, "jdk25"); + + std::fs::write( + &java, + b"#!/bin/sh\nprintf 'probe\\n' >> probes\nprintf 'java.version = 8\\n'\n", + ) + .unwrap(); + wait_for_label(&mut state, &first, "jdk8"); + assert_eq!(probes("first"), 3); + first.created += chrono::TimeDelta::seconds(1); + wait_for_label(&mut state, &first, "jdk8"); + assert_eq!(probes("first"), 4); + + let other_java = temp.path().join("other-java"); + std::fs::write( + &other_java, + b"#!/bin/sh\nprintf 'probe\\n' >> probes\nprintf 'java.version = 11\\n'\n", + ) + .unwrap(); + std::fs::set_permissions(&other_java, std::fs::Permissions::from_mode(0o755)).unwrap(); + first.java_path = Some(other_java.to_string_lossy().into_owned()); + wait_for_label(&mut state, &first, "jdk11"); + assert_eq!(probes("first"), 5); +} diff --git a/src/tui/widgets/account.rs b/src/tui/widgets/account.rs index ff1e843..a4500e2 100644 --- a/src/tui/widgets/account.rs +++ b/src/tui/widgets/account.rs @@ -1,12 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// account management panel: list, add (microsoft/offline), delete -// microsoft auth uses the device code flow, so it polls a shared mutex -// for the result while showing the user a code to enter in their browser - -use std::sync::{Arc, Mutex}; - use crossterm::event::{KeyCode, KeyEvent}; use ratatui::{ Frame, @@ -32,7 +26,7 @@ pub enum AddMode { OfflineBlocked, DeviceCodeWaiting { info: DeviceCodeInfo, - pending: Arc>>, + pending: auth::MicrosoftAuth, }, } @@ -62,7 +56,7 @@ impl AccountState { // can't block on it because the TUI needs to keep rendering pub fn drain_auth_result(&mut self) { if let AddMode::DeviceCodeWaiting { pending, .. } = &self.add_mode { - let result = match pending.lock() { + let result = match pending.result.lock() { Ok(mut slot) => slot.take(), _ => None, }; @@ -70,7 +64,12 @@ impl AccountState { if let Some(result) = result { match result { AuthResult::Success(account) => { - self.store.add(account); + if let Err(error) = self.store.add(account) { + crate::feedback::errors::push_message( + tracing::Level::ERROR, + error.to_string(), + ); + } self.add_mode = AddMode::None; if self.list_state.selected.is_none() && !self.store.accounts.is_empty() { self.list_state.selected = Some(0); @@ -120,7 +119,12 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut AccountState) -> bool { if !trimmed.is_empty() { if state.store.has_microsoft_account() { let account = auth::create_offline_account(&trimmed); - state.store.add(account); + if let Err(error) = state.store.add(account) { + crate::feedback::errors::push_message( + tracing::Level::ERROR, + error.to_string(), + ); + } if state.list_state.selected.is_none() && !state.store.accounts.is_empty() { state.list_state.selected = Some(0); } @@ -173,8 +177,13 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut AccountState) -> bool { true } KeyCode::Enter => { - if let Some(idx) = state.list_state.selected { - state.store.set_active(idx); + if let Some(idx) = state.list_state.selected + && let Err(error) = state.store.set_active(idx) + { + crate::feedback::errors::push_message( + tracing::Level::ERROR, + error.to_string(), + ); } true } @@ -196,12 +205,10 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut AccountState) -> bool { } } -// the device code arrives asynchronously from the auth thread, -// so it gets pulled out of a global mutex once it's ready pub fn drain_device_code(state: &mut AccountState) { - if let AddMode::DeviceCodeWaiting { info, .. } = &mut state.add_mode + if let AddMode::DeviceCodeWaiting { info, pending } = &mut state.add_mode && info.user_code.is_empty() - && let Ok(mut slot) = auth::DEVICE_CODE_DISPLAY.lock() + && let Ok(mut slot) = pending.device_code.lock() && let Some(dc_info) = slot.take() { info.user_code = dc_info.user_code; @@ -335,17 +342,11 @@ fn render_account_list( frame.render_stateful_widget(list, area, &mut state.list_state); } -// center a popup of given size within the terminal. nothing fancy fn popup_area(frame: &Frame, width: u16, height: u16) -> Rect { - let area = frame.area(); - let x = area.x + (area.width.saturating_sub(width)) / 2; - let y = area.y + (area.height.saturating_sub(height)) / 2; - Rect { - x, - y, - width: width.min(area.width), - height: height.min(area.height), - } + frame.area().centered( + ratatui::layout::Constraint::Length(width), + ratatui::layout::Constraint::Length(height), + ) } fn render_choose_popup(frame: &mut Frame) { diff --git a/src/tui/widgets/content/discovery.rs b/src/tui/widgets/content/discovery.rs index 7308867..4e32c8c 100644 --- a/src/tui/widgets/content/discovery.rs +++ b/src/tui/widgets/content/discovery.rs @@ -896,6 +896,13 @@ pub enum DiscoveryActionResult { project_id: String, result: Result, String>, }, + /// The filtered fetch found nothing, so the task retried unfiltered. + /// Drain opens the Minecraft version picker instead of a dead end. + VersionsUnfiltered { + request_id: u64, + project_id: String, + result: Result, String>, + }, Dependencies { request_id: u64, project_id: String, @@ -1364,11 +1371,8 @@ impl DiscoveryState { pub(crate) fn set_filter_loader(&mut self, loader: ModLoader) { if self.filter_loader != loader { - *self - .filter_game_versions - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) = - crate::tui::widgets::popups::LoadState::Idle; + self.filter_game_versions = + Arc::new(Mutex::new(crate::tui::widgets::popups::LoadState::Idle)); } self.filter_loader = loader; } @@ -2550,6 +2554,35 @@ impl DiscoveryState { Err(error) => popup.error = Some(error), } } + DiscoveryActionResult::VersionsUnfiltered { + request_id, + project_id, + result, + } => { + let Some(popup) = self.version_popup.as_mut().filter(|popup| { + popup.request_id == request_id && popup.project_id == project_id + }) else { + continue; + }; + popup.loading = false; + match result { + Ok(versions) if !versions.is_empty() => { + popup.all_game_versions = true; + popup.selecting_minecraft_version = true; + popup.minecraft_versions = minecraft_versions(&versions); + popup.versions = versions; + popup.selected = 0; + popup.error = None; + } + Ok(_) => { + popup.minecraft_versions = Vec::new(); + popup.versions = Vec::new(); + popup.selected = 0; + popup.error = None; + } + Err(error) => popup.error = Some(error), + } + } DiscoveryActionResult::Dependencies { request_id, project_id, @@ -2645,6 +2678,21 @@ impl DiscoveryState { self.pending_orphan_cleanup.take() } + pub(in crate::tui) fn text_input_active(&self) -> bool { + if let Some(popup) = &self.version_popup { + return popup.selecting_world && !popup.confirming && popup.worlds.search.active; + } + if self.project_page_open() { + return false; + } + if self.sort_panel_open && !self.search.active { + return self.sort_panel_focused + && self.filter_version_picker_open + && self.filter_version_search.active; + } + self.search.active + } + fn should_load_more(&self) -> bool { if self.page_loading || (self.preparing_list.is_some() && self.retry_page_at.is_none()) @@ -3004,6 +3052,29 @@ fn loader_slug(loader: ModLoader) -> Option<&'static str> { } } +/// One popup version fetch: compatible versions for `game_version` +/// (empty means unfiltered) plus the installed version when missing. +pub async fn fetch_popup_versions( + provider: &dyn crate::instance::content::provider::ContentProvider, + project_id: &str, + kind: ContentKind, + game_version: &str, + loader: ModLoader, + current_version_id: Option<&str>, +) -> Result, String> { + let mut versions = provider + .compatible_versions(project_id, kind, game_version, loader) + .await + .map_err(|error| error.to_string())?; + if let Some(current) = current_version_id + && !versions.iter().any(|version| version.id == current) + && let Ok(version) = provider.version(current).await + { + versions.push(version); + } + Ok(versions) +} + pub(crate) fn provider_project_entry( project: DiscoveryProject, provider: &str, diff --git a/src/tui/widgets/content/list.rs b/src/tui/widgets/content/list.rs index 2dd2c95..f1dfd61 100644 --- a/src/tui/widgets/content/list.rs +++ b/src/tui/widgets/content/list.rs @@ -1,11 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// generic scrollable list for content items (mods, resource packs, shaders, worlds). -// supports toggling items on/off by renaming files with .disabled suffix, -// search filtering, per-instance caching, and directory change detection. -// also handles minecraft's formatting codes for colored mod names/descriptions - use std::cell::RefCell; use std::collections::{HashMap, HashSet}; use std::path::Path; @@ -17,7 +12,7 @@ use ratatui::{ layout::Rect, style::{Color, Modifier, Style}, text::{Line, Span, Text}, - widgets::{Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState}, + widgets::{Paragraph, ScrollbarState}, }; use ratatui_image::{CropOptions, Resize, StatefulImage, protocol::StatefulProtocol}; use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView}; @@ -175,12 +170,6 @@ enum ContentStreamUpdate { }, } -struct CachedList { - entries: Vec, - selected: Option, - sort_metadata: HashMap, -} - struct FileSortMetadata { name: String, size: Option, @@ -245,7 +234,6 @@ struct PaginationState { const REMOVAL_GRACE: std::time::Duration = std::time::Duration::from_millis(500); -// result from the notify-triggered background diff struct WatcherDiff { toggled: Vec<(String, bool, std::path::PathBuf)>, removed: Vec, @@ -277,6 +265,7 @@ pub struct ContentListState { pending_provider_icons: Arc>>, project_metadata: HashMap<(String, String), crate::net::modrinth::ProjectInfo>, version_metadata: HashMap<(String, String), crate::net::modrinth::VersionInfo>, + unlinked_paths: HashSet, requested_provider_icons: HashSet<(String, String, String)>, pub local_panel_open: bool, pub local_sort_index: usize, @@ -288,23 +277,19 @@ pub struct ContentListState { images_dirty: bool, display_metadata: HashMap, pub search: crate::tui::widgets::search::SearchState, + pub warning_descriptions: bool, filter_search: bool, - cache: HashMap, sort_metadata: RefCell>, filtered_cache: RefCell>, - // streaming: individual entries arrive here during initial load stream_rx: Option>, stream_order: ContentStreamOrder, progressive_source_stream: bool, staged_source_updates: Option>, source_order_ready: bool, preview_count: usize, - // file watcher: notify callback spawns background work, - // precomputed diff lands here for the UI to pick up watcher_diff: Arc>>, _watcher: Option, watched_dir: Option, - // stored for the watcher to scan individual new files scan_one_fn: Option, content_ext: Option<&'static str>, pagination: Option, @@ -332,6 +317,7 @@ impl Default for ContentListState { pending_provider_icons: Arc::new(Mutex::new(Vec::new())), project_metadata: HashMap::new(), version_metadata: HashMap::new(), + unlinked_paths: HashSet::new(), requested_provider_icons: HashSet::new(), local_panel_open: false, local_sort_index: 0, @@ -346,8 +332,8 @@ impl Default for ContentListState { images_dirty: true, display_metadata: HashMap::new(), search: crate::tui::widgets::search::SearchState::default(), + warning_descriptions: false, filter_search: true, - cache: HashMap::new(), sort_metadata: RefCell::new(HashMap::new()), filtered_cache: RefCell::new(None), stream_rx: None, @@ -368,6 +354,10 @@ impl Default for ContentListState { } impl ContentListState { + pub(crate) fn is_scanning(&self) -> bool { + self.stream_rx.is_some() + } + pub(crate) fn has_pending_icons(&self) -> bool { !self.pending_entry_images.is_empty() } @@ -417,6 +407,21 @@ impl ContentListState { kind: crate::instance::ContentKind, ) { let mut changed = false; + // Unmatched can also mean identification was skipped, so require + // at least one completed provider lookup before showing the notice. + let unlinked_paths = manifest + .files + .iter() + .filter(|record| { + record.kind == kind + && matches!(&record.resolution, crate::instance::Resolution::Unmatched { providers, .. } if !providers.is_empty()) + }) + .map(|record| minecraft_dir.join(&record.relative_path)) + .collect::>(); + if self.unlinked_paths != unlinked_paths { + self.unlinked_paths = unlinked_paths; + changed = true; + } let mut invalidated_icons = Vec::new(); for entry in &mut self.entries { let Ok(relative_path) = entry.path.strip_prefix(minecraft_dir) else { @@ -596,7 +601,7 @@ impl ContentListState { && !self .version_metadata .contains_key(&(project.provider.clone(), project.version_id.clone())); - if !self.requested_provider_icons.insert(key) && !missing_version { + if !self.requested_provider_icons.insert(key) { continue; } let pending = self.pending_provider_icons.clone(); @@ -754,6 +759,7 @@ impl ContentListState { self.pending_removals.clear(); self.requested_provider_icons.clear(); self.entries.clear(); + self.unlinked_paths.clear(); self.invalidate_filtered(); self.sort_metadata.get_mut().clear(); self.display_metadata.clear(); @@ -893,8 +899,6 @@ impl ContentListState { } } - // drain streaming entries from the initial load. each entry arrives - // individually and is inserted in sorted position for a smooth fill-in pub fn drain_pending(&mut self) -> bool { let Some(rx) = &self.stream_rx else { return false; @@ -1175,7 +1179,6 @@ impl ContentListState { }; self.images_dirty |= update.requires_reconcile; - // apply toggles (enabled/path changes) tracing::debug!( "Applying content watcher diff for {}: toggled={} removed={} added={}", self.loaded_for.as_deref().unwrap_or(""), @@ -1193,6 +1196,9 @@ impl ContentListState { }; self.sort_metadata.get_mut().remove(&old_path); self.sort_metadata.get_mut().remove(path); + if self.unlinked_paths.remove(&old_path) { + self.unlinked_paths.insert(path.clone()); + } update.toggles.push(ContentToggle { old_path, new_path: path.clone(), @@ -1214,14 +1220,15 @@ impl ContentListState { .or_insert_with(std::time::Instant::now); } - // insert new entries in sorted position for mut entry in diff.added { self.sort_metadata.get_mut().remove(&entry.path); + self.unlinked_paths.remove(&entry.path); let replacement = self.entries.iter().position(|existing| { self.pending_removals.contains_key(&existing.file_stem) && existing.name.eq_ignore_ascii_case(&entry.name) }); if let Some(index) = replacement { + self.unlinked_paths.remove(&self.entries[index].path); let old_stem = self.entries[index].file_stem.clone(); self.sort_metadata .get_mut() @@ -1294,6 +1301,7 @@ impl ContentListState { let before = self.entries.len(); if let Some(entry) = self.entries.iter().find(|entry| entry.file_stem == stem) { self.sort_metadata.get_mut().remove(&entry.path); + self.unlinked_paths.remove(&entry.path); } self.entries.retain(|entry| entry.file_stem != stem); removed |= self.entries.len() != before; @@ -1310,14 +1318,12 @@ impl ContentListState { removed } - // starts a notify file watcher on the given directory. changes trigger - // a background diff that lands in watcher_diff for drain_watcher to apply. pub fn watch_dir(&mut self, dir: std::path::PathBuf) { use notify::{RecursiveMode, Watcher}; use std::sync::atomic::{AtomicBool, Ordering}; - // drop previous watcher self._watcher = None; + self.watcher_diff = Arc::new(Mutex::new(None)); let watcher_diff = self.watcher_diff.clone(); let ext: &'static str = self.content_ext.unwrap_or(".jar"); @@ -1691,24 +1697,6 @@ async fn load_installed_version( } impl ContentListState { - pub fn forget_instance(&mut self, instance_name: &str) { - let world_prefix = format!("{instance_name}:"); - self.cache - .retain(|source, _| source != instance_name && !source.starts_with(&world_prefix)); - if self - .loaded_for - .as_deref() - .is_some_and(|source| source == instance_name || source.starts_with(&world_prefix)) - { - self.loaded_for = None; - self.sort_metadata.get_mut().clear(); - self.invalidate_filtered(); - } - } - - // saves current entries to cache before loading new ones, and restores - // from cache if this instance was seen before (avoids re-scanning). - // content_dir is the actual directory to scan (e.g. .minecraft/mods). pub fn start_load( &mut self, content_dir: &Path, @@ -1724,52 +1712,6 @@ impl ContentListState { self.pending_entry_images.clear(); self.pending_removals.clear(); - // save current entries to cache - if let Some(prev) = self.loaded_for.take() - && !self.entries.is_empty() - { - tracing::trace!( - "Caching {} content entries for {}", - self.entries.len(), - prev - ); - self.cache.insert( - prev, - CachedList { - entries: std::mem::take(&mut self.entries), - selected: self.list_state.selected, - sort_metadata: std::mem::take(self.sort_metadata.get_mut()), - }, - ); - } - - // try cache first - // files modified while another instance was active become a real problem. - if let Some(cached) = self.cache.remove(instance_name) { - self.entries = cached.entries; - self.invalidate_filtered(); - *self.sort_metadata.get_mut() = cached.sort_metadata; - self.pending_entry_images.extend( - self.entries - .iter() - .filter(|entry| entry.icon_bytes.is_some() || entry.provider_icon) - .map(|entry| entry.file_stem.clone()), - ); - self.rebuild_display_metadata(); - self.list_state.selected = cached.selected; - self.loading = false; - self.stream_rx = None; - self.loaded_for = Some(instance_name.to_string()); - self.update_scrollbar(); - tracing::debug!( - "Restored {} cached content entries for {}", - self.entries.len(), - instance_name - ); - return; - } - - // no cache, stream entries one by one as each file is scanned let stream = self.start_stream(instance_name); let dir = content_dir.to_path_buf(); @@ -1881,8 +1823,6 @@ impl ContentListState { .collect(); } - // enable/disable by renaming the file with/without .disabled extension. - // this is how most minecraft launchers handle it pub fn toggle_selected(&mut self) { let Some(index) = self.list_state.selected else { return; @@ -1912,6 +1852,7 @@ impl ContentListState { } pub fn remove_path(&mut self, path: &Path) { + self.unlinked_paths.remove(path); self.invalidate_filtered(); self.sort_metadata.get_mut().remove(path); let file_stem = self @@ -2089,9 +2030,13 @@ fn handle_key_inner( KeyCode::Enter if key_event.modifiers.contains(KeyModifiers::SHIFT) => { if let Some(&real_idx) = state.list_state.selected.and_then(|i| filtered.get(i)) && let Some(dir) = state.entries[real_idx].path.parent() - && let Err(e) = open::that_detached(dir) + && let Err(error) = open::that_detached(dir) { - tracing::error!("Failed to open directory: {}", e); + tracing::error!("Failed to open directory: {}", error); + crate::feedback::errors::push_message( + tracing::Level::ERROR, + format!("Could not open {}: {error}", dir.display()), + ); } true } @@ -2173,8 +2118,10 @@ pub fn render( let display_metadata = &state.display_metadata; let version_metadata = &state.version_metadata; let local_game_version = state.local_game_version.clone(); + let unlinked_paths = &state.unlinked_paths; let filtered_rows = &filtered; let search = &state.search; + let warning_descriptions = state.warning_descriptions; let ready_image_stems: HashSet = state.image_protocols.keys().cloned().collect(); let builder = ListBuilder::new(move |context| { @@ -2188,7 +2135,11 @@ pub fn render( let title_suffix = world_details .and_then(|details| details.game_mode) .map(WorldGameMode::label) - .or(entry.title_suffix.as_deref()); + .or(entry.title_suffix.as_deref()) + .or_else(|| { + (entry.provider_project.is_none() && unlinked_paths.contains(&entry.path)) + .then_some("Unlinked") + }); let world_footer = world_details.map(|details| format_relative_time(details.last_played)); let footer_label = world_footer.as_deref().or(entry.footer_label.as_deref()); // Keep rendering the terminal fallback until the asynchronous image @@ -2205,7 +2156,7 @@ pub fn render( theme.stripe() }; - let (name_style, description_style, background) = match (enabled, show_selected) { + let (name_style, mut description_style, background) = match (enabled, show_selected) { (true, true) => ( Style::default() .fg(theme.accent()) @@ -2235,6 +2186,9 @@ pub fn render( stripe_bg, ), }; + if warning_descriptions { + description_style = Style::default().fg(theme.warning()); + } let title_suffix_color = world_details .and_then(|details| details.game_mode) .map(world_game_mode_color) @@ -2245,7 +2199,11 @@ pub fn render( theme.success() } }); - let title_suffix_style = crate::tui::widgets::status_badge_style(title_suffix_color); + let title_suffix_style = if title_suffix == Some("Unlinked") { + crate::tui::widgets::status_badge_style(theme.text_dim()) + } else { + crate::tui::widgets::status_badge_style(title_suffix_color) + }; let incompatible_version = !local_game_version.is_empty() && entry.provider_project.as_ref().is_some_and(|installed| { !installed.version_id.is_empty() @@ -2460,17 +2418,7 @@ pub fn render( height: list_area.height.saturating_sub(2), }; frame.render_stateful_widget( - Scrollbar::default() - .orientation(ScrollbarOrientation::VerticalRight) - .begin_symbol(Some("\u{25b2}")) - .style( - Style::default() - .fg(theme.text_dim()) - .add_modifier(Modifier::BOLD), - ) - .thumb_symbol("\u{2551}") - .track_symbol(Some("")) - .end_symbol(Some("\u{25bc}")), + crate::tui::widgets::scrollbar(theme.text_dim()), scrollbar_area, &mut state.scrollbar_state, ); @@ -2690,8 +2638,6 @@ fn searchable_spans( } } -// parses minecraft's section-sign (U+00A7) formatting codes into styled spans. -// handles colors (0-f), bold (l), strikethrough (m), underline (n), italic (o), reset (r) fn parse_mc_text(text: &str, base_style: Style) -> Vec> { let mut spans = Vec::new(); let mut current_style = base_style; @@ -2779,9 +2725,6 @@ fn preserve_visual_metadata(entry: &mut ContentEntry, previous: &mut ContentEntr } } -// renders one row of a mod icon using half-block characters (U+2584). -// each cell packs two vertical pixels via fg/bg colors, giving -// double the vertical resolution out of the terminal fn icon_spans( icon_pixels: Option<&Vec>>, row: usize, @@ -2976,10 +2919,6 @@ fn watcher_event_handling(kind: ¬ify::EventKind) -> WatcherEventHandling { } } -// reads a content directory and builds a stem -> (path, enabled) map. -// used both by watch_dir to initialize known state and by the watcher -// thread to detect changes. when ext is empty (worlds), only directories -// are included. fn diff_directory( dir: &std::path::Path, ext: &str, diff --git a/src/tui/widgets/content/mod.rs b/src/tui/widgets/content/mod.rs index d580c42..9068b77 100644 --- a/src/tui/widgets/content/mod.rs +++ b/src/tui/widgets/content/mod.rs @@ -1,8 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// the tabbed content area: mods, resource packs, shaders, screenshots, worlds, logs - pub mod discovery; pub mod list; pub mod tabs; diff --git a/src/tui/widgets/content/tabs.rs b/src/tui/widgets/content/tabs.rs index 846b4ca..8608ded 100644 --- a/src/tui/widgets/content/tabs.rs +++ b/src/tui/widgets/content/tabs.rs @@ -1,10 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// the outer frame for the content area: tab bar, keybind footer, -// and dispatching render calls to the active tab's widget. -// also renders the instance name/version header with run state indicators. - use ratatui::{ Frame, layout::{Alignment, Constraint, Direction, Layout, Margin, Rect}, @@ -357,8 +353,6 @@ pub fn render( _ => false, }; - // keybinds change depending on which tab is active and whether - // the content panel or instances panel has focus let kb: Option<&[(&str, &str)]> = if is_focused { Some(match (mode, tab) { (ContentMode::Discover, _) if discovery_unavailable => { @@ -459,6 +453,7 @@ pub fn render( if logs_state.viewer_focused { &[ ("j/k", " scroll"), + ("f", " filter"), ("g/G", " top/bottom"), ("d", " delete"), ("Esc", " back"), @@ -470,6 +465,8 @@ pub fn render( ("j/k", " navigate"), ("⏎", " view"), ("d", " delete"), + ("Shift+⏎", " open dir"), + ("f", " filter"), ("h/l", " tabs"), ("/", " search"), ("Tab", " discovery"), @@ -496,6 +493,13 @@ pub fn render( }; let mut keybinds = kb.map_or_else(Vec::new, <[_]>::to_vec); + if is_focused + && mode == ContentMode::Installed + && tab == ContentTab::Logs + && logs_state.selection.range.is_some() + { + keybinds.insert(0, ("y", " yank")); + } if is_focused && (mode == ContentMode::Installed || (!discovery_page_open && !discovery_unavailable)) && (matches!( @@ -603,7 +607,6 @@ pub fn render( return; } - // lazy-load: only scan when switching to an instance that hasn't been loaded yet match tab { ContentTab::Mods | ContentTab::ResourcePacks @@ -649,8 +652,8 @@ pub fn render( } ContentTab::Worlds => { if let Some(instance) = instance { - if let Some((world_name, world_path)) = open_world_datapacks { - let cache_key = format!("{}:{world_name}", instance.name); + if let Some((_, world_path)) = open_world_datapacks { + let cache_key = format!("{}:{world_path:?}", instance.name); let content_dir = world_path.join("datapacks"); if world_datapacks_state.loaded_for.as_deref() != Some(cache_key.as_str()) { world_datapacks_state.start_load( @@ -1631,7 +1634,9 @@ pub(crate) fn render_version_popup( .style(Style::default().fg(THEME.as_ref().text_dim())) .render(area, buffer); } else { - crate::tui::widgets::popups::select_list::render( + // render_styled preserves the badge spans: highlight only adds + // bold instead of painting fg/bg over the whole row. + crate::tui::widgets::popups::select_list::render_styled( items.clone(), selected, area, @@ -1762,8 +1767,6 @@ fn discovery_version_label(version: &crate::net::modrinth::VersionInfo) -> Strin version.version_number.clone() } -// the header bar above the content tabs, showing instance name, loader info, -// and a spinner/error indicator when the instance is running or crashed pub fn title( frame: &mut Frame, area: Rect, diff --git a/src/tui/widgets/content/update.rs b/src/tui/widgets/content/update.rs index e77ed45..d7a8a5c 100644 --- a/src/tui/widgets/content/update.rs +++ b/src/tui/widgets/content/update.rs @@ -9,6 +9,8 @@ use std::time::Instant; use ratatui::{ Frame, layout::{Constraint, Margin}, + style::Style, + widgets::{Paragraph, Widget}, }; use crate::instance::ContentKind; @@ -30,6 +32,7 @@ pub enum Phase { } pub struct State { + pub instance_name: String, pub phase: Phase, pub plan: Option, pub snapshot: Option, @@ -38,17 +41,20 @@ pub struct State { pub target_world: Option<(String, PathBuf)>, pub completed: bool, pub applied: bool, + pub abort_handle: Option, pub list: super::list::ContentListState, source_entries: HashMap, } impl State { pub fn checking( + instance_name: String, kind: ContentKind, target_world: Option<(String, PathBuf)>, entries: Vec, ) -> Self { Self { + instance_name, phase: Phase::Checking, plan: None, snapshot: None, @@ -57,6 +63,7 @@ impl State { target_world, completed: false, applied: false, + abort_handle: None, list: super::list::ContentListState::default(), source_entries: entries .into_iter() @@ -65,6 +72,12 @@ impl State { } } + pub fn cancel(&self) { + if let Some(handle) = &self.abort_handle { + handle.abort(); + } + } + pub fn drain(&mut self) -> bool { let pending = match self.pending.lock() { Ok(mut pending) => pending.drain(..).collect::>(), @@ -113,7 +126,10 @@ impl State { } pub fn visible(&self) -> bool { - matches!(self.phase, Phase::Conflicts | Phase::Review) && !self.completed + matches!( + self.phase, + Phase::Checking | Phase::Conflicts | Phase::Review + ) && !self.completed } pub fn has_updates(&self) -> bool { @@ -161,7 +177,8 @@ impl State { .flat_map(|plan| plan.roots.iter()) .map(|root| { let mut entry = self.entry_for(&root.installed_path, &root.title); - entry.title_suffix = Some("Update".to_owned()); + // Every row here is an update; a badge would repeat the popup title. + entry.title_suffix = None; entry.footer_label = None; entry.footer_change = Some(( root.current_version.clone(), @@ -172,6 +189,7 @@ impl State { .collect(), Phase::Checking | Phase::Applying => Vec::new(), }; + self.list.warning_descriptions = matches!(self.phase, Phase::Conflicts); self.list.set_entries(entries); } @@ -208,13 +226,35 @@ pub fn render(frame: &mut Frame, state: &mut State, picker: &ratatui_image::pick if !state.visible() { return; } + let theme = crate::config::theme::THEME.as_ref(); + if state.phase == Phase::Checking { + let area = frame.area().centered( + Constraint::Percentage(40), + Constraint::Length(5.min(frame.area().height.saturating_sub(4))), + ); + let popup = PopupFrame { + title: crate::tui::widgets::styled_title("Preparing updates", false), + border_color: theme.accent(), + bg: Some(theme.surface()), + keybinds: Some(crate::tui::widgets::popups::keybind_line(&[( + "Esc", " cancel", + )])), + search_line: None, + content: Box::new(|area, buffer| { + Paragraph::new("Resolving dependencies…") + .style(Style::default().fg(crate::config::theme::THEME.as_ref().text_dim())) + .render(area, buffer); + }), + }; + frame.render_widget(popup, area); + return; + } let count = state.list.entries.len() as u16; let height = count.saturating_mul(3).saturating_add(2).clamp(5, 20); let area = frame.area().centered( Constraint::Percentage(60), Constraint::Length(height.min(frame.area().height.saturating_sub(4))), ); - let theme = crate::config::theme::THEME.as_ref(); let (title, keybinds) = match state.phase { Phase::Conflicts => ( "Updates needing attention", diff --git a/src/tui/widgets/instances.rs b/src/tui/widgets/instances.rs index d59381d..7c69c85 100644 --- a/src/tui/widgets/instances.rs +++ b/src/tui/widgets/instances.rs @@ -1,10 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// the instance list on the left side of the UI. -// handles search/filter, scrollbar sync, and inline renaming. -// each row shows instance name + "last played" or current run state. - use crate::config::theme::{BORDER_STYLE, THEME}; use crossterm::event::KeyCode; use ratatui::{ @@ -12,7 +8,7 @@ use ratatui::{ layout::Rect, style::{Modifier, Style}, text::{Line, Span, Text}, - widgets::{Block, Borders, Scrollbar, ScrollbarOrientation, ScrollbarState}, + widgets::{Block, Borders, ScrollbarState}, }; use std::collections::HashMap; use std::sync::{Arc, LazyLock, Mutex}; @@ -388,17 +384,7 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut S frame.render_stateful_widget(list, area, &mut state.list_state); frame.render_stateful_widget( - Scrollbar::default() - .orientation(ScrollbarOrientation::VerticalRight) - .begin_symbol(Some("\u{25b2}")) - .style( - Style::default() - .fg(theme.text_dim()) - .add_modifier(Modifier::BOLD), - ) - .thumb_symbol("\u{2551}") - .track_symbol(Some("")) - .end_symbol(Some("\u{25bc}")), + super::scrollbar(theme.text_dim()), scrollbar_area, &mut state.scrollbar_state, ); diff --git a/src/tui/widgets/log_selection.rs b/src/tui/widgets/log_selection.rs new file mode 100644 index 0000000..1e8265d --- /dev/null +++ b/src/tui/widgets/log_selection.rs @@ -0,0 +1,158 @@ +// SPDX-FileCopyrightText: 2026 Constantin Bauer +// SPDX-License-Identifier: GPL-3.0-only + +use crossterm::event::{MouseButton, MouseEvent, MouseEventKind}; +use ratatui::{ + layout::{Position, Rect}, + style::{Modifier, Style}, + text::{Line, Span}, +}; +use unicode_segmentation::UnicodeSegmentation; + +use super::search::SearchState; + +// Positions are (filtered line index, UTF-8 byte boundary). Mouse columns +// are converted using grapheme widths, including wide and combining glyphs. +#[derive(Debug, Default)] +pub(crate) struct LogSelection { + anchor: Option<(usize, usize)>, + pub range: Option<((usize, usize), (usize, usize))>, +} + +impl LogSelection { + pub fn clear(&mut self) { + *self = Self::default(); + } + + pub fn finish(&mut self) { + self.anchor = None; + } + + pub fn handle_mouse( + &mut self, + event: MouseEvent, + area: Rect, + scroll: usize, + lines: &[impl AsRef], + ) -> bool { + match event.kind { + MouseEventKind::Down(MouseButton::Left) => { + self.clear(); + if area.is_empty() + || !area.contains(Position::new(event.column, event.row)) + || lines.is_empty() + { + return false; + } + self.anchor = Some(mouse_position(event, area, scroll, lines)); + true + } + MouseEventKind::Drag(MouseButton::Left) => { + let Some(anchor) = self.anchor else { + return false; + }; + if lines.is_empty() { + self.clear(); + return true; + } + let end = mouse_position(event, area, scroll, lines); + self.range = (anchor != end).then_some((anchor, end)); + true + } + MouseEventKind::Up(MouseButton::Left) => self.anchor.take().is_some(), + _ => false, + } + } + + pub fn text(&self, lines: &[impl AsRef]) -> Option { + let (start, end) = self.ordered()?; + let selected = lines.get(start.0..=end.0)?; + let mut text = Vec::with_capacity(selected.len()); + for (offset, line) in selected.iter().enumerate() { + let line = line.as_ref(); + let from = if offset == 0 { start.1 } else { 0 }; + let to = if offset == selected.len() - 1 { + end.1 + } else { + line.len() + }; + text.push(line.get(from..to)?); + } + Some(text.join("\n")) + } + + pub fn highlight_line( + &self, + index: usize, + text: &str, + search: &SearchState, + style: Style, + ) -> Line<'static> { + let Some((start, end)) = self.ordered() else { + return search.highlight_line(text, style); + }; + if index < start.0 || index > end.0 { + return search.highlight_line(text, style); + } + let from = if index == start.0 { start.1 } else { 0 }; + let to = if index == end.0 { end.1 } else { text.len() }; + if !text.is_char_boundary(from) || !text.is_char_boundary(to) { + return search.highlight_line(text, style); + } + let mut offset = 0; + let mut spans = Vec::new(); + for span in search.highlight_spans(text, style) { + let len = span.content.len(); + let left = from.saturating_sub(offset).min(len); + let right = to.saturating_sub(offset).min(len); + for (range, selected) in [(0..left, false), (left..right, true), (right..len, false)] { + if !range.is_empty() { + spans.push(Span::styled( + span.content[range].to_owned(), + if selected { + span.style.add_modifier(Modifier::REVERSED) + } else { + span.style + }, + )); + } + } + offset += len; + } + Line::from(spans) + } + + fn ordered(&self) -> Option<((usize, usize), (usize, usize))> { + self.range.map(|(a, b)| (a.min(b), a.max(b))) + } +} + +fn mouse_position( + event: MouseEvent, + area: Rect, + scroll: usize, + lines: &[impl AsRef], +) -> (usize, usize) { + let row = event + .row + .saturating_sub(area.y) + .min(area.height.saturating_sub(1)); + let index = scroll + usize::from(row); + if index >= lines.len() { + return (lines.len() - 1, lines.last().unwrap().as_ref().len()); + } + let column = usize::from(event.column.saturating_sub(area.x).min(area.width)); + let text = lines[index].as_ref(); + let mut width = 0; + for (byte, grapheme) in text.grapheme_indices(true) { + width += Span::raw(grapheme).width(); + if column < width { + return (index, byte); + } + } + (index, text.len()) +} + +#[cfg(test)] +#[path = "../tests/widgets/log_selection.rs"] +mod tests; diff --git a/src/tui/widgets/logs_viewer.rs b/src/tui/widgets/logs_viewer.rs index 229b8a1..5186d00 100644 --- a/src/tui/widgets/logs_viewer.rs +++ b/src/tui/widgets/logs_viewer.rs @@ -1,11 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// split-pane log viewer: file list on the left, log content on the right. -// supports live log tailing when the instance is running, plus search -// filtering in both the file list and the viewer pane. -// log scanning runs on a background thread to avoid blocking the UI. - use std::path::Path; use std::sync::{Arc, Mutex}; @@ -15,14 +10,18 @@ use ratatui::{ layout::{Constraint, Layout, Rect}, style::{Modifier, Style}, text::{Line, Span}, - widgets::{Block, Borders, Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState}, + widgets::{Block, Borders, Paragraph, ScrollbarState}, }; use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView}; +use super::content::discovery::CategoryFilter; +use super::log_selection::LogSelection; use crate::config::theme::{BORDER_STYLE, THEME}; use crate::instance::launch::parser::LogLevel; use crate::instance::logs::files::{LogFileEntry, read_log_file, scan_log_files}; +pub(crate) type LevelFilters = [Option; 5]; + type PendingLogs = Arc)>>>; pub struct LogsState { @@ -34,6 +33,11 @@ pub struct LogsState { pub viewer_lines: Vec, pub viewer_scroll: usize, pub viewer_max_scroll: usize, + pub filter_open: bool, + pub filter_selected: usize, + pub(crate) level_filters: LevelFilters, + pub(crate) selection: LogSelection, + pub viewer_area: Rect, pub scrollbar_state: ScrollbarState, pub viewer_scrollbar_state: ScrollbarState, pub search: super::search::SearchState, @@ -56,6 +60,11 @@ impl Default for LogsState { viewer_lines: Vec::new(), viewer_scroll: 0, viewer_max_scroll: 0, + filter_open: false, + filter_selected: 0, + level_filters: [None; 5], + selection: LogSelection::default(), + viewer_area: Rect::default(), scrollbar_state: ScrollbarState::default(), viewer_scrollbar_state: ScrollbarState::default(), search: super::search::SearchState::default(), @@ -71,15 +80,18 @@ impl Default for LogsState { impl LogsState { pub fn start_load(&mut self, instances_dir: &Path, instance_name: &str) { + self.pending = Arc::new(Mutex::new(None)); self.loading = true; self.loaded_for = Some(instance_name.to_string()); self.instances_dir_cache = Some(instances_dir.to_path_buf()); self.entries.clear(); self.list_state = TuiListState::default(); self.viewer_lines.clear(); + self.selection.clear(); self.viewer_scroll = 0; self.viewer_focused = false; self.selected_path = None; + self.was_live = false; self.last_rescan = std::time::Instant::now(); let dir = instances_dir.to_path_buf(); @@ -103,36 +115,40 @@ impl LogsState { pub fn drain_pending(&mut self) { let live_now = self.has_live(); - self.was_live = live_now; + let live_changed = live_now != self.was_live; + let selected_live = + self.was_live && self.selected_path.is_none() && self.list_state.selected.is_some(); let taken = match self.pending.lock() { Ok(mut slot) => slot.take(), _ => None, }; - if let Some((instance_name, entries)) = taken + let updated = if let Some((instance_name, entries)) = taken && self.loaded_for.as_deref() == Some(&instance_name) { - let prev_selected = self.list_state.selected; self.entries = entries; self.loading = false; - - let display_count = self.display_count(); - - if display_count > 0 && prev_selected.is_none() { - self.list_state.selected = Some(0); - self.load_selected_content(); - } else if let Some(sel) = prev_selected - && sel >= display_count - && display_count > 0 - { - self.list_state.selected = Some(display_count - 1); - } + true + } else { + false + }; + if updated || live_changed { + let previous = self.list_state.selected.unwrap_or(0); + let indices = self.display_indices(); + self.list_state.selected = indices + .iter() + .position(|index| match index { + None => selected_live, + Some(index) => self.selected_path.as_ref() == Some(&self.entries[*index].path), + }) + .or_else(|| (!indices.is_empty()).then(|| previous.min(indices.len() - 1))); self.update_scrollbar(); + self.load_selected_content(); } + self.was_live = live_now; } - // periodically re-scan log files in case new ones appeared while playing. pub fn try_rescan(&mut self) { if self.last_rescan.elapsed() < std::time::Duration::from_secs(2) { return; @@ -155,6 +171,7 @@ impl LogsState { let dir = dir.clone(); let tag = name.clone(); + self.pending = Arc::new(Mutex::new(None)); let pending = self.pending.clone(); tokio::spawn(async move { @@ -224,6 +241,9 @@ impl LogsState { fn load_selected_content(&mut self) { if self.is_live_selected() { + if self.selected_path.is_some() { + self.selection.clear(); + } self.selected_path = None; self.viewer_lines.clear(); self.viewer_scroll = 0; @@ -239,6 +259,7 @@ impl LogsState { return; } self.selected_path = path.clone(); + self.selection.clear(); self.viewer_scroll = 0; if let Some(path) = path { @@ -293,6 +314,7 @@ impl LogsState { self.selected_path = None; self.viewer_lines.clear(); self.viewer_scroll = 0; + self.selection.clear(); } else if let Some(sel) = self.list_state.selected { self.list_state.selected = Some(sel.min(display_count.saturating_sub(1))); self.load_selected_content(); @@ -304,8 +326,22 @@ impl LogsState { pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool { let shift = key_event.modifiers.contains(KeyModifiers::SHIFT); + if state.filter_open { + if handle_level_filter_key( + key_event, + &mut state.filter_open, + &mut state.filter_selected, + &mut state.level_filters, + ) { + state.selection.clear(); + state.viewer_scroll = 0; + } + return true; + } + if state.viewer_focused { if state.viewer_search.active { + state.selection.clear(); match key_event.code { KeyCode::Enter => { state.viewer_search.confirm(); @@ -329,11 +365,18 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool { } if key_event.code == KeyCode::Char('/') { + state.selection.clear(); state.viewer_search.activate(); state.viewer_scroll = 0; return true; } + if key_event.code == KeyCode::Char('f') { + state.filter_open = true; + state.filter_selected = 0; + return true; + } + match key_event.code { KeyCode::Char('j') | KeyCode::Down => { if state.viewer_scroll < state.viewer_max_scroll { @@ -349,22 +392,28 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool { ScrollbarState::new(state.viewer_max_scroll).position(state.viewer_scroll); true } - KeyCode::Char('G') => { + KeyCode::Char('G') | KeyCode::End => { state.viewer_scroll = state.viewer_max_scroll; state.viewer_scrollbar_state = ScrollbarState::new(state.viewer_max_scroll).position(state.viewer_scroll); true } - KeyCode::Char('g') => { + KeyCode::Char('g') | KeyCode::Home => { state.viewer_scroll = 0; state.viewer_scrollbar_state = ScrollbarState::new(state.viewer_max_scroll).position(state.viewer_scroll); true } KeyCode::Esc => { + state.selection.clear(); state.viewer_focused = false; true } + KeyCode::Char('y') => { + state.selection.finish(); + yank_viewer_selection(state); + true + } KeyCode::Char('H') | KeyCode::Left if shift => { state.viewer_focused = false; true @@ -373,6 +422,7 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool { } } else { if state.search.active { + state.selection.clear(); match key_event.code { KeyCode::Enter => { state.search.confirm(); @@ -404,12 +454,19 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool { } if key_event.code == KeyCode::Char('/') { + state.selection.clear(); state.search.activate(); state.list_state.selected = Some(0); state.update_scrollbar(); return true; } + if key_event.code == KeyCode::Char('f') { + state.filter_open = true; + state.filter_selected = 0; + return true; + } + let display_count = state.display_count(); match key_event.code { KeyCode::Char('j') | KeyCode::Down => { @@ -429,6 +486,21 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool { state.update_scrollbar(); true } + KeyCode::Enter if shift => { + if let Some(dir) = state + .file_index_for_selected() + .and_then(|index| state.entries.get(index)) + .and_then(|entry| entry.path.parent()) + && let Err(error) = open::that_detached(dir) + { + tracing::error!("Failed to open directory: {error}"); + crate::feedback::errors::push_message( + tracing::Level::ERROR, + format!("Could not open {}: {error}", dir.display()), + ); + } + true + } KeyCode::Enter => { state.viewer_focused = true; true @@ -437,6 +509,15 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool { state.viewer_focused = true; true } + KeyCode::Esc if state.selection.range.is_some() => { + state.selection.clear(); + true + } + KeyCode::Char('y') => { + state.selection.finish(); + yank_viewer_selection(state); + true + } _ => false, } } @@ -445,6 +526,7 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool { pub fn render(frame: &mut Frame, area: Rect, state: &mut LogsState, is_focused: bool) { let theme = THEME.as_ref(); if state.loading { + state.viewer_area = Rect::default(); frame.render_widget( Paragraph::new("Loading logs...").style(Style::default().fg(theme.text_dim())), area, @@ -452,10 +534,10 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut LogsState, is_focused: return; } - let has_live = state.has_live(); let display_count = state.display_count(); if display_count == 0 { + state.viewer_area = Rect::default(); frame.render_widget( Paragraph::new("No logs yet.").style(Style::default().fg(theme.text_dim())), area, @@ -472,7 +554,7 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut LogsState, is_focused: Layout::horizontal([Constraint::Length(30), Constraint::Min(0)]).areas(area); render_list(frame, list_area, state, is_focused); - render_viewer(frame, viewer_area, state, is_focused, has_live); + render_viewer(frame, viewer_area, state); } fn render_list(frame: &mut Frame, area: Rect, state: &mut LogsState, is_focused: bool) { @@ -556,33 +638,141 @@ fn render_list(frame: &mut Frame, area: Rect, state: &mut LogsState, is_focused: height: inner.height.saturating_sub(2), }; frame.render_stateful_widget( - Scrollbar::default() - .orientation(ScrollbarOrientation::VerticalRight) - .begin_symbol(Some("\u{25b2}")) - .style( - Style::default() - .fg(theme.accent()) - .add_modifier(Modifier::BOLD), - ) - .thumb_symbol("\u{2551}") - .track_symbol(Some("")) - .end_symbol(Some("\u{25bc}")), + super::scrollbar(theme.accent()), scrollbar_area, &mut state.scrollbar_state, ); } -fn render_viewer( - frame: &mut Frame, - area: Rect, - state: &mut LogsState, - _is_focused: bool, - has_live: bool, -) { +fn render_viewer(frame: &mut Frame, area: Rect, state: &mut LogsState) { let theme = THEME.as_ref(); - let is_live = has_live && state.list_state.selected == Some(0); + state.viewer_area = area; + let is_live = state.is_live_selected(); - let all_lines: Vec = if is_live { + let lines = filtered_viewer_lines(state); + + let visible_height = area.height as usize; + // auto-scroll: if the user was already at the bottom, keep following + // new lines as they come in (like `tail -f` behavior) + let was_at_bottom = state.viewer_scroll >= state.viewer_max_scroll; + state.update_viewer_scrollbar(visible_height, lines.len()); + + if is_live && was_at_bottom && !state.viewer_search.active && state.selection.range.is_none() { + state.viewer_scroll = state.viewer_max_scroll; + state.viewer_scrollbar_state = + ScrollbarState::new(state.viewer_max_scroll).position(state.viewer_scroll); + } + + if lines.is_empty() { + return; + } + + let search = &state.viewer_search; + let styled_lines: Vec = lines + .iter() + .enumerate() + .skip(state.viewer_scroll) + .take(visible_height) + .map(|(index, line)| { + let style = line + .level + .map(log_level_style) + .unwrap_or_else(|| line_level_style(&line.text)); + state + .selection + .highlight_line(index, &line.text, search, style) + }) + .collect(); + + frame.render_widget(Paragraph::new(styled_lines), area); + + let scrollbar_area = Rect { + x: area.x + area.width.saturating_sub(0), + y: area.y + 1, + width: 1, + height: area.height.saturating_sub(2), + }; + frame.render_stateful_widget( + super::scrollbar(theme.accent()), + scrollbar_area, + &mut state.viewer_scrollbar_state, + ); +} + +pub(crate) const LOG_LEVEL_FILTER_ORDER: [LogLevel; 5] = [ + LogLevel::Error, + LogLevel::Warn, + LogLevel::Info, + LogLevel::Debug, + LogLevel::Trace, +]; + +pub(crate) fn level_label(level: LogLevel) -> &'static str { + match level { + LogLevel::Error => "Error", + LogLevel::Warn => "Warn", + LogLevel::Info => "Info", + LogLevel::Debug => "Debug", + LogLevel::Trace => "Trace", + } +} + +pub(crate) fn level_of_line(line: &str) -> Option { + let upper = line.to_uppercase(); + if upper.contains("ERROR") || upper.contains("FATAL") || upper.contains("[STDERR]") { + Some(LogLevel::Error) + } else if upper.contains("WARN") { + Some(LogLevel::Warn) + } else if upper.contains("DEBUG") { + Some(LogLevel::Debug) + } else if upper.contains("TRACE") { + Some(LogLevel::Trace) + } else if upper.contains("INFO") { + Some(LogLevel::Info) + } else { + None + } +} + +pub(crate) fn level_matches(filters: &LevelFilters, level: Option) -> bool { + let mode = LOG_LEVEL_FILTER_ORDER + .iter() + .position(|value| Some(*value) == level) + .and_then(|index| filters[index]); + mode != Some(CategoryFilter::Exclude) + && (!filters.contains(&Some(CategoryFilter::Include)) + || mode == Some(CategoryFilter::Include)) +} + +pub(crate) fn handle_level_filter_key( + key: &KeyEvent, + open: &mut bool, + selected: &mut usize, + filters: &mut LevelFilters, +) -> bool { + match key.code { + KeyCode::Esc | KeyCode::Char('f') => *open = false, + KeyCode::Char('j') | KeyCode::Down => *selected = (*selected + 1).min(filters.len() - 1), + KeyCode::Char('k') | KeyCode::Up => *selected = selected.saturating_sub(1), + KeyCode::Enter | KeyCode::Char(' ') => { + filters[*selected] = match filters[*selected] { + None => Some(CategoryFilter::Include), + Some(CategoryFilter::Include) => Some(CategoryFilter::Exclude), + Some(CategoryFilter::Exclude) => None, + }; + return true; + } + KeyCode::Char('r') => { + *filters = [None; 5]; + return true; + } + _ => {} + } + false +} + +fn filtered_viewer_lines(state: &LogsState) -> Vec { + let all_lines: Vec = if state.is_live_selected() { let name = state.loaded_for.as_deref().unwrap_or(""); crate::instance::logs::live::get_entries(name) .into_iter() @@ -599,66 +789,145 @@ fn render_viewer( .map(|text| ViewerLine { text, level: None }) .collect() }; - - let lines: Vec<&ViewerLine> = all_lines - .iter() - .filter(|l| state.viewer_search.matches(&l.text)) - .collect(); - - let visible_height = area.height as usize; - // auto-scroll: if the user was already at the bottom, keep following - // new lines as they come in (like `tail -f` behavior) - let was_at_bottom = state.viewer_scroll >= state.viewer_max_scroll.saturating_sub(1); - state.update_viewer_scrollbar(visible_height, lines.len()); - - if is_live && was_at_bottom && !state.viewer_search.active { - state.viewer_scroll = state.viewer_max_scroll; - state.viewer_scrollbar_state = - ScrollbarState::new(state.viewer_max_scroll).position(state.viewer_scroll); - } - - if lines.is_empty() { - return; - } - - let search = &state.viewer_search; - let styled_lines: Vec = lines - .iter() - .skip(state.viewer_scroll) - .take(visible_height) - .map(|line| { - search.highlight_line( - &line.text, - line.level - .map(log_level_style) - .unwrap_or_else(|| line_level_style(&line.text)), + all_lines + .into_iter() + .filter(|line| state.viewer_search.matches(&line.text)) + .filter(|line| { + level_matches( + &state.level_filters, + line.level.or_else(|| level_of_line(&line.text)), ) }) - .collect(); + .collect() +} - frame.render_widget(Paragraph::new(styled_lines), area); +pub(crate) fn handle_selection_mouse( + event: crossterm::event::MouseEvent, + state: &mut LogsState, +) -> bool { + let lines = filtered_viewer_lines(state); + let handled = + state + .selection + .handle_mouse(event, state.viewer_area, state.viewer_scroll, &lines); + if handled { + state.viewer_focused = true; + } + handled +} - let scrollbar_area = Rect { - x: area.x + area.width.saturating_sub(0), - y: area.y + 1, - width: 1, - height: area.height.saturating_sub(2), +pub(crate) fn yank_viewer_selection(state: &mut LogsState) { + let lines = filtered_viewer_lines(state); + yank_selection(&state.selection, &lines); +} + +pub(crate) fn yank_selection(selection: &LogSelection, lines: &[impl AsRef]) { + let Some(text) = selection.text(lines) else { + return; }; - frame.render_stateful_widget( - Scrollbar::default() - .orientation(ScrollbarOrientation::VerticalRight) - .begin_symbol(Some("\u{25b2}")) - .style( - Style::default() - .fg(theme.accent()) - .add_modifier(Modifier::BOLD), - ) - .thumb_symbol("\u{2551}") - .track_symbol(Some("")) - .end_symbol(Some("\u{25bc}")), - scrollbar_area, - &mut state.viewer_scrollbar_state, + match copy_to_clipboard(&text) { + Some((count, false)) => crate::feedback::errors::push_message( + tracing::Level::INFO, + format!("Yanked {count} line(s) to the clipboard"), + ), + Some((count, true)) => crate::feedback::errors::push_message( + tracing::Level::WARN, + format!("Yanked the first {count} lines; the selection was truncated"), + ), + None => {} + } +} + +/// Copies text through the terminal (OSC 52) so it works over SSH too. +/// Returns the copied line count and whether the payload was truncated. +pub(crate) fn copy_to_clipboard(text: &str) -> Option<(usize, bool)> { + use base64::Engine; + const MAX_LINES: usize = 2000; + let lines: Vec<&str> = text.split_inclusive('\n').take(MAX_LINES + 1).collect(); + if lines.is_empty() { + return None; + } + let truncated = lines.len() > MAX_LINES; + let count = lines.len().min(MAX_LINES); + let encoded = base64::engine::general_purpose::STANDARD.encode(lines[..count].concat()); + let sequence = format!("\x1b]52;c;{encoded}\x07"); + use std::io::Write; + if let Err(error) = std::io::stdout() + .write_all(sequence.as_bytes()) + .and_then(|_| std::io::stdout().flush()) + { + crate::feedback::errors::push_message( + tracing::Level::ERROR, + format!("Could not yank to the terminal clipboard: {error}"), + ); + return None; + } + Some((count, truncated)) +} + +pub(crate) fn render_level_filter(frame: &mut Frame, selected: usize, filters: &LevelFilters) { + use ratatui::layout::Constraint; + use ratatui::widgets::Widget; + let theme = THEME.as_ref(); + let keybinds = super::popups::keybind_line(&[("r", " reset"), ("Esc", " close")]); + let popup = frame.area().centered( + Constraint::Length((keybinds.width() as u16 + 2).max(26)), + Constraint::Length(7), ); + let rows = LOG_LEVEL_FILTER_ORDER + .iter() + .enumerate() + .map(|(index, level)| { + let mode = filters[index]; + let (marker, color) = match mode { + Some(CategoryFilter::Include) => ("+ ", theme.success()), + Some(CategoryFilter::Exclude) => ("− ", theme.error()), + None => ("· ", theme.text_dim()), + }; + Line::from(vec![ + Span::styled( + if index == selected { "▌ " } else { " " }, + Style::default().fg(theme.accent()), + ), + Span::styled( + marker, + Style::default().fg(color).add_modifier(Modifier::BOLD), + ), + Span::styled( + level_label(*level), + Style::default().fg(if mode.is_some() { + theme.text() + } else { + theme.text_dim() + }), + ), + ]) + .style(Style::default().bg(if index == selected { + theme.stripe() + } else { + theme.surface() + })) + }) + .collect::>(); + let frame_widget = super::popups::base::PopupFrame { + title: Line::from(" Log levels ").style( + Style::default() + .fg(theme.text()) + .add_modifier(Modifier::BOLD), + ), + border_color: theme.accent(), + bg: Some(theme.surface()), + keybinds: Some(keybinds), + search_line: None, + content: Box::new(move |area, buffer| { + for (line, row_area) in rows.iter().zip(area.rows()) { + Paragraph::new(line.clone()) + .style(line.style) + .render(row_area, buffer); + } + }), + }; + frame.render_widget(frame_widget, popup); } struct ViewerLine { @@ -666,30 +935,27 @@ struct ViewerLine { level: Option, } +impl AsRef for ViewerLine { + fn as_ref(&self) -> &str { + &self.text + } +} + fn log_level_style(level: LogLevel) -> Style { let theme = THEME.as_ref(); match level { LogLevel::Error => Style::default().fg(theme.error()), LogLevel::Warn => Style::default().fg(theme.warning()), - LogLevel::Debug | LogLevel::Trace => Style::default().fg(theme.text_dim()), + LogLevel::Debug => Style::default().fg(theme.text_dim()), + LogLevel::Trace => Style::default().fg(theme.border()), LogLevel::Info => Style::default().fg(theme.text()), } } -// color-code log lines by severity so errors actually stand out -// instead of drowning in a wall of white text -fn line_level_style(line: &str) -> Style { - let theme = THEME.as_ref(); - let upper = line.to_uppercase(); - if upper.contains("ERROR") || upper.contains("FATAL") || upper.contains("[STDERR]") { - Style::default().fg(theme.error()) - } else if upper.contains("WARN") { - Style::default().fg(theme.warning()) - } else if upper.contains("DEBUG") || upper.contains("TRACE") { - Style::default().fg(theme.text_dim()) - } else { - Style::default().fg(theme.text()) - } +pub(crate) fn line_level_style(line: &str) -> Style { + level_of_line(line) + .map(log_level_style) + .unwrap_or_else(|| Style::default().fg(THEME.as_ref().text())) } #[cfg(test)] diff --git a/src/tui/widgets/markdown.rs b/src/tui/widgets/markdown.rs index 001c08a..0237049 100644 --- a/src/tui/widgets/markdown.rs +++ b/src/tui/widgets/markdown.rs @@ -335,6 +335,12 @@ fn normalize_html(source: &str) -> NormalizedDocument { } fn convert_html_fragment(html: &str) -> Result { + // A closing emphasis delimiter after punctuation needs a word boundary. + static EMPHASIS_BOUNDARY: std::sync::LazyLock = std::sync::LazyLock::new(|| { + regex::Regex::new(r"(?i)()([\p{L}\p{N}])") + .expect("valid emphasis boundary regex") + }); + let html = EMPHASIS_BOUNDARY.replace_all(html, "$1 $2"); let image_alignments = Arc::new(Mutex::new(HashMap::new())); let visitor: VisitorHandle = Arc::new(Mutex::new(ImageAlignmentVisitor { centered: Vec::new(), @@ -617,17 +623,13 @@ fn external_markdown_text(source: &str, width: u16) -> (Text<'static>, Vec Line<'_> { let theme = THEME.as_ref(); if !highlight || title.is_empty() { @@ -49,6 +47,16 @@ pub(crate) fn status_badge(label: impl Into, color: Color) -> Span<'stat Span::styled(format!(" {} ", label.into()), status_badge_style(color)) } +pub(crate) fn scrollbar(color: Color) -> Scrollbar<'static> { + Scrollbar::default() + .orientation(ScrollbarOrientation::VerticalRight) + .begin_symbol(Some("\u{25b2}")) + .style(Style::default().fg(color).add_modifier(Modifier::BOLD)) + .thumb_symbol("\u{2551}") + .track_symbol(Some("")) + .end_symbol(Some("\u{25bc}")) +} + pub trait WidgetKey { fn handle_key(&mut self, key_event: &KeyEvent); } diff --git a/src/tui/widgets/popups/base.rs b/src/tui/widgets/popups/base.rs index d008657..a54771c 100644 --- a/src/tui/widgets/popups/base.rs +++ b/src/tui/widgets/popups/base.rs @@ -1,10 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// base frame that all popups render inside. handles the border, title bar, -// keybind footer, and optional search indicator. content is injected via closure -// so each popup type only worries about its inner area. - use ratatui::{ buffer::{Buffer, CellDiffOption}, layout::{Alignment, Rect}, @@ -40,7 +36,6 @@ impl<'a> Widget for PopupFrame<'a> { }) .collect::>(); - // clear first so the popup doesn't layer on top of whatever was underneath Clear.render(area, buf); if let Some(bg) = self.bg { diff --git a/src/tui/widgets/popups/confirm.rs b/src/tui/widgets/popups/confirm.rs index 2ad0189..36906b5 100644 --- a/src/tui/widgets/popups/confirm.rs +++ b/src/tui/widgets/popups/confirm.rs @@ -1,9 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// "are you sure?" popup for destructive actions. uses global state so the -// confirmation target persists across render frames. - use std::sync::LazyLock; use std::sync::Mutex; diff --git a/src/tui/widgets/popups/error.rs b/src/tui/widgets/popups/error.rs index ee8cb08..7af910a 100644 --- a/src/tui/widgets/popups/error.rs +++ b/src/tui/widgets/popups/error.rs @@ -1,9 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// toast-style error/warning popup that auto-dismisses after a timeout. -// stacks in the top-right corner; border color changes based on severity. - use ratatui::{ buffer::Buffer, layout::Rect, @@ -66,8 +63,6 @@ impl Widget for ErrorPopup { } } -// returns None when the toast has lived past its expiry, which is -// what triggers removal from the render loop pub fn popup_area(frame_area: Rect, message: &str, base_y: u16, elapsed_ms: u128) -> Option { use super::word_wrap_size; diff --git a/src/tui/widgets/popups/global_settings.rs b/src/tui/widgets/popups/global_settings.rs index 9593c62..4a14c86 100644 --- a/src/tui/widgets/popups/global_settings.rs +++ b/src/tui/widgets/popups/global_settings.rs @@ -1,8 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// modal editor for launcher-wide settings. - use crossterm::event::{KeyCode, KeyEvent}; use ratatui::{ Frame, @@ -16,7 +14,10 @@ use ratatui_textarea::TextArea; use crate::{ config::{ Config, - settings::{ContentProvider, DEFAULT_RESOLUTION, ImageProtocol, ShortcutHintScope}, + settings::{ + ContentProvider, DEFAULT_RESOLUTION, ImageProtocol, ShortcutHintScope, + format_tag_values, parse_tag_values, + }, theme::{BORDER_STYLE, BorderStyle, THEME, ThemeConfig}, }, instance::models::{memory_kib, normalize_memory_value, parse_resolution}, @@ -24,10 +25,10 @@ use crate::{ DisplayResolution, JavaChoice, JavaPicker, ResolutionChoice, ResolutionPickerAction, SettingsPicker, SettingsPickerAction, SettingsPickerOption, adjust_memory, auto_label, default_label, default_resolution, display_resolutions, environment_labels, - format_tag_values, handle_resolution_picker_key, handle_text_area_input, - is_default_resolution, parse_environment, parse_tag_values, render_memory_gauge, - render_settings_picker, resolution_choices, resolution_items, settings_text_area, - tagged_row_count, tagged_value_lines, toggle_window_mode, window_mode_title, + handle_resolution_picker_key, handle_text_area_input, is_default_resolution, + parse_environment, render_memory_gauge, render_settings_picker, resolution_choices, + resolution_items, settings_text_area, tagged_row_count, tagged_value_lines, + toggle_window_mode, window_mode_title, }, tui::widgets::status_badge, }; @@ -98,8 +99,13 @@ impl State { let java_cache = crate::storage::MetadataPaths::new(runtime_config.paths.resolve_meta_dir()) .java_installations(); - let mut java_picker = - JavaPicker::with_cache(crate::instance::java::detect_java_path(), Some(java_cache)); + let cwd = std::env::current_dir().unwrap_or_default(); + let environment = crate::instance::java::merge_environment( + &config.defaults.environment, + &Default::default(), + ); + let detected = crate::instance::java::resolve_java_path_in(None, &cwd, &environment); + let mut java_picker = JavaPicker::with_cache(detected, Some(java_cache), cwd, environment); java_picker.set_current(config.paths.java_path.as_deref()); Self { config, @@ -195,26 +201,26 @@ impl State { state.editing = Some(settings_text_area(editor.lines().to_vec())); }; match self.selected { - 3 | 4 if normalize_memory_value(value).is_none() => invalid( - self, - "Use a positive memory value ending in K, M, or G.".to_owned(), - ), - 3 => { - let value = normalize_memory_value(value).unwrap(); - self.config.defaults.memory_min = value.clone(); - if memory_kib(&value) > memory_kib(&self.config.defaults.memory_max) { - self.config.defaults.memory_max = value; + 3 | 4 => match normalize_memory_value(value) { + Some(value) => { + if self.selected == 3 { + self.config.defaults.memory_min = value.clone(); + if memory_kib(&value) > memory_kib(&self.config.defaults.memory_max) { + self.config.defaults.memory_max = value; + } + } else { + self.config.defaults.memory_max = value.clone(); + if memory_kib(&value) < memory_kib(&self.config.defaults.memory_min) { + self.config.defaults.memory_min = value; + } + } + self.save_pending = true; } - self.save_pending = true; - } - 4 => { - let value = normalize_memory_value(value).unwrap(); - self.config.defaults.memory_max = value.clone(); - if memory_kib(&value) < memory_kib(&self.config.defaults.memory_min) { - self.config.defaults.memory_min = value; - } - self.save_pending = true; - } + None => invalid( + self, + "Use a positive memory value ending in K, M, or G.".to_owned(), + ), + }, 5 => { self.config.paths.java_path = (!value.is_empty()).then(|| value.to_owned()); self.save_pending = true; @@ -240,6 +246,7 @@ impl State { 9 => match parse_environment(value) { Ok(environment) => { self.config.defaults.environment = environment; + self.refresh_java_context(); self.save_pending = true; } Err(error) => invalid(self, error), @@ -565,7 +572,8 @@ impl State { .iter() .position(|mode| *mode == current); let index = match (index, forward) { - (Some(2), true) | (Some(0), false) => 0, + (Some(2), true) => 0, + (Some(0), false) => 2, (Some(index), true) => index + 1, (Some(index), false) => index - 1, (None, true) => 0, @@ -581,6 +589,7 @@ impl State { } fn open_java_picker(&mut self) { + self.refresh_java_context(); self.java_picker .open(self.config.paths.java_path.as_deref()); self.java_picker.initialize(); @@ -588,6 +597,7 @@ impl State { } fn toggle_auto_java(&mut self) -> Action { + self.refresh_java_context(); let Some(current) = self.config.paths.java_path.as_deref() else { self.config.paths.java_path = Some(self.java_picker.detected_path().to_owned()); self.save_pending = true; @@ -619,6 +629,17 @@ impl State { pub fn invalidate_java_cache(&mut self) { self.java_picker.invalidate_cache(); + self.refresh_java_context(); + } + + fn refresh_java_context(&mut self) { + let cwd = std::env::current_dir().unwrap_or_default(); + let environment = crate::instance::java::merge_environment( + &self.config.defaults.environment, + &Default::default(), + ); + let detected = crate::instance::java::resolve_java_path_in(None, &cwd, &environment); + self.java_picker.set_context(detected, cwd, environment); } fn handle_java_picker_key(&mut self, key: &KeyEvent) { @@ -689,6 +710,13 @@ impl State { self.error = None; } + pub(in crate::tui) fn text_input_active(&self) -> bool { + self.choice_picker.is_none() + && !self.java_picker_open + && !self.theme_picker + && self.editing.is_some() + } + pub fn handle_key(&mut self, key: &KeyEvent) -> Action { let action = self.handle_key_inner(key); if !matches!(action, Action::None) { @@ -1320,6 +1348,88 @@ mod tests { use super::*; use crate::instance::models::WindowMode; + #[test] + fn dispatch_repeats_launcher_text_but_not_setting_toggles() { + use crate::tui::{app::FocusedArea, tests::harness::UiHarness}; + use crossterm::event::{KeyEventKind, KeyModifiers}; + + let mut ui = UiHarness::new(); + let mut state = State::new(); + state.selected = 6; + let mode = state.config.defaults.window_mode; + ui.app.global_settings = Some(state); + ui.app.focused = FocusedArea::GlobalSettings; + for code in [KeyCode::Right, KeyCode::Char('l'), KeyCode::Enter] { + assert!(!ui.key_event(KeyEvent::new_with_kind( + code, + KeyModifiers::NONE, + KeyEventKind::Repeat + ))); + } + assert_eq!( + ui.app + .global_settings + .as_ref() + .unwrap() + .config + .defaults + .window_mode, + mode + ); + + ui.app.global_settings.as_mut().unwrap().editing = + Some(settings_text_area(vec![String::new()])); + ui.key(KeyCode::Char('l')); + assert!(ui.key_event(KeyEvent::new_with_kind( + KeyCode::Char('l'), + KeyModifiers::NONE, + KeyEventKind::Repeat + ))); + assert!(!ui.key_event(KeyEvent::new_with_kind( + KeyCode::Char('l'), + KeyModifiers::NONE, + KeyEventKind::Release + ))); + assert_eq!( + ui.app + .global_settings + .as_ref() + .unwrap() + .editing + .as_ref() + .unwrap() + .lines(), + &["ll"] + ); + assert!(ui.key_event(KeyEvent::new_with_kind( + KeyCode::Left, + KeyModifiers::NONE, + KeyEventKind::Repeat + ))); + assert!(ui.key_event(KeyEvent::new_with_kind( + KeyCode::Delete, + KeyModifiers::NONE, + KeyEventKind::Repeat + ))); + assert_eq!( + ui.app + .global_settings + .as_ref() + .unwrap() + .editing + .as_ref() + .unwrap() + .lines(), + &["l"] + ); + assert!(!ui.key_event(KeyEvent::new_with_kind( + KeyCode::Enter, + KeyModifiers::NONE, + KeyEventKind::Repeat + ))); + assert!(ui.app.global_settings.as_ref().unwrap().editing.is_some()); + } + #[test] fn launcher_memory_uses_slider_and_java_uses_picker() { let mut state = State::new(); @@ -1552,6 +1662,10 @@ mod tests { state.selected = 2; state.handle_key(&KeyEvent::from(KeyCode::Down)); assert_eq!(state.selected, 24); + state.cycle_shortcut_hints(false); + assert_eq!(shortcut_hint_mode(&state.config.ui), "Hidden"); + state.cycle_shortcut_hints(true); + assert_eq!(shortcut_hint_mode(&state.config.ui), "All"); assert!(matches!( state.handle_key(&KeyEvent::from(KeyCode::Right)), diff --git a/src/tui/widgets/popups/import_modpack/mod.rs b/src/tui/widgets/popups/import_modpack/mod.rs index 4bedbe9..17f5fea 100644 --- a/src/tui/widgets/popups/import_modpack/mod.rs +++ b/src/tui/widgets/popups/import_modpack/mod.rs @@ -7,6 +7,7 @@ mod state; #[cfg(test)] pub use render::render; pub use render::{popup_rect, render_with_picker}; +pub(in crate::tui) use state::text_input_active; pub use state::{ ImportResult, ImportStep, ImportWizardState, discovery_activity, drain, handle_discovery_click, handle_key, has_version_popup, open, take_result, diff --git a/src/tui/widgets/popups/import_modpack/render.rs b/src/tui/widgets/popups/import_modpack/render.rs index ba6cb43..f9e40b3 100644 --- a/src/tui/widgets/popups/import_modpack/render.rs +++ b/src/tui/widgets/popups/import_modpack/render.rs @@ -1,9 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// rendering for the modpack import wizard. same pattern as new_instance: -// snapshot the state, pick the right step renderer, done. - use super::super::LoadState; use super::super::base::PopupFrame; use super::state::{DISCOVERY_STATE, IMPORT_STATE, ImportStep, ImportWizardState}; diff --git a/src/tui/widgets/popups/import_modpack/state.rs b/src/tui/widgets/popups/import_modpack/state.rs index 197a1b1..921a1c3 100644 --- a/src/tui/widgets/popups/import_modpack/state.rs +++ b/src/tui/widgets/popups/import_modpack/state.rs @@ -1,10 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// state machine for the modpack import wizard. -// browses modpacks from configured providers and keeps the archive import flow -// for modrinth URLs, project slugs, version IDs, and local pack archives. - use super::super::LoadState; use crate::instance::import::{ImportInput, ImportSummary, parse_import_input}; use crate::net::modrinth::{self, VersionInfo}; @@ -124,6 +120,23 @@ pub fn has_version_popup() -> bool { .is_ok_and(|state| state.version_popup.is_some()) } +pub(in crate::tui) fn text_input_active() -> bool { + let Ok(state) = IMPORT_STATE.lock() else { + return false; + }; + match state.step { + ImportStep::Input => true, + ImportStep::Version => state.version_search.active, + ImportStep::Discover => { + drop(state); + DISCOVERY_STATE + .lock() + .is_ok_and(|discovery| discovery.text_input_active()) + } + _ => false, + } +} + pub fn discovery_activity() -> Option<&'static str> { let wizard = IMPORT_STATE.lock().ok()?; let step = wizard.step.clone(); @@ -387,7 +400,6 @@ fn handle_confirm_key( } } -// pushes an error toast and rewinds the wizard to a previous step fn update_current_request( state_arc: &Arc>, request_id: u64, @@ -419,8 +431,6 @@ fn begin_import_request(state: &mut ImportWizardState) -> u64 { request_id } -// parses user input to figure out what they gave us, then dispatches -// to the appropriate resolve path (slug lookup, direct version, or local file) fn start_resolve(state: &mut ImportWizardState) { let input_text = state.input.clone(); state.step = ImportStep::Fetching; @@ -559,8 +569,6 @@ fn resolve_local_file(state_arc: Arc>, request_id: u64, } } -// user picked a version from the list. download the .mrpack, -// build a summary, and move to confirm. fn start_version_download(state: &mut ImportWizardState) { let version = match selected_version(state) { Some(v) => v.clone(), diff --git a/src/tui/widgets/popups/instance_settings.rs b/src/tui/widgets/popups/instance_settings.rs index 48e0905..f18e476 100644 --- a/src/tui/widgets/popups/instance_settings.rs +++ b/src/tui/widgets/popups/instance_settings.rs @@ -1,8 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// modal editor for settings belonging to the selected Minecraft instance. - use crossterm::event::{KeyCode, KeyEvent}; use ratatui::{ Frame, @@ -18,8 +16,10 @@ use crate::{ auth::{Account, AccountType}, config::{ SETTINGS, + settings::{format_tag_values, parse_tag_values}, theme::{BORDER_STYLE, THEME}, }, + instance::glfw::bundled_glfw_version, instance::loader::GameVersion, instance::models::{ InstanceConfig, LaunchCommand, ModLoader, memory_kib, normalize_memory_value, @@ -32,12 +32,12 @@ use crate::{ DisplayResolution, GlfwChoice, GlfwPicker, JavaChoice, JavaPicker, ResolutionChoice, ResolutionPickerAction, SettingsPicker, SettingsPickerAction, SettingsPickerBadge, SettingsPickerOption, adjust_memory, auto_label, - bundled_glfw_version, bundled_label as bundled_badge, default_label, - default_resolution, display_resolutions, environment_labels, format_tag_values, - handle_resolution_picker_key, handle_text_area_input, is_default_resolution, - parse_environment, parse_tag_values, render_memory_gauge, render_settings_picker, - resolution_choices, resolution_items, settings_text_area, tagged_row_count, - tagged_value_lines, toggle_window_mode, window_mode_title, + bundled_label as bundled_badge, default_label, default_resolution, + display_resolutions, environment_labels, handle_resolution_picker_key, + handle_text_area_input, is_default_resolution, parse_environment, + render_memory_gauge, render_settings_picker, resolution_choices, resolution_items, + settings_text_area, tagged_row_count, tagged_value_lines, toggle_window_mode, + window_mode_title, }, }, search::SearchState, @@ -94,6 +94,7 @@ pub struct State { account_picker: SettingsPicker, accounts: Vec, meta_dir: std::path::PathBuf, + minecraft_dir: std::path::PathBuf, display_resolutions: Vec, runtime_update_pending: bool, save_retry_pending: bool, @@ -113,9 +114,16 @@ pub enum Action { impl State { pub fn new(instance: &InstanceConfig, meta_dir: &std::path::Path) -> Self { + let minecraft_dir = crate::config::SETTINGS + .read() + .paths + .resolve_instances_dir() + .join(&instance.name) + .join(crate::storage::MINECRAFT_DIR_NAME); Self::with_accounts( instance, meta_dir, + &minecraft_dir, crate::auth::AccountStore::load().accounts, ) } @@ -123,16 +131,24 @@ impl State { pub fn with_accounts( instance: &InstanceConfig, meta_dir: &std::path::Path, + minecraft_dir: &std::path::Path, accounts: Vec, ) -> Self { - let auto_java_path = SETTINGS - .read() - .paths - .effective_java_path() - .map(str::to_owned) - .unwrap_or_else(crate::instance::java::detect_java_path); + let settings = SETTINGS.read(); + let cwd = minecraft_dir.to_owned(); + let environment = crate::instance::java::merge_environment( + &settings.defaults.environment, + &instance.environment, + ); + let auto_java_path = crate::instance::java::resolve_java_path_in( + settings.paths.effective_java_path(), + &cwd, + &environment, + ); + drop(settings); let java_cache = crate::storage::MetadataPaths::new(meta_dir).java_installations(); - let mut java_picker = JavaPicker::with_cache(auto_java_path, Some(java_cache)); + let mut java_picker = + JavaPicker::with_cache(auto_java_path, Some(java_cache), cwd, environment); java_picker.set_current(instance.java_path.as_deref()); let desktop = crate::instance::desktop::exists(&instance.name); Self { @@ -160,6 +176,7 @@ impl State { account_picker: SettingsPicker::default(), accounts, meta_dir: meta_dir.to_path_buf(), + minecraft_dir: minecraft_dir.to_owned(), display_resolutions: display_resolutions(), runtime_update_pending: false, save_retry_pending: false, @@ -407,6 +424,7 @@ impl State { .unwrap_or(0); } ChoicePicker::Java => { + self.refresh_java_context(); self.java_picker.open(self.draft.java_path.as_deref()); self.java_picker.initialize(); } @@ -772,6 +790,7 @@ impl State { } fn toggle_auto_java(&mut self) -> Action { + self.refresh_java_context(); let Some(current) = self.draft.java_path.as_deref() else { self.draft.java_path = Some(self.java_picker.detected_path().to_owned()); self.error = None; @@ -939,7 +958,10 @@ impl State { Err(error) => invalid(self, error), }, 7 => match parse_environment(value) { - Ok(environment) => self.draft.environment = environment, + Ok(environment) => { + self.draft.environment = environment; + self.refresh_java_context(); + } Err(error) => invalid(self, error), }, 9 if value.is_empty() => { @@ -966,6 +988,16 @@ impl State { } } + pub(in crate::tui) fn text_input_active(&self) -> bool { + !self.runtime_update_pending + && self.choice_picker.is_none() + && if self.picker.is_some() { + self.picker_search.active + } else { + self.editing.is_some() + } + } + pub fn handle_key(&mut self, key: &KeyEvent) -> Action { if self.runtime_update_pending { return if key.code == KeyCode::Esc { @@ -1108,6 +1140,23 @@ impl State { pub fn invalidate_java_cache(&mut self) { self.java_picker.invalidate_cache(); + self.refresh_java_context(); + } + + fn refresh_java_context(&mut self) { + let settings = SETTINGS.read(); + let environment = crate::instance::java::merge_environment( + &settings.defaults.environment, + &self.draft.environment, + ); + let detected = crate::instance::java::resolve_java_path_in( + settings.paths.effective_java_path(), + &self.minecraft_dir, + &environment, + ); + drop(settings); + self.java_picker + .set_context(detected, self.minecraft_dir.clone(), environment); } pub fn cancel_runtime_change(&mut self) -> Option<(Box, bool)> { @@ -1742,6 +1791,79 @@ mod tests { use crate::instance::WindowMode; use chrono::Utc; + #[test] + fn dispatch_repeats_picker_search_without_snapshot_toggle_or_selection() { + use crate::tui::{app::FocusedArea, tests::harness::UiHarness}; + use crossterm::event::{KeyEventKind, KeyModifiers}; + + let mut ui = UiHarness::new(); + ui.add_instance("Picker Search"); + let config = ui.app.instances_state.selected_instance().unwrap(); + let mut state = State::with_accounts( + config, + &ui.app.instance_manager.meta_dir, + &ui.instance_path(&config.name).join("minecraft"), + Vec::new(), + ); + state.picker = Some(VersionPicker::Game); + state.game_versions = Arc::new(Mutex::new(LoadState::Loaded(vec![GameVersion { + id: "1.21.1".to_owned(), + stable: true, + }]))); + state.picker_search.activate(); + ui.app.instance_settings = Some(state); + ui.app.focused = FocusedArea::InstanceSettings; + assert!(ui.key_event(KeyEvent::new_with_kind( + KeyCode::Char('s'), + KeyModifiers::NONE, + KeyEventKind::Repeat + ))); + let state = ui.app.instance_settings.as_ref().unwrap(); + assert_eq!(state.picker_search.query, "s"); + assert!(!state.show_snapshots); + assert!(!ui.key_event(KeyEvent::new_with_kind( + KeyCode::Enter, + KeyModifiers::NONE, + KeyEventKind::Repeat + ))); + assert_eq!( + ui.app.instance_settings.as_ref().unwrap().picker, + Some(VersionPicker::Game) + ); + assert!(ui.key_event(KeyEvent::new_with_kind( + KeyCode::Backspace, + KeyModifiers::CONTROL, + KeyEventKind::Repeat + ))); + assert!( + ui.app + .instance_settings + .as_ref() + .unwrap() + .picker_search + .query + .is_empty() + ); + ui.key(KeyCode::Enter); + assert!( + !ui.app + .instance_settings + .as_ref() + .unwrap() + .picker_search + .active + ); + assert!(!ui.key_event(KeyEvent::new_with_kind( + KeyCode::Right, + KeyModifiers::NONE, + KeyEventKind::Repeat + ))); + assert_eq!( + ui.app.instance_settings.as_ref().unwrap().picker, + Some(VersionPicker::Game) + ); + } + fn instance() -> InstanceConfig { InstanceConfig { name: "test".to_owned(), @@ -2233,6 +2355,15 @@ mod tests { assert!(lines.len() > 1); assert_eq!(tagged_row_count(&state.draft.jvm_args, 48), lines.len()); assert!(lines.iter().any(|line| line.to_string().contains("second"))); + let values = vec![ + "界界界界界".to_owned(), + "abcdefghijklmn".to_owned(), + "e\u{301}".to_owned(), + ]; + let lines = tagged_field_lines(&state, 6, "JVM args", &values, "", 48); + assert_eq!(lines.len(), 2); + assert_eq!(tagged_row_count(&values, 48), lines.len()); + assert!(lines.iter().all(|line| line.width() <= 48)); } #[test] @@ -2298,7 +2429,12 @@ mod tests { cached_mc_token: None, cached_mc_token_expires_at: None, }]; - let mut state = State::with_accounts(&instance(), temp.path(), accounts); + let mut state = State::with_accounts( + &instance(), + temp.path(), + &temp.path().join("minecraft"), + accounts, + ); state.selected = 10; state.begin_edit(); assert_eq!(state.choice_index, 0); diff --git a/src/tui/widgets/popups/mod.rs b/src/tui/widgets/popups/mod.rs index 9cf6889..890d43a 100644 --- a/src/tui/widgets/popups/mod.rs +++ b/src/tui/widgets/popups/mod.rs @@ -1,9 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// shared utilities for popup widgets: layout helpers, word wrapping, keybind rendering. -// individual popup types live in their own submodules. - pub mod base; pub mod confirm; pub mod error; @@ -41,8 +38,6 @@ pub(crate) fn compare_game_versions(a: &str, b: &str) -> std::cmp::Ordering { a_parts.len().cmp(&b_parts.len()) } -// figures out the (width, height) a text block will need after word wrapping. -// used to size popups before rendering so they fit their content snugly. pub fn word_wrap_size(text: &str, max_inner_width: usize) -> (usize, usize) { if text.is_empty() || max_inner_width == 0 { return (0, 1); diff --git a/src/tui/widgets/popups/new_instance/mod.rs b/src/tui/widgets/popups/new_instance/mod.rs index 97f7535..e422e09 100644 --- a/src/tui/widgets/popups/new_instance/mod.rs +++ b/src/tui/widgets/popups/new_instance/mod.rs @@ -5,6 +5,7 @@ mod render; mod state; pub use render::{popup_rect, render}; +pub(in crate::tui) use state::text_input_active; pub use state::{WizardParams, WizardState, WizardStep, handle_key, take_result}; #[cfg(test)] diff --git a/src/tui/widgets/popups/new_instance/render.rs b/src/tui/widgets/popups/new_instance/render.rs index 2e50f21..f12f63a 100644 --- a/src/tui/widgets/popups/new_instance/render.rs +++ b/src/tui/widgets/popups/new_instance/render.rs @@ -1,9 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// rendering for the new instance wizard. each step gets its own render fn -// and the popup resizes itself based on which step is active. - use super::super::LoadState; use super::state::{ WIZARD_STATE, WizardState, WizardStep, clamp_loader_version_index, clamp_version_index, @@ -33,7 +30,6 @@ pub fn render(frame: &mut Frame, area: Rect, _focused: FocusedArea) { clamp_version_index(&mut state); } - // vanilla has no loader version, so skip straight to confirm if state.step == WizardStep::LoaderVersion { if state.selected_loader() == ModLoader::Vanilla { state.step = WizardStep::Confirm; @@ -141,7 +137,6 @@ fn step_keybinds(state: &WizardState) -> ratatui::text::Line<'static> { fn render_name_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) { let theme = THEME.as_ref(); let value = state.name_state.value(); - // \u{2588} is the full block char used as a fake blinking cursor let line = if value.is_empty() { Line::from(vec![ Span::styled("Instance name...", Style::default().fg(theme.text_dim())), @@ -183,7 +178,6 @@ fn render_version_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffe } LoadState::Loaded(_) => { let items: Vec = visible_versions(state) - .into_iter() .enumerate() .map(|(index, version)| { let suffix = if version.stable { diff --git a/src/tui/widgets/popups/new_instance/state.rs b/src/tui/widgets/popups/new_instance/state.rs index 7afe6aa..c2255dd 100644 --- a/src/tui/widgets/popups/new_instance/state.rs +++ b/src/tui/widgets/popups/new_instance/state.rs @@ -1,10 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// state machine and input handling for the new instance wizard. -// flow: Name -> Loader -> Version -> LoaderVersion -> Confirm -// version lists are fetched lazily from the network when you reach that step. - use crate::instance::{loader::GameVersion, models::ModLoader}; use crate::tui::widgets::instances; use crossterm::event::{KeyCode, KeyEvent}; @@ -16,7 +12,6 @@ use super::super::LoadState; pub(crate) static WIZARD_STATE: LazyLock>> = LazyLock::new(|| Arc::new(Mutex::new(WizardState::default()))); -// populated on confirm, consumed by the main event loop to actually create the instance pub(crate) static WIZARD_RESULT: LazyLock>>> = LazyLock::new(|| Arc::new(Mutex::new(None))); @@ -40,6 +35,7 @@ pub enum WizardStep { #[derive(Debug, Clone)] pub struct WizardState { + request_epoch: u64, pub step: WizardStep, pub name_state: TextState<'static>, pub versions: LoadState>, @@ -54,6 +50,7 @@ pub struct WizardState { impl Default for WizardState { fn default() -> Self { Self { + request_epoch: 0, step: WizardStep::Name, name_state: TextState::new().with_focus(FocusState::Focused), versions: LoadState::Idle, @@ -69,19 +66,13 @@ impl Default for WizardState { impl WizardState { pub fn reset(&mut self) { + let next_epoch = self.request_epoch.wrapping_add(1); *self = WizardState::default(); + self.request_epoch = next_epoch; } pub fn selected_version(&self) -> Option<&GameVersion> { - if let LoadState::Loaded(ref versions) = self.versions { - let visible: Vec<_> = versions - .iter() - .filter(|v| self.show_snapshots || v.stable) - .collect(); - visible.get(self.version_idx).copied() - } else { - None - } + visible_versions(self).nth(self.version_idx) } pub fn selected_loader(&self) -> ModLoader { @@ -125,6 +116,13 @@ pub fn take_result() -> Option { } } +pub(in crate::tui) fn text_input_active() -> bool { + WIZARD_STATE.lock().is_ok_and(|state| { + state.step == WizardStep::Name + || (state.step == WizardStep::Version && state.version_search.active) + }) +} + fn handle_name_key( state: &mut WizardState, key_event: &KeyEvent, @@ -163,7 +161,6 @@ fn handle_version_key( key_event: &KeyEvent, instances_state: &mut instances::State, ) { - // Search mode: route char input to search query if state.version_search.active { match key_event.code { KeyCode::Esc => { @@ -176,22 +173,18 @@ fn handle_version_key( clamp_version_index(state); return; } - KeyCode::Char('j') | KeyCode::Down => { - // fall through to navigation below - } - KeyCode::Char('k') | KeyCode::Up => { - // fall through to navigation below - } + KeyCode::Char('j') | KeyCode::Down => {} + KeyCode::Char('k') | KeyCode::Up => {} KeyCode::Char(c) => { state.version_search.push(c); - state.version_idx = 0; // reset to top of filtered list + state.version_idx = 0; return; } _ => {} } } - let visible_count = visible_versions(state).len(); + let visible_count = visible_versions(state).count(); match key_event.code { KeyCode::Esc => { @@ -350,21 +343,20 @@ fn close_popup(state: &mut WizardState, instances_state: &mut instances::State) instances_state.show_popup = false; } -pub(crate) fn visible_versions(state: &WizardState) -> Vec { +pub(crate) fn visible_versions(state: &WizardState) -> impl Iterator { let q = state.version_search.query.to_lowercase(); - match &state.versions { - LoadState::Loaded(versions) => versions - .iter() - .filter(|v| state.show_snapshots || v.stable) - .filter(|v| q.is_empty() || v.id.to_lowercase().contains(&q)) - .cloned() - .collect(), - _ => Vec::new(), - } + let versions = match &state.versions { + LoadState::Loaded(versions) => versions.as_slice(), + _ => &[], + }; + versions.iter().filter(move |version| { + (state.show_snapshots || version.stable) + && (q.is_empty() || version.id.to_lowercase().contains(&q)) + }) } pub(crate) fn clamp_version_index(state: &mut WizardState) { - let count = visible_versions(state).len(); + let count = visible_versions(state).count(); if count == 0 { state.version_idx = 0; } else if state.version_idx >= count { @@ -384,20 +376,24 @@ pub(crate) fn clamp_loader_version_index(state: &mut WizardState) { } } -// only fires on the Idle -> Loading transition to avoid spamming requests. -// the spawned task writes results back into WIZARD_STATE when done. +// Spawn only on Idle -> Loading to avoid repeating network requests per frame. pub(crate) fn ensure_versions_loaded(state: &mut WizardState) { if !matches!(state.versions, LoadState::Idle) { return; } state.versions = LoadState::Loading; + state.request_epoch = state.request_epoch.wrapping_add(1); + let epoch = state.request_epoch; let versions_arc = WIZARD_STATE.clone(); let loader = state.selected_loader(); tokio::spawn(async move { match super::super::version_lists::game_versions(loader).await { Ok(versions) => match versions_arc.lock() { Ok(mut s) => { + if s.request_epoch != epoch || !matches!(s.versions, LoadState::Loading) { + return; + } s.versions = LoadState::Loaded(versions); clamp_version_index(&mut s); } @@ -407,6 +403,9 @@ pub(crate) fn ensure_versions_loaded(state: &mut WizardState) { }, Err(e) => match versions_arc.lock() { Ok(mut s) => { + if s.request_epoch != epoch || !matches!(s.versions, LoadState::Loading) { + return; + } s.versions = LoadState::Error(e.to_string()); } Err(lock_error) => { @@ -427,11 +426,17 @@ pub(crate) fn ensure_loader_versions_loaded( } state.loader_versions = LoadState::Loading; + state.request_epoch = state.request_epoch.wrapping_add(1); + let epoch = state.request_epoch; let versions_arc = WIZARD_STATE.clone(); tokio::spawn(async move { match super::super::version_lists::loader_versions(loader, &game_version).await { Ok(versions) => match versions_arc.lock() { Ok(mut s) => { + if s.request_epoch != epoch || !matches!(s.loader_versions, LoadState::Loading) + { + return; + } s.loader_versions = LoadState::Loaded(versions); clamp_loader_version_index(&mut s); } @@ -441,6 +446,10 @@ pub(crate) fn ensure_loader_versions_loaded( }, Err(e) => match versions_arc.lock() { Ok(mut s) => { + if s.request_epoch != epoch || !matches!(s.loader_versions, LoadState::Loading) + { + return; + } s.loader_versions = LoadState::Error(e.to_string()); } Err(lock_error) => { diff --git a/src/tui/widgets/popups/select_list.rs b/src/tui/widgets/popups/select_list.rs index d7b3f22..ca65dc2 100644 --- a/src/tui/widgets/popups/select_list.rs +++ b/src/tui/widgets/popups/select_list.rs @@ -1,8 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// Shared selection list used by the new-instance wizard and settings pickers. - use ratatui::{ buffer::Buffer, layout::Rect, @@ -91,4 +89,30 @@ mod tests { assert_eq!(badge_cell.bg, theme.success()); assert_eq!(badge_cell.fg, theme.background()); } + + #[test] + fn version_popup_installed_badge_keeps_colors_on_selection() { + let theme = THEME.as_ref(); + let area = Rect::new(0, 0, 30, 2); + let mut buffer = Buffer::empty(area); + let items = vec![ + ListItem::new(Line::from(vec![Span::raw("1.11.3")])), + ListItem::new(Line::from(vec![ + Span::raw("1.11.2 "), + Span::styled( + " Installed ", + Style::default() + .fg(theme.background()) + .bg(theme.success()) + .add_modifier(Modifier::BOLD), + ), + ])), + ]; + + render_styled(items, 1, area, &mut buffer); + + let badge_cell = buffer.cell((10, 1)).unwrap(); + assert_eq!(badge_cell.bg, theme.success()); + assert_eq!(badge_cell.fg, theme.background()); + } } diff --git a/src/tui/widgets/popups/settings_controls.rs b/src/tui/widgets/popups/settings_controls.rs index 3d0b798..92b04b2 100644 --- a/src/tui/widgets/popups/settings_controls.rs +++ b/src/tui/widgets/popups/settings_controls.rs @@ -1,10 +1,8 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// Reusable interactive controls shared by instance and launcher settings. - use std::{ - collections::{BTreeMap, BTreeSet}, + collections::BTreeMap, path::{Path, PathBuf}, sync::{ Arc, Mutex, @@ -23,8 +21,12 @@ use ratatui::{ use ratatui_textarea::{CursorMove, TextArea}; use crate::{ - config::{settings::DEFAULT_RESOLUTION, theme::THEME}, + config::{ + settings::{DEFAULT_RESOLUTION, parse_tag_values}, + theme::THEME, + }, instance::{ + glfw::{GlfwInstallation, discover_glfw_installations, glfw_version_from_path}, java::JavaInstallation, models::{WindowMode, memory_kib}, }, @@ -206,6 +208,9 @@ pub(crate) struct JavaPicker { cache_path: Option, refresh_started: bool, generation: Arc, + cwd: PathBuf, + environment: BTreeMap, + context_key: String, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -227,12 +232,6 @@ pub(crate) enum GlfwChoice { System(String), } -#[derive(Debug, Clone)] -struct GlfwInstallation { - path: PathBuf, - version: Option, -} - #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct DisplayResolution { pub width: u32, @@ -300,13 +299,24 @@ impl JavaPicker { } pub(crate) fn with_auto_path(detected: String) -> Self { - Self::with_cache(detected, None) + let cwd = std::env::current_dir().unwrap_or_default(); + let environment = crate::instance::java::merge_environment( + &crate::config::SETTINGS.read().defaults.environment, + &BTreeMap::new(), + ); + Self::with_cache(detected, None, cwd, environment) } - pub(crate) fn with_cache(detected: String, cache_path: Option) -> Self { - let cached = cache_path - .as_deref() - .and_then(crate::instance::java::load_installation_cache); + pub(crate) fn with_cache( + detected: String, + cache_path: Option, + cwd: PathBuf, + environment: BTreeMap, + ) -> Self { + let cached = cache_path.as_deref().and_then(|path| { + crate::instance::java::load_installation_cache_in(path, &cwd, &environment) + }); + let context_key = crate::instance::java::probe_context_key(&cwd, &environment); Self { load: Arc::new(Mutex::new( cached.map_or(LoadState::Idle, LoadState::Loaded), @@ -317,6 +327,25 @@ impl JavaPicker { cache_path, refresh_started: false, generation: Arc::new(AtomicU64::new(0)), + cwd, + environment, + context_key, + } + } + + pub(crate) fn set_context( + &mut self, + detected: String, + cwd: PathBuf, + environment: BTreeMap, + ) { + let key = crate::instance::java::probe_context_key(&cwd, &environment); + if key != self.context_key || detected != self.detected { + self.invalidate_cache(); + self.detected = detected; + self.cwd = cwd; + self.environment = environment; + self.context_key = key; } } @@ -344,17 +373,22 @@ impl JavaPicker { let refresh_generation = self.generation.load(Ordering::Relaxed); let generation = self.generation.clone(); let selected_paths = [Some(self.detected.clone()), self.current.clone()]; + let cwd = self.cwd.clone(); + let environment = self.environment.clone(); let discover = move || { - let mut installations = crate::instance::java::discover_installations(); + let mut installations = + crate::instance::java::discover_installations_in(&cwd, &environment); for path in selected_paths.into_iter().flatten() { if installations.iter().any(|installation| { same_executable(&installation.path.to_string_lossy(), &path) }) { continue; } - if let Some(installation) = - crate::instance::java::inspect_installation(Path::new(&path)) - { + if let Some(installation) = crate::instance::java::inspect_installation_in( + Path::new(&path), + &cwd, + &environment, + ) { installations.push(installation); } } @@ -365,8 +399,12 @@ impl JavaPicker { return; } if let Some(cache_path) = cache_path - && let Err(error) = - crate::instance::java::save_installation_cache(&cache_path, &installations) + && let Err(error) = crate::instance::java::save_installation_cache_in( + &cache_path, + &installations, + &cwd, + &environment, + ) { tracing::debug!("Could not cache Java installations: {error}"); } @@ -739,121 +777,6 @@ impl Default for GlfwPicker { } } -pub(crate) fn bundled_glfw_version(meta_dir: &Path, game_version: &str) -> Option { - let path = crate::storage::MetadataPaths::new(meta_dir) - .versions() - .join(game_version) - .join("meta.json"); - let profile: serde_json::Value = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?; - profile - .get("libraries")? - .as_array()? - .iter() - .filter_map(|library| library.get("name")?.as_str()) - .find_map(|coordinate| { - let mut parts = coordinate.split(':'); - match (parts.next(), parts.next(), parts.next()) { - (Some("org.lwjgl"), Some("lwjgl-glfw"), Some(version)) => Some(version.to_owned()), - _ => None, - } - }) -} - -fn discover_glfw_installations() -> Vec { - let mut directories = Vec::::new(); - for variable in ["LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH", "PATH"] { - if let Some(value) = std::env::var_os(variable) { - directories.extend(std::env::split_paths(&value)); - } - } - directories.extend( - [ - "/usr/lib", - "/usr/lib64", - "/usr/local/lib", - "/lib", - "/lib64", - "/opt/homebrew/lib", - "/opt/local/lib", - ] - .into_iter() - .map(PathBuf::from), - ); - - let mut nested = Vec::new(); - for directory in &directories { - if let Ok(entries) = std::fs::read_dir(directory) { - nested.extend( - entries - .flatten() - .map(|entry| entry.path()) - .filter(|path| path.is_dir()), - ); - } - } - directories.extend(nested); - - let mut seen = BTreeSet::new(); - let mut installations = Vec::new(); - for directory in directories { - let Ok(entries) = std::fs::read_dir(directory) else { - continue; - }; - for path in entries.flatten().map(|entry| entry.path()) { - if !is_glfw_library(&path) { - continue; - } - let canonical = std::fs::canonicalize(&path).unwrap_or(path); - if seen.insert(canonical.clone()) { - installations.push(GlfwInstallation { - version: glfw_version_from_path(&canonical), - path: canonical, - }); - } - } - } - installations.sort_by(|left, right| left.path.cmp(&right.path)); - installations -} - -fn is_glfw_library(path: &Path) -> bool { - if !path.is_file() { - return false; - } - let Some(name) = path.file_name().and_then(|name| name.to_str()) else { - return false; - }; - is_glfw_library_name(name) -} - -fn is_glfw_library_name(name: &str) -> bool { - let name = name.to_ascii_lowercase(); - let versioned_so = name.strip_prefix("libglfw.so.").is_some_and(|version| { - version.split('.').all(|part| { - !part.is_empty() && part.chars().all(|character| character.is_ascii_digit()) - }) - }); - name == "libglfw.so" - || versioned_so - || name.starts_with("libglfw.") && name.ends_with(".dylib") - || name.starts_with("glfw") && name.ends_with(".dll") -} - -fn glfw_version_from_path(path: &Path) -> Option { - let name = path.file_name()?.to_str()?.to_ascii_lowercase(); - if let Some((_, suffix)) = name.rsplit_once(".so.") { - return (!suffix.is_empty()).then(|| suffix.to_owned()); - } - let stem = name - .strip_prefix("libglfw.") - .and_then(|name| name.strip_suffix(".dylib")) - .or_else(|| { - name.strip_prefix("glfw") - .and_then(|name| name.strip_suffix(".dll")) - })?; - (!stem.is_empty()).then(|| stem.trim_start_matches(['-', '.']).to_owned()) -} - fn same_executable(left: &str, right: &str) -> bool { if left == right { return true; @@ -997,76 +920,6 @@ pub(crate) fn settings_text_area(lines: Vec) -> TextArea<'static> { editor } -pub(crate) fn parse_tag_values(input: &str) -> Result, String> { - #[derive(Clone, Copy, PartialEq, Eq)] - enum Quote { - None, - Single, - Double, - } - - let mut values = Vec::new(); - let mut current = String::new(); - let mut quote = Quote::None; - let mut started = false; - let mut characters = input.chars().peekable(); - while let Some(character) = characters.next() { - match (quote, character) { - (Quote::None, character) if character.is_whitespace() => { - if started { - values.push(std::mem::take(&mut current)); - started = false; - } - } - (Quote::None, '\'') => { - quote = Quote::Single; - started = true; - } - (Quote::None, '"') => { - quote = Quote::Double; - started = true; - } - (Quote::Single, '\'') => quote = Quote::None, - (Quote::Double, '"') => quote = Quote::None, - (Quote::Double, '\\') if matches!(characters.peek(), Some('"' | '\\')) => { - current.push(characters.next().unwrap_or_default()); - started = true; - } - (_, character) => { - current.push(character); - started = true; - } - } - } - if quote != Quote::None { - return Err("Quoted value is missing its closing quote.".to_owned()); - } - if started { - values.push(current); - } - let mut seen = BTreeSet::new(); - values.retain(|value| seen.insert(value.clone())); - Ok(values) -} - -pub(crate) fn format_tag_values(values: &[String]) -> String { - values - .iter() - .map(|value| { - if !value.is_empty() - && !value - .chars() - .any(|character| character.is_whitespace() || matches!(character, '\'' | '"')) - { - value.clone() - } else { - format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\"")) - } - }) - .collect::>() - .join(" ") -} - pub(crate) fn parse_environment(value: &str) -> Result, String> { let mut environment = BTreeMap::new(); for assignment in parse_tag_values(value)? { @@ -1120,7 +973,7 @@ pub(crate) fn tagged_value_lines( let mut spans = prefix; let mut used = 0usize; for value in values { - let badge_width = value.chars().count() + 2; + let badge_width = Span::raw(value).width() + 2; let separator = usize::from(used > 0); if used > 0 && used + separator + badge_width > available { lines.push(Line::from(spans)); @@ -1149,22 +1002,7 @@ pub(crate) fn tagged_value_lines( } pub(crate) fn tagged_row_count(values: &[String], width: u16) -> usize { - if values.is_empty() { - return 1; - } - let available = width.saturating_sub(20) as usize; - let mut rows = 1; - let mut used = 0usize; - for value in values { - let badge_width = value.chars().count() + 2; - let separator = usize::from(used > 0); - if used > 0 && used + separator + badge_width > available { - rows += 1; - used = 0; - } - used += usize::from(used > 0) + badge_width; - } - rows + tagged_value_lines(Vec::new(), false, false, values, "", width).len() } pub(crate) fn auto_label() -> Span<'static> { @@ -1305,6 +1143,7 @@ pub(crate) fn resolution_items( #[cfg(test)] mod tests { use super::*; + use crate::config::settings::format_tag_values; #[test] fn memory_steps_move_and_clamp() { @@ -1389,7 +1228,12 @@ mod tests { let cache = temp.path().join("cache/java/installations.json"); std::fs::create_dir_all(cache.parent().unwrap()).unwrap(); std::fs::write(&cache, "[]").unwrap(); - let mut picker = JavaPicker::with_cache("/auto/java".to_owned(), Some(cache.clone())); + let mut picker = JavaPicker::with_cache( + "/auto/java".to_owned(), + Some(cache.clone()), + temp.path().to_owned(), + BTreeMap::new(), + ); *picker.load.lock().unwrap() = LoadState::Loaded(vec![JavaInstallation { path: "/cached/java".into(), version: Some("21".to_owned()), @@ -1403,6 +1247,48 @@ mod tests { assert!(matches!(*picker.load.lock().unwrap(), LoadState::Idle)); } + #[test] + fn java_picker_cache_and_workers_are_bound_to_the_captured_context() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("java"); + std::fs::write(&path, b"java").unwrap(); + let cache = temp.path().join("installations.json"); + let environment = BTreeMap::from([("JAVA_TEST_CONTEXT".to_owned(), "first".to_owned())]); + let installations = vec![JavaInstallation { + path: path.clone(), + version: Some("21".to_owned()), + }]; + crate::instance::java::save_installation_cache_in( + &cache, + &installations, + temp.path(), + &environment, + ) + .unwrap(); + let detected = path.to_string_lossy().into_owned(); + let mut picker = JavaPicker::with_cache( + detected.clone(), + Some(cache.clone()), + temp.path().to_owned(), + environment.clone(), + ); + assert!( + matches!(&*picker.load.lock().unwrap(), LoadState::Loaded(found) if *found == installations) + ); + picker.refresh_started = true; + let generation = picker.generation.load(Ordering::Relaxed); + picker.set_context(detected.clone(), temp.path().to_owned(), environment); + assert_eq!(picker.generation.load(Ordering::Relaxed), generation); + let changed = BTreeMap::from([("JAVA_TEST_CONTEXT".to_owned(), "second".to_owned())]); + picker.set_context(detected, temp.path().join("other"), changed.clone()); + assert_eq!(picker.generation.load(Ordering::Relaxed), generation + 1); + assert!(!picker.refresh_started); + assert!(matches!(*picker.load.lock().unwrap(), LoadState::Idle)); + assert!(!cache.exists()); + assert_eq!(picker.cwd, temp.path().join("other")); + assert_eq!(picker.environment, changed); + } + #[test] fn java_title_is_minimal_and_uses_the_major_version() { let picker = JavaPicker::with_auto_path("/opt/jdk-25/bin/java".to_owned()); @@ -1485,7 +1371,7 @@ mod tests { .unwrap(); assert_eq!( - bundled_glfw_version(temp.path(), "1.21.1").as_deref(), + crate::instance::glfw::bundled_glfw_version(temp.path(), "1.21.1").as_deref(), Some("3.3.3") ); let mut picker = GlfwPicker::with_bundled_version(Some("3.3.3".to_owned())); @@ -1497,19 +1383,6 @@ mod tests { ); } - #[test] - fn glfw_library_names_are_recognized() { - assert!(is_glfw_library_name("libglfw.so.3")); - assert!(is_glfw_library_name("libglfw.3.dylib")); - assert!(is_glfw_library_name("glfw3.dll")); - assert!(!is_glfw_library_name("libglfw.so.backup")); - assert!(!is_glfw_library_name("libGL.so")); - assert_eq!( - glfw_version_from_path(Path::new("/usr/lib/libglfw.so.3.4")).as_deref(), - Some("3.4") - ); - } - #[test] fn settings_text_input_deletes_the_previous_word() { let mut input = TextArea::from(["one two"]); @@ -1540,10 +1413,10 @@ mod tests { } #[test] - fn tag_values_drop_exact_duplicates_without_reordering() { + fn tag_values_preserve_repeated_options_and_their_operands() { assert_eq!( - parse_tag_values("-Xmx2G '-Dlabel=hello world' -Xmx2G").unwrap(), - ["-Xmx2G", "-Dlabel=hello world"] + parse_tag_values("--add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED").unwrap(), + ["--add-opens", "java.base/java.lang=ALL-UNNAMED", "--add-opens", "java.base/java.util=ALL-UNNAMED"] ); } @@ -1562,6 +1435,7 @@ mod tests { ); assert!(parse_environment("=missing").is_err()); assert!(parse_environment("KEY=one KEY=two").is_err()); + assert!(parse_environment("KEY=one KEY=one").is_err()); } #[test] diff --git a/src/tui/widgets/popups/version_lists.rs b/src/tui/widgets/popups/version_lists.rs index fdafbb5..24b7677 100644 --- a/src/tui/widgets/popups/version_lists.rs +++ b/src/tui/widgets/popups/version_lists.rs @@ -1,8 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// shared network loading for Minecraft and mod-loader version pickers. - use crate::instance::{ loader::{GameVersion, get_installer}, models::ModLoader, diff --git a/src/tui/widgets/screenshots_grid.rs b/src/tui/widgets/screenshots_grid.rs index 4d6bba4..ebd3607 100644 --- a/src/tui/widgets/screenshots_grid.rs +++ b/src/tui/widgets/screenshots_grid.rs @@ -1,10 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// responsive grid of screenshot thumbnails rendered directly in the terminal. -// images load lazily on background threads as they scroll into view, -// and get converted to terminal graphics via ratatui-image protocols. - use std::collections::{HashMap, HashSet}; use std::path::Path; use std::sync::{Arc, Mutex}; @@ -15,7 +11,7 @@ use ratatui::{ layout::{Constraint, Layout, Rect}, style::{Modifier, Style}, text::Span, - widgets::{Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState}, + widgets::{Paragraph, ScrollbarState}, }; use ratatui_image::{Resize, StatefulImage, protocol::StatefulProtocol}; use unicode_segmentation::UnicodeSegmentation; @@ -23,8 +19,6 @@ use unicode_segmentation::UnicodeSegmentation; use crate::config::theme::THEME; use crate::instance::screenshots::ScreenshotEntry; -// grid cell sizing constraints in terminal columns. -// the grid auto-fits columns within these bounds depending on terminal width const TARGET_CELL_WIDTH: u16 = 34; const MIN_CELL_WIDTH: u16 = 24; const MAX_CELL_WIDTH: u16 = 52; @@ -91,6 +85,8 @@ impl Default for ScreenshotsState { impl ScreenshotsState { pub fn start_load(&mut self, instances_dir: &Path, instance_name: &str) { + self.pending_entries = Arc::new(Mutex::new(None)); + self.pending_images = Arc::new(Mutex::new(Vec::new())); self.loading = true; self.loaded_for = Some(instance_name.to_string()); self.entries.clear(); @@ -223,6 +219,7 @@ impl ScreenshotsState { pub fn remove_path(&mut self, path: &Path) { self.entries.retain(|entry| entry.path != path); + self.pending_images = Arc::new(Mutex::new(Vec::new())); self.protocols.clear(); self.requested.clear(); @@ -293,9 +290,13 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut ScreenshotsState) -> bool { .get(state.selected) .and_then(|index| state.entries.get(*index)) && let Some(dir) = entry.path.parent() - && let Err(e) = open::that_detached(dir) + && let Err(error) = open::that_detached(dir) { - tracing::error!("Failed to open directory: {}", e); + tracing::error!("Failed to open directory: {}", error); + crate::feedback::errors::push_message( + tracing::Level::ERROR, + format!("Could not open {}: {error}", dir.display()), + ); } true } @@ -303,9 +304,13 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut ScreenshotsState) -> bool { if let Some(entry) = filtered .get(state.selected) .and_then(|index| state.entries.get(*index)) - && let Err(e) = open::that_detached(&entry.path) + && let Err(error) = open::that_detached(&entry.path) { - tracing::error!("Failed to open file: {}", e); + tracing::error!("Failed to open file: {}", error); + crate::feedback::errors::push_message( + tracing::Level::ERROR, + format!("Could not open {}: {error}", entry.path.display()), + ); } true } @@ -373,9 +378,7 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut ScreenshotsState, is_fo let cols = target_cols.clamp(min_cols, max_cols); let cell_width = area.width / cols as u16; - // figure out how tall each thumbnail should be in terminal rows. - // need the font's pixel aspect ratio to keep screenshots from - // looking stretched since terminal cells aren't square + // Terminal cells are not square; use the font's aspect ratio to avoid stretching. let (img_w, img_h) = state .entries .first() @@ -453,17 +456,7 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut ScreenshotsState, is_fo height: area.height.saturating_sub(2), }; frame.render_stateful_widget( - Scrollbar::default() - .orientation(ScrollbarOrientation::VerticalRight) - .begin_symbol(Some("\u{25b2}")) - .style( - Style::default() - .fg(theme.text_dim()) - .add_modifier(Modifier::BOLD), - ) - .thumb_symbol("\u{2551}") - .track_symbol(Some("")) - .end_symbol(Some("\u{25bc}")), + super::scrollbar(theme.text_dim()), scrollbar_area, &mut state.scrollbar_state, ); diff --git a/src/tui/widgets/search.rs b/src/tui/widgets/search.rs index edc9459..3f93e7e 100644 --- a/src/tui/widgets/search.rs +++ b/src/tui/widgets/search.rs @@ -1,9 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// reusable incremental search state used across multiple widgets. -// handles case-insensitive filtering and inline match highlighting. - use crossterm::event::KeyModifiers; use ratatui::{ style::{Modifier, Style}, @@ -53,8 +50,6 @@ impl SearchState { text.to_lowercase().contains(&self.query.to_lowercase()) } - // splits text into spans, bolding+underlining the parts that match - // the query so every searchable widget can use the same styling pub fn highlight_spans(&self, text: &str, base_style: Style) -> Vec> { if self.query.is_empty() { return vec![Span::styled(text.to_owned(), base_style)]; @@ -62,12 +57,21 @@ impl SearchState { let query_lower = self.query.to_lowercase(); let text_lower = text.to_lowercase(); + let mut original_ranges = Vec::with_capacity(text_lower.len()); + for (start, character) in text.char_indices() { + let lowercase_bytes = character.to_lowercase().map(char::len_utf8).sum::(); + original_ranges.extend(std::iter::repeat_n( + (start, start + character.len_utf8()), + lowercase_bytes, + )); + } let mut spans = Vec::new(); let mut last = 0; - for (start, _) in text_lower.match_indices(&query_lower) { - let end = start + query_lower.len(); - if !text.is_char_boundary(start) || !text.is_char_boundary(end) { + for (lower_start, _) in text_lower.match_indices(&query_lower) { + let start = original_ranges[lower_start].0; + let end = original_ranges[lower_start + query_lower.len() - 1].1; + if start < last { continue; } if start > last { @@ -94,7 +98,6 @@ impl SearchState { Line::from(self.highlight_spans(text, base_style)) } - // renders the "/ query█" indicator in the block title bar pub fn title_line(&self) -> Option> { if !self.active && self.query.is_empty() { return None; diff --git a/src/tui/widgets/settings.rs b/src/tui/widgets/settings.rs index 206cbe0..4659d10 100644 --- a/src/tui/widgets/settings.rs +++ b/src/tui/widgets/settings.rs @@ -1,10 +1,11 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// settings panel: manages config profiles and shows compact instance info. -// detailed instance and launcher configuration opens in the TUI popups. - -use std::path::{Path, PathBuf}; +use std::{ + collections::HashMap, + path::{Path, PathBuf}, + sync::{Arc, Mutex}, +}; use crossterm::event::{KeyCode, KeyEvent}; use ratatui::{ @@ -47,14 +48,21 @@ pub struct SettingsState { pub add_mode: AddMode, pub pane: SettingsPane, meta_dir: PathBuf, + instances_dir: PathBuf, active_profile: Option, instance_name: Option, - java_key: Option, java_label: String, + java_cache: HashMap, +} + +#[derive(Default)] +struct CachedJavaLabel { + key: Option<(chrono::DateTime, String)>, + result: Arc>>, } impl SettingsState { - pub fn new(meta_dir: PathBuf) -> Self { + pub fn new(meta_dir: PathBuf, instances_dir: PathBuf) -> Self { let profiles = crate::instance::config_sync::list_profiles(&meta_dir).unwrap_or_else(|e| { tracing::warn!("Failed to load config sync profiles: {}", e); Vec::new() @@ -65,10 +73,11 @@ impl SettingsState { add_mode: AddMode::None, pane: SettingsPane::Profile, meta_dir, + instances_dir, active_profile: None, instance_name: None, - java_key: None, java_label: "unknown".to_string(), + java_cache: HashMap::new(), }; state.select_active(); state @@ -107,6 +116,14 @@ impl SettingsState { self.list_state.selected = Some(self.list_state.selected.unwrap_or(0).min(last)); } + pub fn invalidate_java_cache(&mut self, instance_name: Option<&str>) { + if let Some(name) = instance_name { + self.java_cache.remove(name); + } else { + self.java_cache.clear(); + } + } + fn update_for_instance(&mut self, instance: Option<&InstanceConfig>) { let instance_name = instance.map(|inst| inst.name.clone()); let active_profile = instance.and_then(|inst| inst.config_sync_profile.clone()); @@ -119,15 +136,48 @@ impl SettingsState { self.select_active(); } - let java_key = instance.map(java_path_key); - if self.java_key != java_key { - let java_source = instance.map(effective_java_path); - self.java_label = java_source - .as_deref() - .map(java_version_label) - .unwrap_or_else(|| "unknown".to_string()); - self.java_key = java_key; - } + self.java_label = if let Some(instance) = instance { + let settings = SETTINGS.read(); + let cwd = self + .instances_dir + .join(&instance.name) + .join(crate::storage::MINECRAFT_DIR_NAME); + let environment = crate::instance::java::merge_environment( + &settings.defaults.environment, + &instance.environment, + ); + let java = crate::instance::java::resolve_java_path_in( + instance + .java_path + .as_deref() + .filter(|path| !path.is_empty()) + .or(settings.paths.effective_java_path()), + &cwd, + &environment, + ); + let key = (instance.created, java_path_key(&java, &cwd, &environment)); + let cached = self.java_cache.entry(instance.name.clone()).or_default(); + if cached.key.as_ref() != Some(&key) { + cached.key = Some(key); + cached.result = Default::default(); + let pending = cached.result.clone(); + std::thread::spawn(move || { + let label = java_version_label(&java, &cwd, &environment); + *pending + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(label); + crate::feedback::request_redraw(); + }); + } + cached + .result + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .unwrap_or_else(|| "unknown".to_owned()) + } else { + "unknown".to_owned() + }; } } @@ -140,38 +190,35 @@ fn add_active_profile(profiles: &mut Vec, active_profile: Option<&str>) } } -fn java_path_key(instance: &InstanceConfig) -> String { - instance - .java_path - .as_deref() - .filter(|path| !path.is_empty()) - .map(str::to_owned) - .or_else(|| { - SETTINGS - .read() - .paths - .effective_java_path() - .map(str::to_owned) - }) - .unwrap_or_else(|| "".to_owned()) +fn java_path_key( + java: &str, + cwd: &Path, + environment: &std::collections::BTreeMap, +) -> String { + let path = cwd.join(java); + let metadata = std::fs::metadata(&path).ok().map(|metadata| { + ( + metadata.len(), + metadata.modified().ok(), + metadata.created().ok(), + metadata.permissions(), + ) + }); + format!( + "{java}:{}:{:?}:{metadata:?}", + crate::instance::java::probe_context_key(cwd, environment), + std::fs::canonicalize(path).ok(), + ) } -fn effective_java_path(instance: &InstanceConfig) -> String { - instance - .java_path - .clone() - .or_else(|| { - SETTINGS - .read() - .paths - .effective_java_path() - .map(str::to_owned) - }) - .unwrap_or_else(crate::instance::java::detect_java_path) -} - -fn java_version_label(java_path: &str) -> String { - let Some(version) = crate::instance::java::java_version(Path::new(java_path)) else { +fn java_version_label( + java_path: &str, + cwd: &Path, + environment: &std::collections::BTreeMap, +) -> String { + let Some(version) = + crate::instance::java::java_version_in(Path::new(java_path), cwd, environment) + else { return "unknown".to_string(); }; let major = crate::instance::java::java_major(Some(&version)); @@ -255,7 +302,10 @@ pub fn render( render_separator(frame, chunks[1], focused, state.pane); render_instance_info(frame, chunks[2], focused, state, instance); } else { - render_profile_list(frame, inner, focused, state); + match state.pane { + SettingsPane::Profile => render_profile_list(frame, inner, focused, state), + SettingsPane::Info => render_instance_info(frame, inner, focused, state, instance), + } } if let AddMode::ProfileName(name) = &state.add_mode { @@ -445,15 +495,9 @@ fn render_add_profile_popup(frame: &mut Frame, name: &str) { } fn popup_area(frame: &Frame, width: u16, height: u16) -> Rect { - let area = frame.area(); - let x = area.x + (area.width.saturating_sub(width)) / 2; - let y = area.y + (area.height.saturating_sub(height)) / 2; - Rect { - x, - y, - width: width.min(area.width), - height: height.min(area.height), - } + frame + .area() + .centered(Constraint::Length(width), Constraint::Length(height)) } pub enum SettingsAction { diff --git a/src/tui/widgets/status.rs b/src/tui/widgets/status.rs index 2065a54..99d7cdb 100644 --- a/src/tui/widgets/status.rs +++ b/src/tui/widgets/status.rs @@ -1,9 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// the "overview" panel showing download/install progress. -// shows a gauge when the total is known, or a spinner when it's not. - use ratatui::{ Frame, layout::{Constraint, Layout, Rect}, diff --git a/tests/content_scanners.rs b/tests/content_scanners.rs index 71ed055..9e60b39 100644 --- a/tests/content_scanners.rs +++ b/tests/content_scanners.rs @@ -1,11 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// integration tests for the public content-scanner APIs: shaders, worlds, -// and resource packs. each scanner walks an instance's minecraft subdir -// and returns ContentEntry rows; shape varies slightly per content type -// (worlds are directories only, packs and shaders accept .zip or dir, etc.). - use std::path::{Path, PathBuf}; use rmcl::instance::content::resource_packs::scan_resource_packs; diff --git a/tests/fixtures/InstallerLifetimeFixture.java b/tests/fixtures/InstallerLifetimeFixture.java new file mode 100644 index 0000000..0a90335 --- /dev/null +++ b/tests/fixtures/InstallerLifetimeFixture.java @@ -0,0 +1,21 @@ +// SPDX-FileCopyrightText: 2026 Constantin Bauer +// SPDX-License-Identifier: GPL-3.0-only + +import java.nio.file.Files; +import java.nio.file.Paths; + +public final class InstallerLifetimeFixture { + public static void main(String[] args) throws Exception { + boolean child = args.length != 0 && args[0].equals("child"); + if (!child) { + String java = Paths.get(System.getProperty("java.home"), "bin", + System.getProperty("os.name").startsWith("Windows") ? "java.exe" : "java").toString(); + new ProcessBuilder(java, "-cp", System.getProperty("java.class.path"), + "InstallerLifetimeFixture", "child").inheritIO().start(); + } + String prefix = child ? "installer-child" : "installer"; + Files.write(Paths.get(prefix + "-ready"), new byte[] {1}); + Thread.sleep(1200); + Files.write(Paths.get(prefix + "-survived"), new byte[] {1}); + } +} diff --git a/tests/launch_pipeline.rs b/tests/launch_pipeline.rs index b51d76f..06c3d61 100644 --- a/tests/launch_pipeline.rs +++ b/tests/launch_pipeline.rs @@ -1,12 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// integration tests for build_launch_invocation - the seam that takes an -// instance config plus resolved auth credentials and returns the full java -// invocation that would be spawned. these tests build the expected on-disk -// fixture layout in a tempdir, call the seam, and assert on the rendered -// LaunchInvocation. nothing here actually spawns a process. - use std::path::{Path, PathBuf}; use chrono::Utc; @@ -14,16 +8,32 @@ use serde_json::json; use tempfile::TempDir; use rmcl::instance::launch::{ - LaunchAuth, LaunchError, build_launch_invocation, supports_quick_play, + LaunchAuth, LaunchError, build_launch_invocation_with_settings, supports_quick_play, }; use rmcl::instance::models::{InstanceConfig, ModLoader}; -// ---------- helpers ---------- - const PLAYER: &str = "TestPlayer"; const PLAYER_UUID: &str = "00000000-0000-0000-0000-000000000001"; const PLAYER_TOKEN: &str = "secret-access-token"; +async fn build_launch_invocation( + config: &InstanceConfig, + instances_dir: &Path, + meta_dir: &Path, + auth: &LaunchAuth<'_>, + quick_play_world: Option<&str>, +) -> Result { + build_launch_invocation_with_settings( + config, + instances_dir, + meta_dir, + auth, + quick_play_world, + &rmcl::config::Config::default(), + ) + .await +} + fn test_auth() -> LaunchAuth<'static> { LaunchAuth { username: PLAYER, @@ -50,9 +60,7 @@ fn make_config_with( loader_version: loader_version.map(str::to_owned), created: Utc::now(), last_played: None, - // pinned to a deterministic value so detect_java_path is never - // invoked and tests don't depend on the host's java install. - java_path: Some("/usr/bin/java-test".into()), + java_path: Some(default_fake_java()), memory_max: None, memory_min: None, jvm_args: Vec::new(), @@ -70,27 +78,117 @@ fn make_config_with( } } -#[cfg(unix)] fn fake_java(tmp: &TempDir, major: u32) -> String { - use std::os::unix::fs::PermissionsExt; + fake_java_platform(tmp, major, &host_java_platform()) +} - let path = tmp.path().join(format!("java-{major}")); +fn host_java_platform() -> rmcl::launch_profile::system::JavaPlatform { + rmcl::launch_profile::system::JavaPlatform::from_java_properties( + match std::env::consts::OS { + "windows" => "Windows 10", + "macos" => "Mac OS X", + _ => "Linux", + }, + std::env::consts::ARCH, + if cfg!(target_pointer_width = "64") { + "64" + } else { + "32" + }, + "10.0", + ) + .unwrap() +} + +fn default_fake_java() -> String { + static JAVA: std::sync::OnceLock<(TempDir, String)> = std::sync::OnceLock::new(); + JAVA.get_or_init(|| { + let temp = tempfile::tempdir().unwrap(); + let java = fake_java(&temp, 25); + (temp, java) + }) + .1 + .clone() +} + +fn fake_java_platform( + tmp: &TempDir, + major: u32, + platform: &rmcl::launch_profile::system::JavaPlatform, +) -> String { + let os_name = match platform.os_name { + "windows" => "Windows 10", + "osx" => "Mac OS X", + _ => "Linux", + }; + let text = format!( + "java.version = {major}.0.1\nos.name = {os_name}\nos.arch = {}\nsun.arch.data.model = {}\nos.version = {}", + platform.arch, platform.bitness, platform.os_version + ); + let path = tmp.path().join(format!( + "java probe-{major}-{}.{}", + platform.arch, + if cfg!(windows) { "cmd" } else { "sh" } + )); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::write( + &path, + format!( + "#!/bin/sh\nprintf '%s\\n' {} >&2\n", + text.lines() + .map(|line| format!("'{line}'")) + .collect::>() + .join(" ") + ), + ) + .unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + #[cfg(windows)] std::fs::write( &path, - format!("#!/bin/sh\necho 'openjdk version \"{major}.0.1\"' >&2\n"), + format!( + "@echo off\r\n{}\r\n", + text.lines() + .map(|line| format!("echo {line} 1>&2")) + .collect::>() + .join("\r\n") + ), ) .unwrap(); - let mut permissions = std::fs::metadata(&path).unwrap().permissions(); - permissions.set_mode(0o755); - std::fs::set_permissions(&path, permissions).unwrap(); path.to_string_lossy().into_owned() } -// builds the on-disk layout that build_launch_invocation expects: -// /instances//minecraft/ (instance dir, created empty) -// /meta/versions//meta.json -// /meta/cache/loaders/profiles/ (created empty) -// /meta/libraries/ (created empty) +fn cache_fixture_artifacts(meta_dir: &Path, profile: &mut serde_json::Value) { + use sha1::Digest; + let bytes = b"synthetic jar"; + if let Some(libraries) = profile["libraries"].as_array_mut() { + for library in libraries { + let name = library["name"].as_str().unwrap().to_owned(); + if let Some(artifact) = library["downloads"] + .get_mut("artifact") + .filter(|value| value.is_object()) + { + let path = artifact["path"] + .as_str() + .filter(|path| !path.is_empty()) + .map(str::to_owned) + .or_else(|| rmcl::instance::loader::maven::maven_coord_to_path(&name)) + .unwrap(); + let dest = rmcl::storage::MetadataPaths::new(meta_dir) + .libraries() + .join(path); + std::fs::create_dir_all(dest.parent().unwrap()).unwrap(); + std::fs::write(dest, bytes).unwrap(); + artifact["sha1"] = json!(format!("{:x}", sha1::Sha1::digest(bytes))); + artifact["size"] = json!(bytes.len()); + } + } + } +} + struct Fixture { _tmp: TempDir, instances_dir: PathBuf, @@ -98,7 +196,7 @@ struct Fixture { } impl Fixture { - fn new(instance_name: &str, game_version: &str, vanilla_meta: serde_json::Value) -> Self { + fn new(instance_name: &str, game_version: &str, mut vanilla_meta: serde_json::Value) -> Self { let tmp = tempfile::tempdir().unwrap(); let instances_dir = tmp.path().join("instances"); let meta_dir = tmp.path().join("meta"); @@ -107,6 +205,7 @@ impl Fixture { std::fs::create_dir_all(&instance_minecraft).unwrap(); std::fs::create_dir_all(meta_dir.join("cache/minecraft/libraries")).unwrap(); + cache_fixture_artifacts(&meta_dir, &mut vanilla_meta); std::fs::create_dir_all(meta_dir.join("cache/loaders/profiles")).unwrap(); let version_dir = meta_dir.join("cache/minecraft/versions").join(game_version); std::fs::create_dir_all(&version_dir).unwrap(); @@ -123,7 +222,8 @@ impl Fixture { } } - fn write_loader_profile(&self, filename: &str, content: serde_json::Value) { + fn write_loader_profile(&self, filename: &str, mut content: serde_json::Value) { + cache_fixture_artifacts(&self.meta_dir, &mut content); std::fs::write( self.meta_dir.join("cache/loaders/profiles").join(filename), serde_json::to_vec_pretty(&content).unwrap(), @@ -179,7 +279,6 @@ fn modern_vanilla_meta(id: &str) -> serde_json::Value { }) } -#[cfg(unix)] fn modern_vanilla_meta_with_java(id: &str, java_major: u32) -> serde_json::Value { let mut meta = modern_vanilla_meta(id); meta["javaVersion"] = json!({ @@ -208,8 +307,6 @@ fn platform_classpath_sep() -> &'static str { if cfg!(windows) { ";" } else { ":" } } -// ---------- vanilla ---------- - #[tokio::test] async fn vanilla_modern_builds_complete_invocation() { let fx = Fixture::new("v1", "1.20.1", modern_vanilla_meta("1.20.1")); @@ -219,15 +316,11 @@ async fn vanilla_modern_builds_complete_invocation() { .await .unwrap(); - assert_eq!(inv.java, "/usr/bin/java-test"); + assert_eq!(inv.java, config.java_path.as_deref().unwrap()); assert_eq!(inv.main_class, "net.minecraft.client.main.Main"); assert!(inv.extra_args.is_empty()); - let expected_natives = fx - .meta_dir - .join("cache/minecraft/versions") - .join("1.20.1") - .join("natives"); + let expected_natives = host_java_platform().natives_directory(&fx.meta_dir, "1.20.1"); let actual_natives = inv .jvm_args .iter() @@ -247,12 +340,10 @@ async fn vanilla_modern_builds_complete_invocation() { inv.jvm_args ); - // working_dir is //minecraft assert_eq!( inv.working_dir, fx.instances_dir.join("v1").join("minecraft") ); - // classpath = the one vanilla lib + the vanilla client jar let slf4j = fx .meta_dir .join("cache/minecraft/libraries/org/slf4j/slf4j-api/2.0.7/slf4j-api-2.0.7.jar"); @@ -300,7 +391,6 @@ async fn quick_play_passes_the_selected_save_folder() { ); } -#[cfg(unix)] #[tokio::test] async fn launch_fails_when_selected_java_is_older_than_profile_requires() { let fx = Fixture::new( @@ -339,12 +429,11 @@ async fn vanilla_legacy_args_format_substitutes_tokens() { assert_eq!(inv.main_class, "net.minecraft.launchwrapper.Launch"); - // legacy format has no upstream jvm args; jvm_args should be just Xms/Xmx - assert_eq!(inv.jvm_args.len(), 2); + assert_eq!(inv.jvm_args.len(), 3); + assert!(inv.jvm_args[2].starts_with("-Djava.library.path=")); assert!(inv.jvm_args[0].starts_with("-Xms")); assert!(inv.jvm_args[1].starts_with("-Xmx")); - // game_args should be space-split with substitutions applied let joined = inv.game_args.join(" "); assert!(joined.contains(&format!("--username {}", PLAYER))); assert!(joined.contains(&format!("--uuid {}", PLAYER_UUID))); @@ -352,7 +441,37 @@ async fn vanilla_legacy_args_format_substitutes_tokens() { assert!(joined.contains("--userType msa")); } -// ---------- forge ---------- +#[tokio::test] +async fn missing_or_empty_artifact_paths_use_maven_coordinates() { + for path in [None, Some("")] { + let mut meta = modern_vanilla_meta("1.20.1"); + let artifact = meta["libraries"][0]["downloads"]["artifact"] + .as_object_mut() + .unwrap(); + if let Some(path) = path { + artifact.insert("path".to_owned(), json!(path)); + } else { + artifact.remove("path"); + } + let fixture = Fixture::new("artifact", "1.20.1", meta); + let invocation = build_launch_invocation( + &make_config("artifact", "1.20.1", ModLoader::Vanilla), + &fixture.instances_dir, + &fixture.meta_dir, + &test_auth(), + None, + ) + .await + .unwrap(); + assert!( + invocation.classpath.contains( + &rmcl::storage::MetadataPaths::new(&fixture.meta_dir) + .libraries() + .join("org/slf4j/slf4j-api/2.0.7/slf4j-api-2.0.7.jar") + ) + ); + } +} #[tokio::test] async fn forge_modern_includes_add_opens() { @@ -444,18 +563,15 @@ async fn forge_local_lib_dir_preferred_over_meta_dir() { "expected local fmlloader on classpath: {:?}", inv.classpath ); - // and the meta-dir candidate should not appear - let meta_candidate = fx - .meta_dir - .join("libraries/net/minecraftforge/fmlloader/1.20.1-47.2.0/fmlloader-1.20.1-47.2.0.jar"); + let meta_candidate = rmcl::storage::MetadataPaths::new(&fx.meta_dir) + .libraries() + .join("net/minecraftforge/fmlloader/1.20.1-47.2.0/fmlloader-1.20.1-47.2.0.jar"); assert!( !inv.classpath.contains(&meta_candidate), "meta-dir candidate should not be on classpath when local exists" ); } -// ---------- fabric ---------- - #[tokio::test] async fn fabric_implicit_inheritsfrom_resolves() { let fx = Fixture::new("fab", "1.20.1", modern_vanilla_meta("1.20.1")); @@ -482,7 +598,6 @@ async fn fabric_implicit_inheritsfrom_resolves() { inv.main_class, "net.fabricmc.loader.impl.launch.knot.KnotClient" ); - // both fabric-loader and vanilla slf4j must appear on the merged classpath let fabric_loader = fx.meta_dir.join( "cache/minecraft/libraries/net/fabricmc/fabric-loader/0.15.0/fabric-loader-0.15.0.jar", ); @@ -501,8 +616,6 @@ async fn fabric_implicit_inheritsfrom_resolves() { ); } -// ---------- neoforge ---------- - #[tokio::test] async fn neoforge_inheritsfrom_resolves() { let fx = Fixture::new("ne", "1.20.6", modern_vanilla_meta("1.20.6")); @@ -541,8 +654,6 @@ async fn neoforge_inheritsfrom_resolves() { ); } -// ---------- template substitution ---------- - #[tokio::test] async fn auth_credentials_substituted_in_game_args() { let fx = Fixture::new("auth", "1.20.1", modern_vanilla_meta("1.20.1")); @@ -576,7 +687,6 @@ async fn auth_credentials_substituted_in_game_args() { #[tokio::test] async fn version_type_substituted() { - // type = "snapshot" in the fixture; ${version_type} should render that let mut meta = modern_vanilla_meta("1.20.1"); meta["type"] = json!("snapshot"); let fx = Fixture::new("vt", "1.20.1", meta); @@ -593,8 +703,6 @@ async fn version_type_substituted() { ); } -// ---------- classpath ---------- - #[tokio::test] async fn classpath_uses_platform_separator() { let fx = Fixture::new("cp", "1.20.1", modern_vanilla_meta("1.20.1")); @@ -604,7 +712,6 @@ async fn classpath_uses_platform_separator() { .await .unwrap(); - // with two classpath entries we should see exactly one separator assert_eq!(inv.classpath.len(), 2); let sep = platform_classpath_sep(); assert_eq!(inv.classpath_string.matches(sep).count(), 1); @@ -612,7 +719,6 @@ async fn classpath_uses_platform_separator() { #[tokio::test] async fn rule_disallow_excludes_library() { - // a library whose rule always denies must not appear on the classpath let mut meta = modern_vanilla_meta("1.20.1"); meta["libraries"] = json!([ { @@ -646,7 +752,9 @@ async fn rule_disallow_excludes_library() { .await .unwrap(); - let denied = fx.meta_dir.join("libraries/com/denied/lib/1.0/lib-1.0.jar"); + let denied = rmcl::storage::MetadataPaths::new(&fx.meta_dir) + .libraries() + .join("com/denied/lib/1.0/lib-1.0.jar"); assert!( !inv.classpath.contains(&denied), "denied library was included: {:?}", @@ -654,8 +762,6 @@ async fn rule_disallow_excludes_library() { ); } -// ---------- memory ---------- - #[tokio::test] async fn xms_xmx_use_config_memory() { let fx = Fixture::new("mem", "1.20.1", modern_vanilla_meta("1.20.1")); @@ -707,7 +813,6 @@ async fn instance_launch_options_are_injected() { async fn default_memory_used_when_unset() { let fx = Fixture::new("memdef", "1.20.1", modern_vanilla_meta("1.20.1")); let config = make_config("memdef", "1.20.1", ModLoader::Vanilla); - // memory_min and memory_max default to None in make_config let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth(), None) .await @@ -717,8 +822,6 @@ async fn default_memory_used_when_unset() { assert!(inv.jvm_args.iter().any(|a| a == "-Xmx2G")); } -// ---------- error paths ---------- - #[tokio::test] async fn meta_not_found_returns_error() { let tmp = tempfile::tempdir().unwrap(); @@ -829,3 +932,362 @@ async fn legacy_loader_profile_missing_installer_json_errors() { "expected Parse error about missing installer JSON, got: {err:?}" ); } + +#[tokio::test] +async fn rules_and_natives_directory_follow_the_selected_java_properties() { + for (os, arch, bits, normalized) in [ + ("Windows 10", "x86", "32", "x86"), + ("Windows 10", "amd64", "64", "x86_64"), + ("Mac OS X", "x86_64", "64", "x86_64"), + ("Mac OS X", "aarch64", "64", "arm64"), + ("Linux", "amd64", "64", "x86_64"), + ] { + let platform = rmcl::launch_profile::system::JavaPlatform::from_java_properties( + os, arch, bits, "10.0", + ) + .unwrap(); + let mut meta = modern_vanilla_meta("1.16.5"); + for cpu in ["x86", "x86_64", "arm64"] { + meta["libraries"].as_array_mut().unwrap().push(json!({ + "name":format!("test:only-{cpu}:1"), "rules":[{"action":"allow", "os":{"arch":cpu}}], + })); + } + meta["arguments"]["jvm"] + .as_array_mut() + .unwrap() + .push(json!({ + "rules":[{"action":"allow", "os":{"name":"windows", "version":"^10\\."}}], + "value":["-Dos.name=Windows 10", "-Dos.version=10.0"], + })); + let fixture = Fixture::new("java rules", "1.16.5", meta); + let mut config = make_config("java rules", "1.16.5", ModLoader::Vanilla); + config.java_path = Some(fake_java_platform(&fixture._tmp, 25, &platform)); + let invocation = build_launch_invocation( + &config, + &fixture.instances_dir, + &fixture.meta_dir, + &test_auth(), + None, + ) + .await + .unwrap(); + let cpu_jars: Vec<_> = invocation + .classpath + .iter() + .filter(|path| path.to_string_lossy().contains("only-")) + .collect(); + assert_eq!(cpu_jars.len(), 1); + assert!(cpu_jars[0].ends_with(format!("only-{normalized}-1.jar"))); + assert!(invocation.jvm_args.contains(&format!( + "-Djava.library.path={}", + platform + .natives_directory(&fixture.meta_dir, "1.16.5") + .display() + ))); + assert_eq!( + invocation + .jvm_args + .contains(&"-Dos.version=10.0".to_owned()), + platform.os_name == "windows" + ); + } +} + +fn zip_entries(entries: &[(&str, &[u8])]) -> Vec { + use std::io::Write; + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for (name, bytes) in entries { + zip.start_file(*name, zip::write::SimpleFileOptions::default()) + .unwrap(); + zip.write_all(bytes).unwrap(); + } + zip.finish().unwrap().into_inner() +} + +fn install_test_lwjgl3ify(fixture: &Fixture, base_url: &str) { + use sha1::Digest; + let bytes = b"declared library bytes"; + let mut libraries = Vec::new(); + for module in ["lwjgl", "lwjgl-sdl", "lwjgl-spng"] { + libraries.push(json!({"name":format!("org.lwjgl:{module}:3.4.2"), "downloads":{"artifact":{ + "url":format!("{base_url}/{module}-3.4.2.jar"), "sha1":format!("{:x}", sha1::Sha1::digest(bytes)), "size":bytes.len(), + }}})); + for (classifier, os) in [ + ("natives-linux", "linux"), + ("natives-linux-arm64", "linux"), + ("natives-macos", "osx"), + ("natives-macos-arm64", "osx"), + ("natives-windows", "windows"), + ("natives-windows-x86", "windows"), + ("natives-windows-arm64", "windows"), + ] { + libraries.push( + json!({"name":format!("org.lwjgl:{module}-{classifier}:3.4.2"), + "rules":[{"action":"allow", "os":{"name":os}}], "downloads":{"artifact":{ + "url":format!("{base_url}/{module}-3.4.2-{classifier}.jar"), + "sha1":format!("{:x}", sha1::Sha1::digest(bytes)), "size":bytes.len(), + }}}), + ); + } + } + let payload = zip_entries(&[("META-INF/MANIFEST.MF", b"Manifest-Version: 1.0\r\n")]); + libraries.push(json!({"name":"com.github.GTNewHorizons:lwjgl3ify:3.0.35:forgePatches", "downloads":{"artifact":{ + "url":format!("{base_url}/forgePatches.jar"), "sha1":format!("{:x}", sha1::Sha1::digest(&payload)), "size":payload.len(), + }}})); + let profile = json!({"id":"lwjgl3ify-client", "mainClass":"com.gtnewhorizons.retrofuturabootstrap.MainStartOnFirstThread", + "javaVersion":{"majorVersion":25}, "libraries":libraries, + "arguments":{"game":["--username", "${auth_player_name}", "--tweakClass", "metadata.ClientTweaker"], "jvm":[ + {"rules":[{"action":"allow", "os":{"name":"osx"}}], "value":"-XstartOnFirstThread"}, + "--add-opens", "java.base/java.lang=ALL-UNNAMED", "--enable-native-access", "ALL-UNNAMED", + "-Djava.library.path=${natives_directory}", "-cp", "${classpath}", + "-Djava.system.class.loader=com.gtnewhorizons.retrofuturabootstrap.RfbSystemClassLoader", + ]}, + }); + let mods = fixture.instances_dir.join("patched/minecraft/mods"); + std::fs::create_dir_all(&mods).unwrap(); + std::fs::write( + mods.join("lwjgl3ify-3.0.35.jar"), + zip_entries(&[ + ( + "me/eigenraven/lwjgl3ify/relauncher/version.json", + &serde_json::to_vec(&profile).unwrap(), + ), + ( + "me/eigenraven/lwjgl3ify/relauncher/forgePatches.zip", + &payload, + ), + ]), + ) + .unwrap(); + fixture.write_loader_profile("forge-1.7.10-10.13.4.1614.json", json!({ + "id":"forge-1.7.10", "inheritsFrom":"1.7.10", "mainClass":"net.minecraft.launchwrapper.Launch", + "libraries":[{"name":"net.minecraft:launchwrapper:1.12"}, {"name":"org.lwjgl.lwjgl:lwjgl-platform:2.9.4"}], + "arguments":{"game":["--tweakClass", "old.parent.Tweaker"], "jvm":["-Dold.parent.jvm=true"]}, + })); +} + +#[tokio::test] +async fn lwjgl3ify_empty_cache_downloads_exact_metadata_and_renders_client_startup() { + use wiremock::{Mock, MockServer, ResponseTemplate, matchers::method}; + for (os, arch, bits, classifier) in [ + ("Linux", "amd64", "64", "natives-linux"), + ("Linux", "aarch64", "64", "natives-linux-arm64"), + ("Mac OS X", "amd64", "64", "natives-macos"), + ("Mac OS X", "aarch64", "64", "natives-macos-arm64"), + ("Windows 10", "x86", "32", "natives-windows-x86"), + ("Windows 10", "amd64", "64", "natives-windows"), + ("Windows 10", "aarch64", "64", "natives-windows-arm64"), + ] { + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with( + ResponseTemplate::new(200).set_body_bytes(b"declared library bytes".to_vec()), + ) + .expect(6) + .mount(&server) + .await; + let fixture = Fixture::new("patched", "1.7.10", legacy_vanilla_meta("1.7.10")); + install_test_lwjgl3ify(&fixture, &server.uri()); + let platform = rmcl::launch_profile::system::JavaPlatform::from_java_properties( + os, arch, bits, "10.0", + ) + .unwrap(); + let mut config = + make_config_with("patched", "1.7.10", ModLoader::Forge, Some("10.13.4.1614")); + config.java_path = Some(fake_java_platform(&fixture._tmp, 25, &platform)); + for _ in 0..2 { + let invocation = build_launch_invocation( + &config, + &fixture.instances_dir, + &fixture.meta_dir, + &test_auth(), + None, + ) + .await + .unwrap(); + assert_eq!(invocation.main_class, "RmclShim"); + assert_eq!( + invocation.extra_args, + ["com.gtnewhorizons.retrofuturabootstrap.MainStartOnFirstThread"] + ); + assert_eq!( + invocation + .jvm_args + .contains(&"-XstartOnFirstThread".to_owned()), + platform.os_name == "osx" + ); + assert!( + invocation + .jvm_args + .windows(2) + .any(|args| args == ["--enable-native-access", "ALL-UNNAMED"]) + ); + assert!( + invocation + .jvm_args + .windows(2) + .any(|args| args[0] == "-cp" && args[1] == invocation.classpath_string) + ); + assert!( + invocation + .game_args + .contains(&"metadata.ClientTweaker".to_owned()) + ); + assert!( + !invocation + .game_args + .contains(&"old.parent.Tweaker".to_owned()) + ); + assert!( + !invocation + .jvm_args + .contains(&"-Dold.parent.jvm=true".to_owned()) + ); + assert!(invocation.game_args.contains(&PLAYER.to_owned())); + let natives: Vec<_> = invocation + .classpath + .iter() + .filter(|path| path.to_string_lossy().contains("-natives-")) + .collect(); + assert_eq!(natives.len(), 3); + assert!(natives.iter().all(|path| { + path.to_string_lossy() + .contains(&format!("-{classifier}-3.4.2.jar")) + })); + for path in invocation.classpath.iter().filter(|path| { + path.to_string_lossy().contains("org/lwjgl") + || path.to_string_lossy().contains("org\\lwjgl") + }) { + assert_eq!(std::fs::read(path).unwrap(), b"declared library bytes"); + } + assert!( + !invocation + .classpath + .iter() + .any(|path| path.to_string_lossy().contains("2.9.4") + || path.to_string_lossy().contains("launchwrapper-")) + ); + } + server.verify().await; + } +} + +#[tokio::test] +async fn lwjgl3ify_download_failure_does_not_launch_with_missing_libraries() { + use wiremock::{Mock, MockServer, ResponseTemplate, matchers::method}; + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with(ResponseTemplate::new(404)) + .mount(&server) + .await; + let fixture = Fixture::new("patched", "1.7.10", legacy_vanilla_meta("1.7.10")); + install_test_lwjgl3ify(&fixture, &server.uri()); + let config = make_config_with("patched", "1.7.10", ModLoader::Forge, Some("10.13.4.1614")); + let error = build_launch_invocation( + &config, + &fixture.instances_dir, + &fixture.meta_dir, + &test_auth(), + None, + ) + .await + .unwrap_err(); + assert!(matches!(error, LaunchError::Download(_)), "{error}"); +} + +#[tokio::test] +async fn selected_java_is_resolved_and_probed_in_the_launch_environment_and_cwd() { + let fixture = Fixture::new("context", "1.20.1", modern_vanilla_meta("1.20.1")); + let minecraft = fixture.instances_dir.join("context/minecraft"); + std::fs::write(minecraft.join("expected-cwd"), b"ready").unwrap(); + let bin = fixture._tmp.path().join("custom java bin"); + std::fs::create_dir_all(&bin).unwrap(); + let name = if cfg!(windows) { + "context-java.cmd" + } else { + "context-java" + }; + let java = bin.join(name); + let original = fake_java(&fixture._tmp, 25); + let mut script = std::fs::read_to_string(original).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + script = script.replacen("#!/bin/sh\n", "#!/bin/sh\n[ \"$PROBE_CONTEXT\" = instance ] && [ -f expected-cwd ] || exit 77\nprintf '%s' \"$PROBE_CONTEXT\" > probe-context\n", 1); + std::fs::write(&java, &script).unwrap(); + std::fs::set_permissions(&java, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + #[cfg(windows)] + { + script = script.replacen("@echo off\r\n", "@echo off\r\nif not \"%PROBE_CONTEXT%\"==\"instance\" exit /b 77\r\nif not exist expected-cwd exit /b 78\r\necho %PROBE_CONTEXT%>probe-context\r\n", 1); + std::fs::write(&java, &script).unwrap(); + } + let mut settings = rmcl::config::Config::default(); + settings + .defaults + .environment + .insert("PATH".into(), "missing-global-path".into()); + settings + .defaults + .environment + .insert("PROBE_CONTEXT".into(), "global".into()); + let mut config = make_config("context", "1.20.1", ModLoader::Vanilla); + config.java_path = Some(name.into()); + config.environment.insert( + if cfg!(windows) { "path" } else { "PATH" }.into(), + bin.to_string_lossy().into_owned(), + ); + config.environment.insert( + if cfg!(windows) { + "probe_context" + } else { + "PROBE_CONTEXT" + } + .into(), + "instance".into(), + ); + let invocation = build_launch_invocation_with_settings( + &config, + &fixture.instances_dir, + &fixture.meta_dir, + &test_auth(), + None, + &settings, + ) + .await + .unwrap(); + assert_eq!( + Path::new(&invocation.java).canonicalize().unwrap(), + java.canonicalize().unwrap() + ); + assert_eq!( + std::fs::read_to_string(minecraft.join("probe-context")) + .unwrap() + .trim(), + "instance" + ); + assert_eq!(invocation.working_dir, minecraft); + let cwd = invocation.working_dir.clone(); + let environment = invocation.environment.clone(); + let installation = tokio::task::spawn_blocking(move || { + rmcl::instance::java::inspect_installation_in(Path::new(name), &cwd, &environment) + }) + .await + .unwrap() + .unwrap(); + assert_eq!( + installation.path.canonicalize().unwrap(), + java.canonicalize().unwrap() + ); + assert_eq!(installation.version.as_deref(), Some("25.0.1")); + if cfg!(windows) { + assert_eq!( + invocation + .environment + .keys() + .filter(|key| key.eq_ignore_ascii_case("PATH")) + .count(), + 1 + ); + } +} diff --git a/tests/log_files.rs b/tests/log_files.rs index b0ee3ef..25ff954 100644 --- a/tests/log_files.rs +++ b/tests/log_files.rs @@ -1,10 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// integration tests for the public log files API. -// these tests touch the filesystem and exercise the module as an external -// consumer would. - use std::path::{Path, PathBuf}; use rmcl::instance::logs::files::{create_log_file, log_dir, read_log_file, scan_log_files}; diff --git a/tests/net_loaders.rs b/tests/net_loaders.rs index ac3383c..c20427c 100644 --- a/tests/net_loaders.rs +++ b/tests/net_loaders.rs @@ -1,27 +1,22 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// integration tests for the loader-specific net::* fetchers (forge, -// fabric, quilt, neoforge). each module's fetch_* function now has a -// _from variant that lets the test point the HTTP call at a wiremock -// server; the production constants stay unchanged. - use serde_json::json; use wiremock::matchers::{method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; use rmcl::net::HttpClient; use rmcl::net::fabric::{ - fetch_fabric_game_versions_from, fetch_fabric_profile_from, fetch_fabric_versions_from, + FabricLibrary, FabricProfile, download_fabric_libraries, fetch_fabric_game_versions_from, + fetch_fabric_profile_from, fetch_fabric_versions_from, }; use rmcl::net::forge::{fetch_forge_game_versions_from, fetch_forge_versions_from}; use rmcl::net::neoforge::{fetch_neoforge_game_versions_from, fetch_neoforge_versions_from}; use rmcl::net::quilt::{ - fetch_quilt_game_versions_from, fetch_quilt_profile_from, fetch_quilt_versions_from, + QuiltLibrary, QuiltProfile, download_quilt_libraries, fetch_quilt_game_versions_from, + fetch_quilt_profile_from, fetch_quilt_versions_from, }; -// ---------- forge ---------- - #[tokio::test] async fn forge_fetch_versions_filters_by_prefix() { let server = MockServer::start().await; @@ -67,12 +62,9 @@ async fn forge_fetch_game_versions_extracts_unique() { .expect("forge game versions"); let ids: Vec<&str> = versions.iter().map(|v| v.id.as_str()).collect(); - // dedup + reverse-sort assert_eq!(ids, vec!["1.20.1", "1.19.4"]); } -// ---------- fabric ---------- - #[tokio::test] async fn fabric_fetch_game_versions_parses_response() { let server = MockServer::start().await; @@ -146,8 +138,6 @@ async fn fabric_fetch_profile_parses_libraries() { assert_eq!(profile.libraries[0].url, "https://maven.fabricmc.net/"); } -// ---------- quilt ---------- - #[tokio::test] async fn quilt_fetch_game_versions_parses_response() { let server = MockServer::start().await; @@ -208,7 +198,103 @@ async fn quilt_fetch_profile_parses_libraries() { ); } -// ---------- neoforge ---------- +#[tokio::test] +async fn fabric_and_quilt_download_libraries_into_the_shared_cache() { + let server = MockServer::start().await; + let temp = tempfile::tempdir().unwrap(); + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + use std::io::Write; + zip.start_file( + "META-INF/MANIFEST.MF", + zip::write::SimpleFileOptions::default(), + ) + .unwrap(); + zip.write_all(b"Manifest-Version: 1.0\n").unwrap(); + let jar = zip.finish().unwrap().into_inner(); + for name in ["fabric", "quilt"] { + Mock::given(method("GET")) + .and(path(format!("/example/{name}/1.0/{name}-1.0.jar"))) + .respond_with(ResponseTemplate::new(200).set_body_bytes(jar.clone())) + .expect(1) + .mount(&server) + .await; + } + + let fabric = FabricProfile { + id: "fabric".into(), + main_class: String::new(), + libraries: vec![FabricLibrary { + name: "example:fabric:1.0".into(), + url: server.uri(), + }], + }; + let quilt = QuiltProfile { + id: "quilt".into(), + main_class: String::new(), + libraries: vec![QuiltLibrary { + name: "example:quilt:1.0".into(), + url: server.uri(), + }], + }; + + let client = HttpClient::new(); + download_fabric_libraries(&client, &fabric, temp.path()) + .await + .unwrap(); + download_quilt_libraries(&client, &quilt, temp.path()) + .await + .unwrap(); + download_fabric_libraries(&client, &fabric, temp.path()) + .await + .unwrap(); + for name in ["fabric", "quilt"] { + assert_eq!( + std::fs::read( + rmcl::storage::MetadataPaths::new(temp.path()) + .libraries() + .join(format!("example/{name}/1.0/{name}-1.0.jar")) + ) + .unwrap(), + jar + ); + } +} + +#[tokio::test] +async fn fabric_replaces_a_truncated_cached_library() { + let server = MockServer::start().await; + let temp = tempfile::tempdir().unwrap(); + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + use std::io::Write; + zip.start_file("valid.txt", zip::write::SimpleFileOptions::default()) + .unwrap(); + zip.write_all(b"ok").unwrap(); + let jar = zip.finish().unwrap().into_inner(); + Mock::given(method("GET")) + .and(path("/example/fabric/1.0/fabric-1.0.jar")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(jar.clone())) + .expect(1) + .mount(&server) + .await; + let profile = FabricProfile { + id: "fabric".into(), + main_class: String::new(), + libraries: vec![FabricLibrary { + name: "example:fabric:1.0".into(), + url: server.uri(), + }], + }; + let destination = rmcl::storage::MetadataPaths::new(temp.path()) + .libraries() + .join("example/fabric/1.0/fabric-1.0.jar"); + std::fs::create_dir_all(destination.parent().unwrap()).unwrap(); + std::fs::write(&destination, b"truncated").unwrap(); + + download_fabric_libraries(&HttpClient::new(), &profile, temp.path()) + .await + .unwrap(); + assert_eq!(std::fs::read(destination).unwrap(), jar); +} #[tokio::test] async fn neoforge_fetch_versions_filters_by_prefix() { @@ -292,7 +378,6 @@ async fn neoforge_fetch_game_versions_reverse_engineers_mc_versions() { assert!(ids.contains(&"26.1.1")); assert!(ids.contains(&"1.21")); assert!(ids.contains(&"1.20.4")); - // both versions should be marked stable (no snapshot flag in maven) assert!(versions.iter().all(|v| v.stable)); } @@ -300,7 +385,6 @@ async fn neoforge_fetch_game_versions_reverse_engineers_mc_versions() { async fn neoforge_fetch_versions_rejects_invalid_game_version() { let server = MockServer::start().await; let url = format!("{}/maven-api", server.uri()); - // no mock - the function should error out before hitting the network let err = fetch_neoforge_versions_from(&HttpClient::new(), &url, "bogus") .await .expect_err("invalid game version"); diff --git a/tests/net_mojang.rs b/tests/net_mojang.rs index 4882640..25f450f 100644 --- a/tests/net_mojang.rs +++ b/tests/net_mojang.rs @@ -1,12 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// integration tests for the public mojang fetchers. wiremock stands in for -// Mojang so tests are fast, deterministic, and don't depend on the live -// endpoint. these are different from the #[ignore = "hits live Mojang API"] -// tests in tests/live_apis.rs which verify the upstream schema hasn't drifted; -// these here verify our parsing + retry envelope on synthetic responses. - use serde_json::json; use wiremock::matchers::{method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; @@ -14,10 +8,41 @@ use wiremock::{Mock, MockServer, ResponseTemplate}; use rmcl::net::HttpClient; use rmcl::net::mojang::{ Artifact, AssetIndex, Download, JavaVersion, Library, LibraryDownloads, VersionDownloads, - VersionEntry, VersionMeta, download_assets, download_assets_from, download_libraries, - fetch_version_manifest_from, fetch_version_meta_with_raw, + VersionEntry, VersionMeta, download_assets, download_assets_from, + download_libraries_for_platform, fetch_version_manifest_from, fetch_version_meta_with_raw, }; +fn test_platform() -> rmcl::launch_profile::system::JavaPlatform { + rmcl::launch_profile::system::JavaPlatform::from_java_properties( + match std::env::consts::OS { + "windows" => "Windows 10", + "macos" => "Mac OS X", + _ => "Linux", + }, + std::env::consts::ARCH, + if cfg!(target_pointer_width = "64") { + "64" + } else { + "32" + }, + "10.0", + ) + .unwrap() +} + +async fn download_libraries( + client: &HttpClient, + meta: &VersionMeta, + meta_dir: &std::path::Path, +) -> Result<(), rmcl::net::NetError> { + download_libraries_for_platform(client, meta, meta_dir, &test_platform()).await +} + +fn sha1(bytes: &[u8]) -> String { + use sha1::Digest; + format!("{:x}", sha1::Sha1::digest(bytes)) +} + fn synthetic_manifest() -> serde_json::Value { json!({ "latest": { "release": "1.20.1", "snapshot": "24w01a" }, @@ -85,12 +110,10 @@ async fn fetch_version_manifest_parses_synthetic_response() { async fn fetch_version_meta_returns_struct_and_raw_bytes() { let server = MockServer::start().await; let body_json = synthetic_version_meta(); - // serialise once so we can assert the raw bytes equal what the mock - // actually sent (wiremock re-serialises the json, so we have to match - // its output format) + let body = serde_json::to_vec(&body_json).unwrap(); Mock::given(method("GET")) .and(path("/1.20.1.json")) - .respond_with(ResponseTemplate::new(200).set_body_json(body_json.clone())) + .respond_with(ResponseTemplate::new(200).set_body_bytes(body.clone())) .expect(1) .mount(&server) .await; @@ -99,7 +122,7 @@ async fn fetch_version_meta_returns_struct_and_raw_bytes() { id: "1.20.1".to_string(), version_type: "release".to_string(), url: format!("{}/1.20.1.json", server.uri()), - sha1: "0".repeat(40), + sha1: sha1(&body), }; let (meta, raw) = fetch_version_meta_with_raw(&HttpClient::new(), &entry) @@ -112,13 +135,32 @@ async fn fetch_version_meta_returns_struct_and_raw_bytes() { assert_eq!(meta.downloads.client.size, 12345); assert_eq!(meta.java_version.unwrap().major_version, 17); - // the raw bytes must parse back to the same struct - verifies the - // get_json_with_raw plumbing actually captures the upstream body intact. let reparsed: serde_json::Value = serde_json::from_slice(&raw).expect("raw is json"); assert_eq!(reparsed["id"], "1.20.1"); assert_eq!(reparsed["mainClass"], "net.minecraft.client.main.Main"); } +#[tokio::test] +async fn version_metadata_rejects_a_wrong_manifest_hash() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/version.json")) + .respond_with(ResponseTemplate::new(200).set_body_json(synthetic_version_meta())) + .mount(&server) + .await; + let entry = VersionEntry { + id: "1.20.1".to_owned(), + version_type: "release".to_owned(), + url: format!("{}/version.json", server.uri()), + sha1: "0".repeat(40), + }; + assert!( + fetch_version_meta_with_raw(&HttpClient::new(), &entry) + .await + .is_err() + ); +} + // constructs a minimal VersionMeta with a single library pointing at the // wiremock server. lets download_libraries hit synthetic URLs without any // production-side URL override. @@ -144,8 +186,8 @@ fn meta_with_one_library(server_uri: &str) -> VersionMeta { artifact: Some(Artifact { url: format!("{server_uri}/slf4j.jar"), path: "org/slf4j/slf4j-api/2.0.7/slf4j-api-2.0.7.jar".to_string(), - sha1: "0".repeat(40), - size: 11, + sha1: sha1(b"jar-bytes"), + size: b"jar-bytes".len() as u64, }), classifiers: None, }, @@ -214,7 +256,6 @@ async fn download_libraries_skips_when_destination_exists() { .await .expect("noop succeeds"); - // file untouched, mock untouched (server drop will panic if it isn't) assert_eq!(std::fs::read(&existing).unwrap(), b"already there"); } @@ -230,7 +271,10 @@ async fn download_libraries_redownloads_corrupted_cache() { .mount(&server) .await; - let meta = meta_with_one_library(&server.uri()); + let mut meta = meta_with_one_library(&server.uri()); + let artifact = meta.libraries[0].downloads.artifact.as_mut().unwrap(); + artifact.sha1 = sha1(b"fresh-bytes"); + artifact.size = b"fresh-bytes".len() as u64; let tmp = tempfile::tempdir().unwrap(); let existing = tmp .path() @@ -246,33 +290,63 @@ async fn download_libraries_redownloads_corrupted_cache() { } #[tokio::test] -async fn download_assets_from_writes_index_and_assets() { - // exercises the full path: index fetch + write, then per-asset download - // from the configurable assets base. uses download_assets_from so the - // hardcoded ASSETS_BASE_URL stays out of the way. +async fn library_rejects_wrong_download_bytes_and_unsafe_paths() { let server = MockServer::start().await; Mock::given(method("GET")) - .and(path("/assets/index.json")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "objects": { - "minecraft/lang/en_us.json": { - "hash": "ab1234567890abcdef1234567890abcdef123456", - "size": 11 - } - } - }))) + .and(path("/slf4j.jar")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"wrong".to_vec())) .expect(1) .mount(&server) .await; - // asset hash starts with "ab" so the per-asset URL is //ab/. + let mut meta = meta_with_one_library(&server.uri()); + let temp = tempfile::tempdir().unwrap(); + let library = temp + .path() + .join("cache/minecraft/libraries/org/slf4j/slf4j-api/2.0.7/slf4j-api-2.0.7.jar"); + assert!( + download_libraries(&HttpClient::new(), &meta, temp.path()) + .await + .is_err() + ); + assert!(!library.exists()); + + meta.libraries[0].downloads.artifact.as_mut().unwrap().path = + "../../../../escape.jar".to_owned(); + assert!( + download_libraries(&HttpClient::new(), &meta, temp.path()) + .await + .is_err() + ); + assert!(!temp.path().join("escape.jar").exists()); +} + +#[tokio::test] +async fn download_assets_from_writes_index_and_assets() { + let server = MockServer::start().await; + let hash = sha1(b"asset-bytes"); + let index = serde_json::to_vec(&json!({ + "virtual": true, + "objects": { + "minecraft/lang/en_us.json": {"hash": hash, "size": b"asset-bytes".len()}, + "lang/en_us.lang": {"hash": hash, "size": b"asset-bytes".len()} + } + })) + .unwrap(); Mock::given(method("GET")) - .and(path("/cdn/ab/ab1234567890abcdef1234567890abcdef123456")) + .and(path("/assets/index.json")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(index.clone())) + .expect(1) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path(format!("/cdn/{}/{}", &hash[..2], hash))) .respond_with(ResponseTemplate::new(200).set_body_bytes(b"asset-bytes".to_vec())) .expect(1) .mount(&server) .await; - let meta = meta_with_one_library(&server.uri()); + let mut meta = meta_with_one_library(&server.uri()); + meta.asset_index.sha1 = sha1(&index); let tmp = tempfile::tempdir().unwrap(); let cdn_base = format!("{}/cdn", server.uri()); @@ -284,9 +358,25 @@ async fn download_assets_from_writes_index_and_assets() { assert!(index_path.exists(), "index file missing"); let asset_path = tmp .path() - .join("cache/minecraft/assets/objects/ab/ab1234567890abcdef1234567890abcdef123456"); + .join("cache/minecraft/assets/objects") + .join(&hash[..2]) + .join(&hash); assert!(asset_path.exists(), "asset file missing"); assert_eq!(std::fs::read(&asset_path).unwrap(), b"asset-bytes"); + for name in ["minecraft/lang/en_us.json", "lang/en_us.lang"] { + assert_eq!( + std::fs::read( + tmp.path() + .join("cache/minecraft/assets/virtual/5") + .join(name) + ) + .unwrap(), + b"asset-bytes" + ); + } + download_assets_from(&HttpClient::new(), &meta, tmp.path(), &cdn_base) + .await + .unwrap(); } #[tokio::test] @@ -295,14 +385,16 @@ async fn download_assets_writes_index_when_objects_is_empty() { // path without triggering individual asset downloads (which go to the // hardcoded ASSETS_BASE_URL and can't be wiremocked here). let server = MockServer::start().await; + let index = serde_json::to_vec(&json!({"objects": {}})).unwrap(); Mock::given(method("GET")) .and(path("/assets/index.json")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({"objects": {}}))) + .respond_with(ResponseTemplate::new(200).set_body_bytes(index.clone())) .expect(1) .mount(&server) .await; - let meta = meta_with_one_library(&server.uri()); + let mut meta = meta_with_one_library(&server.uri()); + meta.asset_index.sha1 = sha1(&index); let tmp = tempfile::tempdir().unwrap(); download_assets(&HttpClient::new(), &meta, tmp.path()) @@ -319,6 +411,93 @@ async fn download_assets_writes_index_when_objects_is_empty() { assert!(body.get("objects").is_some()); } +#[tokio::test] +async fn invalid_cached_index_is_refetched() { + let server = MockServer::start().await; + let body = serde_json::to_vec(&json!({"objects": {}})).unwrap(); + Mock::given(method("GET")) + .and(path("/assets/index.json")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(body.clone())) + .expect(1) + .mount(&server) + .await; + let mut meta = meta_with_one_library(&server.uri()); + meta.asset_index.sha1 = sha1(&body); + let tmp = tempfile::tempdir().unwrap(); + let index_path = tmp.path().join("cache/minecraft/assets/indexes/5.json"); + std::fs::create_dir_all(index_path.parent().unwrap()).unwrap(); + std::fs::write(&index_path, b"{\"objects\":{\"fake\":{}}}").unwrap(); + + download_assets(&HttpClient::new(), &meta, tmp.path()) + .await + .unwrap(); + assert_eq!(std::fs::read(index_path).unwrap(), body); +} + +#[tokio::test] +async fn invalid_asset_hash_returns_an_error_without_escaping_or_panicking() { + let server = MockServer::start().await; + let body = + serde_json::to_vec(&json!({"objects": {"bad": {"hash": "aé/../escape", "size": 1}}})) + .unwrap(); + let mut meta = meta_with_one_library(&server.uri()); + meta.asset_index.sha1 = sha1(&body); + let tmp = tempfile::tempdir().unwrap(); + let index_path = tmp.path().join("cache/minecraft/assets/indexes/5.json"); + std::fs::create_dir_all(index_path.parent().unwrap()).unwrap(); + std::fs::write(&index_path, body).unwrap(); + + assert!( + download_assets(&HttpClient::new(), &meta, tmp.path()) + .await + .is_err() + ); + assert!(!tmp.path().join("escape").exists()); + meta.asset_index.id = "../outside".to_owned(); + assert!( + download_assets(&HttpClient::new(), &meta, tmp.path()) + .await + .is_err() + ); +} + +#[tokio::test] +async fn downloaded_asset_must_match_index_hash_and_size() { + let server = MockServer::start().await; + let hash = sha1(b"expected"); + let body = serde_json::to_vec(&json!({"objects": {"one": {"hash": hash, "size": 8}}})).unwrap(); + Mock::given(method("GET")) + .and(path("/assets/index.json")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(body.clone())) + .mount(&server) + .await; + Mock::given(method("GET")) + .and(path(format!("/cdn/{}/{}", &hash[..2], hash))) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"bad bytes".to_vec())) + .mount(&server) + .await; + let mut meta = meta_with_one_library(&server.uri()); + meta.asset_index.sha1 = sha1(&body); + let tmp = tempfile::tempdir().unwrap(); + let asset = tmp + .path() + .join("cache/minecraft/assets/objects") + .join(&hash[..2]) + .join(&hash); + + assert!( + download_assets_from( + &HttpClient::new(), + &meta, + tmp.path(), + &format!("{}/cdn", server.uri()) + ) + .await + .is_err() + ); + assert!(!asset.exists()); +} + #[tokio::test] async fn download_libraries_downloads_and_extracts_natives() { // pre-1.13-era library: no artifact, only a natives classifier for the @@ -372,7 +551,14 @@ async fn download_libraries_downloads_and_extracts_natives() { downloads: LibraryDownloads { artifact: None, classifiers: Some(std::collections::HashMap::from([( - "natives-linux".to_string(), + format!( + "natives-linux-{}", + if cfg!(target_pointer_width = "64") { + "64" + } else { + "32" + } + ), Artifact { url: format!("{server_uri}/lwjgl-natives.jar"), path: "org/lwjgl/lwjgl/lwjgl/2.9.4/lwjgl-2.9.4-natives-linux.jar" @@ -385,7 +571,7 @@ async fn download_libraries_downloads_and_extracts_natives() { rules: None, natives: Some(std::collections::HashMap::from([( rmcl::launch_profile::system::mojang_os_name().to_string(), - "natives-linux".to_string(), + "natives-linux-${arch}".to_string(), )])), extract: Some(rmcl::net::mojang::LibraryExtract { exclude: Some(vec!["META-INF/".to_string()]), @@ -404,18 +590,151 @@ async fn download_libraries_downloads_and_extracts_natives() { ); assert_eq!(std::fs::read(&cached_jar).unwrap(), jar_bytes); - let extracted = tmp - .path() - .join("cache/minecraft/versions/test/natives/lib/native.so"); + let natives = test_platform().natives_directory(tmp.path(), "test"); + let extracted = natives.join("lib/native.so"); assert_eq!( std::fs::read(&extracted).unwrap(), b"native-bits", "natives payload must be unpacked next to java.library.path" ); + let original_permissions = std::fs::metadata(&extracted).unwrap().permissions(); + let modified = std::fs::metadata(&extracted).unwrap().modified().unwrap(); + let mut protected = original_permissions.clone(); + protected.set_readonly(true); + std::fs::set_permissions(&extracted, protected).unwrap(); + let reuse = download_libraries(&HttpClient::new(), &meta, tmp.path()).await; + std::fs::set_permissions(&extracted, original_permissions).unwrap(); + reuse.expect("unchanged natives must be reusable without replacing a protected/loaded library"); + assert_eq!( + std::fs::metadata(&extracted).unwrap().modified().unwrap(), + modified + ); + std::fs::write(&extracted, b"corrupted extraction").unwrap(); + download_libraries(&HttpClient::new(), &meta, tmp.path()) + .await + .unwrap(); + assert_eq!(std::fs::read(&extracted).unwrap(), b"native-bits"); assert!( - !tmp.path() - .join("cache/minecraft/versions/test/natives/META-INF") - .exists(), + !natives.join("META-INF").exists(), "extract.exclude prefixes must be skipped" ); } + +fn native_zip(payload: &[u8]) -> Vec { + use std::io::Write; + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + zip.start_file("native.dll", zip::write::SimpleFileOptions::default()) + .unwrap(); + zip.write_all(payload).unwrap(); + zip.finish().unwrap().into_inner() +} + +#[tokio::test] +async fn selected_java_bitness_controls_downloads_and_extraction_is_isolated() { + let server = MockServer::start().await; + let mut classifiers = serde_json::Map::new(); + for bits in [32, 64] { + let bytes = native_zip(bits.to_string().as_bytes()); + let url = format!("/native-{bits}.jar"); + Mock::given(method("GET")) + .and(path(&url)) + .respond_with(ResponseTemplate::new(200).set_body_bytes(bytes.clone())) + .expect(1) + .mount(&server) + .await; + classifiers.insert( + format!("natives-windows-{bits}"), + json!({ + "url":format!("{}{url}", server.uri()), "sha1":sha1(&bytes), "size":bytes.len(), + }), + ); + } + let mut meta = meta_with_one_library(&server.uri()); + meta.libraries = serde_json::from_value(json!([{ + "name":"tv.twitch:twitch-platform:5.16", "downloads":{"classifiers":classifiers}, + "natives":{"windows":"natives-windows-${arch}"}, + "rules":[{"action":"allow", "os":{"name":"windows", "version":"^10\\."}}], + }])) + .unwrap(); + let temp = tempfile::tempdir().unwrap(); + for (arch, bits) in [("x86", "32"), ("amd64", "64")] { + let platform = rmcl::launch_profile::system::JavaPlatform::from_java_properties( + "Windows 10", + arch, + bits, + "10.0", + ) + .unwrap(); + download_libraries_for_platform(&HttpClient::new(), &meta, temp.path(), &platform) + .await + .unwrap(); + let natives = platform.natives_directory(temp.path(), &meta.id); + assert_eq!( + std::fs::read(natives.join("native.dll")).unwrap(), + bits.as_bytes() + ); + } + // The second extraction must leave the first architecture's payload intact. + let java32 = rmcl::launch_profile::system::JavaPlatform::from_java_properties( + "Windows 10", + "x86", + "32", + "10.0", + ) + .unwrap(); + assert_eq!( + std::fs::read( + java32 + .natives_directory(temp.path(), &meta.id) + .join("native.dll") + ) + .unwrap(), + b"32" + ); + assert!( + !temp + .path() + .join("cache/minecraft/versions") + .join(&meta.id) + .join("natives/native.dll") + .exists() + ); + let old_windows = rmcl::launch_profile::system::JavaPlatform::from_java_properties( + "Windows 7", + "x86", + "32", + "6.1", + ) + .unwrap(); + let other = tempfile::tempdir().unwrap(); + download_libraries_for_platform(&HttpClient::new(), &meta, other.path(), &old_windows) + .await + .unwrap(); + assert!( + !old_windows + .natives_directory(other.path(), &meta.id) + .exists() + ); +} + +#[tokio::test] +async fn missing_selected_native_classifier_is_reported() { + let mut meta = meta_with_one_library("https://example.invalid"); + meta.libraries = serde_json::from_value(json!([{ + "name":"tv.twitch:twitch-platform:5.16", "downloads":{"classifiers":{}}, + "natives":{"windows":"natives-windows-${arch}"}, + }])) + .unwrap(); + let java32 = rmcl::launch_profile::system::JavaPlatform::from_java_properties( + "Windows 10", + "x86", + "32", + "10.0", + ) + .unwrap(); + let temp = tempfile::tempdir().unwrap(); + let error = download_libraries_for_platform(&HttpClient::new(), &meta, temp.path(), &java32) + .await + .unwrap_err(); + assert!(error.to_string().contains("natives-windows-32")); +} diff --git a/tests/net_retry.rs b/tests/net_retry.rs index 148c706..31ba676 100644 --- a/tests/net_retry.rs +++ b/tests/net_retry.rs @@ -1,12 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// integration tests for the retry envelope in src/net/mod.rs. wiremock -// stands in for live upstream APIs so we can assert that 5xx responses -// retry, 4xx responses fail fast, and the cap (MAX_RETRIES = 3, total -// 4 attempts) is honoured. these tests exercise public HttpClient methods, -// not the private retry helper directly. -// // Tokio time is paused in retrying tests so the production backoff remains // covered without adding wall-clock delay to the suite. @@ -32,14 +26,11 @@ fn client_without_timeout() -> HttpClient { reqwest::Client::builder().build().unwrap().into() } -// ---------- get_json (via get_with_retry) ---------- - #[tokio::test(start_paused = true)] async fn get_json_retries_5xx_then_succeeds() { let server = MockServer::start().await; let attempts = Arc::new(AtomicUsize::new(0)); - // first request: 503. second request: 200. Mock::given(method("GET")) .and(path("/api")) .respond_with(move |_: &wiremock::Request| { @@ -58,12 +49,34 @@ async fn get_json_retries_5xx_then_succeeds() { assert!(result.ok); } +#[tokio::test(start_paused = true)] +async fn get_json_retries_rate_limit() { + let server = MockServer::start().await; + let attempts = Arc::new(AtomicUsize::new(0)); + Mock::given(method("GET")) + .and(path("/limited")) + .respond_with(move |_: &wiremock::Request| { + if attempts.fetch_add(1, Ordering::SeqCst) == 0 { + ResponseTemplate::new(429) + } else { + ResponseTemplate::new(200).set_body_json(json!({"ok": true})) + } + }) + .expect(2) + .mount(&server) + .await; + + let result: ApiResponse = client_without_timeout() + .get_json(&format!("{}/limited", server.uri())) + .await + .unwrap(); + assert!(result.ok); +} + #[tokio::test] async fn get_json_fails_fast_on_4xx() { let server = MockServer::start().await; - // expect(1) makes wiremock panic on drop if the mock matches more than - // once. that's how we assert "no retries" without watching the clock. Mock::given(method("GET")) .and(path("/api")) .respond_with(ResponseTemplate::new(404)) @@ -86,8 +99,6 @@ async fn get_json_fails_fast_on_4xx() { async fn get_json_gives_up_after_max_retries() { let server = MockServer::start().await; - // MAX_RETRIES = 3 means we expect exactly 4 attempts before giving up. - // expect(4) asserts that. Mock::given(method("GET")) .and(path("/api")) .respond_with(ResponseTemplate::new(503)) @@ -124,8 +135,6 @@ async fn get_bytes_limited_rejects_oversized_responses() { assert!(error.to_string().contains("8-byte limit")); } -// ---------- download_file ---------- - #[tokio::test(start_paused = true)] async fn download_file_retries_5xx_then_succeeds() { let server = MockServer::start().await; @@ -179,3 +188,112 @@ async fn download_file_fails_fast_on_4xx() { "expected 404 in error, got: {err:?}" ); } + +#[tokio::test] +async fn cancelled_downloads_preserve_the_destination_and_remove_all_staging_files() { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + for verified in [false, true] { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut connection, _) = listener.accept().await.unwrap(); + let mut request = [0; 4096]; + assert!(connection.read(&mut request).await.unwrap() > 0); + connection + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\nConnection: close\r\n\r\nx") + .await + .unwrap(); + std::future::pending::<()>().await; + }); + let temp = tempfile::tempdir().unwrap(); + let destination = temp.path().join("content.jar"); + std::fs::write(&destination, b"original").unwrap(); + let directory = temp.path().to_owned(); + let target = destination.clone(); + let download = tokio::spawn(async move { + let client = client_without_timeout(); + let url = format!("http://{address}/content.jar"); + if verified { + let version = serde_json::from_value(json!({ + "id": "version", "name": "Version", "version_number": "1", + "game_versions": [], "loaders": [], + "files": [{"url": url, "filename": "content.jar", "size": 100, "primary": true}] + })) + .unwrap(); + rmcl::net::modrinth::download_version_file_for_update( + &client, &version, &directory, &target, + ) + .await + .map(|_| ()) + } else { + download_file(&client, &url, &target, |_, _| {}).await + } + }); + tokio::time::timeout(std::time::Duration::from_secs(5), async { + loop { + if std::fs::read_dir(temp.path()).unwrap().any(|entry| { + let entry = entry.unwrap(); + // Windows directory metadata can lag writes to an open file. + entry.path() != destination + && std::fs::File::open(entry.path()).is_ok_and(|mut file| { + matches!(std::io::Read::read(&mut file, &mut [0]), Ok(1)) + }) + }) { + break; + } + assert!( + !download.is_finished(), + "download finished before cancellation" + ); + tokio::time::sleep(std::time::Duration::from_millis(5)).await; + } + }) + .await + .unwrap(); + download.abort(); + assert!(download.await.unwrap_err().is_cancelled()); + server.abort(); + assert!(server.await.unwrap_err().is_cancelled()); + assert_eq!(std::fs::read(&destination).unwrap(), b"original"); + assert_eq!( + std::fs::read_dir(temp.path()).unwrap().count(), + 1, + "verified={verified}" + ); + } +} + +#[tokio::test] +async fn flowing_downloads_can_take_longer_than_thirty_seconds() { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (mut connection, _) = listener.accept().await.unwrap(); + let mut request = [0; 4096]; + assert!(connection.read(&mut request).await.unwrap() > 0); + connection + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 8\r\nConnection: close\r\n\r\nx") + .await + .unwrap(); + for _ in 0..7 { + tokio::time::sleep(std::time::Duration::from_millis(4500)).await; + if connection.write_all(b"x").await.is_err() { + break; + } + } + }); + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("slow.bin"); + let result = download_file( + &HttpClient::new(), + &format!("http://{address}/slow"), + &path, + |_, _| {}, + ) + .await; + server.await.unwrap(); + result.unwrap(); + assert_eq!(std::fs::read(path).unwrap(), b"xxxxxxxx"); +} diff --git a/tests/screenshots.rs b/tests/screenshots.rs index 8235a20..bd26faf 100644 --- a/tests/screenshots.rs +++ b/tests/screenshots.rs @@ -1,8 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// integration tests for the public scan_screenshots API. - use std::path::{Path, PathBuf}; use rmcl::instance::screenshots::scan_screenshots;