From 783fb76f06e24338342b24c3dafc8471791a58ca Mon Sep 17 00:00:00 2001 From: objz Date: Thu, 1 Oct 2026 13:53:12 +0200 Subject: [PATCH 01/34] style: remove redundant code narration --- .github/workflows/build-release.yml | 34 ---------------- build.rs | 2 - cliff.toml | 39 +------------------ dist-workspace.toml | 13 ------- src/auth/accounts.rs | 2 - src/auth/mod.rs | 1 - src/auth/oauth.rs | 6 --- src/cli/account.rs | 3 -- src/cli/content.rs | 3 -- src/cli/import.rs | 2 - src/cli/instance.rs | 2 - src/cli/log.rs | 2 - src/cli/mod.rs | 5 --- src/cli/output.rs | 3 -- src/cli/utils.rs | 1 - src/cli/version.rs | 3 -- src/config/mod.rs | 4 -- src/config/settings.rs | 4 -- src/config/theme.rs | 6 --- src/feedback/errors.rs | 4 -- src/feedback/mod.rs | 2 - src/feedback/progress.rs | 3 -- src/instance/content/datapacks.rs | 2 - src/instance/content/entry.rs | 1 - src/instance/content/icons.rs | 3 -- src/instance/content/mod.rs | 4 -- src/instance/content/mods.rs | 14 ------- src/instance/content/packs.rs | 2 - src/instance/content/resource_packs.rs | 2 - src/instance/content/shaders.rs | 2 - src/instance/content/worlds.rs | 5 --- src/instance/desktop.rs | 5 --- src/instance/import/mmc.rs | 6 --- src/instance/import/mod.rs | 8 ---- src/instance/import/mrpack.rs | 7 ---- src/instance/java.rs | 2 - src/instance/launch/mod.rs | 25 +----------- src/instance/launch/parser.rs | 2 - src/instance/launch/patches.rs | 19 ++------- src/instance/loader/fabric.rs | 3 -- src/instance/loader/forge.rs | 9 +---- src/instance/loader/maven.rs | 2 - src/instance/loader/mod.rs | 8 +--- src/instance/loader/neoforge.rs | 3 -- src/instance/loader/quilt.rs | 3 -- src/instance/logs/files.rs | 4 -- src/instance/logs/live.rs | 4 -- src/instance/manager.rs | 4 -- src/instance/mod.rs | 3 -- src/instance/models.rs | 3 -- src/instance/runtime.rs | 4 -- src/instance/screenshots.rs | 4 -- src/instance/tests/content/resource_packs.rs | 1 - src/instance/tests/import/mmc.rs | 8 ---- src/instance/tests/launch/patches.rs | 5 --- src/instance/tests/runtime.rs | 8 ---- src/launch_profile/mod.rs | 5 --- src/launch_profile/model.rs | 8 +--- src/launch_profile/render.rs | 6 --- src/launch_profile/resolve.rs | 12 ------ src/launch_profile/rules.rs | 5 --- src/launch_profile/system.rs | 3 +- src/launch_profile/templates.rs | 11 +----- src/launch_profile/tests/model.rs | 3 -- src/launch_profile/tests/render.rs | 3 -- src/launch_profile/tests/resolve.rs | 11 ------ src/launch_profile/tests/rules.rs | 4 -- src/lib.rs | 6 --- src/net/curseforge.rs | 3 -- src/net/fabric.rs | 8 ---- src/net/forge.rs | 9 ----- src/net/mod.rs | 11 +----- src/net/modrinth.rs | 2 - src/net/mojang.rs | 25 +----------- src/net/neoforge.rs | 12 ------ src/net/quilt.rs | 5 --- src/tui/app.rs | 8 ---- src/tui/event.rs | 9 ----- src/tui/input.rs | 11 ------ src/tui/logging.rs | 10 ----- src/tui/mod.rs | 2 - src/tui/render.rs | 12 ------ src/tui/tests/widgets/content/discovery.rs | 2 - src/tui/tests/widgets/search.rs | 2 - src/tui/widgets/account.rs | 7 ---- src/tui/widgets/content/list.rs | 27 ------------- src/tui/widgets/content/mod.rs | 2 - src/tui/widgets/content/tabs.rs | 8 ---- src/tui/widgets/instances.rs | 4 -- src/tui/widgets/logs_viewer.rs | 8 ---- src/tui/widgets/mod.rs | 2 - src/tui/widgets/popups/base.rs | 5 --- src/tui/widgets/popups/confirm.rs | 3 -- src/tui/widgets/popups/error.rs | 5 --- src/tui/widgets/popups/global_settings.rs | 2 - .../widgets/popups/import_modpack/render.rs | 3 -- .../widgets/popups/import_modpack/state.rs | 9 ----- src/tui/widgets/popups/instance_settings.rs | 2 - src/tui/widgets/popups/mod.rs | 5 --- src/tui/widgets/popups/new_instance/render.rs | 5 --- src/tui/widgets/popups/new_instance/state.rs | 17 ++------ src/tui/widgets/popups/select_list.rs | 2 - src/tui/widgets/popups/settings_controls.rs | 2 - src/tui/widgets/popups/version_lists.rs | 2 - src/tui/widgets/screenshots_grid.rs | 10 +---- src/tui/widgets/search.rs | 6 --- src/tui/widgets/settings.rs | 3 -- src/tui/widgets/status.rs | 3 -- tests/content_scanners.rs | 5 --- tests/launch_pipeline.rs | 39 ------------------- tests/log_files.rs | 4 -- tests/net_loaders.rs | 16 -------- tests/net_mojang.rs | 9 ----- tests/net_retry.rs | 11 ------ tests/screenshots.rs | 2 - 115 files changed, 19 insertions(+), 746 deletions(-) diff --git a/.github/workflows/build-release.yml b/.github/workflows/build-release.yml index bea0f88..bbde2c9 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: @@ -330,7 +300,6 @@ jobs: persist-credentials: true repository: ${{ env.HOMEBREW_TAP_REPOSITORY }} token: ${{ secrets.HOMEBREW_TAP_TOKEN }} - # So we have access to the formula - name: Fetch homebrew formulae uses: actions/download-artifact@v7 with: @@ -379,7 +348,6 @@ jobs: plan: ${{ needs.plan.outputs.val }} dry_run: false secrets: inherit - # publish jobs get escalated permissions permissions: "contents": "read" @@ -392,7 +360,6 @@ jobs: with: plan: ${{ needs.plan.outputs.val }} secrets: inherit - # publish jobs get escalated permissions permissions: "contents": "read" @@ -405,7 +372,6 @@ jobs: with: plan: ${{ needs.plan.outputs.val }} secrets: inherit - # publish jobs get escalated permissions permissions: "contents": "write" diff --git a/build.rs b/build.rs index 957ee58..a0e9529 100644 --- a/build.rs +++ b/build.rs @@ -11,7 +11,6 @@ fn main() { let out_dir = env::var("OUT_DIR").unwrap(); let out = Path::new(&out_dir); - // compile RmclShim.java into a jar that gets embedded via include_bytes! let status = Command::new("javac") .arg("-source") .arg("8") @@ -25,7 +24,6 @@ fn main() { assert!(status.success(), "javac failed to compile RmclShim.java"); - // package into a jar let jar_path = out.join("rmcl-shim.jar"); let status = Command::new("jar") .arg("cfe") diff --git a/cliff.toml b/cliff.toml index 98becde..e7f6e20 100644 --- a/cliff.toml +++ b/cliff.toml @@ -1,14 +1,8 @@ -# git-cliff ~ configuration file -# https://git-cliff.org/docs/configuration - - [remote.github] owner = "objz" repo = "rmcl" [changelog] -# A Tera template to be rendered for each release in the changelog. -# See https://keats.github.io/tera/docs/#introduction body = """ {% if version %}\ ## {{ version | trim_start_matches(pat="v") }} - {{ timestamp | date(format="%Y-%m-%d") }} @@ -32,41 +26,19 @@ body = """ {% endfor %} {% endif %} """ -# Remove leading and trailing whitespaces from the changelog's body. trim = true -# Render body even when there are no releases to process. render_always = true -# An array of regex based postprocessors to modify the changelog. -postprocessors = [ - # Replace the placeholder with a URL. - #{ pattern = '', replace = "https://github.com/orhun/git-cliff" }, -] -# render body even when there are no releases to process -# render_always = true -# output file path -# output = "test.md" +postprocessors = [] [git] -# Parse commits according to the conventional commits specification. -# See https://www.conventionalcommits.org conventional_commits = true -# Exclude commits that do not match the conventional commits specification. filter_unconventional = false -# Require all commits to be conventional. -# Takes precedence over filter_unconventional. require_conventional = false -# Split commits on newlines, treating each line as an individual commit. split_commits = false -# An array of regex based parsers to modify commit messages prior to further processing. commit_preprocessors = [ - # Replace issue numbers in commit messages with links. { pattern = '\((\w+\s)?#([0-9]+)\)', replace = "([#${2}](https://github.com/objz/rmcl/issues/${2}))" }, ] -# Prevent commits that are breaking from being excluded by commit parsers. protect_breaking_commits = false -# An array of regex based parsers for extracting data from the commit message. -# Assigns commits to groups. -# Optionally sets the commit's scope and can decide to exclude commits from further processing. commit_parsers = [ { message = "^feat", group = "features" }, { message = "^fix", group = "bug fixes" }, @@ -84,20 +56,11 @@ commit_parsers = [ { message = "^revert", group = "reverts" }, { message = ".*", group = "other changes" }, ] -# Exclude commits that are not matched by any commit parser. filter_commits = false -# Fail on a commit that is not matched by any commit parser. fail_on_unmatched_commit = false -# An array of link parsers for extracting external references, and turning them into URLs, using regex. link_parsers = [] -# Include only the tags that belong to the current branch. use_branch_tags = false -# Order releases topologically instead of chronologically. topo_order = false -# Order commits topologically instead of chronologically. topo_order_commits = true -# Order of commits in each group/release within the changelog. -# Allowed values: newest, oldest sort_commits = "oldest" -# Process submodules commits recurse_submodules = false diff --git a/dist-workspace.toml b/dist-workspace.toml index 4561c87..bdbc3ca 100644 --- a/dist-workspace.toml +++ b/dist-workspace.toml @@ -1,29 +1,16 @@ [workspace] members = ["cargo:."] -# Config for 'dist' [dist] -# The preferred dist version to use in CI (Cargo.toml SemVer syntax) cargo-dist-version = "0.31.0" -# CI backends to support ci = "github" -# The installers to generate for each app installers = ["homebrew", "msi"] -# A GitHub repo to push Homebrew formulas to tap = "objz/homebrew-tap" -# Target platforms to build apps for (Rust target-triple syntax) targets = ["aarch64-apple-darwin", "aarch64-unknown-linux-gnu", "x86_64-apple-darwin", "x86_64-unknown-linux-gnu", "x86_64-pc-windows-msvc"] -# Path that installers should place binaries in install-path = "CARGO_HOME" -# Publish jobs to run in CI publish-jobs = ["homebrew", "./publish-crates", "./publish-aur", "./publish-winget"] -# Custom permissions for publish jobs github-custom-job-permissions = { publish-crates = { contents = "read" }, publish-aur = { contents = "read" }, publish-winget = { contents = "read" } } -# Extra setup steps for release artifact builders github-build-setup = "../dist-build-setup.yml" -# Where to host releases hosting = "github" -# Whether to install an updater program install-updater = false -# Allow custom edits to the generated CI file allow-dirty = ["ci", "msi"] diff --git a/src/auth/accounts.rs b/src/auth/accounts.rs index e6102c4..c749986 100644 --- a/src/auth/accounts.rs +++ b/src/auth/accounts.rs @@ -1,8 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// account management: persistence, switching active accounts, and offline uuid generation - use std::path::PathBuf; use serde::{Deserialize, Serialize}; diff --git a/src/auth/mod.rs b/src/auth/mod.rs index 6890662..144ec16 100644 --- a/src/auth/mod.rs +++ b/src/auth/mod.rs @@ -1,7 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// auth module: account storage (offline + microsoft) and the oauth device code flow mod accounts; mod oauth; diff --git a/src/auth/oauth.rs b/src/auth/oauth.rs index 022e82d..7a76fa9 100644 --- a/src/auth/oauth.rs +++ b/src/auth/oauth.rs @@ -1,8 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// microsoft oauth device code flow for minecraft authentication. -// the flow goes: MSA device code -> MSA token -> xbox/mc token exchange -> mc profile fetch. // device code auth is used because it works without a redirect URI, which is nice for a TUI. use std::sync::{Arc, LazyLock, Mutex}; @@ -50,7 +48,6 @@ fn normalize_profile_uuid(id: &str) -> Option { }) } -// shared slot so the TUI can poll for the device code to show the user pub static DEVICE_CODE_DISPLAY: LazyLock>>> = LazyLock::new(|| Arc::new(Mutex::new(None))); @@ -92,8 +89,6 @@ async fn run_full_oauth_flow() -> Result<(String, Option), String> { Ok((ms_access_token, ms_refresh_token)) } -// kicks off auth on a background task, returns a mutex the caller can poll for the result. -// the TUI checks DEVICE_CODE_DISPLAY for the code to show, and this mutex for completion. pub fn start_microsoft_auth() -> Arc>> { let result: Arc>> = Arc::new(Mutex::new(None)); let result_clone = result.clone(); @@ -183,7 +178,6 @@ fn valid_cached_mc_token(account: &Account, now: i64) -> Option<&str> { } } -// returns (mc_access_token, new_refresh_token, new_mc_token_expires_at). // cached tokens return no expiry so callers don't rewrite the account store. pub async fn refresh_and_get_token( account: &Account, diff --git a/src/cli/account.rs b/src/cli/account.rs index e9f63ff..b630668 100644 --- a/src/cli/account.rs +++ b/src/cli/account.rs @@ -1,7 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// cli handlers for account management (microsoft oauth + offline accounts) use std::io; use std::time::Duration; @@ -65,7 +64,6 @@ async fn add_microsoft_account() -> CliResult { let result_arc = crate::auth::start_microsoft_auth(); - // wait for the device code to become available before showing it loop { if let Ok(slot) = crate::auth::DEVICE_CODE_DISPLAY.lock() && let Some(info) = slot.as_ref() @@ -77,7 +75,6 @@ async fn add_microsoft_account() -> CliResult { tokio::time::sleep(Duration::from_millis(200)).await; } - // now wait for the user to complete auth in their browser loop { if let Ok(slot) = result_arc.lock() && let Some(result) = slot.as_ref() diff --git a/src/cli/content.rs b/src/cli/content.rs index 38b3d55..517e540 100644 --- a/src/cli/content.rs +++ b/src/cli/content.rs @@ -1,9 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// unified content management for mods, resource packs, and shaders. -// all three content types share the same list/enable/disable workflow, -// just with different scanner functions plugged in. use std::io; use std::path::Path; diff --git a/src/cli/import.rs b/src/cli/import.rs index 790ece1..6a7eb17 100644 --- a/src/cli/import.rs +++ b/src/cli/import.rs @@ -1,8 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// modpack importing from modrinth (remote slug/url) or local files (.mrpack, mmc zips). -// resolves the input, downloads if needed, then hands off to the import engine. use clap::ArgMatches; use crate::instance::InstanceManager; diff --git a/src/cli/instance.rs b/src/cli/instance.rs index a443e53..93926bf 100644 --- a/src/cli/instance.rs +++ b/src/cli/instance.rs @@ -1,8 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// instance lifecycle: create, delete, rename, launch, config, desktop shortcuts. -// the heaviest handler in the CLI since instances are the core concept. use std::io; use std::time::Duration; diff --git a/src/cli/log.rs b/src/cli/log.rs index 09599b5..0d16732 100644 --- a/src/cli/log.rs +++ b/src/cli/log.rs @@ -1,7 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// viewing minecraft log files from the CLI, with optional `--follow` for tailing use std::io; use std::path::{Path, PathBuf}; use std::time::Duration; @@ -67,7 +66,6 @@ async fn show_log(matches: &ArgMatches) -> CliResult { Ok(()) } -// if no file is specified, grab the most recent log (first from the sorted scan) pub(crate) fn resolve_log_path( instances_dir: &Path, instance: &str, diff --git a/src/cli/mod.rs b/src/cli/mod.rs index e155c3c..d2e65df 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -1,8 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// cli entry point and clap command definitions. -// no subcommand = launch TUI, otherwise dispatch to the appropriate handler. mod account; mod content; mod import; @@ -17,9 +15,7 @@ use clap::{Arg, ArgAction, ArgGroup, Command}; pub async fn init() { let matches = build_command().get_matches(); - // no subcommand means the user just ran `rmcl` bare, so fall through to TUI mode if matches.subcommand().is_none() { - // force-init the theme so it's ready before the TUI renders let _ = &*crate::config::theme::THEME; if let Err(e) = crate::tui::show().await { tracing::error!("TUI error: {}", e); @@ -265,7 +261,6 @@ fn build_command() -> Command { ) } -// mods, resource packs, and shaders all share the same list/enable/disable shape fn build_content_command(name: &'static str, about: &'static str) -> Command { Command::new(name) .about(format!("Manage {}", about)) diff --git a/src/cli/output.rs b/src/cli/output.rs index 8041220..7f40e85 100644 --- a/src/cli/output.rs +++ b/src/cli/output.rs @@ -1,8 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// plain-text table rendering for CLI output. no fancy box-drawing, -// just left-aligned columns with two-space gaps. keeps it pipeable. use chrono::{DateTime, Utc}; use ratatui::text::Span; @@ -47,7 +45,6 @@ fn display_width(value: &str) -> usize { Span::raw(value).width() } -// find the widest value in each column to pad everything evenly fn column_widths(headers: &[&str], rows: &[Vec]) -> Vec { let mut widths: Vec = headers.iter().map(|header| display_width(header)).collect(); diff --git a/src/cli/utils.rs b/src/cli/utils.rs index 195a000..46c2dc1 100644 --- a/src/cli/utils.rs +++ b/src/cli/utils.rs @@ -1,7 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// shared CLI helpers: confirmation prompts, arg extraction, instance validation use std::io::{self, Write}; use clap::ArgMatches; diff --git a/src/cli/version.rs b/src/cli/version.rs index 0968cd0..d9d6caf 100644 --- a/src/cli/version.rs +++ b/src/cli/version.rs @@ -1,9 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// lists available game versions, optionally filtered by mod loader support. -// fetches the mojang manifest and cross-references with loader APIs -// to show only versions that actually work with a given loader. use std::collections::HashSet; use std::io; diff --git a/src/config/mod.rs b/src/config/mod.rs index 77c657a..0406a6f 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -1,9 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// config loading: reads config.toml from the platform config dir, creates defaults if missing. -// everything lands in the SETTINGS static so the rest of the app can just grab it. - use config::{Config as ConfigLoader, ConfigError, File}; use std::fs; use std::io; @@ -22,7 +19,6 @@ pub fn get_config_path() -> PathBuf { .join("rmcl") } -// seeds the config file from the bundled default on first run fn ensure_config_exists() -> PathBuf { let config_path = get_config_path().join("config.toml"); if !config_path.exists() { diff --git a/src/config/settings.rs b/src/config/settings.rs index 623d47b..6e7d6dc 100644 --- a/src/config/settings.rs +++ b/src/config/settings.rs @@ -1,9 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// all the config structs that map to sections in config.toml. -// everything has sane defaults so a blank file (or no file) still works. - use std::{ collections::{BTreeMap, BTreeSet}, fmt, @@ -250,7 +247,6 @@ impl Default for Paths { } } -// expand ~ in paths since toml doesn't do that for us pub fn resolve_path(raw: &str) -> PathBuf { if let Some(stripped) = raw.strip_prefix("~/") { if let Some(home) = dirs_next::home_dir() { diff --git a/src/config/theme.rs b/src/config/theme.rs index 7b5cbbb..ee147a8 100644 --- a/src/config/theme.rs +++ b/src/config/theme.rs @@ -1,10 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// theme resolution: loads theme.toml, picks a base theme (builtin or custom file), -// then layers user color overrides on top. supports loading .toml themes from the -// config/theme/ directory or by absolute path. - use std::path::Path; use std::sync::{Arc, LazyLock, RwLock}; @@ -101,7 +97,6 @@ fn ensure_theme_exists(path: &Path) { let _ = std::fs::write(path, include_str!("../../assets/theme.toml")); } -// start from a base theme, then override individual colors if the user specified any fn resolve_app_theme(config: &ThemeConfig) -> Box { let base = load_base_theme(&config.theme); @@ -134,7 +129,6 @@ fn resolve_app_theme(config: &ThemeConfig) -> Box { }) } -// tries to find the theme: absolute path > config/theme/ > config/theme/.toml > builtin fn load_base_theme(name: &str) -> Box { let path = if Path::new(name).is_absolute() { Some(std::path::PathBuf::from(name)) diff --git a/src/feedback/errors.rs b/src/feedback/errors.rs index 29d96d5..68206bc 100644 --- a/src/feedback/errors.rs +++ b/src/feedback/errors.rs @@ -1,10 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// thread-safe FIFO queue for error/warning toasts displayed in the UI. -// also (ab)used for INFO toasts like "desktop shortcut created" because -// why build a separate notification system when this one works fine. -// // callers pass id: 0 and push_error assigns a real unique id. the id is // used by the render layer to track per-toast animation state. diff --git a/src/feedback/mod.rs b/src/feedback/mod.rs index 87f3b0d..5bc1730 100644 --- a/src/feedback/mod.rs +++ b/src/feedback/mod.rs @@ -1,8 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// application feedback shared by background work and every frontend. - use std::sync::atomic::{AtomicBool, Ordering}; pub mod errors; diff --git a/src/feedback/progress.rs b/src/feedback/progress.rs index a0e1219..20b5b5b 100644 --- a/src/feedback/progress.rs +++ b/src/feedback/progress.rs @@ -1,9 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// global progress state shared between background tasks and the status bar widget. -// background tasks set the action/progress, the render loop reads it every frame. - use std::collections::BTreeMap; use std::sync::LazyLock; use std::sync::atomic::{AtomicU64, Ordering}; diff --git a/src/instance/content/datapacks.rs b/src/instance/content/datapacks.rs index a090508..f65252e 100644 --- a/src/instance/content/datapacks.rs +++ b/src/instance/content/datapacks.rs @@ -1,8 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// data pack scanning backed by the same pack.mcmeta reader as resource packs. - use std::path::Path; use super::entry::ContentEntry; diff --git a/src/instance/content/entry.rs b/src/instance/content/entry.rs index 7434f4d..a9eb7e6 100644 --- a/src/instance/content/entry.rs +++ b/src/instance/content/entry.rs @@ -55,7 +55,6 @@ pub struct ContentEntry { pub icon_lines: Option>>, } -// enable/disable by renaming the file with/without ".disabled" suffix. pub fn toggle_entry(entry: &ContentEntry) -> Result<(), std::io::Error> { toggle_entry_path(entry).map(drop) } diff --git a/src/instance/content/icons.rs b/src/instance/content/icons.rs index 9dc88bf..c0493df 100644 --- a/src/instance/content/icons.rs +++ b/src/instance/content/icons.rs @@ -1,9 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// terminal icon rasterization shared by every content type and markdown. - -// a single "pixel" in a terminal icon. #[derive(Debug, Clone, Copy)] pub struct IconCell { pub symbol: char, diff --git a/src/instance/content/mod.rs b/src/instance/content/mod.rs index 919abd6..801c453 100644 --- a/src/instance/content/mod.rs +++ b/src/instance/content/mod.rs @@ -1,7 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// scanning and toggling instance content (mods, resource packs, shaders, worlds). // minecraft uses a ".disabled" suffix convention for disabled content, so this leans on that heavily. pub mod datapacks; @@ -30,8 +29,6 @@ pub use worlds::{scan_one_world, scan_worlds}; use std::io::Read; -// figures out if a file is enabled or disabled based on the ".disabled" suffix, -// and strips the extension to get a clean stem name pub(crate) fn parse_enabled_stem(file_name: &str, ext: &str) -> Option<(bool, String)> { let disabled_ext = format!("{ext}.disabled"); if let Some(stem) = file_name.strip_suffix(&disabled_ext) { @@ -43,7 +40,6 @@ pub(crate) fn parse_enabled_stem(file_name: &str, ext: &str) -> Option<(bool, St } } -// same idea but for directories, which don't have a file extension to strip pub(crate) fn parse_enabled_stem_dir(file_name: &str) -> (bool, String) { if let Some(stem) = file_name.strip_suffix(".disabled") { (false, stem.to_string()) diff --git a/src/instance/content/mods.rs b/src/instance/content/mods.rs index 043aa25..2c67dc3 100644 --- a/src/instance/content/mods.rs +++ b/src/instance/content/mods.rs @@ -1,12 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// mod scanning and loader-specific metadata extraction. -// jar files are just zips, so it cracks them open looking for loader-specific -// metadata (fabric.mod.json, quilt.mod.json, mods.toml, mcmod.info) to get -// names, descriptions, and icons. if none of those work, falls back to common -// root-level icon paths (logo.png, icon.png, pack.png) or just the filename. - use std::io::Read; use std::path::Path; @@ -47,7 +41,6 @@ fn icon_path_from_value(value: &serde_json::Value) -> String { } } -// quilt puts its metadata under a "metadata" sub-object #[derive(Deserialize, Default)] struct QuiltModJson { #[serde(default)] @@ -142,10 +135,6 @@ pub fn scan_mods(instances_dir: &Path, instance_name: &str) -> Vec entries } -// tries each loader's metadata file to extract name, description, and icon. -// checks fabric.mod.json, quilt.mod.json, META-INF/mods.toml (forge), -// META-INF/neoforge.mods.toml, and mcmod.info (legacy forge). if none of -// those yield an icon, falls back to common root-level paths. fn read_mod_metadata(jar_path: &Path) -> (String, String, String, Option>) { let file = match std::fs::File::open(jar_path) { Ok(file) => file, @@ -197,7 +186,6 @@ fn read_mod_metadata(jar_path: &Path) -> (String, String, String, Option } } - // no recognized metadata at all, try common icon paths let icon_bytes = try_fallback_icons(&mut archive); tracing::trace!( "No recognized mod metadata in {}; fallback_icon={}", @@ -291,8 +279,6 @@ fn read_forge_toml_meta( Some((name, description, version, logo)) } -// legacy forge mcmod.info is either a bare json array of mod entries -// or an object with a "modList" key wrapping the array fn read_mcmod_info( archive: &mut zip::ZipArchive, ) -> Option<(String, String, String, String)> { diff --git a/src/instance/content/packs.rs b/src/instance/content/packs.rs index fee1567..fbb6efa 100644 --- a/src/instance/content/packs.rs +++ b/src/instance/content/packs.rs @@ -1,8 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// shared pack.mcmeta scanning for resource packs and shader packs. - use std::path::Path; use serde::Deserialize; diff --git a/src/instance/content/resource_packs.rs b/src/instance/content/resource_packs.rs index 162d760..9708a48 100644 --- a/src/instance/content/resource_packs.rs +++ b/src/instance/content/resource_packs.rs @@ -1,8 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// resource pack scanner backed by the shared pack.mcmeta reader. - use std::path::Path; use super::entry::ContentEntry; diff --git a/src/instance/content/shaders.rs b/src/instance/content/shaders.rs index 59892f3..969b243 100644 --- a/src/instance/content/shaders.rs +++ b/src/instance/content/shaders.rs @@ -1,8 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// shader pack scanner backed by the shared pack.mcmeta reader. - use std::path::Path; use super::entry::ContentEntry; diff --git a/src/instance/content/worlds.rs b/src/instance/content/worlds.rs index 9a844ea..532a558 100644 --- a/src/instance/content/worlds.rs +++ b/src/instance/content/worlds.rs @@ -1,10 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// world save scanning. worlds are always directories (never zips) and store -// their icon as icon.png. also computes an approximate size from top-level -// files + region data so the user gets some sense of how chonky their world is. - use std::{fs::File, path::Path}; use flate2::read::GzDecoder; @@ -204,7 +200,6 @@ fn dir_size_approx(path: &Path) -> u64 { } } } - // Check region folder too (main chunk data) let region = path.join("region"); if let Ok(rd) = std::fs::read_dir(region) { for entry in rd.flatten() { diff --git a/src/instance/desktop.rs b/src/instance/desktop.rs index 1846758..f0314c8 100644 --- a/src/instance/desktop.rs +++ b/src/instance/desktop.rs @@ -1,9 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// creates OS-native shortcuts for launching instances directly: -// .desktop files on linux, .bat on windows, .command on macos - use std::path::{Path, PathBuf}; use crate::instance::models::InstanceConfig; @@ -42,7 +39,6 @@ pub fn icon_path() -> Option { dirs_next::data_dir().map(|d| d.join("rmcl").join("icon.svg")) } -// lazily writes the bundled svg icon to disk the first time a shortcut needs it fn ensure_icon() -> Option { let path = icon_path()?; if std::fs::read(&path).ok().as_deref() == Some(ICON_BYTES) { @@ -229,7 +225,6 @@ fn quote_windows_arg(value: &str) -> String { quoted } -// replaces anything that isn't alphanumeric, dash, or underscore with _ fn sanitize(name: &str) -> String { name.chars() .map(|c| { diff --git a/src/instance/import/mmc.rs b/src/instance/import/mmc.rs index 50cdb96..8a3fe24 100644 --- a/src/instance/import/mmc.rs +++ b/src/instance/import/mmc.rs @@ -1,10 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// multimc / prism launcher instance import: mods and configs are bundled -// in the zip. we install the game + loader normally, then extract the -// archive contents over it. - use std::path::Path; use crate::feedback::progress; @@ -119,7 +115,6 @@ pub async fn execute_import( Ok(()) } -// extracts everything under .minecraft/ from the archive into the instance dir fn extract_mmc_archive( archive_path: &Path, minecraft_dir: &Path, @@ -239,7 +234,6 @@ fn instance_name_from_cfg(path: &Path) -> Option { None } -// finds the prefix for the archive: empty for flat zips, "DirName/" for nested fn find_archive_prefix(archive: &zip::ZipArchive) -> String { for name in archive.file_names() { if name.ends_with("mmc-pack.json") { diff --git a/src/instance/import/mod.rs b/src/instance/import/mod.rs index c61afae..6de63f8 100644 --- a/src/instance/import/mod.rs +++ b/src/instance/import/mod.rs @@ -1,9 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// modpack importing: parses user input, detects pack format from zip contents, -// builds a summary, and delegates the actual import to format-specific modules. - pub mod curseforge; pub mod mmc; pub mod mrpack; @@ -28,9 +25,6 @@ pub enum ImportInput { LocalFile(String), } -// figures out what the user gave us: a modrinth URL, a local pack file, -// or just a project slug. accepts a pretty wide range of inputs so users -// don't have to think about it. pub fn parse_import_input(input: &str) -> ImportInput { let input = input.trim(); @@ -78,8 +72,6 @@ pub struct ImportSummary { pub source: Option, } -// peeks inside a zip to figure out what format it is. -// checks provider manifests first, then mmc-pack.json. pub fn detect_format(path: &Path) -> Result { tracing::debug!("Detecting modpack format for {}", path.display()); let file = diff --git a/src/instance/import/mrpack.rs b/src/instance/import/mrpack.rs index 2d2d000..49d9377 100644 --- a/src/instance/import/mrpack.rs +++ b/src/instance/import/mrpack.rs @@ -1,9 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// modrinth .mrpack import: parse the manifest, download all the mods, -// and extract config/resource overrides from the zip - use std::collections::HashMap; use std::path::{Path, PathBuf}; @@ -43,7 +40,6 @@ pub struct MrpackFile { pub file_size: u64, } -// .mrpack is just a zip with modrinth.index.json at the root pub fn parse_mrpack(path: &Path) -> Result { tracing::debug!("Parsing .mrpack manifest from {}", path.display()); let file = std::fs::File::open(path).map_err(|e| format!("Cannot open .mrpack: {e}"))?; @@ -63,8 +59,6 @@ pub fn parse_mrpack(path: &Path) -> Result { Ok(index) } -// mrpack dependencies use keys like "fabric-loader", "forge", etc. -// checks in priority order and returns the first match. pub fn loader_from_dependencies( deps: &HashMap, ) -> (Option, Option) { @@ -132,7 +126,6 @@ pub fn build_summary(path: &Path) -> Result { }) } -// peek into the zip to count files under overrides/ and client-overrides/ fn count_overrides(mrpack_path: &Path) -> Result { let file = std::fs::File::open(mrpack_path).map_err(|e| e.to_string())?; let archive = zip::ZipArchive::new(file).map_err(|e| e.to_string())?; diff --git a/src/instance/java.rs b/src/instance/java.rs index 3d57f8d..32d04cf 100644 --- a/src/instance/java.rs +++ b/src/instance/java.rs @@ -1,8 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// java runtime discovery shared by launching, loader installation, and settings. - use std::{ collections::HashSet, path::{Path, PathBuf}, diff --git a/src/instance/launch/mod.rs b/src/instance/launch/mod.rs index 1fef4bd..ae038b2 100644 --- a/src/instance/launch/mod.rs +++ b/src/instance/launch/mod.rs @@ -1,10 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// builds the full java command line and spawns minecraft as a child process. -// handles classpath assembly, auth token injection, and log capture. -// loader-specific patches live in submodules (e.g. patches.rs for lwjgl3ify). - pub(crate) mod parser; mod patches; @@ -300,9 +296,6 @@ async fn migrate_legacy_loader_profile_if_needed( Ok(Some(refreshed)) } -// resolved auth credentials passed into the launch-invocation builder. -// keeping these as borrowed strs lets callers pass owned strings or string -// slices without forcing allocation. #[derive(Debug, Clone)] pub struct LaunchAuth<'a> { pub username: &'a str, @@ -312,9 +305,7 @@ pub struct LaunchAuth<'a> { pub user_type: &'a str, } -// everything the spawner needs to construct the java command. assembled by -// build_launch_invocation, consumed by launch(). exposed so integration tests -// can assert on the rendered invocation without spawning a real process. +// Exposed so integration tests can inspect the invocation without spawning Java. #[derive(Debug, Clone)] pub struct LaunchInvocation { pub java: String, @@ -368,11 +359,6 @@ fn validate_quick_play_world(minecraft_dir: &Path, world: &str) -> Result<(), La Ok(()) } -// builds a fully-resolved java invocation for the given instance. reads -// meta.json and the loader profile from disk, migrates legacy formats if -// needed (may hit Mojang to refetch), resolves inheritsFrom, applies -// loader-specific patches, and renders all template arguments. all I/O -// except auth resolution and process spawning happens here. pub async fn build_launch_invocation( config: &InstanceConfig, instances_dir: &Path, @@ -555,7 +541,6 @@ pub async fn build_launch_invocation( .collect::>() .join(sep); - // java resolution: instance override > global setting > auto-detect let java = config .java_path .clone() @@ -739,10 +724,6 @@ fn finish_config_sync( } } -// resolves auth credentials, then builds the launch invocation and spawns -// the java process. only thin wrapper logic lives here: token refresh, -// process spawn, child supervision. all the heavy lifting (profile loading, -// classpath assembly, template rendering) sits behind build_launch_invocation. pub async fn launch( config: &InstanceConfig, instances_dir: &Path, @@ -751,7 +732,6 @@ pub async fn launch( ) -> Result<(), LaunchError> { let name = config.name.clone(); - // resolve auth credentials, refreshing the microsoft token if needed. let mut account_store = crate::auth::AccountStore::load(); let account = select_launch_account(&account_store.accounts, config.preferred_account.as_deref()); @@ -919,8 +899,6 @@ pub async fn launch( let config_for_post_exit = config.clone(); let invocation_for_post_exit = invocation.clone(); - // spawn a background task to babysit the child process: capture stdout/stderr - // into both the TUI log viewer and a timestamped log file on disk tokio::spawn(async move { use std::io::Write; use std::sync::{Arc, Mutex}; @@ -1004,7 +982,6 @@ pub async fn launch( } drop(log_tx); - // wait for either the process to exit naturally or a kill signal from the TUI let (code, killed_by_user) = tokio::select! { _ = kill_rx => { tracing::info!("[{}] Kill requested, terminating process", name_for_task); diff --git a/src/instance/launch/parser.rs b/src/instance/launch/parser.rs index 7397ac6..f92cf90 100644 --- a/src/instance/launch/parser.rs +++ b/src/instance/launch/parser.rs @@ -1,8 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// live minecraft process log parser. -// // disk launch logs stay raw, but the tui needs enough structure to color and // group output sanely. this parser keeps stdout/stderr as a hint, frames // multiline java/jvm/native bursts into events, then assigns a semantic level. diff --git a/src/instance/launch/patches.rs b/src/instance/launch/patches.rs index d9d0a4a..64ce74a 100644 --- a/src/instance/launch/patches.rs +++ b/src/instance/launch/patches.rs @@ -1,11 +1,9 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// classpath and jvm patches for legacy forge on java 9+. // lwjgl3ify ships a patched launchwrapper and retrofuturabootstrap that // replace the old URLClassLoader-based launcher with one that works on -// modern java. this module handles extracting those patches, building -// the right --add-opens flags, and swapping out the broken log4j jars. +// modern java. use std::path::{Path, PathBuf}; @@ -19,12 +17,6 @@ pub struct LwjglifyPatches { pub extra_args: Vec, } -// checks if lwjgl3ify is present in the mods folder, and if so: -// 1. extracts forge patches from the lwjgl3ify jar -// 2. prepends them to the classpath so they shadow vanilla launchwrapper -// 3. parses --add-opens from the patches manifest -// 4. replaces log4j 2.0-beta9 with prism's patched builds -// 5. returns the jvm args and overridden main class pub async fn apply( minecraft_dir: &Path, lib_dir: &Path, @@ -43,7 +35,6 @@ pub async fn apply( return None; } - // prepend so patched classes shadow vanilla launchwrapper classpath.insert(0, patches_dest.clone()); let mut jvm_args = parse_add_opens(&patches_dest).unwrap_or_default(); @@ -214,7 +205,6 @@ fn add_lwjgl3(lib_dir: &Path, classpath: &mut Vec) { insert_pos += 1; } - // natives let natives = if *module == "lwjgl" { lib_dir.join(format!( "org/lwjgl/lwjgl/3.3.3/lwjgl-3.3.3-{os_classifier}.jar" @@ -234,11 +224,8 @@ fn add_lwjgl3(lib_dir: &Path, classpath: &mut Vec) { tracing::info!("Added {} LWJGL 3.3.3 jars to classpath", insert_pos - 1); } -// writes a log4j2.xml config that sets the root logger to INFO. this -// prevents LaunchClassLoader's debug() call from ever firing, which -// avoids the ThrowableProxy -> SecurityManager -> StackWalker infinite -// recursion on java 24+. the config is written to .minecraft/ and -// pointed to via -Dlog4j.configurationFile. +// Suppresses LaunchClassLoader's debug() call to avoid the +// ThrowableProxy -> SecurityManager -> StackWalker recursion on Java 24+. fn write_log4j_config(minecraft_dir: &Path, jvm_args: &mut Vec) { let config_path = minecraft_dir.join(".rmcl-log4j2.xml"); let config = r#" diff --git a/src/instance/loader/fabric.rs b/src/instance/loader/fabric.rs index 8a16782..d78eadc 100644 --- a/src/instance/loader/fabric.rs +++ b/src/instance/loader/fabric.rs @@ -1,9 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// fabric installation. the nice one: just fetch a profile json and download -// the libraries. no java installer nonsense required. - use std::path::Path; use async_trait::async_trait; diff --git a/src/instance/loader/forge.rs b/src/instance/loader/forge.rs index 44b9559..343fc08 100644 --- a/src/instance/loader/forge.rs +++ b/src/instance/loader/forge.rs @@ -1,9 +1,8 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// forge installation. modern forge runs a java installer, old forge (pre-1.13) -// can't run headless so we extract the profile and libraries from the jar -// directly. the installer jar gets cleaned up either way. +// Old Forge installers cannot run headless, so their profiles and libraries +// must be extracted from the jar instead. use std::path::Path; @@ -85,7 +84,6 @@ impl ModLoaderInstaller for ForgeInstaller { let profile_filename = format!("forge-{game_version}-{loader_version}.json"); if has_legacy_install_profile(&installer_jar) { - // old forge: no --installClient support, extract directly from jar tracing::debug!("Forge installer uses legacy install_profile.json path"); if let Err(e) = install_forge_from_profile(client, &installer_jar, meta_dir, &profile_filename) @@ -95,7 +93,6 @@ impl ModLoaderInstaller for ForgeInstaller { return Err(e); } } else { - // modern forge: run the java installer let java_path = java_path.map(str::to_owned).unwrap_or_else(|| { crate::config::SETTINGS .read() @@ -110,7 +107,6 @@ impl ModLoaderInstaller for ForgeInstaller { return Err(InstallError::Installer(e)); } - // extract the profile from what the installer just wrote to disk save_forge_profile(instance_dir, meta_dir, game_version, loader_version) .map_err(InstallError::Installer)?; } @@ -271,7 +267,6 @@ pub(crate) async fn install_forge_from_profile( InstallError::Installer(InstallerError::Profile("missing install.path".into())) })?; - // extract the universal jar to the correct maven location let universal_maven_path = crate::instance::loader::maven::maven_coord_to_path( install_path_coord, ) diff --git a/src/instance/loader/maven.rs b/src/instance/loader/maven.rs index 8848113..64ed46e 100644 --- a/src/instance/loader/maven.rs +++ b/src/instance/loader/maven.rs @@ -1,8 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// maven coordinate handling shared by loader installation and launch profiles. - #[must_use] pub fn maven_coord_to_path(coord: &str) -> Option { let parts: Vec<&str> = coord.split(':').collect(); diff --git a/src/instance/loader/mod.rs b/src/instance/loader/mod.rs index 8c52a6c..4e18c94 100644 --- a/src/instance/loader/mod.rs +++ b/src/instance/loader/mod.rs @@ -1,11 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// mod loader installation. each loader (fabric, forge, neoforge, quilt, vanilla) -// implements the same trait so the UI can treat them uniformly: pick game version, -// pick loader version, install. the actual installation strategies differ wildly -// though (fabric/quilt just download jars, forge/neoforge run a whole java installer). - mod fabric; pub mod forge; pub mod maven; @@ -83,8 +78,7 @@ pub trait ModLoaderInstaller: Send + Sync { } } -// writes raw profile JSON bytes to meta_dir/loader-profiles/. -// callers that already have the upstream bytes (fabric/quilt http fetch, +// Callers that already have the upstream bytes (fabric/quilt http fetch, // legacy forge versionInfo extract) use this directly to keep the on-disk // file byte-for-byte identical to the source. pub(crate) fn save_profile_bytes( diff --git a/src/instance/loader/neoforge.rs b/src/instance/loader/neoforge.rs index 8692423..8f16ee8 100644 --- a/src/instance/loader/neoforge.rs +++ b/src/instance/loader/neoforge.rs @@ -1,9 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// neoforge installation. same java installer dance as forge (they forked from it, -// after all), just with different URLs and version naming. - use std::path::Path; use async_trait::async_trait; diff --git a/src/instance/loader/quilt.rs b/src/instance/loader/quilt.rs index 940f237..aa25111 100644 --- a/src/instance/loader/quilt.rs +++ b/src/instance/loader/quilt.rs @@ -1,9 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// quilt installation. same clean approach as fabric (profile json + library -// downloads). they're basically fabric's cooler sibling. - use std::path::Path; use async_trait::async_trait; diff --git a/src/instance/logs/files.rs b/src/instance/logs/files.rs index cef626c..f6e37fe 100644 --- a/src/instance/logs/files.rs +++ b/src/instance/logs/files.rs @@ -1,10 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// per-launch log files stored under minecraft/logs/launches/ -// each launch gets its own timestamped file so you can go back and see what -// crashed last tuesday at 3am - use std::path::{Path, PathBuf}; #[derive(Debug, Clone)] diff --git a/src/instance/logs/live.rs b/src/instance/logs/live.rs index a02e2d2..0034981 100644 --- a/src/instance/logs/live.rs +++ b/src/instance/logs/live.rs @@ -1,10 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// in-memory ring buffer for stdout/stderr from running mc instances. -// capped at 2000 lines per instance so it doesn't eat all the RAM -// if someone leaves a server running for a week. you're welcome. - use std::collections::{HashMap, VecDeque}; use std::sync::LazyLock; use std::sync::{Arc, Mutex}; diff --git a/src/instance/manager.rs b/src/instance/manager.rs index f988a92..ad89388 100644 --- a/src/instance/manager.rs +++ b/src/instance/manager.rs @@ -1,9 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// CRUD for instances: create, delete, rename, load, save. -// creation is the heavy one since it downloads the game, assets, and libraries. - use std::path::PathBuf; use chrono::Utc; @@ -94,7 +91,6 @@ impl InstanceManager { .create_inner(name, game_version, loader, loader_version, &instance_dir) .await; - // clean up on failure so there's no half-baked instance left around if result.is_err() { tracing::debug!( "Cleaning up incomplete instance '{}' after creation failed", diff --git a/src/instance/mod.rs b/src/instance/mod.rs index 0265d4f..6145a76 100644 --- a/src/instance/mod.rs +++ b/src/instance/mod.rs @@ -1,9 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// instance management: creation, launching, importing modpacks, and all the -// bookkeeping that comes with pretending to be a real launcher - pub mod config_sync; pub mod content; pub mod desktop; diff --git a/src/instance/models.rs b/src/instance/models.rs index 323721a..88f7bdd 100644 --- a/src/instance/models.rs +++ b/src/instance/models.rs @@ -1,9 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// core data types for an instance: what loader it uses, what version, memory -// settings, etc. this is what gets persisted to instance.json - use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use serde_json::Value; diff --git a/src/instance/runtime.rs b/src/instance/runtime.rs index e358f26..c2d19e5 100644 --- a/src/instance/runtime.rs +++ b/src/instance/runtime.rs @@ -1,10 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// global tracking for running minecraft instances. everything is behind -// Arc> because the launch/monitor tasks live on separate tokio threads -// and the TUI render loop needs to read state every frame. - use chrono::{DateTime, Utc}; use std::collections::HashMap; use std::sync::LazyLock; diff --git a/src/instance/screenshots.rs b/src/instance/screenshots.rs index 461ab14..c44d4c5 100644 --- a/src/instance/screenshots.rs +++ b/src/instance/screenshots.rs @@ -3,9 +3,6 @@ use std::path::{Path, PathBuf}; -// width/height are read from the actual image file so the TUI can show -// dimensions. falls back to 1920x1080 if the file is corrupt or unreadable -// because honestly, what else are you gonna pick #[derive(Debug, Clone)] pub struct ScreenshotEntry { pub name: String, @@ -44,7 +41,6 @@ pub fn scan_screenshots(instances_dir: &Path, instance_name: &str) -> Vec PathBuf { let path = tmp.join(name); let file = std::fs::File::create(&path).unwrap(); @@ -29,7 +27,6 @@ fn strip_replaced_libs_removes_dominated_prefixes() { PathBuf::from("/libs/commons-compress-1.4.1.jar"), PathBuf::from("/libs/commons-io-2.4.jar"), PathBuf::from("/libs/guava-15.0.jar"), - // these stay PathBuf::from("/libs/log4j-core-2.0.jar"), PathBuf::from("/libs/guava-21.0.jar"), ]; @@ -130,8 +127,6 @@ fn add_lwjgl3_inserts_only_jars_that_exist() { let mut classpath = vec![PathBuf::from("/leading/forge-patches.jar")]; add_lwjgl3(lib_dir, &mut classpath); - // forge-patches stays at index 0; lwjgl core is inserted at index 1. - // none of the other modules existed so nothing else was added. assert_eq!(classpath[0], PathBuf::from("/leading/forge-patches.jar")); assert_eq!(classpath[1], core_jar); assert_eq!(classpath.len(), 2); diff --git a/src/instance/tests/runtime.rs b/src/instance/tests/runtime.rs index fc191db..09a393c 100644 --- a/src/instance/tests/runtime.rs +++ b/src/instance/tests/runtime.rs @@ -57,13 +57,6 @@ fn push_and_drain_last_played() { assert!(drained.iter().any(|(k, _)| k == "run_test_lp")); } -// Removed drain_empty_returns_empty: it relied on no other test pushing -// to LAST_PLAYED between the two drain calls, which races with the -// parallel push_and_drain_last_played test. The drain semantics are -// already covered by push_and_drain_last_played, which asserts a -// specific entry is present, and the empty-result path is exercised -// implicitly any time drain runs after that test's cleanup. - #[test] fn send_kill_returns_false_for_missing() { assert!(!send_kill("run_never_registered_xyz")); @@ -74,7 +67,6 @@ fn register_and_send_kill() { let (tx, mut rx) = tokio::sync::oneshot::channel::<()>(); register_kill("run_test_kill", tx); assert!(send_kill("run_test_kill")); - // the kill signal itself must arrive, not just report success assert!(rx.try_recv().is_ok()); } diff --git a/src/launch_profile/mod.rs b/src/launch_profile/mod.rs index 6e3bdf1..6c11dbd 100644 --- a/src/launch_profile/mod.rs +++ b/src/launch_profile/mod.rs @@ -1,11 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// primitives for parsing, merging, and rendering mojang-format launch -// profiles. consumed by the vanilla launcher and the loader install paths -// (forge/neoforge/fabric/quilt) - anything that reads a mojang-style -// version JSON. - pub mod model; pub mod render; pub mod resolve; diff --git a/src/launch_profile/model.rs b/src/launch_profile/model.rs index f30d35c..f1920ec 100644 --- a/src/launch_profile/model.rs +++ b/src/launch_profile/model.rs @@ -1,12 +1,8 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// mojang-format launch profile types. mirrors the on-disk JSON schema -// used by vanilla versions, forge installer output, neoforge installer -// output, fabric profiles, and quilt profiles. parsing is lossless for -// the fields we care about; unknown fields are silently dropped (serde -// default behavior) - which is fine because we write upstream JSON -// byte-for-byte on the install side. +// Unknown JSON fields are dropped when parsing, but installer paths write the +// upstream bytes unchanged, so this model never strips fields from the cache. use serde::{Deserialize, Serialize}; diff --git a/src/launch_profile/render.rs b/src/launch_profile/render.rs index 0c11b83..bfdb1ca 100644 --- a/src/launch_profile/render.rs +++ b/src/launch_profile/render.rs @@ -1,12 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// renders a parsed launch profile into final argv-style lists for the JVM -// and the game. resolves conditional argument shapes (`{rules, value}`), -// filters them through the rule evaluator, and substitutes mojang template -// variables. legacy `minecraftArguments` strings are tokenised on whitespace -// and treated as a list of game args. pure function; no I/O. - use super::model::{Argument, ArgumentValue, LaunchProfile}; use super::rules::{RuleContext, evaluate}; use super::templates::{TemplateContext, substitute}; diff --git a/src/launch_profile/resolve.rs b/src/launch_profile/resolve.rs index b53d34a..1ed40c8 100644 --- a/src/launch_profile/resolve.rs +++ b/src/launch_profile/resolve.rs @@ -1,12 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// resolves the `inheritsFrom` chain of a parsed `LaunchProfile`. mojang's -// version JSON allows a profile to inherit from another profile by id; the -// loaders (forge / neoforge / fabric / quilt) use this to layer their -// additions on top of a vanilla base. this module walks the chain and -// returns a single flat profile. -// // merge semantics (per the mojang launcher and the major third-party // launchers that interoperate with it): // - scalar fields: child wins if Some, else parent. @@ -15,10 +9,6 @@ // - merge_into preserves parent's inherits_from so resolve() can keep // walking; resolve() clears the final result's inherits_from after // the loop exits. -// -// pure function `merge_into` handles the field-by-field merge math. -// async `resolve` does the chain walking with cycle detection and a depth -// cap. tests cover both layers independently. use std::path::Path; @@ -68,8 +58,6 @@ pub fn merge_into(child: LaunchProfile, parent: LaunchProfile) -> LaunchProfile // version and any classifier. used as the dedup key when merging library // lists from a child profile on top of its parent. fn coord_key(name: &str) -> &str { - // mojang maven coords are `group:artifact:version[:classifier]`. take - // everything up to the second colon. let mut it = name.match_indices(':').map(|(i, _)| i); it.next(); it.next().map_or(name, |i| &name[..i]) diff --git a/src/launch_profile/rules.rs b/src/launch_profile/rules.rs index 1c7ebe7..4c003f6 100644 --- a/src/launch_profile/rules.rs +++ b/src/launch_profile/rules.rs @@ -1,11 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// mojang rule evaluation. profiles, libraries, and argument entries can -// carry conditional rules that filter them by OS, architecture, or feature -// flags. this module is the single source of truth for that semantics - -// see `evaluate` below for the exact rules. - use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)] diff --git a/src/launch_profile/system.rs b/src/launch_profile/system.rs index a8661ef..e6f834d 100644 --- a/src/launch_profile/system.rs +++ b/src/launch_profile/system.rs @@ -1,8 +1,7 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// system-detection helpers shared by launch and install paths. mojang -// names some things differently from rust's std::env::consts (e.g. macOS +// Mojang names some things differently from rust's std::env::consts (e.g. macOS // is "osx" in mojang profile rules), so this module is the single source // of truth for translating. diff --git a/src/launch_profile/templates.rs b/src/launch_profile/templates.rs index 25e9fd6..34ad1d6 100644 --- a/src/launch_profile/templates.rs +++ b/src/launch_profile/templates.rs @@ -1,15 +1,8 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// template substitution for mojang-style launch arguments. profiles use -// `${variable_name}` placeholders that the launcher fills in at launch -// time from the active session: paths, the user's account info, the -// classpath, the resolved natives directory, and so on. -// -// the full set of variables is documented in `TemplateContext`. unknown -// placeholders are left as-is and logged at `warn` level - that way if -// mojang adds a new variable in the future, the launcher fails open -// rather than silently swallowing it. +// Keep unknown placeholders and warn so future Mojang variables remain visible +// instead of silently disappearing. use std::path::Path; diff --git a/src/launch_profile/tests/model.rs b/src/launch_profile/tests/model.rs index 1c98571..68b99fc 100644 --- a/src/launch_profile/tests/model.rs +++ b/src/launch_profile/tests/model.rs @@ -95,12 +95,10 @@ fn parses_modern_arguments_object() { assert_eq!(args.game.len(), 3); assert_eq!(args.jvm.len(), 2); - // first game arg should be a literal "--username" match &args.game[0] { Argument::Literal(s) => assert_eq!(s, "--username"), _ => panic!("expected literal"), } - // third game arg should be a conditional with a single-string value match &args.game[2] { Argument::Conditional { rules, value } => { assert_eq!(rules.len(), 1); @@ -109,7 +107,6 @@ fn parses_modern_arguments_object() { } _ => panic!("expected conditional"), } - // second jvm arg should be a conditional with a multi-string value match &args.jvm[1] { Argument::Conditional { value, .. } => { assert!(matches!(value, ArgumentValue::Multiple(_))); diff --git a/src/launch_profile/tests/render.rs b/src/launch_profile/tests/render.rs index 1bb3dec..37fc962 100644 --- a/src/launch_profile/tests/render.rs +++ b/src/launch_profile/tests/render.rs @@ -239,12 +239,10 @@ async fn end_to_end_resolve_then_render_modern_forge_shape() { let fx = Fixture::new(); let rendered = render_args(&merged, &fx.rule_ctx(), &fx.template_ctx()).unwrap(); - // child main_class wins after merge assert_eq!( rendered.main_class, "cpw.mods.bootstraplauncher.BootstrapLauncher" ); - // game args: parent first then child assert_eq!( rendered.game, vec![ @@ -256,7 +254,6 @@ async fn end_to_end_resolve_then_render_modern_forge_shape() { "forge_client" ] ); - // jvm args: parent first then child assert_eq!( rendered.jvm, vec![ diff --git a/src/launch_profile/tests/resolve.rs b/src/launch_profile/tests/resolve.rs index f3bd408..2eaadaf 100644 --- a/src/launch_profile/tests/resolve.rs +++ b/src/launch_profile/tests/resolve.rs @@ -54,7 +54,6 @@ fn merge_carries_parent_inherits_from() { #[test] fn merge_with_root_parent_clears_inherits_from() { - // parent with no inherits_from means the chain ends. let mut child = empty_profile("child"); child.inherits_from = Some("parent".into()); let parent = empty_profile("parent"); @@ -109,8 +108,6 @@ fn child_library_supersedes_parent_with_same_group_artifact() { ]; let merged = merge_into(child, parent); let names: Vec<_> = merged.libraries.iter().map(|l| l.name.as_str()).collect(); - // parent's log4j-core is filtered (superseded by child); parent's - // lwjgl stays (no conflict); child's log4j and forge come last. assert_eq!( names, vec![ @@ -128,12 +125,10 @@ fn coord_key_extracts_group_artifact() { coord_key("org.apache.logging.log4j:log4j-core:2.17.0"), "org.apache.logging.log4j:log4j-core" ); - // with classifier assert_eq!( coord_key("org.lwjgl:lwjgl:3.3.1:natives-linux"), "org.lwjgl:lwjgl" ); - // malformed (no colons) - return as-is assert_eq!(coord_key("malformed"), "malformed"); } @@ -346,7 +341,6 @@ async fn resolve_errors_when_parent_is_invalid_json() { async fn resolve_multi_level_chain_merges_all_parents() { let tmp = TempDir::new().unwrap(); - // chain: grandchild -> child -> root (vanilla). let mut root = empty_profile("1.20.1"); root.main_class = Some("net.minecraft.client.main.Main".into()); root.libraries = vec![lib("vanilla-lib")]; @@ -368,7 +362,6 @@ async fn resolve_multi_level_chain_merges_all_parents() { resolved.main_class.as_deref(), Some("net.minecraft.client.main.Main") ); - // libs: root ++ child ++ grandchild (each parent prepended) let names: Vec<_> = resolved.libraries.iter().map(|l| l.name.as_str()).collect(); assert_eq!(names, vec!["vanilla-lib", "forge-lib", "modpack-lib"]); } @@ -377,7 +370,6 @@ async fn resolve_multi_level_chain_merges_all_parents() { async fn resolve_detects_circular_chain() { let tmp = TempDir::new().unwrap(); - // a -> b -> a (cycle) let mut a = empty_profile("a"); a.inherits_from = Some("b".into()); write_profile(tmp.path(), &a); @@ -386,7 +378,6 @@ async fn resolve_detects_circular_chain() { b.inherits_from = Some("a".into()); write_profile(tmp.path(), &b); - // start from a fresh "a" profile that asks to inherit from b let mut entry = empty_profile("a"); entry.inherits_from = Some("b".into()); @@ -401,8 +392,6 @@ async fn resolve_detects_circular_chain() { async fn resolve_caps_depth() { let tmp = TempDir::new().unwrap(); - // build a chain 0 -> 1 -> 2 -> ... -> 10. with cap of 8, hitting 10 - // should fail with DepthExceeded. for i in 0..=10 { let mut p = empty_profile(&format!("v{i}")); if i < 10 { diff --git a/src/launch_profile/tests/rules.rs b/src/launch_profile/tests/rules.rs index 7b10337..9a5058d 100644 --- a/src/launch_profile/tests/rules.rs +++ b/src/launch_profile/tests/rules.rs @@ -53,8 +53,6 @@ fn single_disallow_matching_os_disallows() { #[test] fn allow_without_os_match_disallows_by_default() { - // explicit allow for windows; we are on linux; nothing matches; - // default state remains disallow. let rules = vec![Rule { action: RuleAction::Allow, os: Some(OsCondition { @@ -95,7 +93,6 @@ fn last_matching_rule_wins_when_allow_then_disallow() { features: &features, }; assert!(!evaluate(&rules, &osx_ctx)); - // and on linux: only the first rule matches → still allow. let lin = linux_ctx(&features); assert!(evaluate(&rules, &lin)); } @@ -136,7 +133,6 @@ fn arch_mismatch_blocks_rule() { }]; let features = FeatureSet::default(); let ctx = linux_ctx(&features); - // we are on linux but x86_64, not arm64 → rule does not match. assert!(!evaluate(&rules, &ctx)); } diff --git a/src/lib.rs b/src/lib.rs index 958e8f7..c76783b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,12 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// crate root. main.rs is a thin wrapper that imports the two entry points -// re-exported below; everything else stays crate-private. integration tests -// in tests/ that need to reach in deeper can use `rmcl::auth`, `rmcl::net`, -// etc. directly; cli + migrate stay private because they have nothing -// general to expose. - pub mod auth; mod cli; pub mod config; diff --git a/src/net/curseforge.rs b/src/net/curseforge.rs index 8131252..a76f62d 100644 --- a/src/net/curseforge.rs +++ b/src/net/curseforge.rs @@ -1,9 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// curseforge api client. responses are mapped into the same app-facing -// project/version types used by discovery, so the tui stays provider-neutral. - use serde::Deserialize; use crate::instance::{ContentKind, ModLoader}; diff --git a/src/net/fabric.rs b/src/net/fabric.rs index d79d3b5..50a94b0 100644 --- a/src/net/fabric.rs +++ b/src/net/fabric.rs @@ -1,9 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// fabric mod loader: fetches loader metadata and downloads libraries -// from fabric's maven. structurally very similar to quilt (they forked). - use std::path::Path; use serde::{Deserialize, Serialize}; @@ -51,9 +48,6 @@ pub async fn fetch_fabric_game_versions(client: &HttpClient) -> Result, } -// forge promotions use keys like "1.20.1-recommended", "1.20.1-latest" -// so this filters by game version prefix and extracts the forge version values pub async fn fetch_forge_versions( client: &HttpClient, game_version: &str, @@ -32,7 +26,6 @@ pub async fn fetch_forge_versions( fetch_forge_versions_from(client, FORGE_PROMOTIONS_URL, game_version).await } -// same as fetch_forge_versions but lets tests point at a wiremock server. pub async fn fetch_forge_versions_from( client: &HttpClient, promotions_url: &str, @@ -58,8 +51,6 @@ pub async fn fetch_forge_versions_from( Ok(versions) } -// extracts unique game versions from the promotion keys by splitting off -// the "-recommended"/"-latest" suffix pub async fn fetch_forge_game_versions(client: &HttpClient) -> Result, NetError> { fetch_forge_game_versions_from(client, FORGE_PROMOTIONS_URL).await } diff --git a/src/net/mod.rs b/src/net/mod.rs index 2561352..0f73a06 100644 --- a/src/net/mod.rs +++ b/src/net/mod.rs @@ -1,9 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// networking layer: http client, file downloads, and shared utilities -// for fetching game assets from mojang, mod loaders, and modrinth. - pub mod curseforge; pub mod fabric; pub mod forge; @@ -181,9 +178,6 @@ impl HttpClient { } } -// shared retry envelope around `client.get(url).await? -> decode`. retries -// transient failures (timeouts, connect errors, 5xx) with exponential -// backoff. used by both get_json and get_bytes. async fn get_with_retry(client: &HttpClient, url: &str, decode: F) -> Result where F: Fn(reqwest::Response) -> Fut, @@ -230,9 +224,7 @@ async fn sleep_before_retry(kind: &str, url: &str, attempt: u32, err: &NetError) tokio::time::sleep(std::time::Duration::from_millis(delay)).await; } -// streams a file to disk in chunks, calling progress_cb(downloaded, total) along the way. -// total will be 0 if the server doesn't send content-length, so callers -// should handle that gracefully. retries transient failures with exponential backoff. +// total is 0 without a Content-Length; callers must handle unknown sizes. pub async fn download_file( client: &HttpClient, url: &str, @@ -265,7 +257,6 @@ pub async fn download_file( result } -// single attempt at downloading a file to disk async fn download_file_once( client: &HttpClient, url: &str, diff --git a/src/net/modrinth.rs b/src/net/modrinth.rs index e44b472..7640594 100644 --- a/src/net/modrinth.rs +++ b/src/net/modrinth.rs @@ -1,8 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// modrinth api client and provider file downloads. - use serde::Deserialize; use std::collections::HashMap; diff --git a/src/net/mojang.rs b/src/net/mojang.rs index 9268ae0..8c091a1 100644 --- a/src/net/mojang.rs +++ b/src/net/mojang.rs @@ -1,10 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// handles all downloads from mojang's servers: version manifests, -// client jars, libraries, and asset objects. this is the core of -// getting vanilla minecraft onto disk. - use std::{ collections::HashMap, path::{Path, PathBuf}, @@ -136,9 +132,6 @@ pub async fn fetch_version_manifest(client: &HttpClient) -> Result Option { use sha1::Digest; use std::io::Read; @@ -187,7 +179,6 @@ fn sha1_hex(path: &Path) -> Option { Some(format!("{:x}", hasher.finalize())) } -// true when the cached file matches mojang's recorded size + sha1. // guards against partial files left by killed downloads: those used to be // trusted forever on the strength of an exists() check alone. size is // checked first so truncated files skip the hashing cost. @@ -282,8 +273,6 @@ pub async fn download_libraries( features: &features, }; - // matches the directory launch passes as java.library.path - // (instance/launch/mod.rs). let natives_dir = crate::storage::MetadataPaths::new(meta_dir) .versions() .join(&meta.id) @@ -383,9 +372,6 @@ pub async fn download_libraries( Ok(()) } -// relative path of a library artifact inside the shared library cache. -// upstream usually records it; fall back to deriving it from the maven -// coordinate when the field is missing/empty. fn library_relative_path(library: &Library, recorded_path: &str) -> Option { if !recorded_path.is_empty() { return Some(recorded_path.to_owned()); @@ -393,8 +379,6 @@ fn library_relative_path(library: &Library, recorded_path: &str) -> Option Result<(), NetError> { let file = std::fs::File::open(jar)?; let mut archive = zip::ZipArchive::new(file) @@ -410,7 +394,6 @@ fn extract_natives(jar: &Path, dest: &Path, exclude: &[String]) -> Result<(), Ne if entry.is_dir() { continue; } - // enclosed_name is None for absolute paths / .. traversal let Some(rel) = entry.enclosed_name() else { tracing::warn!( "Skipping unsafe path in natives jar {}: {}", @@ -443,8 +426,6 @@ pub async fn download_assets( download_assets_from(client, meta, meta_dir, ASSETS_BASE_URL).await } -// same as download_assets but lets tests point at a wiremock server for the -// per-asset CDN downloads. the asset index URL still comes from meta. pub async fn download_assets_from( client: &HttpClient, meta: &VersionMeta, @@ -503,8 +484,6 @@ pub async fn download_assets_from( index }; - // assets are stored by hash with the first 2 chars as a directory prefix, - // e.g. "ab/ab1234..." - same layout mojang uses on their CDN let mut downloads = Vec::new(); for object in asset_index.objects.values() { if object.hash.len() < 2 { @@ -546,9 +525,7 @@ pub async fn download_assets_from( result } -// bounded parallel downloader. spawns up to MAX_CONCURRENT_DOWNLOADS tasks -// and feeds new ones in as each completes. collects errors but keeps going -// so it downloads as much as possible before reporting the first failure. +// Continue other downloads after one fails; report the first error afterward. async fn run_parallel_downloads( client: &HttpClient, downloads: Vec<(String, PathBuf, String)>, diff --git a/src/net/neoforge.rs b/src/net/neoforge.rs index 4fea7e3..a7f7137 100644 --- a/src/net/neoforge.rs +++ b/src/net/neoforge.rs @@ -1,11 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// neoforge: the forge fork that broke away after 1.20.1. -// uses a different versioning scheme where neoforge versions map to -// minecraft versions by dropping the "1." prefix (e.g. MC 1.21 = NF 21.x). -// like forge, installation requires running their installer jar. - use std::path::Path; use serde::Deserialize; @@ -30,15 +25,11 @@ struct NeoForgeMavenVersions { fn game_version_to_neoforge_prefix(game_version: &str) -> Option { let parts: Vec<&str> = game_version.split('.').collect(); match parts.as_slice() { - // "1.21" → prefix "21.0." ["1", minor] => Some(format!("{}.0.", minor)), - // "1.20.4" → prefix "20.4." ["1", minor, patch] => Some(format!("{}.{}.", minor, patch)), - // "26.1.2" → prefix "26.1.2." [major, minor, patch] if leading_u32(major).is_some_and(|major| major >= 26) => { Some(format!("{major}.{minor}.{patch}.")) } - // "26.1" → prefix "26.1." [major, minor] if leading_u32(major).is_some_and(|major| major >= 26) => { Some(format!("{major}.{minor}.")) } @@ -80,7 +71,6 @@ pub async fn fetch_neoforge_versions( fetch_neoforge_versions_from(client, NEOFORGE_API_BASE, game_version).await } -// same as fetch_neoforge_versions but lets tests point at a wiremock server. pub async fn fetch_neoforge_versions_from( client: &HttpClient, api_url: &str, @@ -113,8 +103,6 @@ pub async fn fetch_neoforge_versions_from( Ok(versions) } -// reverse-engineers minecraft versions from neoforge version numbers. -// e.g. neoforge "21.0.x" means MC 1.21, "20.4.x" means MC 1.20.4 pub async fn fetch_neoforge_game_versions( client: &HttpClient, ) -> Result, NetError> { diff --git a/src/net/quilt.rs b/src/net/quilt.rs index 6fed8f1..ed5e977 100644 --- a/src/net/quilt.rs +++ b/src/net/quilt.rs @@ -1,9 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// quilt mod loader: fabric fork with a nearly identical metadata API. -// if you're getting deja vu reading this after fabric.rs, that's why. - use std::path::Path; use serde::{Deserialize, Serialize}; @@ -48,8 +45,6 @@ pub async fn fetch_quilt_game_versions(client: &HttpClient) -> Result>>> = LazyLock::new(|| Arc::new(Mutex::new(Vec::new()))); pub(super) static COMPLETED_INSTANCE_SETTINGS_UPDATES: LazyLock>>> = @@ -78,7 +71,6 @@ pub(super) struct ProviderConflictState { pub selected: usize, } -// lifecycle of an error toast animation: slide in -> sit there -> fade out pub(super) enum ErrorEffectState { SlidingIn(Effect, std::time::Instant), Idle, diff --git a/src/tui/event.rs b/src/tui/event.rs index f441843..26930c3 100644 --- a/src/tui/event.rs +++ b/src/tui/event.rs @@ -20,7 +20,6 @@ use crate::feedback::progress; use crate::instance::InstanceManager; impl App { - /// main loop: poll async results and input at ~60Hz, drawing only when state changes pub async fn run(&mut self, terminal: &mut Tui) -> color_eyre::Result<()> { let mut last_draw = std::time::Instant::now() .checked_sub(Duration::from_secs(1)) @@ -30,7 +29,6 @@ impl App { let mut image_redraw_marker = false; while !self.exit { let redraw_requested = crate::feedback::take_redraw_request(); - // check if any popup wizard finished and wants to create/import if let Some(params) = new_instance::take_result() { self.spawn_create(params); } @@ -42,9 +40,6 @@ impl App { self.dismiss_expired_errors(); - // drain all the channels from background tasks. - // every content type has its own pending queue because they each - // get scanned/loaded on separate tokio tasks self.drain_pending_instances(); self.drain_completed_instance_settings_updates(); self.drain_failed_instance_settings_updates(); @@ -543,8 +538,6 @@ impl App { }); } - // polls for input with a 16ms timeout (~60fps). only key presses are handled, - // releases and repeats are ignored thanks to the enhanced keyboard protocol fn handle_events(&mut self) -> color_eyre::Result { match crossterm::event::poll(Duration::from_millis(16)) { Ok(true) => match event::read() { @@ -879,8 +872,6 @@ impl App { }); } - // pops errors from the front of the queue once they've been visible long enough. - // loops because multiple errors could expire in the same frame fn dismiss_expired_errors(&self) { use crate::config::SETTINGS; loop { diff --git a/src/tui/input.rs b/src/tui/input.rs index 262bc7a..f14c32e 100644 --- a/src/tui/input.rs +++ b/src/tui/input.rs @@ -1,11 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// keybindings and input dispatch. -// the general pattern: check which area is focused, give it first crack at the -// keypress, and fall through to global bindings if nobody claimed it. -// vim-style navigation (j/k/g/G) where it makes sense. - use ratatui::crossterm::event::{ KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind, }; @@ -415,8 +410,6 @@ impl App { } } - // content area delegates to whichever tab is active. - // worlds use the same list navigation without the toggle if self.focused == FocusedArea::Content && self.content_mode == widgets::content::ContentMode::Installed && let Some(state) = self.active_discovery_state_mut() @@ -956,7 +949,6 @@ impl App { return Ok(()); } - // global keybindings (uppercase = area switch, lowercase = action) match key_event.code { KeyCode::Char('q') => self.exit = true, KeyCode::Esc @@ -1049,7 +1041,6 @@ impl App { } } } - // shift+enter = open .minecraft folder in file manager KeyCode::Enter if self.focused == FocusedArea::Instances && !self.instances_state.search.active @@ -1066,7 +1057,6 @@ impl App { } } } - // plain enter = focus the content area for the selected instance KeyCode::Enter if self.focused == FocusedArea::Instances && !self.instances_state.search.active => @@ -1110,7 +1100,6 @@ impl App { } } } - // esc = kill running instance. brutal but effective KeyCode::Esc if self.focused == FocusedArea::Instances && !self.instances_state.search.active => diff --git a/src/tui/logging.rs b/src/tui/logging.rs index cc968ed..73539c9 100644 --- a/src/tui/logging.rs +++ b/src/tui/logging.rs @@ -1,10 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// sets up the tracing subscriber stack: file logging, tui-logger widget, and -// our custom StatusLayer that feeds WARN/ERROR events into the error toast system. -// also keeps an in-memory ring buffer of log lines for the log overlay viewer. - use std::fmt; use std::path::Path; use std::sync::{Arc, Mutex}; @@ -24,7 +20,6 @@ use crate::feedback::errors::{self as error_buffer, ErrorEvent}; const MINECRAFT_LOG_TARGET: &str = "mc_instance"; const DEFAULT_FILE_FILTER: &str = "warn,rmcl=trace"; -// capped at 5000 lines so it doesn't eat all the ram if something goes haywire static APP_LOG_LINES: LazyLock>>> = LazyLock::new(|| Arc::new(Mutex::new(Vec::new()))); @@ -44,8 +39,6 @@ fn push_app_log(line: String) { // returns a WorkerGuard that must be held alive for the duration of the // program, otherwise the file logging thread gets dropped immediately. -// yes, you will spend 30 minutes debugging "why aren't my logs writing" -// before you remember this. ask me how i know. pub fn init() -> WorkerGuard { let log_dir = match dirs_next::cache_dir() { Some(d) => d.join("rmcl"), @@ -118,9 +111,6 @@ fn open_log_writer(log_dir: &Path) -> (NonBlocking, WorkerGuard) { } } -// custom tracing layer that intercepts all log events: -// - everything gets appended to the in-memory log buffer for the overlay viewer -// - WARN and ERROR additionally get pushed as error toasts struct StatusLayer; impl StatusLayer { 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..178eea3 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}, @@ -165,7 +160,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,8 +214,6 @@ impl App { } } - // full-screen log viewer with search highlighting and auto-scroll. - // auto-sticks to the bottom unless the user scrolled up manually fn render_log_overlay(&mut self, frame: &mut Frame) { use crate::config::theme::{BORDER_STYLE, THEME}; use crate::tui::logging::get_app_logs; @@ -322,8 +314,6 @@ impl App { ); } - // 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 +338,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/widgets/content/discovery.rs b/src/tui/tests/widgets/content/discovery.rs index c7c4d14..6d811a5 100644 --- a/src/tui/tests/widgets/content/discovery.rs +++ b/src/tui/tests/widgets/content/discovery.rs @@ -1428,7 +1428,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 +1504,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/search.rs b/src/tui/tests/widgets/search.rs index eea224b..a6e328a 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")); } diff --git a/src/tui/widgets/account.rs b/src/tui/widgets/account.rs index ff1e843..f6ce5e2 100644 --- a/src/tui/widgets/account.rs +++ b/src/tui/widgets/account.rs @@ -1,10 +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}; @@ -196,8 +192,6 @@ 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 && info.user_code.is_empty() @@ -335,7 +329,6 @@ 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; diff --git a/src/tui/widgets/content/list.rs b/src/tui/widgets/content/list.rs index 2dd2c95..c4f39b6 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; @@ -245,7 +240,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, @@ -292,19 +286,15 @@ pub struct ContentListState { 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, @@ -1175,7 +1165,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(""), @@ -1214,7 +1203,6 @@ 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); let replacement = self.entries.iter().position(|existing| { @@ -1310,13 +1298,10 @@ 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; let watcher_diff = self.watcher_diff.clone(); @@ -1706,9 +1691,6 @@ impl ContentListState { } } - // 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,7 +1706,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() { @@ -1743,7 +1724,6 @@ impl ContentListState { ); } - // 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; @@ -1769,7 +1749,6 @@ impl ContentListState { 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(); @@ -2690,8 +2669,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; @@ -2976,10 +2953,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..6e49e07 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 => { @@ -1762,8 +1756,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/instances.rs b/src/tui/widgets/instances.rs index d59381d..e4ee452 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::{ diff --git a/src/tui/widgets/logs_viewer.rs b/src/tui/widgets/logs_viewer.rs index 229b8a1..8555958 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}; @@ -132,7 +127,6 @@ impl LogsState { } } - // 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; @@ -676,8 +670,6 @@ fn log_level_style(level: LogLevel) -> Style { } } -// 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(); diff --git a/src/tui/widgets/mod.rs b/src/tui/widgets/mod.rs index b00cba9..faf4607 100644 --- a/src/tui/widgets/mod.rs +++ b/src/tui/widgets/mod.rs @@ -1,8 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// shared widget utilities and the trait all key-handling widgets implement - use crate::config::theme::THEME; use crossterm::event::KeyEvent; use ratatui::{ 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..61a04b5 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, 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..a49167a 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}; @@ -387,7 +383,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 +414,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 +552,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..249dad8 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, 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/render.rs b/src/tui/widgets/popups/new_instance/render.rs index 2e50f21..ab5f2f7 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())), diff --git a/src/tui/widgets/popups/new_instance/state.rs b/src/tui/widgets/popups/new_instance/state.rs index 7afe6aa..ac37d4c 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))); @@ -163,7 +158,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,12 +170,8 @@ 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 @@ -384,8 +374,7 @@ 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; diff --git a/src/tui/widgets/popups/select_list.rs b/src/tui/widgets/popups/select_list.rs index d7b3f22..fcfa8a5 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, diff --git a/src/tui/widgets/popups/settings_controls.rs b/src/tui/widgets/popups/settings_controls.rs index 3d0b798..921e33a 100644 --- a/src/tui/widgets/popups/settings_controls.rs +++ b/src/tui/widgets/popups/settings_controls.rs @@ -1,8 +1,6 @@ // 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}, path::{Path, PathBuf}, 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..21e5381 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}; @@ -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; @@ -373,9 +367,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() diff --git a/src/tui/widgets/search.rs b/src/tui/widgets/search.rs index edc9459..4b54685 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)]; @@ -94,7 +89,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..492e69f 100644 --- a/src/tui/widgets/settings.rs +++ b/src/tui/widgets/settings.rs @@ -1,9 +1,6 @@ // 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 crossterm::event::{KeyCode, KeyEvent}; 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/launch_pipeline.rs b/tests/launch_pipeline.rs index b51d76f..e235c78 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; @@ -18,8 +12,6 @@ use rmcl::instance::launch::{ }; 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"; @@ -86,11 +78,6 @@ fn fake_java(tmp: &TempDir, major: u32) -> String { 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) struct Fixture { _tmp: TempDir, instances_dir: PathBuf, @@ -208,8 +195,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")); @@ -247,12 +232,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"); @@ -339,12 +322,10 @@ 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!(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,8 +333,6 @@ async fn vanilla_legacy_args_format_substitutes_tokens() { assert!(joined.contains("--userType msa")); } -// ---------- forge ---------- - #[tokio::test] async fn forge_modern_includes_add_opens() { let fx = Fixture::new("f1", "1.20.1", modern_vanilla_meta("1.20.1")); @@ -444,7 +423,6 @@ 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"); @@ -454,8 +432,6 @@ async fn forge_local_lib_dir_preferred_over_meta_dir() { ); } -// ---------- 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 +458,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 +476,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 +514,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 +547,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 +563,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 +572,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 +579,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!([ { @@ -654,8 +620,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 +671,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 +680,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(); 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..ab7a6f1 100644 --- a/tests/net_loaders.rs +++ b/tests/net_loaders.rs @@ -1,11 +1,6 @@ // 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}; @@ -20,8 +15,6 @@ use rmcl::net::quilt::{ 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 +60,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 +136,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,8 +196,6 @@ async fn quilt_fetch_profile_parses_libraries() { ); } -// ---------- neoforge ---------- - #[tokio::test] async fn neoforge_fetch_versions_filters_by_prefix() { let server = MockServer::start().await; @@ -292,7 +278,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 +285,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..afa09e4 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}; @@ -112,8 +106,6 @@ 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"); @@ -214,7 +206,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"); } diff --git a/tests/net_retry.rs b/tests/net_retry.rs index 148c706..ec2d4ec 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| { @@ -124,8 +115,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; 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; From 7e7e5c0c31a0d7a05e09e71bd9364b115952fe1b Mon Sep 17 00:00:00 2001 From: objz Date: Thu, 1 Oct 2026 14:21:27 +0200 Subject: [PATCH 02/34] refactor: share loader library downloads and validate settings --- src/cli/import.rs | 3 +- src/layout_migration.rs | 6 +-- src/net/fabric.rs | 42 ++++------------ src/net/mod.rs | 25 ++++++++++ src/net/quilt.rs | 42 ++++------------ src/tui/widgets/popups/global_settings.rs | 38 +++++++-------- tests/net_loaders.rs | 59 ++++++++++++++++++++++- 7 files changed, 126 insertions(+), 89 deletions(-) diff --git a/src/cli/import.rs b/src/cli/import.rs index 6a7eb17..279be27 100644 --- a/src/cli/import.rs +++ b/src/cli/import.rs @@ -3,6 +3,7 @@ use clap::ArgMatches; +use super::utils::required_arg; use crate::instance::InstanceManager; use crate::instance::import::{ImportInput, parse_import_input}; use crate::net::modrinth; @@ -10,7 +11,7 @@ use crate::net::modrinth; type CliResult = Result<(), Box>; pub async fn handle_import(matches: &ArgMatches) -> CliResult { - let input = matches.get_one::("source").unwrap(); + let input = required_arg(matches, "source")?; let override_name = matches.get_one::("name"); let override_version = matches.get_one::("version"); diff --git a/src/layout_migration.rs b/src/layout_migration.rs index 7a9d97f..62e7987 100644 --- a/src/layout_migration.rs +++ b/src/layout_migration.rs @@ -353,9 +353,9 @@ fn backup_user_data( }, )?; if config_file.exists() { - let destination = partial.join("config").join("config.toml"); - fs::create_dir_all(destination.parent().unwrap())?; - let bytes = fs::copy(config_file, destination)?; + let config_backup = partial.join("config"); + fs::create_dir_all(&config_backup)?; + let bytes = fs::copy(config_file, config_backup.join("config.toml"))?; copied = copied.saturating_add(bytes); report(copied, total, config_file); } diff --git a/src/net/fabric.rs b/src/net/fabric.rs index 50a94b0..12d8c59 100644 --- a/src/net/fabric.rs +++ b/src/net/fabric.rs @@ -5,9 +5,8 @@ use std::path::Path; use serde::{Deserialize, Serialize}; -use crate::feedback::progress::set_sub_action; use crate::instance::loader::GameVersion; -use crate::net::{HttpClient, NetError, download_file}; +use crate::net::{HttpClient, NetError, download_loader_libraries}; const FABRIC_META_BASE: &str = "https://meta.fabricmc.net/v2"; @@ -150,40 +149,19 @@ pub async fn download_fabric_libraries( profile: &FabricProfile, meta_dir: &Path, ) -> Result<(), NetError> { - let libraries_dir = crate::storage::MetadataPaths::new(meta_dir).libraries(); tracing::debug!( "Resolving {} Fabric libraries into {}", profile.libraries.len(), - libraries_dir.display() + crate::storage::MetadataPaths::new(meta_dir) + .libraries() + .display() ); - - for lib in &profile.libraries { - let maven_path = match crate::instance::loader::maven::maven_coord_to_path(&lib.name) { - Some(p) => p, - None => { - return Err(NetError::Parse(format!( - "Invalid Maven coordinate: {}", - lib.name - ))); - } - }; - - let dest = libraries_dir.join(&maven_path); - - if dest.exists() { - tracing::debug!("Fabric library already exists: {}", lib.name); - continue; - } - - let base_url = lib.url.trim_end_matches('/'); - let download_url = format!("{}/{}", base_url, maven_path); - - set_sub_action(&lib.name); - tracing::info!("Downloading Fabric library: {}", lib.name); - tracing::trace!("Fabric library destination: {}", dest.display()); - - download_file(client, &download_url, &dest, |_, _| {}).await?; - } + let libraries: Vec<_> = profile + .libraries + .iter() + .map(|lib| (lib.name.as_str(), lib.url.as_str())) + .collect(); + download_loader_libraries(client, libraries, meta_dir, "Fabric").await?; tracing::debug!("Fabric library resolution complete for {}", profile.id); Ok(()) diff --git a/src/net/mod.rs b/src/net/mod.rs index 0f73a06..a0c597a 100644 --- a/src/net/mod.rs +++ b/src/net/mod.rs @@ -257,6 +257,31 @@ pub async fn download_file( result } +pub(crate) async fn download_loader_libraries<'a>( + client: &HttpClient, + libraries: impl IntoIterator, + meta_dir: &Path, + loader: &str, +) -> Result<(), NetError> { + let libraries_dir = crate::storage::MetadataPaths::new(meta_dir).libraries(); + for (name, url) in libraries { + let maven_path = crate::instance::loader::maven::maven_coord_to_path(name) + .ok_or_else(|| NetError::Parse(format!("Invalid Maven coordinate: {name}")))?; + let dest = libraries_dir.join(&maven_path); + if dest.exists() { + tracing::debug!("{loader} library already exists: {name}"); + continue; + } + + let download_url = format!("{}/{}", url.trim_end_matches('/'), maven_path); + crate::feedback::progress::set_sub_action(name); + tracing::info!("Downloading {loader} library: {name}"); + tracing::trace!("{loader} library destination: {}", dest.display()); + download_file(client, &download_url, &dest, |_, _| {}).await?; + } + Ok(()) +} + async fn download_file_once( client: &HttpClient, url: &str, diff --git a/src/net/quilt.rs b/src/net/quilt.rs index ed5e977..fd4565e 100644 --- a/src/net/quilt.rs +++ b/src/net/quilt.rs @@ -5,9 +5,8 @@ use std::path::Path; use serde::{Deserialize, Serialize}; -use crate::feedback::progress::set_sub_action; use crate::instance::loader::GameVersion; -use crate::net::{HttpClient, NetError, download_file}; +use crate::net::{HttpClient, NetError, download_loader_libraries}; const QUILT_META_BASE: &str = "https://meta.quiltmc.org/v3"; @@ -147,40 +146,19 @@ pub async fn download_quilt_libraries( profile: &QuiltProfile, meta_dir: &Path, ) -> Result<(), NetError> { - let libraries_dir = crate::storage::MetadataPaths::new(meta_dir).libraries(); tracing::debug!( "Resolving {} Quilt libraries into {}", profile.libraries.len(), - libraries_dir.display() + crate::storage::MetadataPaths::new(meta_dir) + .libraries() + .display() ); - - for lib in &profile.libraries { - let maven_path = match crate::instance::loader::maven::maven_coord_to_path(&lib.name) { - Some(p) => p, - None => { - return Err(NetError::Parse(format!( - "Invalid Maven coordinate: {}", - lib.name - ))); - } - }; - - let dest = libraries_dir.join(&maven_path); - - if dest.exists() { - tracing::debug!("Quilt library already exists: {}", lib.name); - continue; - } - - let base_url = lib.url.trim_end_matches('/'); - let download_url = format!("{}/{}", base_url, maven_path); - - set_sub_action(&lib.name); - tracing::info!("Downloading Quilt library: {}", lib.name); - tracing::trace!("Quilt library destination: {}", dest.display()); - - download_file(client, &download_url, &dest, |_, _| {}).await?; - } + let libraries: Vec<_> = profile + .libraries + .iter() + .map(|lib| (lib.name.as_str(), lib.url.as_str())) + .collect(); + download_loader_libraries(client, libraries, meta_dir, "Quilt").await?; tracing::debug!("Quilt library resolution complete for {}", profile.id); Ok(()) diff --git a/src/tui/widgets/popups/global_settings.rs b/src/tui/widgets/popups/global_settings.rs index 61a04b5..3dcb2c8 100644 --- a/src/tui/widgets/popups/global_settings.rs +++ b/src/tui/widgets/popups/global_settings.rs @@ -193,26 +193,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; diff --git a/tests/net_loaders.rs b/tests/net_loaders.rs index ab7a6f1..89059cb 100644 --- a/tests/net_loaders.rs +++ b/tests/net_loaders.rs @@ -7,12 +7,14 @@ 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, }; #[tokio::test] @@ -196,6 +198,59 @@ async fn quilt_fetch_profile_parses_libraries() { ); } +#[tokio::test] +async fn fabric_and_quilt_download_libraries_into_the_shared_cache() { + let server = MockServer::start().await; + let temp = tempfile::tempdir().unwrap(); + for (name, content) in [("fabric", "fabric jar"), ("quilt", "quilt jar")] { + Mock::given(method("GET")) + .and(path(format!("/example/{name}/1.0/{name}-1.0.jar"))) + .respond_with(ResponseTemplate::new(200).set_body_string(content)) + .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, content) in [("fabric", "fabric jar"), ("quilt", "quilt jar")] { + assert_eq!( + std::fs::read( + rmcl::storage::MetadataPaths::new(temp.path()) + .libraries() + .join(format!("example/{name}/1.0/{name}-1.0.jar")) + ) + .unwrap(), + content.as_bytes() + ); + } +} + #[tokio::test] async fn neoforge_fetch_versions_filters_by_prefix() { let server = MockServer::start().await; From 22a3eebe789e8d5ed0a06b4bc2dd7204c634c5aa Mon Sep 17 00:00:00 2001 From: objz Date: Thu, 1 Oct 2026 14:29:24 +0200 Subject: [PATCH 03/34] refactor: reuse shortcut sanitizer and scrollbar styling --- src/instance/desktop.rs | 2 +- src/migrate.rs | 17 ++--------------- src/tui/render.rs | 14 ++------------ src/tui/widgets/content/list.rs | 14 ++------------ src/tui/widgets/instances.rs | 14 ++------------ src/tui/widgets/logs_viewer.rs | 26 +++----------------------- src/tui/widgets/mod.rs | 11 +++++++++++ src/tui/widgets/screenshots_grid.rs | 14 ++------------ 8 files changed, 25 insertions(+), 87 deletions(-) diff --git a/src/instance/desktop.rs b/src/instance/desktop.rs index f0314c8..82b8654 100644 --- a/src/instance/desktop.rs +++ b/src/instance/desktop.rs @@ -225,7 +225,7 @@ fn quote_windows_arg(value: &str) -> String { quoted } -fn sanitize(name: &str) -> String { +pub(crate) fn sanitize(name: &str) -> String { name.chars() .map(|c| { if c.is_alphanumeric() || c == '-' || c == '_' { diff --git a/src/migrate.rs b/src/migrate.rs index 2c64ff1..8098e5d 100644 --- a/src/migrate.rs +++ b/src/migrate.rs @@ -126,7 +126,7 @@ fn rewrite_linux_desktop_entries(_data_dir: &Path, _instances_dir: &Path) { }; for entry in entries.flatten() { let name = entry.file_name(); - let sanitized = sanitize(&name.to_string_lossy()); + let sanitized = crate::instance::desktop::sanitize(&name.to_string_lossy()); let old = apps_dir.join(format!("mcl-{sanitized}.desktop")); let new = apps_dir.join(format!("rmcl-{sanitized}.desktop")); if old.exists() @@ -159,7 +159,7 @@ fn rewrite_native_desktop_shortcuts(_desktop_dir: &Path, _instances_dir: &Path) let display = entry.file_name().to_string_lossy().into_owned(); // mcl named shortcut files with the sanitized form of the // instance name ("My Pack" -> "My_Pack"), so look those up. - let sanitized = sanitize(&display); + let sanitized = crate::instance::desktop::sanitize(&display); let path = _desktop_dir.join(format!("Minecraft - {sanitized}.{ext}")); if !path.exists() { continue; @@ -174,19 +174,6 @@ fn rewrite_native_desktop_shortcuts(_desktop_dir: &Path, _instances_dir: &Path) } } -#[allow(dead_code)] -fn sanitize(name: &str) -> String { - name.chars() - .map(|c| { - if c.is_alphanumeric() || c == '-' || c == '_' { - c - } else { - '_' - } - }) - .collect() -} - #[cfg(test)] #[path = "tests/migrate.rs"] mod tests; diff --git a/src/tui/render.rs b/src/tui/render.rs index 178eea3..f434f09 100644 --- a/src/tui/render.rs +++ b/src/tui/render.rs @@ -221,7 +221,7 @@ impl App { layout::{Alignment, Margin}, style::{Modifier, Style}, text::Line, - widgets::{Block, Clear, Paragraph, Scrollbar, ScrollbarOrientation}, + widgets::{Block, Clear, Paragraph}, }; let theme = THEME.as_ref(); @@ -298,17 +298,7 @@ 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, ); diff --git a/src/tui/widgets/content/list.rs b/src/tui/widgets/content/list.rs index c4f39b6..fb1c96b 100644 --- a/src/tui/widgets/content/list.rs +++ b/src/tui/widgets/content/list.rs @@ -12,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}; @@ -2439,17 +2439,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, ); diff --git a/src/tui/widgets/instances.rs b/src/tui/widgets/instances.rs index e4ee452..7c69c85 100644 --- a/src/tui/widgets/instances.rs +++ b/src/tui/widgets/instances.rs @@ -8,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}; @@ -384,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/logs_viewer.rs b/src/tui/widgets/logs_viewer.rs index 8555958..8d4b06b 100644 --- a/src/tui/widgets/logs_viewer.rs +++ b/src/tui/widgets/logs_viewer.rs @@ -10,7 +10,7 @@ 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}; @@ -550,17 +550,7 @@ 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, ); @@ -639,17 +629,7 @@ fn render_viewer( 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.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.viewer_scrollbar_state, ); diff --git a/src/tui/widgets/mod.rs b/src/tui/widgets/mod.rs index faf4607..31ba915 100644 --- a/src/tui/widgets/mod.rs +++ b/src/tui/widgets/mod.rs @@ -6,6 +6,7 @@ use crossterm::event::KeyEvent; use ratatui::{ style::{Color, Modifier, Style}, text::{Line, Span}, + widgets::{Scrollbar, ScrollbarOrientation}, }; pub mod account; @@ -47,6 +48,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/screenshots_grid.rs b/src/tui/widgets/screenshots_grid.rs index 21e5381..c4f6ddc 100644 --- a/src/tui/widgets/screenshots_grid.rs +++ b/src/tui/widgets/screenshots_grid.rs @@ -11,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; @@ -445,17 +445,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, ); From 2b6750a9710e51a9d2633eecb4ed20da8afbf833 Mon Sep 17 00:00:00 2001 From: objz Date: Thu, 1 Oct 2026 17:40:14 +0200 Subject: [PATCH 04/34] fix: preserve account data and validate CLI operations --- src/auth/accounts.rs | 96 ++++++++++++++++++++++---------------- src/auth/oauth.rs | 14 ++++-- src/auth/tests/accounts.rs | 89 ++++++++++++++++++++++++----------- src/cli/account.rs | 69 +++++++++++++++++---------- src/cli/instance.rs | 20 +++++--- src/cli/log.rs | 31 +++++++----- src/cli/tests/account.rs | 35 +++++++++++++- src/cli/tests/instance.rs | 12 +++++ src/cli/tests/log.rs | 18 +++++++ src/cli/utils.rs | 1 + src/storage.rs | 34 +++++++++++--- 11 files changed, 300 insertions(+), 119 deletions(-) diff --git a/src/auth/accounts.rs b/src/auth/accounts.rs index c749986..cde129d 100644 --- a/src/auth/accounts.rs +++ b/src/auth/accounts.rs @@ -34,26 +34,36 @@ pub enum AuthResult { pub struct AccountStore { pub accounts: Vec, path: PathBuf, + load_error: Option, } impl AccountStore { pub fn load() -> Self { - let path = account_store_path(); - let accounts = match std::fs::read_to_string(&path) { + Self::load_from(account_store_path()) + } + + fn load_from(path: PathBuf) -> Self { + let (accounts, load_error) = match std::fs::read_to_string(&path) { Ok(content) => match serde_json::from_str(&content) { - Ok(accounts) => accounts, + Ok(accounts) => (accounts, None), Err(e) => { tracing::warn!("Failed to parse accounts file {}: {}", path.display(), e); - Vec::new() + ( + Vec::new(), + Some(format!("Invalid accounts file {}: {e}", path.display())), + ) } }, Err(e) if e.kind() == std::io::ErrorKind::NotFound => { tracing::debug!("No accounts file at {}", path.display()); - Vec::new() + (Vec::new(), None) } Err(e) => { tracing::warn!("Failed to read accounts file {}: {}", path.display(), e); - Vec::new() + ( + Vec::new(), + Some(format!("Cannot read accounts file {}: {e}", path.display())), + ) } }; tracing::debug!( @@ -61,36 +71,25 @@ impl AccountStore { accounts.len(), path.display() ); - Self { accounts, path } + Self { + accounts, + path, + load_error, + } } - pub fn save(&self) { - if let Some(parent) = self.path.parent() - && let Err(e) = std::fs::create_dir_all(parent) - { - tracing::error!("Failed to create accounts directory: {}", e); - return; - } - match serde_json::to_string_pretty(&self.accounts) { - Ok(json) => { - // this file holds microsoft refresh tokens: a torn write on - // crash would permanently lock the user out, so write atomically. - if let Err(e) = crate::storage::write_atomic(&self.path, json.as_bytes()) { - tracing::error!( - "Failed to write accounts file {}: {}", - self.path.display(), - e - ); - } else { - tracing::debug!( - "Saved {} account(s) to {}", - self.accounts.len(), - self.path.display() - ); - } - } - Err(e) => tracing::error!("Failed to serialize accounts: {}", e), + pub fn save(&self) -> std::io::Result<()> { + if let Some(error) = &self.load_error { + return Err(std::io::Error::other(error.clone())); } + let json = serde_json::to_vec_pretty(&self.accounts).map_err(std::io::Error::other)?; + crate::storage::write_atomic_private(&self.path, &json)?; + tracing::debug!( + "Saved {} account(s) to {}", + self.accounts.len(), + self.path.display() + ); + Ok(()) } pub fn active_account(&self) -> Option<&Account> { @@ -103,25 +102,31 @@ impl AccountStore { .any(|account| account.account_type == AccountType::Microsoft) } - pub fn set_active(&mut self, index: usize) { + pub fn set_active(&mut self, index: usize) -> std::io::Result<()> { let Some(account) = self.accounts.get(index) else { // out-of-range: leave the current selection untouched. marking // every account inactive here would break the single-active // invariant and orphan the store with no usable account. tracing::warn!("Tried to select missing account index {}", index); - return; + return Ok(()); }; + let previous = self.accounts.clone(); let username = account.username.clone(); for (i, acc) in self.accounts.iter_mut().enumerate() { acc.active = i == index; } tracing::info!("Selected account '{}'", username); - self.save(); + if let Err(error) = self.save() { + self.accounts = previous; + return Err(error); + } + Ok(()) } // if an account with the same uuid already exists, replace it. // first account added auto-becomes active so there's always a selection. - pub fn add(&mut self, account: Account) { + pub fn add(&mut self, account: Account) -> std::io::Result<()> { + let previous = self.accounts.clone(); let uuid = &account.uuid; let replaced = self.accounts.iter().any(|a| a.uuid == *uuid); // re-adding the currently active account must not drop the selection: @@ -141,14 +146,19 @@ impl AccountStore { account_type, username ); - self.save(); + if let Err(error) = self.save() { + self.accounts = previous; + return Err(error); + } + Ok(()) } - pub fn remove(&mut self, index: usize) { + pub fn remove(&mut self, index: usize) -> std::io::Result<()> { if index >= self.accounts.len() { tracing::warn!("Tried to remove missing account index {}", index); - return; + return Ok(()); } + let previous = self.accounts.clone(); let account = self.accounts.remove(index); tracing::info!( "Removed {:?} account '{}'", @@ -159,7 +169,11 @@ impl AccountStore { self.accounts[0].active = true; tracing::debug!("Activated fallback account '{}'", self.accounts[0].username); } - self.save(); + if let Err(error) = self.save() { + self.accounts = previous; + return Err(error); + } + Ok(()) } } diff --git a/src/auth/oauth.rs b/src/auth/oauth.rs index 7a76fa9..377d792 100644 --- a/src/auth/oauth.rs +++ b/src/auth/oauth.rs @@ -90,6 +90,9 @@ async fn run_full_oauth_flow() -> Result<(String, Option), String> { } pub fn start_microsoft_auth() -> Arc>> { + if let Ok(mut slot) = DEVICE_CODE_DISPLAY.lock() { + *slot = None; + } let result: Arc>> = Arc::new(Mutex::new(None)); let result_clone = result.clone(); @@ -110,7 +113,12 @@ async fn run_full_auth_flow() -> AuthResult { Err(e) => return AuthResult::Error(e), }; - exchange_and_build_account(&ms_access_token, ms_refresh_token.as_deref()).await + let Some(refresh_token) = ms_refresh_token.as_deref() else { + return AuthResult::Error( + "Microsoft did not return a refresh token; try signing in again".to_owned(), + ); + }; + exchange_and_build_account(&ms_access_token, Some(refresh_token)).await } async fn exchange_and_build_account( @@ -158,8 +166,8 @@ async fn exchange_and_build_account( account_type: AccountType::Microsoft, active: false, refresh_token: ms_refresh_token.map(|s| s.to_owned()), - cached_mc_token: None, - cached_mc_token_expires_at: None, + cached_mc_token: Some(mc_token.access_token().as_ref().to_owned()), + cached_mc_token_expires_at: Some(chrono::Utc::now().timestamp() + MC_TOKEN_CACHE_TTL_SECS), }) } diff --git a/src/auth/tests/accounts.rs b/src/auth/tests/accounts.rs index f5ca818..500f7e3 100644 --- a/src/auth/tests/accounts.rs +++ b/src/auth/tests/accounts.rs @@ -8,6 +8,7 @@ impl AccountStore { Self { accounts: Vec::new(), path, + load_error: None, } } } @@ -58,6 +59,7 @@ fn make_store(dir: &std::path::Path) -> AccountStore { AccountStore { accounts: Vec::new(), path: dir.join("accounts.json"), + load_error: None, } } @@ -77,7 +79,7 @@ fn microsoft_account(name: &str) -> Account { fn store_add_first_becomes_active() { let tmp = tempfile::tempdir().unwrap(); let mut store = make_store(tmp.path()); - store.add(create_offline_account("Alice")); + store.add(create_offline_account("Alice")).unwrap(); assert_eq!(store.accounts.len(), 1); assert!(store.accounts[0].active); } @@ -86,8 +88,8 @@ fn store_add_first_becomes_active() { fn store_add_second_stays_inactive() { let tmp = tempfile::tempdir().unwrap(); let mut store = make_store(tmp.path()); - store.add(create_offline_account("Alice")); - store.add(create_offline_account("Bob")); + store.add(create_offline_account("Alice")).unwrap(); + store.add(create_offline_account("Bob")).unwrap(); assert_eq!(store.accounts.len(), 2); assert!(store.accounts[0].active); assert!(!store.accounts[1].active); @@ -97,11 +99,11 @@ fn store_add_second_stays_inactive() { fn store_add_duplicate_uuid_replaces() { let tmp = tempfile::tempdir().unwrap(); let mut store = make_store(tmp.path()); - store.add(create_offline_account("Alice")); + store.add(create_offline_account("Alice")).unwrap(); let mut dup = create_offline_account("Alice"); dup.username = "AliceRenamed".to_owned(); dup.uuid = store.accounts[0].uuid.clone(); - store.add(dup); + store.add(dup).unwrap(); assert_eq!(store.accounts.len(), 1); assert_eq!(store.accounts[0].username, "AliceRenamed"); } @@ -117,10 +119,10 @@ fn store_active_account_none_when_empty() { fn store_has_microsoft_account_when_one_exists() { let tmp = tempfile::tempdir().unwrap(); let mut store = make_store(tmp.path()); - store.add(create_offline_account("Offline")); + store.add(create_offline_account("Offline")).unwrap(); assert!(!store.has_microsoft_account()); - store.add(microsoft_account("Owner")); + store.add(microsoft_account("Owner")).unwrap(); assert!(store.has_microsoft_account()); } @@ -128,8 +130,8 @@ fn store_has_microsoft_account_when_one_exists() { fn store_active_account_returns_active() { let tmp = tempfile::tempdir().unwrap(); let mut store = make_store(tmp.path()); - store.add(create_offline_account("Alice")); - store.add(create_offline_account("Bob")); + store.add(create_offline_account("Alice")).unwrap(); + store.add(create_offline_account("Bob")).unwrap(); let active = store.active_account().unwrap(); assert_eq!(active.username, "Alice"); } @@ -138,9 +140,9 @@ fn store_active_account_returns_active() { fn store_set_active_changes_active() { let tmp = tempfile::tempdir().unwrap(); let mut store = make_store(tmp.path()); - store.add(create_offline_account("Alice")); - store.add(create_offline_account("Bob")); - store.set_active(1); + store.add(create_offline_account("Alice")).unwrap(); + store.add(create_offline_account("Bob")).unwrap(); + store.set_active(1).unwrap(); assert!(!store.accounts[0].active); assert!(store.accounts[1].active); } @@ -149,9 +151,9 @@ fn store_set_active_changes_active() { fn store_set_active_out_of_bounds_keeps_selection() { let tmp = tempfile::tempdir().unwrap(); let mut store = make_store(tmp.path()); - store.add(create_offline_account("Alice")); - store.add(create_offline_account("Bob")); - store.set_active(99); + store.add(create_offline_account("Alice")).unwrap(); + store.add(create_offline_account("Bob")).unwrap(); + store.set_active(99).unwrap(); assert!( store.accounts[0].active, "existing selection must survive a bad index" @@ -163,11 +165,11 @@ fn store_set_active_out_of_bounds_keeps_selection() { fn store_add_replacing_active_keeps_active() { let tmp = tempfile::tempdir().unwrap(); let mut store = make_store(tmp.path()); - store.add(create_offline_account("Alice")); - store.add(create_offline_account("Bob")); + store.add(create_offline_account("Alice")).unwrap(); + store.add(create_offline_account("Bob")).unwrap(); let mut dup = create_offline_account("Alice"); dup.username = "AliceRenamed".to_owned(); - store.add(dup); + store.add(dup).unwrap(); assert!( store.accounts.iter().any(|a| a.active), "re-adding the active account must not orphan the selection" @@ -180,9 +182,9 @@ fn store_add_replacing_active_keeps_active() { fn store_remove_activates_first_remaining() { let tmp = tempfile::tempdir().unwrap(); let mut store = make_store(tmp.path()); - store.add(create_offline_account("Alice")); - store.add(create_offline_account("Bob")); - store.remove(0); + store.add(create_offline_account("Alice")).unwrap(); + store.add(create_offline_account("Bob")).unwrap(); + store.remove(0).unwrap(); assert_eq!(store.accounts.len(), 1); assert_eq!(store.accounts[0].username, "Bob"); assert!(store.accounts[0].active); @@ -192,8 +194,8 @@ fn store_remove_activates_first_remaining() { fn store_remove_out_of_bounds_noop() { let tmp = tempfile::tempdir().unwrap(); let mut store = make_store(tmp.path()); - store.add(create_offline_account("Alice")); - store.remove(5); + store.add(create_offline_account("Alice")).unwrap(); + store.remove(5).unwrap(); assert_eq!(store.accounts.len(), 1); } @@ -201,9 +203,9 @@ fn store_remove_out_of_bounds_noop() { fn store_save_and_reload() { let tmp = tempfile::tempdir().unwrap(); let mut store = make_store(tmp.path()); - store.add(create_offline_account("Alice")); - store.add(create_offline_account("Bob")); - store.save(); + store.add(create_offline_account("Alice")).unwrap(); + store.add(create_offline_account("Bob")).unwrap(); + store.save().unwrap(); let reloaded = AccountStore { accounts: serde_json::from_str( @@ -211,8 +213,43 @@ fn store_save_and_reload() { ) .unwrap(), path: tmp.path().join("accounts.json"), + load_error: None, }; assert_eq!(reloaded.accounts.len(), 2); assert_eq!(reloaded.accounts[0].username, "Alice"); assert!(reloaded.accounts[0].active); } + +#[cfg(unix)] +#[test] +fn account_file_remains_owner_only_after_replacement() { + use std::os::unix::fs::PermissionsExt; + + let tmp = tempfile::tempdir().unwrap(); + let mut store = make_store(tmp.path()); + store.add(microsoft_account("Owner")).unwrap(); + let path = tmp.path().join("accounts.json"); + assert_eq!( + std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap(); + store.add(create_offline_account("Player")).unwrap(); + assert_eq!( + std::fs::metadata(path).unwrap().permissions().mode() & 0o777, + 0o600 + ); +} + +#[test] +fn invalid_account_file_cannot_be_overwritten_by_a_new_account() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("accounts.json"); + std::fs::write(&path, b"{broken credentials").unwrap(); + let mut store = AccountStore::load_from(path.clone()); + + assert!(store.add(microsoft_account("Owner")).is_err()); + assert!(store.accounts.is_empty()); + assert_eq!(std::fs::read(path).unwrap(), b"{broken credentials"); +} diff --git a/src/cli/account.rs b/src/cli/account.rs index b630668..ff38bfc 100644 --- a/src/cli/account.rs +++ b/src/cli/account.rs @@ -2,6 +2,7 @@ // SPDX-License-Identifier: GPL-3.0-only use std::io; +use std::sync::{Arc, Mutex}; use std::time::Duration; use clap::ArgMatches; @@ -58,22 +59,11 @@ async fn add_account(matches: &ArgMatches) -> CliResult { // then one for the final auth result. not the prettiest pattern // but it keeps the oauth complexity out of the CLI layer. async fn add_microsoft_account() -> CliResult { - if let Ok(mut slot) = crate::auth::DEVICE_CODE_DISPLAY.lock() { - *slot = None; - } - let result_arc = crate::auth::start_microsoft_auth(); - loop { - if let Ok(slot) = crate::auth::DEVICE_CODE_DISPLAY.lock() - && let Some(info) = slot.as_ref() - { - println!("Open: {}", info.verification_uri); - println!("Code: {}", info.user_code); - break; - } - tokio::time::sleep(Duration::from_millis(200)).await; - } + let info = wait_for_device_code(&result_arc).await?; + println!("Open: {}", info.verification_uri); + println!("Code: {}", info.user_code); loop { if let Ok(slot) = result_arc.lock() @@ -82,7 +72,7 @@ async fn add_microsoft_account() -> CliResult { return match result { AuthResult::Success(account) => { let mut store = AccountStore::load(); - store.add(account.clone()); + store.add(account.clone())?; println!("Added Microsoft account '{}'.", account.username); Ok(()) } @@ -93,6 +83,24 @@ async fn add_microsoft_account() -> CliResult { } } +async fn wait_for_device_code( + result: &Arc>>, +) -> io::Result { + loop { + if let Ok(slot) = crate::auth::DEVICE_CODE_DISPLAY.lock() + && let Some(info) = slot.as_ref() + { + return Ok(info.clone()); + } + if let Ok(slot) = result.lock() + && let Some(AuthResult::Error(message)) = slot.as_ref() + { + return Err(io::Error::other(message.clone())); + } + tokio::time::sleep(Duration::from_millis(200)).await; + } +} + fn add_offline_account(store: &mut AccountStore, username: &str) -> CliResult { let username = username.trim(); if username.is_empty() { @@ -105,22 +113,21 @@ fn add_offline_account(store: &mut AccountStore, username: &str) -> CliResult { .into()); } - store.add(crate::auth::create_offline_account(username)); + store.add(crate::auth::create_offline_account(username))?; Ok(()) } fn delete_account(matches: &ArgMatches) -> CliResult { let username = required_arg(matches, "username")?; let mut store = AccountStore::load(); - let index = find_account_index(&store.accounts, username) - .ok_or_else(|| io::Error::other(format!("account '{}' not found", username)))?; + let index = find_account_index(&store.accounts, username)?; if !matches.get_flag("yes") && !confirm(&format!("Delete '{}'", username))? { println!("Cancelled."); return Ok(()); } - store.remove(index); + store.remove(index)?; println!("Deleted '{}'.", username); Ok(()) } @@ -128,17 +135,29 @@ fn delete_account(matches: &ArgMatches) -> CliResult { fn use_account(matches: &ArgMatches) -> CliResult { let username = required_arg(matches, "username")?; let mut store = AccountStore::load(); - let index = find_account_index(&store.accounts, username) - .ok_or_else(|| io::Error::other(format!("account '{}' not found", username)))?; - store.set_active(index); + let index = find_account_index(&store.accounts, username)?; + store.set_active(index)?; println!("Active account set to '{}'.", username); Ok(()) } -fn find_account_index(accounts: &[Account], username: &str) -> Option { - accounts +fn find_account_index(accounts: &[Account], selector: &str) -> io::Result { + if let Some(index) = accounts.iter().position(|account| account.uuid == selector) { + return Ok(index); + } + let mut matches = accounts .iter() - .position(|account| account.username.eq_ignore_ascii_case(username)) + .enumerate() + .filter(|(_, account)| account.username.eq_ignore_ascii_case(selector)); + let (index, _) = matches + .next() + .ok_or_else(|| io::Error::other(format!("account '{selector}' not found")))?; + if matches.next().is_some() { + return Err(io::Error::other(format!( + "Account '{selector}' is ambiguous; use its UUID" + ))); + } + Ok(index) } use super::utils::{confirm, required_arg}; diff --git a/src/cli/instance.rs b/src/cli/instance.rs index 93926bf..e085fad 100644 --- a/src/cli/instance.rs +++ b/src/cli/instance.rs @@ -128,12 +128,10 @@ async fn launch_instance(matches: &ArgMatches) -> CliResult { loop { match crate::instance::runtime::get(name) { Some(RunState::Crashed(Some(code))) => { - println!("Game exited with status {}", code); - break; + return Err(io::Error::other(format!("Game exited with status {code}")).into()); } Some(RunState::Crashed(None)) => { - println!("Game was terminated"); - break; + return Err(io::Error::other("Game was terminated without an exit code").into()); } Some(_) => tokio::time::sleep(Duration::from_millis(500)).await, None => { @@ -297,10 +295,10 @@ fn apply_config_update( ) -> CliResult { match key { "memory-max" => { - config.memory_max = crate::instance::normalize_memory_value(value); + config.memory_max = parse_memory_update(value)?; } "memory-min" => { - config.memory_min = crate::instance::normalize_memory_value(value); + config.memory_min = parse_memory_update(value)?; } "java-path" => { config.java_path = if value.is_empty() { @@ -327,6 +325,16 @@ fn apply_config_update( Ok(()) } +fn parse_memory_update(value: &str) -> Result, io::Error> { + if value.is_empty() { + Ok(None) + } else { + crate::instance::normalize_memory_value(value) + .map(Some) + .ok_or_else(|| io::Error::other(format!("invalid memory size '{value}'"))) + } +} + #[cfg(test)] #[path = "tests/instance.rs"] mod tests; diff --git a/src/cli/log.rs b/src/cli/log.rs index 0d16732..bb7fe67 100644 --- a/src/cli/log.rs +++ b/src/cli/log.rs @@ -71,19 +71,28 @@ pub(crate) fn resolve_log_path( instance: &str, file: Option<&str>, ) -> Result { - if let Some(name) = file { - let path = crate::instance::logs::files::log_dir(instances_dir, instance).join(name); - if !path.exists() { - return Err(io::Error::other(format!("log '{}' not found", name))); + let log_dir = crate::instance::logs::files::log_dir(instances_dir, instance); + let path = if let Some(name) = file { + let filename = Path::new(name); + if !crate::storage::safe_relative_path(filename) || filename.components().count() != 1 { + return Err(io::Error::other("log file must be a single filename")); } - return Ok(path); + log_dir.join(filename) + } else { + crate::instance::logs::files::scan_log_files(instances_dir, instance) + .into_iter() + .next() + .map(|entry| entry.path) + .ok_or_else(|| io::Error::other(format!("no log files found for '{}'", instance)))? + }; + let log_dir = std::fs::canonicalize(log_dir)?; + let path = std::fs::canonicalize(path)?; + if path.parent() != Some(log_dir.as_path()) || !path.is_file() { + return Err(io::Error::other( + "log file is outside the instance log directory", + )); } - - crate::instance::logs::files::scan_log_files(instances_dir, instance) - .into_iter() - .next() - .map(|entry| entry.path) - .ok_or_else(|| io::Error::other(format!("no log files found for '{}'", instance))) + Ok(path) } use super::utils::{require_instance, required_arg}; diff --git a/src/cli/tests/account.rs b/src/cli/tests/account.rs index 9a087d4..1bc3a11 100644 --- a/src/cli/tests/account.rs +++ b/src/cli/tests/account.rs @@ -20,7 +20,7 @@ fn microsoft_account() -> Account { fn creates_offline_account_after_microsoft_account_exists() { let temp = tempfile::tempdir().unwrap(); let mut store = AccountStore::empty_for_test(temp.path().join("accounts.json")); - store.add(microsoft_account()); + store.add(microsoft_account()).unwrap(); add_offline_account(&mut store, "Steve").expect("offline account should be added"); assert_eq!(store.accounts.len(), 2); @@ -45,3 +45,36 @@ fn rejects_empty_offline_username() { let mut store = AccountStore::empty_for_test(temp.path().join("accounts.json")); assert!(add_offline_account(&mut store, " ").is_err()); } + +#[test] +fn duplicate_usernames_require_a_unique_account_selector() { + let mut microsoft = microsoft_account(); + microsoft.username = "Steve".to_owned(); + let offline = crate::auth::create_offline_account("Steve"); + let accounts = vec![microsoft, offline.clone()]; + + assert!(super::find_account_index(&accounts, "Steve").is_err()); + assert_eq!( + super::find_account_index(&accounts, &offline.uuid).unwrap(), + 1 + ); +} + +#[test] +fn device_code_failure_does_not_wait_for_a_code() { + let _guard = crate::tests::TEST_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + *crate::auth::DEVICE_CODE_DISPLAY.lock().unwrap() = None; + let result = std::sync::Arc::new(std::sync::Mutex::new(Some(crate::auth::AuthResult::Error( + "device code failed".to_owned(), + )))); + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_time() + .build() + .unwrap(); + let error = runtime + .block_on(super::wait_for_device_code(&result)) + .unwrap_err(); + assert!(error.to_string().contains("device code failed")); +} diff --git a/src/cli/tests/instance.rs b/src/cli/tests/instance.rs index f6b26e5..3e0b57f 100644 --- a/src/cli/tests/instance.rs +++ b/src/cli/tests/instance.rs @@ -17,3 +17,15 @@ fn rejects_invalid_resolution_format() { assert!(parse_resolution("1920xa").is_err()); assert!(parse_resolution("0x1080").is_err()); } + +#[test] +fn invalid_memory_update_keeps_existing_setting() { + let mut config: crate::instance::InstanceConfig = serde_json::from_value(serde_json::json!({ + "name": "test", "game_version": "1.21.1", "loader": "vanilla", + "loader_version": null, "created": "2026-01-01T00:00:00Z", "memory_max": "8G" + })) + .unwrap(); + + assert!(super::apply_config_update(&mut config, "memory-max", "garbage").is_err()); + assert_eq!(config.memory_max.as_deref(), Some("8G")); +} diff --git a/src/cli/tests/log.rs b/src/cli/tests/log.rs index 1d78847..badce0d 100644 --- a/src/cli/tests/log.rs +++ b/src/cli/tests/log.rs @@ -32,3 +32,21 @@ fn resolves_named_log_file() { Some("latest.log") ); } + +#[test] +fn rejects_log_paths_outside_the_instance() { + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path().join("demo/minecraft/logs/launches"); + std::fs::create_dir_all(&dir).unwrap(); + let outside = tmp.path().join("outside.txt"); + std::fs::write(&outside, "private").unwrap(); + + assert!(resolve_log_path(tmp.path(), "demo", Some(outside.to_str().unwrap())).is_err()); + assert!(resolve_log_path(tmp.path(), "demo", Some("../../outside.txt")).is_err()); + #[cfg(unix)] + { + std::os::unix::fs::symlink(&outside, dir.join("escape.log")).unwrap(); + assert!(resolve_log_path(tmp.path(), "demo", Some("escape.log")).is_err()); + assert!(resolve_log_path(tmp.path(), "demo", None).is_err()); + } +} diff --git a/src/cli/utils.rs b/src/cli/utils.rs index 46c2dc1..1002746 100644 --- a/src/cli/utils.rs +++ b/src/cli/utils.rs @@ -23,6 +23,7 @@ pub fn required_arg<'a>(matches: &'a ArgMatches, name: &str) -> Result<&'a str, // checks for instance.json rather than just the directory, since a folder // without config is just a sad empty directory pretending to be an instance pub fn require_instance(instances_dir: &std::path::Path, name: &str) -> Result<(), io::Error> { + crate::instance::manager::validate_name(name).map_err(io::Error::other)?; if !instances_dir.join(name).join("instance.json").exists() { return Err(io::Error::other(format!("Instance '{name}' not found"))); } diff --git a/src/storage.rs b/src/storage.rs index 914905d..a9e7b64 100644 --- a/src/storage.rs +++ b/src/storage.rs @@ -153,7 +153,23 @@ pub fn clear_disposable_caches(meta_dir: &Path) -> io::Result<()> { Ok(()) } +pub fn safe_relative_path(path: &Path) -> bool { + let mut components = path.components(); + components + .next() + .is_some_and(|part| matches!(part, std::path::Component::Normal(_))) + && components.all(|part| matches!(part, std::path::Component::Normal(_))) +} + pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { + write_atomic_with_mode(path, bytes, false) +} + +pub fn write_atomic_private(path: &Path, bytes: &[u8]) -> io::Result<()> { + write_atomic_with_mode(path, bytes, true) +} + +fn write_atomic_with_mode(path: &Path, bytes: &[u8], private: bool) -> io::Result<()> { let parent = path .parent() .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no parent"))?; @@ -167,10 +183,16 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { let result = (|| { use std::io::Write; - let mut file = std::fs::OpenOptions::new() - .create_new(true) - .write(true) - .open(&temporary)?; + let mut options = std::fs::OpenOptions::new(); + options.create_new(true).write(true); + #[cfg(unix)] + if private { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + #[cfg(not(unix))] + let _ = private; + let mut file = options.open(&temporary)?; file.write_all(bytes)?; file.sync_all()?; replace_file(&temporary, path) @@ -182,12 +204,12 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { } #[cfg(not(windows))] -fn replace_file(source: &Path, destination: &Path) -> io::Result<()> { +pub(crate) fn replace_file(source: &Path, destination: &Path) -> io::Result<()> { std::fs::rename(source, destination) } #[cfg(windows)] -fn replace_file(source: &Path, destination: &Path) -> io::Result<()> { +pub(crate) fn replace_file(source: &Path, destination: &Path) -> io::Result<()> { if !destination.exists() { return std::fs::rename(source, destination); } From 3149b9697159e768d114256821794f8f3181d412 Mon Sep 17 00:00:00 2001 From: objz Date: Thu, 1 Oct 2026 17:44:06 +0200 Subject: [PATCH 05/34] fix: verify downloads and bound imported metadata --- src/instance/content/mod.rs | 16 +- src/instance/content/mods.rs | 32 ++- src/instance/content/packs.rs | 15 +- src/instance/content/worlds.rs | 4 +- src/instance/import/curseforge.rs | 17 +- src/instance/import/mmc.rs | 16 +- src/instance/import/mod.rs | 44 ++++ src/instance/import/mrpack.rs | 21 +- src/instance/loader/maven.rs | 15 +- src/instance/tests/content/mods.rs | 9 + src/instance/tests/import/curseforge.rs | 22 ++ src/instance/tests/import/format_detection.rs | 10 + src/instance/tests/import/mrpack.rs | 7 + src/instance/tests/loader/maven.rs | 11 +- src/launch_profile/rules.rs | 20 +- src/launch_profile/tests/rules.rs | 8 + src/net/curseforge.rs | 61 +++--- src/net/mod.rs | 67 ++++-- src/net/modrinth.rs | 6 +- src/net/mojang.rs | 167 +++++++++------ src/net/tests/curseforge.rs | 40 ++++ src/net/tests/modrinth.rs | 8 +- tests/net_loaders.rs | 53 ++++- tests/net_mojang.rs | 200 +++++++++++++++--- tests/net_retry.rs | 24 +++ 25 files changed, 678 insertions(+), 215 deletions(-) diff --git a/src/instance/content/mod.rs b/src/instance/content/mod.rs index 801c453..a3cd23e 100644 --- a/src/instance/content/mod.rs +++ b/src/instance/content/mod.rs @@ -29,6 +29,17 @@ pub use worlds::{scan_one_world, scan_worlds}; use std::io::Read; +const MAX_LOCAL_METADATA_BYTES: u64 = 8 * 1024 * 1024; + +fn read_local_metadata(reader: impl Read) -> Option> { + let mut bytes = Vec::new(); + reader + .take(MAX_LOCAL_METADATA_BYTES + 1) + .read_to_end(&mut bytes) + .ok()?; + (bytes.len() as u64 <= MAX_LOCAL_METADATA_BYTES).then_some(bytes) +} + pub(crate) fn parse_enabled_stem(file_name: &str, ext: &str) -> Option<(bool, String)> { let disabled_ext = format!("{ext}.disabled"); if let Some(stem) = file_name.strip_suffix(&disabled_ext) { @@ -49,10 +60,7 @@ pub(crate) fn parse_enabled_stem_dir(file_name: &str) -> (bool, String) { } pub(crate) fn read_icon_from_zip(archive: &mut zip::ZipArchive) -> Option> { - let mut entry = archive.by_name("pack.png").ok()?; - let mut buf = Vec::new(); - entry.read_to_end(&mut buf).ok()?; - Some(buf) + read_local_metadata(archive.by_name("pack.png").ok()?) } pub(crate) fn open_zip(path: &std::path::Path) -> Option> { diff --git a/src/instance/content/mods.rs b/src/instance/content/mods.rs index 2c67dc3..a3c2f88 100644 --- a/src/instance/content/mods.rs +++ b/src/instance/content/mods.rs @@ -1,7 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -use std::io::Read; use std::path::Path; use serde::Deserialize; @@ -212,9 +211,10 @@ fn try_fallback_icons(archive: &mut zip::ZipArchive) -> Option, ) -> Option<(String, String, String, String)> { - let mut entry = archive.by_name("fabric.mod.json").ok()?; - let mut raw = String::new(); - entry.read_to_string(&mut raw).ok()?; + let raw = String::from_utf8(super::read_local_metadata( + archive.by_name("fabric.mod.json").ok()?, + )?) + .ok()?; let sanitized = sanitize_json_strings(&raw); let data: FabricModJson = serde_json::from_str(&sanitized).ok()?; let icon = data.icon_path(); @@ -224,9 +224,10 @@ fn read_fabric_meta( fn read_quilt_meta( archive: &mut zip::ZipArchive, ) -> Option<(String, String, String, String)> { - let mut entry = archive.by_name("quilt.mod.json").ok()?; - let mut raw = String::new(); - entry.read_to_string(&mut raw).ok()?; + let raw = String::from_utf8(super::read_local_metadata( + archive.by_name("quilt.mod.json").ok()?, + )?) + .ok()?; let sanitized = sanitize_json_strings(&raw); let data: QuiltModJson = serde_json::from_str(&sanitized).ok()?; let version = data.quilt_loader.version; @@ -282,9 +283,10 @@ fn read_forge_toml_meta( fn read_mcmod_info( archive: &mut zip::ZipArchive, ) -> Option<(String, String, String, String)> { - let mut entry = archive.by_name("mcmod.info").ok()?; - let mut raw = String::new(); - entry.read_to_string(&mut raw).ok()?; + let raw = String::from_utf8(super::read_local_metadata( + archive.by_name("mcmod.info").ok()?, + )?) + .ok()?; let sanitized = sanitize_json_strings(&raw); let parsed: serde_json::Value = serde_json::from_str(&sanitized).ok()?; let first = match &parsed { @@ -316,10 +318,7 @@ fn read_mcmod_info( } fn read_zip_string(archive: &mut zip::ZipArchive, path: &str) -> Option { - let mut entry = archive.by_name(path).ok()?; - let mut s = String::new(); - entry.read_to_string(&mut s).ok()?; - Some(s) + String::from_utf8(super::read_local_metadata(archive.by_name(path).ok()?)?).ok() } // some mod authors put raw newlines/tabs inside json string values which is @@ -360,10 +359,7 @@ fn sanitize_json_strings(input: &str) -> String { } fn read_zip_bytes(archive: &mut zip::ZipArchive, path: &str) -> Option> { - let mut entry = archive.by_name(path).ok()?; - let mut bytes = Vec::new(); - entry.read_to_end(&mut bytes).ok()?; - Some(bytes) + super::read_local_metadata(archive.by_name(path).ok()?) } #[cfg(test)] diff --git a/src/instance/content/packs.rs b/src/instance/content/packs.rs index fbb6efa..436daab 100644 --- a/src/instance/content/packs.rs +++ b/src/instance/content/packs.rs @@ -110,7 +110,8 @@ fn read_metadata_from_zip(path: &Path) -> (String, Option>) { let description = archive .by_name("pack.mcmeta") .ok() - .and_then(|entry| serde_json::from_reader::<_, PackMcMeta>(entry).ok()) + .and_then(super::read_local_metadata) + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) .map(|meta| extract_description(&meta.pack.description)) .unwrap_or_default(); let icon_bytes = super::read_icon_from_zip(&mut archive); @@ -118,10 +119,16 @@ fn read_metadata_from_zip(path: &Path) -> (String, Option>) { } fn read_metadata_from_dir(path: &Path) -> (String, Option>) { - let description = std::fs::read_to_string(path.join("pack.mcmeta")) + let description = std::fs::File::open(path.join("pack.mcmeta")) .ok() - .and_then(|content| serde_json::from_str::(&content).ok()) + .and_then(super::read_local_metadata) + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) .map(|meta| extract_description(&meta.pack.description)) .unwrap_or_default(); - (description, std::fs::read(path.join("pack.png")).ok()) + ( + description, + std::fs::File::open(path.join("pack.png")) + .ok() + .and_then(super::read_local_metadata), + ) } diff --git a/src/instance/content/worlds.rs b/src/instance/content/worlds.rs index 532a558..f63c4a5 100644 --- a/src/instance/content/worlds.rs +++ b/src/instance/content/worlds.rs @@ -10,7 +10,9 @@ use super::entry::{ContentEntry, WorldDetails, WorldGameMode}; use super::{fallback_icon_large, make_icon_pixels}; pub fn scan_one_world(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry { - let icon_bytes = std::fs::read(path.join("icon.png")).ok(); + let icon_bytes = File::open(path.join("icon.png")) + .ok() + .and_then(super::read_local_metadata); let icon_lines = icon_bytes .as_ref() .and_then(|bytes| make_icon_pixels(bytes, 12, 6)) diff --git a/src/instance/import/curseforge.rs b/src/instance/import/curseforge.rs index e63ae10..542dc88 100644 --- a/src/instance/import/curseforge.rs +++ b/src/instance/import/curseforge.rs @@ -65,7 +65,8 @@ fn parse(path: &Path) -> Result { let entry = archive .by_name("manifest.json") .map_err(|_| "Missing manifest.json in CurseForge pack".to_owned())?; - serde_json::from_reader(entry).map_err(|error| format!("Invalid CurseForge manifest: {error}")) + let raw = super::read_pack_manifest(entry)?; + serde_json::from_slice(&raw).map_err(|error| format!("Invalid CurseForge manifest: {error}")) } fn loader(manifest: &Manifest) -> (ModLoader, Option) { @@ -178,14 +179,18 @@ async fn download_files( pub(super) async fn owned_files(path: &Path) -> Result, String> { let manifest = parse(path)?; - let api_key = crate::net::curseforge::api_key() - .ok_or_else(|| "CurseForge API key is not configured".to_owned())?; + let overrides = super::override_files(path, &[manifest.overrides.trim_matches('/')])?; let ids = manifest .files .iter() .filter(|file| file.required) .map(|file| file.file_id) .collect::>(); + if ids.is_empty() { + return Ok(overrides); + } + let api_key = crate::net::curseforge::api_key() + .ok_or_else(|| "CurseForge API key is not configured".to_owned())?; let versions = crate::net::curseforge::fetch_file_versions(&crate::net::HttpClient::new(), api_key, &ids) .await @@ -197,7 +202,7 @@ pub(super) async fn owned_files(path: &Path) -> Result, ids.len() )); } - versions + let mut files: Vec<_> = versions .into_iter() .map(|version| { version @@ -208,7 +213,9 @@ pub(super) async fn owned_files(path: &Path) -> Result, .map(|file| std::path::PathBuf::from("mods").join(&file.filename)) .ok_or_else(|| format!("CurseForge file '{}' has no artifact", version.id)) }) - .collect() + .collect::>()?; + files.extend(overrides); + Ok(files) } fn count_overrides(path: &Path, root: &str) -> Result { diff --git a/src/instance/import/mmc.rs b/src/instance/import/mmc.rs index 8a3fe24..b531a20 100644 --- a/src/instance/import/mmc.rs +++ b/src/instance/import/mmc.rs @@ -119,8 +119,6 @@ fn extract_mmc_archive( archive_path: &Path, minecraft_dir: &Path, ) -> Result<(), Box> { - use std::io::Read; - progress::set_action("Extracting pack contents...".to_string()); progress::set_sub_action(String::new()); @@ -178,15 +176,14 @@ fn extract_mmc_archive( .unwrap_or_default(); progress::set_sub_action(filename.to_string()); - let mut buf = Vec::new(); - entry.read_to_end(&mut buf)?; + let mut destination = std::fs::File::create(&dest)?; + let size = std::io::copy(&mut entry, &mut destination)?; tracing::trace!( "Extracting MultiMC entry {} to {} ({} bytes)", entry_name, dest.display(), - buf.len() + size ); - std::fs::write(&dest, &buf)?; extracted += 1; } @@ -210,7 +207,8 @@ fn parse_mmc_pack(path: &Path) -> Result { .by_name(&entry_name) .map_err(|e| format!("Failed to read mmc-pack.json: {e}"))?; - serde_json::from_reader(entry).map_err(|e| format!("Invalid mmc-pack.json: {e}")) + let raw = super::read_pack_manifest(entry)?; + serde_json::from_slice(&raw).map_err(|e| format!("Invalid mmc-pack.json: {e}")) } fn instance_name_from_cfg(path: &Path) -> Option { @@ -220,8 +218,8 @@ fn instance_name_from_cfg(path: &Path) -> Option { let entry_name = find_entry(&archive, "instance.cfg")?; tracing::trace!("Reading instance name from {}", entry_name); let entry = archive.by_name(&entry_name).ok()?; - - let reader = std::io::BufRead::lines(std::io::BufReader::new(entry)); + let raw = super::read_pack_manifest(entry).ok()?; + let reader = std::io::BufRead::lines(std::io::BufReader::new(raw.as_slice())); for line in reader.map_while(Result::ok) { if let Some(value) = line.strip_prefix("name=") { let name = value.trim().to_string(); diff --git a/src/instance/import/mod.rs b/src/instance/import/mod.rs index 6de63f8..830b5c8 100644 --- a/src/instance/import/mod.rs +++ b/src/instance/import/mod.rs @@ -8,6 +8,22 @@ pub mod refresh; use std::path::{Path, PathBuf}; +const MAX_PACK_MANIFEST_BYTES: u64 = 8 * 1024 * 1024; + +fn read_pack_manifest(reader: impl std::io::Read) -> Result, String> { + use std::io::Read; + + let mut bytes = Vec::new(); + reader + .take(MAX_PACK_MANIFEST_BYTES + 1) + .read_to_end(&mut bytes) + .map_err(|error| error.to_string())?; + if bytes.len() as u64 > MAX_PACK_MANIFEST_BYTES { + return Err("Pack manifest exceeds 8 MiB".to_owned()); + } + Ok(bytes) +} + use crate::instance::manager::InstanceManager; use crate::instance::models::ModLoader; @@ -270,6 +286,34 @@ async fn owned_files(summary: &ImportSummary) -> Result, String> { } } +fn override_files(path: &Path, roots: &[&str]) -> Result, String> { + let file = std::fs::File::open(path).map_err(|error| error.to_string())?; + let mut archive = zip::ZipArchive::new(file).map_err(|error| error.to_string())?; + let mut files = Vec::new(); + for index in 0..archive.len() { + let entry = archive.by_index(index).map_err(|error| error.to_string())?; + if entry.is_dir() { + continue; + } + let Some(root) = roots + .iter() + .find(|root| entry.name().starts_with(&format!("{root}/"))) + else { + continue; + }; + let relative = entry + .enclosed_name() + .ok_or_else(|| format!("Unsafe override path: {}", entry.name()))? + .strip_prefix(root) + .map_err(|error| error.to_string())? + .to_owned(); + if !relative.as_os_str().is_empty() { + files.push(relative); + } + } + Ok(files) +} + fn cleanup_failed_import(manager: &InstanceManager, name: &str) { let instance_dir = manager.instances_dir.join(name); if let Err(error) = std::fs::remove_dir_all(&instance_dir) diff --git a/src/instance/import/mrpack.rs b/src/instance/import/mrpack.rs index 49d9377..f0c0c85 100644 --- a/src/instance/import/mrpack.rs +++ b/src/instance/import/mrpack.rs @@ -47,8 +47,9 @@ pub fn parse_mrpack(path: &Path) -> Result { let entry = archive .by_name("modrinth.index.json") .map_err(|_| "Missing modrinth.index.json in .mrpack".to_string())?; + let raw = super::read_pack_manifest(entry)?; let index: MrpackIndex = - serde_json::from_reader(entry).map_err(|e| format!("Invalid manifest JSON: {e}"))?; + serde_json::from_slice(&raw).map_err(|e| format!("Invalid manifest JSON: {e}"))?; tracing::debug!( "Parsed .mrpack '{}' version_id={} files={} deps={}", index.name, @@ -310,11 +311,16 @@ fn safe_mrpack_path(path: &str) -> Result { } pub(super) fn owned_files(path: &Path) -> Result, String> { - parse_mrpack(path)? + let mut files: Vec<_> = parse_mrpack(path)? .files .into_iter() .map(|file| safe_mrpack_path(&file.path).map_err(|error| error.to_string())) - .collect() + .collect::>()?; + files.extend(super::override_files( + path, + &["overrides", "client-overrides"], + )?); + Ok(files) } fn verify_mrpack_file( @@ -420,8 +426,6 @@ fn extract_overrides( mrpack_path: &Path, minecraft_dir: &Path, ) -> Result<(), Box> { - use std::io::Read; - progress::set_action("Extracting overrides...".to_string()); progress::set_sub_action(String::new()); @@ -466,15 +470,14 @@ fn extract_overrides( std::fs::create_dir_all(parent)?; } - let mut buf = Vec::new(); - entry.read_to_end(&mut buf)?; + let mut destination = std::fs::File::create(&dest)?; + let size = std::io::copy(&mut entry, &mut destination)?; tracing::trace!( "Extracting .mrpack override {} to {} ({} bytes)", entry_name, dest.display(), - buf.len() + size ); - std::fs::write(&dest, &buf)?; extracted += 1; } diff --git a/src/instance/loader/maven.rs b/src/instance/loader/maven.rs index 64ed46e..fffc1d4 100644 --- a/src/instance/loader/maven.rs +++ b/src/instance/loader/maven.rs @@ -4,23 +4,24 @@ #[must_use] pub fn maven_coord_to_path(coord: &str) -> Option { let parts: Vec<&str> = coord.split(':').collect(); - match parts.as_slice() { + let path = match parts.as_slice() { [group, artifact, version] => { let group_path = group.replace('.', "/"); - Some(format!( + format!( "{}/{}/{}/{}-{}.jar", group_path, artifact, version, artifact, version - )) + ) } [group, artifact, version, classifier] => { let group_path = group.replace('.', "/"); - Some(format!( + format!( "{}/{}/{}/{}-{}-{}.jar", group_path, artifact, version, artifact, version, classifier - )) + ) } - _ => None, - } + _ => return None, + }; + crate::storage::safe_relative_path(std::path::Path::new(&path)).then_some(path) } #[cfg(test)] diff --git a/src/instance/tests/content/mods.rs b/src/instance/tests/content/mods.rs index 5809077..59f1250 100644 --- a/src/instance/tests/content/mods.rs +++ b/src/instance/tests/content/mods.rs @@ -2,6 +2,15 @@ // SPDX-License-Identifier: GPL-3.0-only use super::*; + +#[test] +fn local_metadata_reads_have_a_size_limit() { + assert_eq!( + super::super::read_local_metadata(&b"icon"[..]), + Some(b"icon".to_vec()) + ); + assert!(super::super::read_local_metadata(std::io::repeat(0)).is_none()); +} use crate::instance::content::entry::{ContentEntry, toggle_entry}; use std::path::PathBuf; diff --git a/src/instance/tests/import/curseforge.rs b/src/instance/tests/import/curseforge.rs index 2a3f459..6804df6 100644 --- a/src/instance/tests/import/curseforge.rs +++ b/src/instance/tests/import/curseforge.rs @@ -66,3 +66,25 @@ fn empty_overrides_root_does_not_count_the_manifest() { assert_eq!(build_summary(&path).unwrap().override_count, 0); } + +#[tokio::test] +async fn override_only_pack_tracks_files_under_its_configured_root() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("pack.zip"); + let mut zip = zip::ZipWriter::new(std::fs::File::create(&path).unwrap()); + let options = zip::write::SimpleFileOptions::default(); + use std::io::Write; + zip.start_file("manifest.json", options).unwrap(); + zip.write_all( + br#"{"name":"Pack","version":"1","minecraft":{"version":"1.20.1"},"overrides":"client"}"#, + ) + .unwrap(); + zip.start_file("client/config/pack.toml", options).unwrap(); + zip.write_all(b"pack").unwrap(); + zip.finish().unwrap(); + + assert_eq!( + owned_files(&path).await.unwrap(), + vec![std::path::PathBuf::from("config/pack.toml")] + ); +} diff --git a/src/instance/tests/import/format_detection.rs b/src/instance/tests/import/format_detection.rs index 596cc07..c2d7ad3 100644 --- a/src/instance/tests/import/format_detection.rs +++ b/src/instance/tests/import/format_detection.rs @@ -4,6 +4,16 @@ use super::*; use std::io::Write; +#[test] +fn oversized_pack_manifest_is_rejected() { + assert_eq!(read_pack_manifest(&b"{}"[..]).unwrap(), b"{}"); + assert!( + read_pack_manifest(std::io::repeat(0)) + .unwrap_err() + .contains("8 MiB") + ); +} + fn make_pack_zip(tmp: &Path, name: &str, entries: &[(&str, &[u8])]) -> std::path::PathBuf { let path = tmp.join(name); let file = std::fs::File::create(&path).unwrap(); diff --git a/src/instance/tests/import/mrpack.rs b/src/instance/tests/import/mrpack.rs index 72cf34c..9932ce2 100644 --- a/src/instance/tests/import/mrpack.rs +++ b/src/instance/tests/import/mrpack.rs @@ -54,6 +54,13 @@ fn summary_counts_both_override_roots() { assert_eq!(summary.loader, ModLoader::Fabric); assert_eq!(summary.loader_version.as_deref(), Some("0.16.14")); assert_eq!(summary.override_count, 2); + assert_eq!( + owned_files(&path).unwrap(), + vec![ + PathBuf::from("config/test.toml"), + PathBuf::from("options.txt") + ] + ); } #[test] diff --git a/src/instance/tests/loader/maven.rs b/src/instance/tests/loader/maven.rs index 1074972..441b468 100644 --- a/src/instance/tests/loader/maven.rs +++ b/src/instance/tests/loader/maven.rs @@ -29,7 +29,16 @@ fn maven_nested_group() { #[test] fn maven_invalid_coordinates() { - for coordinate in ["org.example:artifact", "a:b:c:d:e", "just-a-string", ""] { + for coordinate in [ + "org.example:artifact", + "a:b:c:d:e", + "just-a-string", + "", + ".example:artifact:1", + "org.example:../escape:1", + "org.example:artifact:../1", + "org.example:artifact:1:../../escape", + ] { assert_eq!(maven_coord_to_path(coordinate), None); } } diff --git a/src/launch_profile/rules.rs b/src/launch_profile/rules.rs index 4c003f6..36dddb2 100644 --- a/src/launch_profile/rules.rs +++ b/src/launch_profile/rules.rs @@ -88,22 +88,18 @@ fn rule_matches(rule: &Rule, ctx: &RuleContext) -> bool { } // mojang's os.version constraints are typically anchored regex patterns -// (e.g. `^10\\.`). we do a substring containment check as a defensive -// approximation that doesn't pull in the `regex` crate. when the host -// os_version is empty (Windows fallback path returns ""), version-gated -// rules don't match - which is the conservative default. +// version-gated rules do not match an unknown host version. fn os_version_matches(pattern: &str, host_version: &str) -> bool { if host_version.is_empty() { return false; } - // strip common regex anchors and metacharacters for substring lookup. - // good enough for the rare profile that uses os.version. - let needle = pattern - .trim_start_matches('^') - .trim_end_matches('$') - .trim_end_matches('.') - .trim_end_matches('\\'); - host_version.contains(needle) + match regex::Regex::new(pattern) { + Ok(regex) => regex.is_match(host_version), + Err(error) => { + tracing::warn!("Invalid OS version pattern '{pattern}': {error}"); + false + } + } } fn features_match(required: &FeatureSet, current: &FeatureSet) -> bool { diff --git a/src/launch_profile/tests/rules.rs b/src/launch_profile/tests/rules.rs index 9a5058d..689009e 100644 --- a/src/launch_profile/tests/rules.rs +++ b/src/launch_profile/tests/rules.rs @@ -235,6 +235,14 @@ fn os_version_pattern_does_not_match_when_host_unknown() { assert!(!evaluate(&rules, &ctx)); } +#[test] +fn os_version_regex_respects_anchors_and_escapes() { + assert!(os_version_matches(r"^10\.", "10.15.7")); + assert!(!os_version_matches(r"^10\.", "110.15.7")); + assert!(!os_version_matches(r"^10\.", "10x15")); + assert!(!os_version_matches("[", "10.15.7")); +} + #[test] fn rule_deserializes_from_mojang_json() { // shape lifted from real mojang library rules. diff --git a/src/net/curseforge.rs b/src/net/curseforge.rs index a76f62d..4f9195b 100644 --- a/src/net/curseforge.rs +++ b/src/net/curseforge.rs @@ -232,19 +232,7 @@ async fn get( api_key: &str, url: &str, ) -> Result { - let response = client - .inner() - .get(url) - .header("x-api-key", api_key) - .send() - .await?; - if !response.status().is_success() { - return Err(NetError::StatusError { - status: response.status().as_u16(), - url: url.to_owned(), - }); - } - Ok(response.json().await?) + authenticated_request(url, || client.inner().get(url).header("x-api-key", api_key)).await } async fn post( @@ -253,20 +241,41 @@ async fn post( url: &str, body: &B, ) -> Result { - let response = client - .inner() - .post(url) - .header("x-api-key", api_key) - .json(body) - .send() - .await?; - if !response.status().is_success() { - return Err(NetError::StatusError { - status: response.status().as_u16(), - url: url.to_owned(), - }); + authenticated_request(url, || { + client + .inner() + .post(url) + .header("x-api-key", api_key) + .json(body) + }) + .await +} + +async fn authenticated_request( + url: &str, + build: impl Fn() -> reqwest::RequestBuilder, +) -> Result { + for attempt in 0..=super::MAX_RETRIES { + let result = async { + let response = build().send().await?; + if !response.status().is_success() { + return Err(NetError::StatusError { + status: response.status().as_u16(), + url: url.to_owned(), + }); + } + Ok(response.json().await?) + } + .await; + match result { + Ok(value) => return Ok(value), + Err(error) if error.is_retryable() && attempt < super::MAX_RETRIES => { + super::sleep_before_retry("request", url, attempt, &error).await; + } + Err(error) => return Err(error), + } } - Ok(response.json().await?) + unreachable!("retry loop returns on success or final error") } #[allow(clippy::too_many_arguments)] diff --git a/src/net/mod.rs b/src/net/mod.rs index a0c597a..67ba14b 100644 --- a/src/net/mod.rs +++ b/src/net/mod.rs @@ -13,9 +13,11 @@ use reqwest::Client; use serde::Serialize; use serde::de::DeserializeOwned; use std::path::Path; +use std::sync::atomic::{AtomicU64, Ordering}; use thiserror::Error; pub const MAX_PROVIDER_ASSET_BYTES: usize = 16 * 1024 * 1024; +static NEXT_DOWNLOAD_ID: AtomicU64 = AtomicU64::new(1); #[derive(Debug, Error)] pub enum NetError { @@ -151,7 +153,7 @@ impl HttpClient { .await; match result { Ok(value) => return Ok(value), - Err(error) if is_retryable(&error) && attempt < MAX_RETRIES => { + Err(error) if error.is_retryable() && attempt < MAX_RETRIES => { sleep_before_retry("request", url, attempt, &error).await; } Err(error) => return Err(error), @@ -187,7 +189,7 @@ where match client.get(url).await { Ok(resp) => match decode(resp).await { Ok(value) => return Ok(value), - Err(e) if is_retryable(&e) => { + Err(e) if e.is_retryable() => { if attempt == MAX_RETRIES { return Err(e); } @@ -195,7 +197,7 @@ where } Err(e) => return Err(e), }, - Err(e) if is_retryable(&e) => { + Err(e) if e.is_retryable() => { if attempt == MAX_RETRIES { return Err(e); } @@ -233,14 +235,14 @@ pub async fn download_file( ) -> Result<(), NetError> { tracing::debug!("Downloading {} to {}", url, dest.display()); - let result = 'download: { + 'download: { for attempt in 0..=MAX_RETRIES { match download_file_once(client, url, dest, &progress_cb).await { Ok(()) => { tracing::debug!("Downloaded {} to {}", url, dest.display()); break 'download Ok(()); } - Err(e) if is_retryable(&e) => { + Err(e) if e.is_retryable() => { if attempt == MAX_RETRIES { break 'download Err(e); } @@ -250,11 +252,7 @@ pub async fn download_file( } } unreachable!("retry loop returns on success or final error") - }; - if result.is_err() { - let _ = tokio::fs::remove_file(dest).await; } - result } pub(crate) async fn download_loader_libraries<'a>( @@ -268,7 +266,7 @@ pub(crate) async fn download_loader_libraries<'a>( let maven_path = crate::instance::loader::maven::maven_coord_to_path(name) .ok_or_else(|| NetError::Parse(format!("Invalid Maven coordinate: {name}")))?; let dest = libraries_dir.join(&maven_path); - if dest.exists() { + if valid_jar(&dest) { tracing::debug!("{loader} library already exists: {name}"); continue; } @@ -278,10 +276,23 @@ pub(crate) async fn download_loader_libraries<'a>( tracing::info!("Downloading {loader} library: {name}"); tracing::trace!("{loader} library destination: {}", dest.display()); download_file(client, &download_url, &dest, |_, _| {}).await?; + if !valid_jar(&dest) { + let _ = tokio::fs::remove_file(&dest).await; + return Err(NetError::Parse(format!( + "Downloaded {loader} library '{name}' is not a valid JAR" + ))); + } } Ok(()) } +fn valid_jar(path: &Path) -> bool { + std::fs::File::open(path) + .ok() + .and_then(|file| zip::ZipArchive::new(file).ok()) + .is_some() +} + async fn download_file_once( client: &HttpClient, url: &str, @@ -298,18 +309,38 @@ async fn download_file_once( tokio::fs::create_dir_all(parent).await?; } - let mut file = tokio::fs::File::create(dest).await?; + let temporary = dest.with_file_name(format!( + ".{}.{}.{}.download", + dest.file_name() + .and_then(|name| name.to_str()) + .unwrap_or("file"), + std::process::id(), + NEXT_DOWNLOAD_ID.fetch_add(1, Ordering::Relaxed) + )); + let mut file = tokio::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&temporary) + .await?; let mut downloaded: u64 = 0; let mut stream = response; - while let Some(chunk) = stream.chunk().await? { - file.write_all(&chunk).await?; - downloaded += chunk.len() as u64; - progress_cb(downloaded, total); + let result = async { + while let Some(chunk) = stream.chunk().await? { + file.write_all(&chunk).await?; + downloaded += chunk.len() as u64; + progress_cb(downloaded, total); + } + file.flush().await?; + drop(file); + crate::storage::replace_file(&temporary, dest)?; + Ok(()) } - file.flush().await?; - - Ok(()) + .await; + if result.is_err() { + let _ = tokio::fs::remove_file(&temporary).await; + } + result } // body decode errors and timeouts are worth retrying, but a 404 or disk diff --git a/src/net/modrinth.rs b/src/net/modrinth.rs index 7640594..06e48c3 100644 --- a/src/net/modrinth.rs +++ b/src/net/modrinth.rs @@ -525,7 +525,11 @@ pub async fn download_version_file( validate_path_component(&version.id, "provider version id")?; let path = destination.join(&file.filename); if path.exists() { - if verify_version_file(&path, file)? { + if ["sha512", "sha1"] + .iter() + .any(|algorithm| file.hashes.contains_key(*algorithm)) + && verify_version_file(&path, file)? + { return Ok(DownloadOutcome::SkippedExisting(path)); } return Err(crate::net::NetError::Parse(format!( diff --git a/src/net/mojang.rs b/src/net/mojang.rs index 8c091a1..64a32a1 100644 --- a/src/net/mojang.rs +++ b/src/net/mojang.rs @@ -160,7 +160,20 @@ pub async fn fetch_version_meta_with_raw( entry.id, entry.url ); - client.get_json_with_raw(&entry.url, "version meta").await + let (meta, raw): (VersionMeta, Vec) = + client.get_json_with_raw(&entry.url, "version meta").await?; + if !sha1_matches(&raw, &entry.sha1) || meta.id != entry.id { + return Err(NetError::Parse(format!( + "Version metadata for '{}' does not match its manifest", + entry.id + ))); + } + Ok((meta, raw)) +} + +fn sha1_matches(bytes: &[u8], expected: &str) -> bool { + use sha1::Digest; + format!("{:x}", sha1::Sha1::digest(bytes)).eq_ignore_ascii_case(expected) } fn sha1_hex(path: &Path) -> Option { @@ -192,7 +205,7 @@ fn verify_cached(path: &Path, expected_sha1: &str, expected_size: u64) -> bool { return false; } } - sha1_hex(path).is_some_and(|hash| hash == expected_sha1) + sha1_hex(path).is_some_and(|hash| hash.eq_ignore_ascii_case(expected_sha1)) } pub async fn download_client_jar( @@ -278,7 +291,7 @@ pub async fn download_libraries( .join(&meta.id) .join("natives"); - let mut downloads: Vec<(String, PathBuf, String)> = Vec::new(); + let mut downloads: Vec<(String, PathBuf, String, String, u64)> = Vec::new(); // natives jars to unpack once every download has landed: // (jar path inside the library cache, extract.exclude prefixes) let mut natives_jars: Vec<(PathBuf, Vec)> = Vec::new(); @@ -291,20 +304,22 @@ pub async fn download_libraries( } if let Some(artifact) = &library.downloads.artifact { - let rel = match library_relative_path(library, artifact.path.as_str()) { - Some(rel) => rel, - None => { - tracing::warn!("Skipping unresolvable library {}", library.name); - continue; - } - }; + let rel = library_relative_path(library, artifact.path.as_str()).ok_or_else(|| { + NetError::Parse(format!("Invalid library path for {}", library.name)) + })?; let destination = crate::storage::MetadataPaths::new(meta_dir) .libraries() .join(&rel); if verify_cached(&destination, &artifact.sha1, artifact.size) { tracing::trace!("Library already cached: {}", rel); } else { - downloads.push((artifact.url.clone(), destination, rel)); + downloads.push(( + artifact.url.clone(), + destination, + rel, + artifact.sha1.clone(), + artifact.size, + )); } } @@ -326,25 +341,31 @@ pub async fn download_libraries( let rel = if !info.path.is_empty() { info.path.clone() } else { - match crate::instance::loader::maven::maven_coord_to_path(&format!( + crate::instance::loader::maven::maven_coord_to_path(&format!( "{}:{}", library.name, classifier - )) { - Some(rel) => rel, - None => { - tracing::warn!( - "Skipping natives of library {}: no usable path", - library.name - ); - continue; - } - } + )) + .ok_or_else(|| { + NetError::Parse(format!("Invalid native library path for {}", library.name)) + })? }; + if !crate::storage::safe_relative_path(Path::new(&rel)) { + return Err(NetError::Parse(format!( + "Invalid native library path for {}", + library.name + ))); + } let destination = crate::storage::MetadataPaths::new(meta_dir) .libraries() .join(&rel); if !verify_cached(&destination, &info.sha1, info.size) { - downloads.push((info.url.clone(), destination.clone(), rel)); + downloads.push(( + info.url.clone(), + destination.clone(), + rel, + info.sha1.clone(), + info.size, + )); } let exclude = library .extract @@ -373,10 +394,12 @@ pub async fn download_libraries( } fn library_relative_path(library: &Library, recorded_path: &str) -> Option { - if !recorded_path.is_empty() { - return Some(recorded_path.to_owned()); - } - crate::instance::loader::maven::maven_coord_to_path(&library.name) + let path = if recorded_path.is_empty() { + crate::instance::loader::maven::maven_coord_to_path(&library.name)? + } else { + recorded_path.to_owned() + }; + crate::storage::safe_relative_path(Path::new(&path)).then_some(path) } fn extract_natives(jar: &Path, dest: &Path, exclude: &[String]) -> Result<(), NetError> { @@ -433,60 +456,61 @@ pub async fn download_assets_from( assets_base: &str, ) -> Result<(), NetError> { set_action("Downloading assets..."); + if !crate::storage::safe_relative_path(Path::new(&meta.asset_index.id)) + || Path::new(&meta.asset_index.id).components().count() != 1 + { + clear(); + return Err(NetError::Parse("Invalid asset index ID".to_owned())); + } let index_path = crate::storage::MetadataPaths::new(meta_dir) .assets() .join("indexes") .join(format!("{}.json", meta.asset_index.id)); - let asset_index: AssetIndexContent = if index_path.exists() { - let bytes = tokio::fs::read(&index_path).await?; - serde_json::from_slice(&bytes) - .map_err(|error| NetError::Parse(format!("Invalid cached asset index: {error}")))? + let cached = match tokio::fs::read(&index_path).await { + Ok(bytes) if sha1_matches(&bytes, &meta.asset_index.sha1) => { + serde_json::from_slice(&bytes).ok() + } + Ok(_) => { + tracing::warn!( + "Invalid cached asset index at {}; fetching again", + index_path.display() + ); + None + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(error) => return Err(error.into()), + }; + let asset_index: AssetIndexContent = if let Some(index) = cached { + index } else { tracing::debug!( "Fetching asset index {} from {}", meta.asset_index.id, meta.asset_index.url ); - let index = match client.get_json(&meta.asset_index.url).await { - Ok(index) => index, + let bytes = match client.get_bytes(&meta.asset_index.url).await { + Ok(bytes) => bytes, Err(e) => { clear(); return Err(e); } }; - match serde_json::to_string(&index) { - Ok(json) => { - if let Some(parent) = index_path.parent() { - match tokio::fs::create_dir_all(parent).await { - Ok(_) => {} - Err(e) => { - tracing::debug!("Failed to create asset index dir: {}", e); - } - } - } - match tokio::fs::write(&index_path, json).await { - Ok(_) => { - tracing::debug!("Saved asset index to {}", index_path.display()); - } - Err(e) => { - tracing::debug!( - "Failed to write asset index {}: {}", - index_path.display(), - e - ); - } - } - } - Err(e) => { - tracing::debug!("Failed to serialize asset index: {}", e); - } + if !sha1_matches(&bytes, &meta.asset_index.sha1) { + clear(); + return Err(NetError::Parse(format!( + "Asset index '{}' failed its SHA-1 verification", + meta.asset_index.id + ))); } + let index = serde_json::from_slice(&bytes) + .map_err(|error| NetError::Parse(format!("Invalid asset index: {error}")))?; + crate::storage::write_atomic(&index_path, &bytes)?; index }; let mut downloads = Vec::new(); for object in asset_index.objects.values() { - if object.hash.len() < 2 { + if object.hash.len() != 40 || !object.hash.bytes().all(|byte| byte.is_ascii_hexdigit()) { clear(); return Err(NetError::Parse(format!( "Invalid asset hash: {}", @@ -506,7 +530,13 @@ pub async fn download_assets_from( continue; } - downloads.push((url, destination, object.hash.clone())); + downloads.push(( + url, + destination, + object.hash.clone(), + object.hash.clone(), + object.size, + )); } if downloads.is_empty() { @@ -528,7 +558,7 @@ pub async fn download_assets_from( // Continue other downloads after one fails; report the first error afterward. async fn run_parallel_downloads( client: &HttpClient, - downloads: Vec<(String, PathBuf, String)>, + downloads: Vec<(String, PathBuf, String, String, u64)>, report_count_progress: bool, ) -> Result<(), NetError> { let total_downloads = downloads.len() as u64; @@ -592,9 +622,9 @@ async fn run_parallel_downloads( fn spawn_download_task( set: &mut JoinSet>, client: &HttpClient, - job: (String, PathBuf, String), + job: (String, PathBuf, String, String, u64), ) { - let (url, destination, label) = job; + let (url, destination, label, sha1, size) = job; let task_client = client.clone(); set.spawn(async move { @@ -604,7 +634,14 @@ fn spawn_download_task( destination.display() ); let result = download_file(&task_client, &url, &destination, |_current, _total| {}).await; - result.map(|()| { + result?; + if !verify_cached(&destination, &sha1, size) { + tokio::fs::remove_file(&destination).await?; + return Err(NetError::Parse(format!( + "Downloaded '{label}' failed its SHA-1 or size verification" + ))); + } + Ok({ tracing::trace!("Finished parallel download '{}'", label); label }) diff --git a/src/net/tests/curseforge.rs b/src/net/tests/curseforge.rs index 7894c35..614c5c3 100644 --- a/src/net/tests/curseforge.rs +++ b/src/net/tests/curseforge.rs @@ -3,6 +3,46 @@ use super::*; +#[tokio::test(start_paused = true)] +async fn authenticated_requests_retry_transient_failures_with_the_api_key() { + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + use wiremock::matchers::{header, method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let server = MockServer::start().await; + for verb in ["GET", "POST"] { + let attempts = Arc::new(AtomicUsize::new(0)); + Mock::given(method(verb)) + .and(path(format!("/{verb}"))) + .and(header("x-api-key", "test-key")) + .respond_with(move |_: &wiremock::Request| { + if attempts.fetch_add(1, Ordering::SeqCst) == 0 { + ResponseTemplate::new(503) + } else { + ResponseTemplate::new(200).set_body_json(serde_json::json!({"ok": true})) + } + }) + .expect(2) + .mount(&server) + .await; + } + let client: HttpClient = reqwest::Client::builder().build().unwrap().into(); + let fetched: serde_json::Value = get(&client, "test-key", &format!("{}/GET", server.uri())) + .await + .unwrap(); + let posted: serde_json::Value = post( + &client, + "test-key", + &format!("{}/POST", server.uri()), + &serde_json::json!({}), + ) + .await + .unwrap(); + assert!(fetched["ok"].as_bool().unwrap()); + assert!(posted["ok"].as_bool().unwrap()); +} + #[test] fn search_category_ids_match_the_selected_class() { let response: ApiResponse> = serde_json::from_str(r#"{"data":[{"id":6,"slug":"mc-mods","name":"Mods","classId":null},{"id":11,"slug":"magic","name":"Magic","classId":6},{"id":22,"slug":"magic","name":"Magic","classId":4471}]}"#).unwrap(); diff --git a/src/net/tests/modrinth.rs b/src/net/tests/modrinth.rs index 465b846..9362ae3 100644 --- a/src/net/tests/modrinth.rs +++ b/src/net/tests/modrinth.rs @@ -292,7 +292,7 @@ fn modpack_versions_are_not_limited_to_hardcoded_loaders() { } #[tokio::test] -async fn content_download_skips_an_existing_filename() { +async fn content_download_rejects_an_unverifiable_existing_filename() { let directory = tempfile::tempdir().unwrap(); let path = directory.path().join("example.jar"); std::fs::write(&path, b"existing").unwrap(); @@ -304,11 +304,11 @@ async fn content_download_skips_an_existing_filename() { hashes: HashMap::new(), }]); - let outcome = download_version_file(&crate::net::HttpClient::new(), &version, directory.path()) + let error = download_version_file(&crate::net::HttpClient::new(), &version, directory.path()) .await - .unwrap(); + .unwrap_err(); - assert_eq!(outcome, DownloadOutcome::SkippedExisting(path)); + assert!(error.to_string().contains("does not match")); assert_eq!( std::fs::read(directory.path().join("example.jar")).unwrap(), b"existing" diff --git a/tests/net_loaders.rs b/tests/net_loaders.rs index 89059cb..c20427c 100644 --- a/tests/net_loaders.rs +++ b/tests/net_loaders.rs @@ -202,10 +202,19 @@ async fn quilt_fetch_profile_parses_libraries() { async fn fabric_and_quilt_download_libraries_into_the_shared_cache() { let server = MockServer::start().await; let temp = tempfile::tempdir().unwrap(); - for (name, content) in [("fabric", "fabric jar"), ("quilt", "quilt jar")] { + 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_string(content)) + .respond_with(ResponseTemplate::new(200).set_body_bytes(jar.clone())) .expect(1) .mount(&server) .await; @@ -238,7 +247,7 @@ async fn fabric_and_quilt_download_libraries_into_the_shared_cache() { download_fabric_libraries(&client, &fabric, temp.path()) .await .unwrap(); - for (name, content) in [("fabric", "fabric jar"), ("quilt", "quilt jar")] { + for name in ["fabric", "quilt"] { assert_eq!( std::fs::read( rmcl::storage::MetadataPaths::new(temp.path()) @@ -246,11 +255,47 @@ async fn fabric_and_quilt_download_libraries_into_the_shared_cache() { .join(format!("example/{name}/1.0/{name}-1.0.jar")) ) .unwrap(), - content.as_bytes() + 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() { let server = MockServer::start().await; diff --git a/tests/net_mojang.rs b/tests/net_mojang.rs index afa09e4..3fd4c9c 100644 --- a/tests/net_mojang.rs +++ b/tests/net_mojang.rs @@ -12,6 +12,11 @@ use rmcl::net::mojang::{ fetch_version_manifest_from, fetch_version_meta_with_raw, }; +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" }, @@ -79,12 +84,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; @@ -93,7 +96,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) @@ -111,6 +114,27 @@ async fn fetch_version_meta_returns_struct_and_raw_bytes() { 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. @@ -136,8 +160,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, }, @@ -221,7 +245,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() @@ -237,33 +264,61 @@ 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!({ + "objects": { + "minecraft/lang/en_us.json": {"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()); @@ -275,7 +330,9 @@ 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"); } @@ -286,14 +343,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()) @@ -310,6 +369,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 diff --git a/tests/net_retry.rs b/tests/net_retry.rs index ec2d4ec..89ac61c 100644 --- a/tests/net_retry.rs +++ b/tests/net_retry.rs @@ -49,6 +49,30 @@ 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; From 0d1cafcb1096daa015be0249d1179878ec3f3934 Mon Sep 17 00:00:00 2001 From: objz Date: Thu, 1 Oct 2026 17:44:34 +0200 Subject: [PATCH 06/34] fix: preserve instance state through launches and updates --- src/instance/config_sync.rs | 158 +++++++++++++++--- src/instance/content/dependencies.rs | 4 +- src/instance/content/reconcile.rs | 20 ++- src/instance/desktop.rs | 66 +++++++- src/instance/import/refresh.rs | 184 ++++++++++++++++++++- src/instance/launch/mod.rs | 39 +---- src/instance/manager.rs | 26 ++- src/instance/tests/config_sync.rs | 135 +++++++++++++++ src/instance/tests/content/dependencies.rs | 50 ++++++ src/instance/tests/content/reconcile.rs | 15 ++ src/instance/tests/desktop.rs | 17 ++ src/instance/tests/manager.rs | 39 +++++ src/layout_migration.rs | 33 ++-- src/tests/layout_migration.rs | 49 ++++++ 14 files changed, 741 insertions(+), 94 deletions(-) diff --git a/src/instance/config_sync.rs b/src/instance/config_sync.rs index a563eb7..996accc 100644 --- a/src/instance/config_sync.rs +++ b/src/instance/config_sync.rs @@ -11,6 +11,8 @@ pub enum ConfigSyncError { InvalidProfile(String), #[error("Cannot switch config profiles while '{instance}' is running")] InstanceRunning { instance: String }, + #[error("Config profile '{0}' is in use by another instance")] + ProfileInUse(String), #[error("IO error: {0}")] Io(#[from] std::io::Error), #[error("Failed to save config profile: {0}")] @@ -22,6 +24,7 @@ pub enum ConfigSyncError { #[derive(Debug)] pub struct ConfigSyncLock { file: std::fs::File, + profile_dir: PathBuf, } impl Drop for ConfigSyncLock { @@ -37,16 +40,24 @@ pub fn prepare( meta_dir: &Path, minecraft_dir: &Path, ) -> Result { + Ok(prepare_for_launch(profile, meta_dir, minecraft_dir)?.is_some()) +} + +pub fn prepare_for_launch( + profile: Option<&str>, + meta_dir: &Path, + minecraft_dir: &Path, +) -> Result, ConfigSyncError> { let Some(profile) = profile.and_then(normalize_profile) else { - return Ok(false); + return Ok(None); }; validate_profile(profile)?; let profile_dir = profile_dir(meta_dir, profile); if !profile_dir.exists() { - return Ok(false); + return Ok(None); } - let _lock = acquire_lock(&profile_dir)?; + let lock = acquire_lock(&profile_dir)?; if !profile_payload_exists(&profile_dir)? { sync_to_profile(minecraft_dir, &profile_dir)?; @@ -54,7 +65,11 @@ pub fn prepare( sync_from_profile(&profile_dir, minecraft_dir)?; } - Ok(true) + Ok(Some(lock)) +} + +pub fn finish_launch(lock: ConfigSyncLock, minecraft_dir: &Path) -> Result<(), ConfigSyncError> { + sync_to_profile(minecraft_dir, &lock.profile_dir) } pub fn finish( @@ -105,6 +120,7 @@ pub fn delete_profile(meta_dir: &Path, profile: &str) -> Result<(), ConfigSyncEr validate_profile(profile)?; let dir = profile_dir(meta_dir, profile); if dir.exists() { + let _lock = acquire_lock(&dir)?; remove_path(&dir)?; } Ok(()) @@ -291,14 +307,26 @@ fn acquire_lock(profile_dir: &Path) -> Result { .create(true) .truncate(false) .open(path)?; - file.lock()?; - Ok(ConfigSyncLock { file }) + match file.try_lock() { + Ok(()) => {} + Err(std::fs::TryLockError::WouldBlock) => { + return Err(ConfigSyncError::ProfileInUse( + profile_dir + .file_name() + .unwrap_or_default() + .to_string_lossy() + .into_owned(), + )); + } + Err(std::fs::TryLockError::Error(error)) => return Err(error.into()), + } + Ok(ConfigSyncLock { + file, + profile_dir: profile_dir.to_owned(), + }) } fn mirror_dir(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> { - // stage the copy in a sibling temp dir and swap it in only when complete. - // deleting dst up-front (the old behaviour) meant a failure mid-copy - // destroyed the current config tree with nothing to fall back to. let parent = dst.parent().filter(|p| !p.as_os_str().is_empty()); let Some(parent) = parent else { return Err(std::io::Error::new( @@ -310,6 +338,21 @@ fn mirror_dir(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> { std::fs::create_dir_all(parent)?; let name = dst.file_name().and_then(|s| s.to_str()).unwrap_or("mirror"); let staging = parent.join(format!(".{name}.mirror-tmp")); + let backup = parent.join(format!(".{name}.mirror-backup")); + if std::fs::symlink_metadata(dst).is_ok_and(|meta| meta.file_type().is_symlink()) { + return Err(std::io::Error::other(format!( + "Cannot replace symlinked config directory '{}'", + dst.display() + )) + .into()); + } + if backup.exists() { + return Err(std::io::Error::new( + std::io::ErrorKind::AlreadyExists, + format!("Previous config backup remains at {}", backup.display()), + ) + .into()); + } if staging.exists() { remove_path(&staging)?; } @@ -319,10 +362,25 @@ fn mirror_dir(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> { if src.exists() { copy_dir_contents(src, &staging)?; } - if dst.exists() { - remove_path(dst)?; + let had_dst = dst.exists(); + if had_dst { + std::fs::rename(dst, &backup)?; + } + if let Err(error) = std::fs::rename(&staging, dst) { + if had_dst && let Err(rollback) = std::fs::rename(&backup, dst) { + return Err(ConfigSyncError::SaveRollback { + save: error.to_string(), + rollback: rollback.to_string(), + }); + } + return Err(error.into()); + } + if had_dst && let Err(error) = remove_path(&backup) { + tracing::warn!( + "Could not remove old config backup '{}': {error}", + backup.display() + ); } - std::fs::rename(&staging, dst)?; Ok(()) })(); @@ -351,7 +409,9 @@ fn profile_payload_exists(profile_dir: &Path) -> Result { } for entry in std::fs::read_dir(profile_dir)? { let entry = entry?; - if entry.file_type()?.is_file() && is_options_file(&entry.file_name().to_string_lossy()) { + if (entry.file_type()?.is_file() || entry.file_type()?.is_symlink()) + && is_options_file(&entry.file_name().to_string_lossy()) + { return Ok(true); } } @@ -359,30 +419,60 @@ fn profile_payload_exists(profile_dir: &Path) -> Result { } fn mirror_options(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> { - remove_options(dst)?; std::fs::create_dir_all(dst)?; - if !src.exists() { - return Ok(()); + let staging = dst.join(".rmcl-options-stage"); + if staging.exists() { + remove_path(&staging)?; } - - for entry in std::fs::read_dir(src)? { - let entry = entry?; - let name = entry.file_name(); - if entry.file_type()?.is_file() && is_options_file(&name.to_string_lossy()) { - std::fs::copy(entry.path(), dst.join(name))?; + std::fs::create_dir(&staging)?; + let result = (|| { + let mut copied = std::collections::HashSet::new(); + if src.exists() { + for entry in std::fs::read_dir(src)? { + let entry = entry?; + let name = entry.file_name(); + let file_type = entry.file_type()?; + if is_options_file(&name.to_string_lossy()) + && (file_type.is_file() || file_type.is_symlink()) + { + if file_type.is_symlink() { + copy_link(&entry.path(), &staging.join(&name))?; + } else { + std::fs::copy(entry.path(), staging.join(&name))?; + } + copied.insert(name); + } + } } + for entry in std::fs::read_dir(&staging)? { + let entry = entry?; + crate::storage::replace_file(&entry.path(), &dst.join(entry.file_name()))?; + } + remove_options(dst, &copied)?; + Ok(()) + })(); + if let Err(error) = std::fs::remove_dir_all(&staging) { + tracing::warn!( + "Could not remove options staging '{}': {error}", + staging.display() + ); } - Ok(()) + result } -fn remove_options(dir: &Path) -> Result<(), ConfigSyncError> { +fn remove_options( + dir: &Path, + copied: &std::collections::HashSet, +) -> Result<(), ConfigSyncError> { if !dir.exists() { return Ok(()); } for entry in std::fs::read_dir(dir)? { let entry = entry?; - if is_options_file(&entry.file_name().to_string_lossy()) { + if is_options_file(&entry.file_name().to_string_lossy()) + && !copied.contains(&entry.file_name()) + { remove_path(&entry.path())?; } } @@ -415,12 +505,30 @@ fn copy_dir_contents(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> { copy_dir_contents(&source, &target)?; } else if file_type.is_file() { std::fs::copy(&source, &target)?; + } else if file_type.is_symlink() { + copy_link(&source, &target)?; } } Ok(()) } +#[cfg(unix)] +fn copy_link(source: &Path, target: &Path) -> std::io::Result<()> { + std::os::unix::fs::symlink(std::fs::read_link(source)?, target) +} + +#[cfg(not(unix))] +fn copy_link(source: &Path, _target: &Path) -> std::io::Result<()> { + Err(std::io::Error::new( + std::io::ErrorKind::Unsupported, + format!( + "Cannot copy config symlink '{}' on this platform", + source.display() + ), + )) +} + #[cfg(test)] #[path = "tests/config_sync.rs"] mod tests; diff --git a/src/instance/content/dependencies.rs b/src/instance/content/dependencies.rs index 5c6d42d..718f739 100644 --- a/src/instance/content/dependencies.rs +++ b/src/instance/content/dependencies.rs @@ -213,6 +213,8 @@ async fn install_staged( }); } + let previous = + ContentManifest::load(manifest_path).map_err(|error| NetError::Parse(error.to_string()))?; let mut committed = Vec::new(); for (index, file) in staged.iter().enumerate() { let item = &plan.items[file.item]; @@ -241,8 +243,6 @@ async fn install_staged( }); } - let previous = - ContentManifest::load(manifest_path).map_err(|error| NetError::Parse(error.to_string()))?; let records = match build_records(plan, &previous, minecraft_dir, &staged) { Ok(records) => records, Err(error) => { diff --git a/src/instance/content/reconcile.rs b/src/instance/content/reconcile.rs index 3c9da05..ff5f6fb 100644 --- a/src/instance/content/reconcile.rs +++ b/src/instance/content/reconcile.rs @@ -620,7 +620,10 @@ fn content_files(minecraft_dir: &Path) -> std::io::Result std::io::Result bool { - if path.is_dir() { + let Ok(metadata) = std::fs::symlink_metadata(path) else { + return false; + }; + if metadata.file_type().is_symlink() { + return false; + } + if metadata.is_dir() { return matches!( kind, ContentKind::ResourcePack | ContentKind::Shader | ContentKind::DataPack ); } - if !path.is_file() { + if !metadata.is_file() { return false; } let Some(name) = path.file_name().and_then(|name| name.to_str()) else { @@ -661,7 +670,10 @@ fn directory_fingerprint_metadata(path: &Path) -> Result std::io::Result<()> { for entry in std::fs::read_dir(path)? { let entry = entry?; - let metadata = entry.metadata()?; + let metadata = std::fs::symlink_metadata(entry.path())?; + if metadata.file_type().is_symlink() { + continue; + } let modified = metadata .modified() .unwrap_or(SystemTime::UNIX_EPOCH) diff --git a/src/instance/desktop.rs b/src/instance/desktop.rs index 82b8654..1cf05bb 100644 --- a/src/instance/desktop.rs +++ b/src/instance/desktop.rs @@ -8,7 +8,7 @@ use crate::instance::models::InstanceConfig; const ICON_BYTES: &[u8] = include_bytes!("../../assets/icon.svg"); pub fn desktop_path(name: &str) -> Option { - let sanitized = sanitize(name); + let sanitized = shortcut_name(name); #[cfg(target_os = "linux")] { @@ -56,14 +56,54 @@ fn ensure_icon() -> Option { Some(path) } +fn shortcut_name(name: &str) -> String { + let mut encoded = String::new(); + for character in name.chars() { + if character.is_alphanumeric() || matches!(character, '-' | '_') { + encoded.push(character); + } else { + for byte in character.to_string().bytes() { + encoded.push_str(&format!("%{byte:02X}")); + } + } + } + encoded +} + +fn legacy_path(name: &str) -> Option { + let legacy = desktop_path(&sanitize(name))?; + (Some(&legacy) != desktop_path(name).as_ref()).then_some(legacy) +} + +fn owns_legacy_shortcut(path: &Path, name: &str) -> bool { + let content = build_content(name, None); + let command = content.lines().find(|line| { + line.starts_with("Exec=") + || line.starts_with("shell.Run ") + || line.starts_with("rmcl instance launch ") + }); + command.is_some_and(|command| { + std::fs::read_to_string(path) + .is_ok_and(|existing| existing.lines().any(|line| line == command)) + }) +} + pub fn exists(name: &str) -> bool { - desktop_path(name).map(|p| p.exists()).unwrap_or(false) + desktop_path(name).is_some_and(|path| owns_legacy_shortcut(&path, name)) + || legacy_path(name).is_some_and(|path| owns_legacy_shortcut(&path, name)) } pub fn create(config: &InstanceConfig) -> std::io::Result { let path = desktop_path(&config.name) .ok_or_else(|| std::io::Error::other("cannot resolve shortcut directory"))?; + if path.exists() && !owns_legacy_shortcut(&path, &config.name) { + return Err(std::io::Error::new( + std::io::ErrorKind::AlreadyExists, + format!("Another shortcut already exists at '{}'", path.display()), + )); + } + if let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; } @@ -81,6 +121,12 @@ pub fn create(config: &InstanceConfig) -> std::io::Result { std::fs::set_permissions(&path, perms)?; } + if let Some(legacy) = legacy_path(&config.name) + && owns_legacy_shortcut(&legacy, &config.name) + { + std::fs::remove_file(legacy)?; + } + Ok(path) } @@ -88,9 +134,14 @@ pub fn remove(name: &str) -> std::io::Result<()> { let Some(path) = desktop_path(name) else { return Ok(()); }; - if path.exists() { + if owns_legacy_shortcut(&path, name) { std::fs::remove_file(path)?; } + if let Some(legacy) = legacy_path(name) + && owns_legacy_shortcut(&legacy, name) + { + std::fs::remove_file(legacy)?; + } Ok(()) } @@ -109,12 +160,13 @@ pub fn toggle(config: &InstanceConfig) -> std::io::Result { } pub fn rename(old_name: &str, new_config: &InstanceConfig) -> std::io::Result<()> { - let Some(old_path) = desktop_path(old_name).filter(|path| path.exists()) else { + if !exists(old_name) { return Ok(()); - }; + } + let same_path = desktop_path(old_name) == desktop_path(&new_config.name); create(new_config)?; - if desktop_path(&new_config.name).as_ref() != Some(&old_path) { - std::fs::remove_file(old_path)?; + if !same_path { + remove(old_name)?; } Ok(()) } diff --git a/src/instance/import/refresh.rs b/src/instance/import/refresh.rs index bb08b58..12aa6ba 100644 --- a/src/instance/import/refresh.rs +++ b/src/instance/import/refresh.rs @@ -6,6 +6,7 @@ use std::path::{Path, PathBuf}; use serde::{Deserialize, Serialize}; +use crate::instance::content::manifest::ContentManifest; use crate::instance::{InstanceConfig, InstanceManager, ProviderProject}; use crate::net::modrinth::VersionInfo; use crate::storage::InstancePaths; @@ -170,6 +171,13 @@ pub fn apply( &plan.new_owned, replace_conflicts, )?; + preserve_refresh_state( + &live, + &plan.staged_instance, + &plan.old_owned, + &plan.new_owned, + replace_conflicts, + )?; let backup = live.with_file_name(format!(".{}.rmcl-backup", plan.instance.name)); if backup.exists() { @@ -247,6 +255,54 @@ fn user_file_collisions( Ok(collisions) } +fn preserve_refresh_state( + live: &Path, + staged: &Path, + old_owned: &HashSet, + new_owned: &HashSet, + replace_conflicts: &HashSet, +) -> Result<(), String> { + let old = InstancePaths::new(live); + let new = InstancePaths::new(staged); + let local_config = old.local_config(); + if local_config.exists() { + std::fs::create_dir_all(new.local_config()).map_err(|e| e.to_string())?; + preserve_user_files( + &local_config, + &new.local_config(), + &local_config, + &HashSet::new(), + &HashSet::new(), + &HashSet::new(), + )?; + } + + let old_manifest = ContentManifest::load(&old.content_manifest()).map_err(|e| e.to_string())?; + let mut new_manifest = + ContentManifest::load(&new.content_manifest()).map_err(|e| e.to_string())?; + for record in &old_manifest.files { + let path = &record.relative_path; + if !old_owned.contains(path) + && !(new_owned.contains(path) && replace_conflicts.contains(path)) + && old.minecraft().join(path).exists() + { + new_manifest.upsert(record.clone()); + } + } + for path in new_owned { + if !replace_conflicts.contains(path) + && !old_owned.contains(path) + && old.minecraft().join(path).exists() + && old_manifest.record(path).is_none() + { + new_manifest.remove(path); + } + } + new_manifest + .save(&new.content_manifest()) + .map_err(|e| e.to_string()) +} + fn preserve_user_files( source: &Path, destination: &Path, @@ -260,13 +316,34 @@ fn preserve_user_files( let path = entry.path(); let relative = path.strip_prefix(root).map_err(|error| error.to_string())?; let metadata = std::fs::symlink_metadata(&path).map_err(|error| error.to_string())?; + if old_owned.contains(relative) + || new_owned.contains(relative) && replace_conflicts.contains(relative) + { + continue; + } if metadata.file_type().is_symlink() { + let target = destination.join(entry.file_name()); + if let Ok(existing) = std::fs::symlink_metadata(&target) { + if existing.is_dir() { + return Err(format!( + "Cannot replace directory '{}' with a symbolic link", + target.display() + )); + } + std::fs::remove_file(&target).map_err(|error| error.to_string())?; + } + #[cfg(unix)] + std::os::unix::fs::symlink( + std::fs::read_link(&path).map_err(|error| error.to_string())?, + &target, + ) + .map_err(|error| error.to_string())?; + #[cfg(not(unix))] return Err(format!( - "Cannot safely preserve symbolic link '{}'", + "Cannot preserve symbolic link '{}' on this platform", path.display() )); - } - if metadata.is_dir() { + } else if metadata.is_dir() { let target = destination.join(entry.file_name()); std::fs::create_dir_all(&target).map_err(|error| error.to_string())?; preserve_user_files( @@ -277,9 +354,7 @@ fn preserve_user_files( new_owned, replace_conflicts, )?; - } else if !(old_owned.contains(relative) - || new_owned.contains(relative) && replace_conflicts.contains(relative)) - { + } else { let target = destination.join(entry.file_name()); std::fs::copy(&path, target).map_err(|error| error.to_string())?; } @@ -301,7 +376,7 @@ fn collect_files( let metadata = std::fs::symlink_metadata(&path).map_err(|error| error.to_string())?; if metadata.is_dir() { collect_files(&path, root, visit)?; - } else if metadata.is_file() { + } else if metadata.is_file() || metadata.file_type().is_symlink() { visit( path.strip_prefix(root).map_err(|error| error.to_string())?, &path, @@ -332,6 +407,101 @@ fn format_bytes(bytes: u64) -> String { mod tests { use super::*; + use crate::instance::content::manifest::{ContentFileRecord, ContentKind, FileFingerprint}; + + fn record(path: &str) -> ContentFileRecord { + ContentFileRecord { + relative_path: path.into(), + kind: ContentKind::Mod, + enabled: true, + fingerprint: FileFingerprint { + size: 1, + modified_ns: 1, + hashes: Default::default(), + }, + resolution: Default::default(), + provider_aliases: Vec::new(), + provider_checks: Vec::new(), + required_dependencies: Vec::new(), + automatic_dependency: false, + cleanup_eligible: false, + } + } + + #[test] + fn refresh_keeps_local_config_and_user_content_records() { + let temp = tempfile::tempdir().unwrap(); + let old = InstancePaths::new(temp.path().join("old")); + let new = InstancePaths::new(temp.path().join("new")); + std::fs::create_dir_all(old.local_config()).unwrap(); + std::fs::write(old.local_config().join("options.txt"), b"local").unwrap(); + std::fs::create_dir_all(old.minecraft().join("mods")).unwrap(); + std::fs::write(old.minecraft().join("mods/user.jar"), b"user").unwrap(); + std::fs::write(old.minecraft().join("mods/replace.jar"), b"user").unwrap(); + std::fs::create_dir_all(new.minecraft().join("mods")).unwrap(); + let mut previous = ContentManifest::default(); + previous.upsert(record("mods/user.jar")); + previous.upsert(record("mods/replace.jar")); + previous.save(&old.content_manifest()).unwrap(); + let mut staged = ContentManifest::default(); + staged.upsert(record("mods/pack.jar")); + staged.save(&new.content_manifest()).unwrap(); + + preserve_refresh_state( + old.root(), + new.root(), + &HashSet::new(), + &HashSet::from([ + PathBuf::from("mods/pack.jar"), + PathBuf::from("mods/replace.jar"), + ]), + &HashSet::from([PathBuf::from("mods/replace.jar")]), + ) + .unwrap(); + + assert_eq!( + std::fs::read(new.local_config().join("options.txt")).unwrap(), + b"local" + ); + let manifest = ContentManifest::load(&new.content_manifest()).unwrap(); + assert!(manifest.record(Path::new("mods/user.jar")).is_some()); + assert!(manifest.record(Path::new("mods/pack.jar")).is_some()); + assert!(manifest.record(Path::new("mods/replace.jar")).is_none()); + } + + #[cfg(unix)] + #[test] + fn refresh_preserves_user_symlinks_without_following_them() { + let temp = tempfile::tempdir().unwrap(); + let old = temp.path().join("old"); + let new = temp.path().join("new"); + std::fs::create_dir_all(&old).unwrap(); + std::fs::create_dir_all(&new).unwrap(); + std::os::unix::fs::symlink("outside", old.join("linked.jar")).unwrap(); + std::os::unix::fs::symlink(&old, old.join("loop")).unwrap(); + let collisions = user_file_collisions( + &old, + &HashSet::new(), + &HashSet::from([PathBuf::from("linked.jar")]), + ) + .unwrap(); + assert_eq!(collisions, vec![PathBuf::from("linked.jar")]); + preserve_user_files( + &old, + &new, + &old, + &HashSet::new(), + &HashSet::new(), + &HashSet::new(), + ) + .unwrap(); + assert_eq!( + std::fs::read_link(new.join("linked.jar")).unwrap(), + PathBuf::from("outside") + ); + assert_eq!(std::fs::read_link(new.join("loop")).unwrap(), old); + } + #[test] fn preservation_replaces_pack_files_and_keeps_user_files() { let temp = tempfile::tempdir().unwrap(); diff --git a/src/instance/launch/mod.rs b/src/instance/launch/mod.rs index ae038b2..a40ffab 100644 --- a/src/instance/launch/mod.rs +++ b/src/instance/launch/mod.rs @@ -711,14 +711,12 @@ async fn run_launch_command( } fn finish_config_sync( - active: bool, - profile: Option<&str>, - meta_dir: &Path, + lock: Option, minecraft_dir: &Path, instance: &str, ) { - if active - && let Err(error) = crate::instance::config_sync::finish(profile, meta_dir, minecraft_dir) + if let Some(lock) = lock + && let Err(error) = crate::instance::config_sync::finish_launch(lock, minecraft_dir) { tracing::warn!("Failed to sync config for '{}': {}", instance, error); } @@ -771,7 +769,7 @@ pub async fn launch( changed = true; } if changed { - account_store.save(); + account_store.save()?; } } @@ -800,9 +798,8 @@ pub async fn launch( invocation.game_args.len(), invocation.main_class ); - let config_sync_profile = config.config_sync_profile.clone(); - let config_sync_active = crate::instance::config_sync::prepare( - config_sync_profile.as_deref(), + let config_sync_lock = crate::instance::config_sync::prepare_for_launch( + config.config_sync_profile.as_deref(), meta_dir, &invocation.working_dir, )?; @@ -815,13 +812,7 @@ pub async fn launch( ) .await { - finish_config_sync( - config_sync_active, - config_sync_profile.as_deref(), - meta_dir, - &invocation.working_dir, - &name, - ); + finish_config_sync(config_sync_lock, &invocation.working_dir, &name); return Err(error); } @@ -865,13 +856,7 @@ pub async fn launch( Err(e) => { crate::instance::runtime::cleanup_kill_sender(&name); crate::instance::runtime::remove(&name); - finish_config_sync( - config_sync_active, - config_sync_profile.as_deref(), - meta_dir, - &invocation.working_dir, - &name, - ); + finish_config_sync(config_sync_lock, &invocation.working_dir, &name); tracing::error!("[{}] Failed to spawn Minecraft process: {}", name, e); return Err(LaunchError::Io(e)); } @@ -1009,13 +994,7 @@ pub async fn launch( crate::feedback::errors::push_message(tracing::Level::WARN, error.to_string()); } - finish_config_sync( - config_sync_active, - config_sync_profile.as_deref(), - &meta_dir_owned, - &minecraft_dir_owned, - &name_for_task, - ); + finish_config_sync(config_sync_lock, &minecraft_dir_owned, &name_for_task); if code == Some(0) || killed_by_user { crate::instance::runtime::remove(&name_for_task); tracing::debug!( diff --git a/src/instance/manager.rs b/src/instance/manager.rs index ad89388..1b5362b 100644 --- a/src/instance/manager.rs +++ b/src/instance/manager.rs @@ -16,6 +16,8 @@ pub enum InstanceError { AlreadyExists(String), #[error("Instance '{0}' not found")] NotFound(String), + #[error("Stop instance '{0}' before renaming or deleting it")] + InstanceRunning(String), #[error("IO error: {0}")] Io(#[from] std::io::Error), #[error("JSON error: {0}")] @@ -405,6 +407,9 @@ impl InstanceManager { pub fn delete(&self, name: &str) -> Result<(), InstanceError> { validate_name(name)?; + if crate::instance::runtime::is_active(name) { + return Err(InstanceError::InstanceRunning(name.to_owned())); + } let instance_dir = self.instances_dir.join(name); if !instance_dir.exists() { tracing::warn!( @@ -431,6 +436,9 @@ impl InstanceManager { pub fn rename(&self, old_name: &str, new_name: &str) -> Result<(), InstanceError> { validate_name(old_name)?; + if crate::instance::runtime::is_active(old_name) { + return Err(InstanceError::InstanceRunning(old_name.to_owned())); + } let new_name = new_name.trim(); if new_name.is_empty() { tracing::warn!("Cannot rename instance '{}': new name is empty", old_name); @@ -533,7 +541,16 @@ impl InstanceManager { } }; match serde_json::from_str::(&contents) { - Ok(config) => instances.push(config), + Ok(mut config) => { + let Some(directory_name) = entry.file_name().to_str().map(str::to_owned) else { + continue; + }; + if validate_name(&directory_name).is_err() { + continue; + } + config.name = directory_name; + instances.push(config); + } Err(e) => { tracing::error!("Failed to parse {}: {}", config_path.display(), e); } @@ -570,7 +587,10 @@ impl InstanceManager { } }; match serde_json::from_str::(&contents) { - Ok(config) => Ok(config), + Ok(mut config) => { + config.name = name.to_owned(); + Ok(config) + } Err(e) => { tracing::error!( "Failed to parse instance '{}' config {}: {}", @@ -609,7 +629,7 @@ impl InstanceManager { } // guard against path traversal and other filesystem shenanigans -fn validate_name(name: &str) -> Result<(), InstanceError> { +pub(crate) fn validate_name(name: &str) -> Result<(), InstanceError> { if name.is_empty() || name.len() > 64 { return Err(InstanceError::InvalidName(format!( "Name must be 1-64 chars, got: {:?}", diff --git a/src/instance/tests/config_sync.rs b/src/instance/tests/config_sync.rs index 26c6a5d..c8f2818 100644 --- a/src/instance/tests/config_sync.rs +++ b/src/instance/tests/config_sync.rs @@ -107,6 +107,141 @@ fn prepare_releases_lock_for_another_instance() { assert!(prepare(Some("main"), &meta, &second).unwrap()); } +#[test] +fn active_launch_keeps_its_profile_locked_until_finish() { + let tmp = tempfile::tempdir().unwrap(); + let meta = tmp.path().join("meta"); + let first = tmp.path().join("first/minecraft"); + let second = tmp.path().join("second/minecraft"); + std::fs::create_dir_all(first.join("config")).unwrap(); + std::fs::create_dir_all(second.join("config")).unwrap(); + create_profile(&meta, "main").unwrap(); + + let lock = prepare_for_launch(Some("main"), &meta, &first) + .unwrap() + .unwrap(); + assert!(matches!( + prepare_for_launch(Some("main"), &meta, &second), + Err(ConfigSyncError::ProfileInUse(_)) + )); + assert!(matches!( + delete_profile(&meta, "main"), + Err(ConfigSyncError::ProfileInUse(_)) + )); + finish_launch(lock, &first).unwrap(); + assert!( + prepare_for_launch(Some("main"), &meta, &second) + .unwrap() + .is_some() + ); +} + +#[test] +fn failed_options_source_read_keeps_existing_options() { + let tmp = tempfile::tempdir().unwrap(); + let source = tmp.path().join("not-a-directory"); + let target = tmp.path().join("target"); + std::fs::write(&source, b"invalid").unwrap(); + std::fs::create_dir(&target).unwrap(); + std::fs::write(target.join("options.txt"), b"keep").unwrap(); + + assert!(mirror_options(&source, &target).is_err()); + assert_eq!(std::fs::read(target.join("options.txt")).unwrap(), b"keep"); +} + +#[cfg(unix)] +#[test] +fn config_sync_preserves_symlinked_config_and_options() { + let tmp = tempfile::tempdir().unwrap(); + let minecraft = tmp.path().join("minecraft"); + let profile = tmp.path().join("profile"); + std::fs::create_dir_all(minecraft.join("config")).unwrap(); + std::fs::write(tmp.path().join("shared.toml"), "settings").unwrap(); + std::os::unix::fs::symlink( + tmp.path().join("shared.toml"), + minecraft.join("config/mod.toml"), + ) + .unwrap(); + std::os::unix::fs::symlink( + tmp.path().join("shared.toml"), + minecraft.join("options.txt"), + ) + .unwrap(); + + sync_to_profile(&minecraft, &profile).unwrap(); + assert!( + std::fs::symlink_metadata(profile.join("config/mod.toml")) + .unwrap() + .file_type() + .is_symlink() + ); + assert!( + std::fs::symlink_metadata(profile.join("options.txt")) + .unwrap() + .file_type() + .is_symlink() + ); + sync_from_profile(&profile, &minecraft).unwrap(); + assert!( + std::fs::symlink_metadata(minecraft.join("config/mod.toml")) + .unwrap() + .file_type() + .is_symlink() + ); + assert!( + std::fs::symlink_metadata(minecraft.join("options.txt")) + .unwrap() + .file_type() + .is_symlink() + ); +} + +#[cfg(unix)] +#[test] +fn symlink_only_profile_is_not_reinitialized_or_replaced() { + let tmp = tempfile::tempdir().unwrap(); + let minecraft = tmp.path().join("minecraft"); + let meta = tmp.path().join("meta"); + let profile = crate::storage::MetadataPaths::new(&meta) + .profiles() + .join("linked"); + std::fs::create_dir_all(&profile).unwrap(); + std::fs::create_dir_all(&minecraft).unwrap(); + std::fs::write(tmp.path().join("shared-options"), b"profile").unwrap(); + std::os::unix::fs::symlink( + tmp.path().join("shared-options"), + profile.join("options.txt"), + ) + .unwrap(); + + let lock = prepare_for_launch(Some("linked"), &meta, &minecraft).unwrap(); + assert!(lock.is_some()); + assert_eq!( + std::fs::read(minecraft.join("options.txt")).unwrap(), + b"profile" + ); + assert!( + std::fs::symlink_metadata(minecraft.join("options.txt")) + .unwrap() + .file_type() + .is_symlink() + ); + + let external = tmp.path().join("external-config"); + std::fs::create_dir(&external).unwrap(); + std::fs::write(external.join("keep.txt"), b"keep").unwrap(); + std::fs::remove_dir(minecraft.join("config")).unwrap(); + std::os::unix::fs::symlink(&external, minecraft.join("config")).unwrap(); + assert!(sync_from_profile(&profile, &minecraft).is_err()); + assert!( + std::fs::symlink_metadata(minecraft.join("config")) + .unwrap() + .file_type() + .is_symlink() + ); + assert_eq!(std::fs::read(external.join("keep.txt")).unwrap(), b"keep"); +} + #[test] fn profile_rejects_path_traversal() { let tmp = tempfile::tempdir().unwrap(); diff --git a/src/instance/tests/content/dependencies.rs b/src/instance/tests/content/dependencies.rs index feb054c..fbcbec6 100644 --- a/src/instance/tests/content/dependencies.rs +++ b/src/instance/tests/content/dependencies.rs @@ -63,6 +63,56 @@ fn merge_keeps_replacement_when_a_dependency_is_also_an_update_root() { assert!(!merged.items[0].automatic_dependency); } +#[tokio::test] +async fn invalid_manifest_does_not_replace_installed_content() { + let temp = tempfile::tempdir().unwrap(); + let minecraft = temp.path().join("minecraft"); + let mods = minecraft.join("mods"); + tokio::fs::create_dir_all(&mods).await.unwrap(); + let old = mods.join("old.jar"); + tokio::fs::write(&old, b"original").await.unwrap(); + let manifest = temp.path().join("content.json"); + tokio::fs::write(&manifest, b"{bad JSON").await.unwrap(); + let selected = version( + "new", + "root", + VersionType::Release, + "2026-02-01", + Vec::new(), + ); + let plan = DependencyPlan { + items: vec![PlannedInstall { + provider: "modrinth".to_owned(), + project_id: "root".to_owned(), + title: "Root".to_owned(), + version: selected.clone(), + installed_path: Some(old.clone()), + kind: ContentKind::Mod, + destination: mods.clone(), + provider_aliases: Vec::new(), + required_dependencies: Vec::new(), + automatic_dependency: false, + cleanup_eligible: false, + replacement: true, + }], + root_count: 1, + optional_dependencies: 0, + }; + + assert!( + install( + &provider(vec![selected]).registry(), + &manifest, + &minecraft, + &plan + ) + .await + .is_err() + ); + assert_eq!(tokio::fs::read(old).await.unwrap(), b"original"); + assert!(!mods.join("new.jar").exists()); +} + struct FakeProvider { versions: HashMap, compatible: HashMap>, diff --git a/src/instance/tests/content/reconcile.rs b/src/instance/tests/content/reconcile.rs index 05bf6b1..541c04f 100644 --- a/src/instance/tests/content/reconcile.rs +++ b/src/instance/tests/content/reconcile.rs @@ -5,6 +5,21 @@ use super::*; struct NoopProgress; +#[cfg(unix)] +#[test] +fn linked_pack_contents_cannot_recurse_into_themselves() { + let temp = tempfile::tempdir().unwrap(); + let minecraft = temp.path().join("minecraft"); + let pack = minecraft.join("resourcepacks/unpacked"); + std::fs::create_dir_all(&pack).unwrap(); + std::fs::write(pack.join("pack.mcmeta"), b"pack").unwrap(); + std::os::unix::fs::symlink(&pack, pack.join("again")).unwrap(); + + let files = content_files(&minecraft).unwrap(); + assert_eq!(files.len(), 1); + assert_eq!(directory_fingerprint_metadata(&pack).unwrap().size, 4); +} + impl InventoryProgress for NoopProgress { fn set_sub_action(&self, _text: &str) {} diff --git a/src/instance/tests/desktop.rs b/src/instance/tests/desktop.rs index dd9b89c..de99ea0 100644 --- a/src/instance/tests/desktop.rs +++ b/src/instance/tests/desktop.rs @@ -14,6 +14,23 @@ fn sanitize_replaces_special_chars() { assert_eq!(sanitize("path/traversal"), "path_traversal"); } +#[test] +fn shortcut_paths_do_not_collide_after_escaping() { + assert_ne!(shortcut_name("a b"), shortcut_name("a_b")); + assert_ne!(shortcut_name("a?b"), shortcut_name("a b")); + assert_ne!(shortcut_name("a%b"), shortcut_name("a%25b")); + assert_eq!(shortcut_name("my-instance_123"), "my-instance_123"); +} + +#[test] +fn legacy_shortcut_is_attributed_to_the_right_instance() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("rmcl-a_b.desktop"); + std::fs::write(&path, build_content("a b", None)).unwrap(); + assert!(owns_legacy_shortcut(&path, "a b")); + assert!(!owns_legacy_shortcut(&path, "a_b")); +} + #[test] #[cfg(target_os = "linux")] fn build_content_linux() { diff --git a/src/instance/tests/manager.rs b/src/instance/tests/manager.rs index 0709ffc..fc6b65e 100644 --- a/src/instance/tests/manager.rs +++ b/src/instance/tests/manager.rs @@ -62,6 +62,45 @@ fn delete_missing_instance_returns_not_found() { assert!(matches!(result, Err(InstanceError::NotFound(_)))); } +#[test] +fn running_instance_cannot_be_deleted_or_renamed() { + let (manager, tmp) = test_manager(); + let name = format!("running-{}", std::process::id()); + std::fs::create_dir_all(tmp.path().join(&name)).unwrap(); + manager.save(&dummy_config(&name)).unwrap(); + crate::instance::runtime::set_state(&name, crate::instance::runtime::RunState::Running); + + let deletion = manager.delete(&name); + let rename = manager.rename(&name, "changed"); + crate::instance::runtime::remove(&name); + + assert!(matches!(deletion, Err(InstanceError::InstanceRunning(_)))); + assert!(matches!(rename, Err(InstanceError::InstanceRunning(_)))); + assert!(tmp.path().join(&name).exists()); + assert!(!tmp.path().join("changed").exists()); +} + +#[test] +fn copied_instance_uses_its_directory_as_identity() { + let (manager, tmp) = test_manager(); + std::fs::create_dir_all(tmp.path().join("original")).unwrap(); + manager.save(&dummy_config("original")).unwrap(); + std::fs::create_dir_all(tmp.path().join("copy")).unwrap(); + std::fs::copy( + tmp.path().join("original/instance.json"), + tmp.path().join("copy/instance.json"), + ) + .unwrap(); + + assert_eq!(manager.load_one("copy").unwrap().name, "copy"); + assert!( + manager + .load_all() + .iter() + .any(|config| config.name == "copy") + ); +} + #[tokio::test] async fn create_preserves_directory_without_instance_config() { let (manager, tmp) = test_manager(); diff --git a/src/layout_migration.rs b/src/layout_migration.rs index 62e7987..05b9e1a 100644 --- a/src/layout_migration.rs +++ b/src/layout_migration.rs @@ -84,22 +84,21 @@ pub enum MigrationError { pub fn is_needed(instances_dir: &Path, meta_dir: &Path) -> bool { let metadata = MetadataPaths::new(meta_dir); - if metadata.cache_rebuild_pending().exists() { - return true; - } - if marker_version(&metadata.layout_marker()) == Some(LAYOUT_VERSION) { - return false; - } - has_legacy_instances(instances_dir) - || [ - "versions", - "libraries", - "assets", - "loader-profiles", - "config-sync", - ] - .iter() - .any(|path| meta_dir.join(path).exists()) + metadata.cache_rebuild_pending().exists() + || has_legacy_instances(instances_dir) + || has_legacy_shared_data(meta_dir) +} + +fn has_legacy_shared_data(meta_dir: &Path) -> bool { + [ + "versions", + "libraries", + "assets", + "loader-profiles", + "config-sync", + ] + .iter() + .any(|path| meta_dir.join(path).exists()) } pub fn initialize_new_layout(meta_dir: &Path) -> Result<(), MigrationError> { @@ -137,6 +136,8 @@ pub fn run( let metadata = MetadataPaths::new(meta_dir); if marker_version(&metadata.layout_marker()) == Some(LAYOUT_VERSION) && metadata.cache_rebuild_pending().exists() + && !has_legacy_instances(instances_dir) + && !has_legacy_shared_data(meta_dir) { crate::config::upgrade_config_file(config_file)?; return Ok(latest_layout_backup(&metadata).unwrap_or_else(|| metadata.backups())); diff --git a/src/tests/layout_migration.rs b/src/tests/layout_migration.rs index 479fe0c..44e0a96 100644 --- a/src/tests/layout_migration.rs +++ b/src/tests/layout_migration.rs @@ -3,6 +3,52 @@ use super::*; +#[test] +fn migrated_layout_detects_a_newly_copied_legacy_instance() { + let temp = tempfile::tempdir().unwrap(); + let instances = temp.path().join("instances"); + let meta = temp.path().join("meta"); + fs::create_dir_all(&instances).unwrap(); + initialize_new_layout(&meta).unwrap(); + assert!(!is_needed(&instances, &meta)); + + fs::create_dir_all(instances.join("copied/.minecraft/saves")).unwrap(); + assert!(is_needed(&instances, &meta)); + fs::write(temp.path().join("config.toml"), b"[paths]").unwrap(); + fs::write( + MetadataPaths::new(&meta).cache_rebuild_pending(), + LAYOUT_VERSION.to_string(), + ) + .unwrap(); + run(&instances, &meta, &temp.path().join("config.toml"), |_| {}).unwrap(); + assert!(instances.join("copied/minecraft/saves").exists()); +} + +#[test] +fn migrated_layout_detects_newly_copied_shared_data() { + let temp = tempfile::tempdir().unwrap(); + let instances = temp.path().join("instances"); + let meta = temp.path().join("meta"); + let config = temp.path().join("config.toml"); + fs::create_dir_all(&instances).unwrap(); + fs::write(&config, b"[paths]").unwrap(); + initialize_new_layout(&meta).unwrap(); + fs::write( + MetadataPaths::new(&meta).cache_rebuild_pending(), + LAYOUT_VERSION.to_string(), + ) + .unwrap(); + fs::create_dir_all(meta.join("versions")).unwrap(); + fs::write(meta.join("versions/copied.json"), b"data").unwrap(); + + assert!(is_needed(&instances, &meta)); + run(&instances, &meta, &config, |_| {}).unwrap(); + assert_eq!( + fs::read(MetadataPaths::new(&meta).versions().join("copied.json")).unwrap(), + b"data" + ); +} + #[test] fn migration_backs_up_and_renames_instance_directories() { let temp = tempfile::tempdir().unwrap(); @@ -155,7 +201,10 @@ fn migration_need_follows_legacy_data_marker_and_pending_rebuild() { assert!(is_needed(&instances, &meta)); initialize_new_layout(&meta).unwrap(); + assert!(is_needed(&instances, &meta)); + fs::remove_dir_all(instances.join("Example/.minecraft")).unwrap(); assert!(!is_needed(&instances, &meta)); + fs::create_dir_all(meta.join("versions")).unwrap(); fs::write(MetadataPaths::new(&meta).layout_marker(), b"invalid marker").unwrap(); assert!(is_needed(&instances, &meta)); initialize_new_layout(&meta).unwrap(); From 75c74333c5990117729c2ee346aa7f41bd5c4020 Mon Sep 17 00:00:00 2001 From: objz Date: Thu, 1 Oct 2026 17:45:17 +0200 Subject: [PATCH 07/34] fix: ignore stale TUI results and show narrow settings --- src/tui/event.rs | 31 ++++++++- src/tui/input.rs | 45 ++++++++++--- src/tui/tests/event.rs | 8 +-- src/tui/tests/flows.rs | 37 +++++++++++ src/tui/tests/widgets/content/list.rs | 70 ++++++++++++++------ src/tui/tests/widgets/content/update.rs | 2 + src/tui/tests/widgets/settings.rs | 56 ++++++++++++++++ src/tui/widgets/account.rs | 23 +++++-- src/tui/widgets/content/list.rs | 54 +-------------- src/tui/widgets/content/update.rs | 3 + src/tui/widgets/logs_viewer.rs | 2 + src/tui/widgets/popups/new_instance/state.rs | 22 ++++++ src/tui/widgets/screenshots_grid.rs | 3 + src/tui/widgets/settings.rs | 5 +- 14 files changed, 268 insertions(+), 93 deletions(-) diff --git a/src/tui/event.rs b/src/tui/event.rs index 26930c3..a0245bd 100644 --- a/src/tui/event.rs +++ b/src/tui/event.rs @@ -48,6 +48,16 @@ impl App { if let Some(state) = self.modpack_versions_state.as_mut() { state.drain_pending(); } + if self.content_update_popup.as_ref().is_some_and(|update| { + update.phase != widgets::content::update::Phase::Applying + && self + .instances_state + .selected_instance() + .map(|instance| instance.name.as_str()) + != Some(update.instance_name.as_str()) + }) { + self.content_update_popup = None; + } let content_update_completed = self.content_update_popup.as_mut().and_then(|update| { update.drain(); update.list.request_image_loads(&self.picker); @@ -700,15 +710,21 @@ impl App { let editor = std::env::var("EDITOR") .or_else(|_| std::env::var("VISUAL")) .unwrap_or_else(|_| default_editor.to_owned()); + let parts = editor_parts(&editor); + let Some((program, args)) = parts.split_first() else { + tracing::error!("Editor command is empty"); + return false; + }; - let is_tui_editor = editor_runs_in_terminal(&editor); + let is_tui_editor = editor_runs_in_terminal(program); if is_tui_editor { let _ = stdout().execute(DisableMouseCapture); let _ = stdout().execute(LeaveAlternateScreen); let _ = disable_raw_mode(); - let result = std::process::Command::new(&editor) + let result = std::process::Command::new(program) + .args(args) .arg(path) .stdin(std::process::Stdio::inherit()) .stdout(std::process::Stdio::inherit()) @@ -726,7 +742,8 @@ impl App { } true } else { - if let Err(e) = std::process::Command::new(&editor) + if let Err(e) = std::process::Command::new(program) + .args(args) .arg(path) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) @@ -1106,6 +1123,14 @@ fn editor_runs_in_terminal(editor: &str) -> bool { ) } +fn editor_parts(editor: &str) -> Vec<&str> { + if std::path::Path::new(editor).is_file() { + vec![editor] + } else { + editor.split_whitespace().collect() + } +} + #[cfg(test)] #[path = "tests/event.rs"] mod tests; diff --git a/src/tui/input.rs b/src/tui/input.rs index f14c32e..f8edec5 100644 --- a/src/tui/input.rs +++ b/src/tui/input.rs @@ -58,6 +58,17 @@ impl App { } pub(super) fn handle_key_event(&mut self, key_event: KeyEvent) -> color_eyre::Result<()> { + if self.content_update_popup.as_ref().is_some_and(|update| { + update.phase != widgets::content::update::Phase::Applying + && self + .instances_state + .selected_instance() + .map(|instance| instance.name.as_str()) + != Some(update.instance_name.as_str()) + }) { + self.content_update_popup = None; + return Ok(()); + } if self .content_update_popup .as_ref() @@ -206,7 +217,15 @@ impl App { .accounts .get(index) .map(|account| account.uuid.clone()); - self.account_state.store.remove(index); + if let Err(error) = self.account_state.store.remove(index) { + error_buffer::push_message( + tracing::Level::ERROR, + error.to_string(), + ); + self.focused = FocusedArea::Account; + confirm_popup::clear_pending(); + return Ok(()); + } if let Some(removed_uuid) = removed_uuid { for instance in &mut self.instances_state.instances { if instance.preferred_account.as_deref() @@ -679,6 +698,12 @@ impl App { } } + if self.focused == FocusedArea::Account + && widgets::account::handle_key(&key_event, &mut self.account_state) + { + return Ok(()); + } + if self.focused == FocusedArea::Account && let KeyCode::Char('d') = key_event.code && let Some(index) = self.account_state.list_state.selected @@ -692,12 +717,6 @@ impl App { return Ok(()); } - if self.focused == FocusedArea::Account - && widgets::account::handle_key(&key_event, &mut self.account_state) - { - return Ok(()); - } - if self.focused == FocusedArea::Settings { let editing_profile = matches!( &self.settings_state.add_mode, @@ -1484,8 +1503,12 @@ impl App { { return; } - let state = - widgets::content::update::State::checking(kind, target_world.clone(), source_entries); + let state = widgets::content::update::State::checking( + instance.name.clone(), + kind, + target_world.clone(), + source_entries, + ); let pending = state.pending.clone(); self.content_update_popup = Some(state); tokio::spawn(async move { @@ -1590,6 +1613,10 @@ impl App { let Some(state) = self.content_update_popup.as_mut() else { return; }; + if state.instance_name != instance.name { + self.content_update_popup = None; + return; + } let Some(plan) = state.plan.as_ref().map(|plan| plan.dependency_plan.clone()) else { return; }; diff --git a/src/tui/tests/event.rs b/src/tui/tests/event.rs index 3465d3b..cd0e76b 100644 --- a/src/tui/tests/event.rs +++ b/src/tui/tests/event.rs @@ -200,11 +200,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 +251,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 +363,7 @@ 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"), ["nvim", "-u", "NONE"]); } #[test] diff --git a/src/tui/tests/flows.rs b/src/tui/tests/flows.rs index a3560af..b524704 100644 --- a/src/tui/tests/flows.rs +++ b/src/tui/tests/flows.rs @@ -666,6 +666,43 @@ 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 settings_panel_routes_legacy_edit_keys_to_tui_popups() { let mut ui = UiHarness::new(); diff --git a/src/tui/tests/widgets/content/list.rs b/src/tui/tests/widgets/content/list.rs index 4711e06..78b55f4 100644 --- a/src/tui/tests/widgets/content/list.rs +++ b/src/tui/tests/widgets/content/list.rs @@ -967,7 +967,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 +1003,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] diff --git a/src/tui/tests/widgets/content/update.rs b/src/tui/tests/widgets/content/update.rs index 960c8b8..3d2b4f6 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")], @@ -101,6 +102,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")], diff --git a/src/tui/tests/widgets/settings.rs b/src/tui/tests/widgets/settings.rs index 519faed..58d1070 100644 --- a/src/tui/tests/widgets/settings.rs +++ b/src/tui/tests/widgets/settings.rs @@ -3,6 +3,62 @@ use super::*; +#[test] +fn narrow_settings_shows_the_selected_pane() { + let tmp = tempfile::tempdir().unwrap(); + let mut state = SettingsState::new(tmp.path().to_path_buf()); + 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(); + state.java_key = Some("test-java".to_owned()); + state.java_label = "jdk17".to_owned(); + 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 removing_selected_last_profile_clamps_selection() { let tmp = tempfile::tempdir().unwrap(); diff --git a/src/tui/widgets/account.rs b/src/tui/widgets/account.rs index f6ce5e2..a54bde7 100644 --- a/src/tui/widgets/account.rs +++ b/src/tui/widgets/account.rs @@ -66,7 +66,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); @@ -116,7 +121,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); } @@ -169,8 +179,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 } diff --git a/src/tui/widgets/content/list.rs b/src/tui/widgets/content/list.rs index fb1c96b..dc175fc 100644 --- a/src/tui/widgets/content/list.rs +++ b/src/tui/widgets/content/list.rs @@ -170,12 +170,6 @@ enum ContentStreamUpdate { }, } -struct CachedList { - entries: Vec, - selected: Option, - sort_metadata: HashMap, -} - struct FileSortMetadata { name: String, size: Option, @@ -283,7 +277,6 @@ pub struct ContentListState { display_metadata: HashMap, pub search: crate::tui::widgets::search::SearchState, filter_search: bool, - cache: HashMap, sort_metadata: RefCell>, filtered_cache: RefCell>, stream_rx: Option>, @@ -337,7 +330,6 @@ impl Default for ContentListState { display_metadata: HashMap::new(), search: crate::tui::widgets::search::SearchState::default(), filter_search: true, - cache: HashMap::new(), sort_metadata: RefCell::new(HashMap::new()), filtered_cache: RefCell::new(None), stream_rx: None, @@ -1303,6 +1295,7 @@ impl ContentListState { use std::sync::atomic::{AtomicBool, Ordering}; 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"); @@ -1678,8 +1671,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() @@ -1706,49 +1697,6 @@ impl ContentListState { self.pending_entry_images.clear(); self.pending_removals.clear(); - 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()), - }, - ); - } - - // 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; - } - let stream = self.start_stream(instance_name); let dir = content_dir.to_path_buf(); diff --git a/src/tui/widgets/content/update.rs b/src/tui/widgets/content/update.rs index e77ed45..b5702c6 100644 --- a/src/tui/widgets/content/update.rs +++ b/src/tui/widgets/content/update.rs @@ -30,6 +30,7 @@ pub enum Phase { } pub struct State { + pub instance_name: String, pub phase: Phase, pub plan: Option, pub snapshot: Option, @@ -44,11 +45,13 @@ pub struct State { 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, diff --git a/src/tui/widgets/logs_viewer.rs b/src/tui/widgets/logs_viewer.rs index 8d4b06b..acf5633 100644 --- a/src/tui/widgets/logs_viewer.rs +++ b/src/tui/widgets/logs_viewer.rs @@ -66,6 +66,7 @@ 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()); @@ -149,6 +150,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 { diff --git a/src/tui/widgets/popups/new_instance/state.rs b/src/tui/widgets/popups/new_instance/state.rs index ac37d4c..4d6a1a5 100644 --- a/src/tui/widgets/popups/new_instance/state.rs +++ b/src/tui/widgets/popups/new_instance/state.rs @@ -35,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>, @@ -49,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, @@ -64,7 +66,9 @@ 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> { @@ -381,12 +385,17 @@ pub(crate) fn ensure_versions_loaded(state: &mut WizardState) { } 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); } @@ -396,6 +405,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) => { @@ -416,11 +428,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); } @@ -430,6 +448,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/screenshots_grid.rs b/src/tui/widgets/screenshots_grid.rs index c4f6ddc..cbe2c5f 100644 --- a/src/tui/widgets/screenshots_grid.rs +++ b/src/tui/widgets/screenshots_grid.rs @@ -85,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(); @@ -217,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(); diff --git a/src/tui/widgets/settings.rs b/src/tui/widgets/settings.rs index 492e69f..0458e6e 100644 --- a/src/tui/widgets/settings.rs +++ b/src/tui/widgets/settings.rs @@ -252,7 +252,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 { From 4de886fcd0a51076ee8db697079325c37a81a61c Mon Sep 17 00:00:00 2001 From: objz Date: Thu, 1 Oct 2026 18:48:05 +0200 Subject: [PATCH 08/34] fix: select the displayed version in the instance wizard --- .../widgets/popups/new_instance/state.rs | 23 ++++++++---- src/tui/widgets/popups/new_instance/render.rs | 1 - src/tui/widgets/popups/new_instance/state.rs | 35 +++++++------------ 3 files changed, 29 insertions(+), 30 deletions(-) diff --git a/src/tui/tests/widgets/popups/new_instance/state.rs b/src/tui/tests/widgets/popups/new_instance/state.rs index 71e415e..3638f47 100644 --- a/src/tui/tests/widgets/popups/new_instance/state.rs +++ b/src/tui/tests/widgets/popups/new_instance/state.rs @@ -12,7 +12,7 @@ fn key(code: KeyCode) -> KeyEvent { } #[test] -fn vanilla_wizard_reaches_confirm_and_returns_parameters() { +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 +32,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 +75,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/widgets/popups/new_instance/render.rs b/src/tui/widgets/popups/new_instance/render.rs index ab5f2f7..f12f63a 100644 --- a/src/tui/widgets/popups/new_instance/render.rs +++ b/src/tui/widgets/popups/new_instance/render.rs @@ -178,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 4d6a1a5..9a69cfe 100644 --- a/src/tui/widgets/popups/new_instance/state.rs +++ b/src/tui/widgets/popups/new_instance/state.rs @@ -72,15 +72,7 @@ impl WizardState { } 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 { @@ -178,14 +170,14 @@ fn handle_version_key( 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 => { @@ -344,21 +336,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 { From 2114cdc72a14afa1af2873b405deff4ac9599d63 Mon Sep 17 00:00:00 2001 From: objz Date: Thu, 1 Oct 2026 18:48:37 +0200 Subject: [PATCH 09/34] refactor: share filesystem helpers and correct pack imports --- src/instance/config_sync.rs | 22 +-- src/instance/import/archive.rs | 92 +++++++++ src/instance/import/curseforge.rs | 56 +----- src/instance/import/mmc.rs | 9 +- src/instance/import/mod.rs | 54 +----- src/instance/import/mrpack.rs | 179 ++++-------------- src/instance/import/refresh.rs | 118 ++++++++++-- src/instance/tests/import/curseforge.rs | 3 + src/instance/tests/import/format_detection.rs | 17 +- src/instance/tests/import/mmc.rs | 26 +++ src/instance/tests/import/mrpack.rs | 88 ++++++++- src/layout_migration.rs | 27 +-- src/migrate.rs | 4 +- src/net/mod.rs | 2 +- src/storage.rs | 67 +------ src/storage/filesystem.rs | 66 +++++++ src/tests/layout_migration.rs | 38 ++++ src/tests/migrate.rs | 22 +++ src/tests/storage.rs | 12 ++ 19 files changed, 524 insertions(+), 378 deletions(-) create mode 100644 src/instance/import/archive.rs create mode 100644 src/storage/filesystem.rs diff --git a/src/instance/config_sync.rs b/src/instance/config_sync.rs index 996accc..e8755e3 100644 --- a/src/instance/config_sync.rs +++ b/src/instance/config_sync.rs @@ -436,7 +436,7 @@ fn mirror_options(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> { && (file_type.is_file() || file_type.is_symlink()) { if file_type.is_symlink() { - copy_link(&entry.path(), &staging.join(&name))?; + crate::storage::copy_symlink(&entry.path(), &staging.join(&name))?; } else { std::fs::copy(entry.path(), staging.join(&name))?; } @@ -446,7 +446,7 @@ fn mirror_options(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> { } for entry in std::fs::read_dir(&staging)? { let entry = entry?; - crate::storage::replace_file(&entry.path(), &dst.join(entry.file_name()))?; + std::fs::rename(entry.path(), dst.join(entry.file_name()))?; } remove_options(dst, &copied)?; Ok(()) @@ -506,29 +506,13 @@ fn copy_dir_contents(src: &Path, dst: &Path) -> Result<(), ConfigSyncError> { } else if file_type.is_file() { std::fs::copy(&source, &target)?; } else if file_type.is_symlink() { - copy_link(&source, &target)?; + crate::storage::copy_symlink(&source, &target)?; } } Ok(()) } -#[cfg(unix)] -fn copy_link(source: &Path, target: &Path) -> std::io::Result<()> { - std::os::unix::fs::symlink(std::fs::read_link(source)?, target) -} - -#[cfg(not(unix))] -fn copy_link(source: &Path, _target: &Path) -> std::io::Result<()> { - Err(std::io::Error::new( - std::io::ErrorKind::Unsupported, - format!( - "Cannot copy config symlink '{}' on this platform", - source.display() - ), - )) -} - #[cfg(test)] #[path = "tests/config_sync.rs"] mod tests; diff --git a/src/instance/import/archive.rs b/src/instance/import/archive.rs new file mode 100644 index 0000000..4f421bf --- /dev/null +++ b/src/instance/import/archive.rs @@ -0,0 +1,92 @@ +// SPDX-FileCopyrightText: 2026 Constantin Bauer +// SPDX-License-Identifier: GPL-3.0-only + +use std::io::Read; +use std::path::{Path, PathBuf}; + +const MAX_PACK_MANIFEST_BYTES: u64 = 8 * 1024 * 1024; + +pub(super) fn read_pack_manifest(reader: impl Read) -> Result, String> { + let mut bytes = Vec::new(); + reader + .take(MAX_PACK_MANIFEST_BYTES + 1) + .read_to_end(&mut bytes) + .map_err(|error| error.to_string())?; + if bytes.len() as u64 > MAX_PACK_MANIFEST_BYTES { + return Err("Pack manifest exceeds 8 MiB".to_owned()); + } + Ok(bytes) +} + +fn relative_path( + entry: &zip::read::ZipFile<'_, std::fs::File>, + root: &str, +) -> Result, String> { + let root = root.trim_matches('/'); + if root.is_empty() || !entry.name().starts_with(&format!("{root}/")) { + return Ok(None); + } + let enclosed = entry + .enclosed_name() + .ok_or_else(|| format!("Unsafe override path: {}", entry.name()))?; + let relative = enclosed + .strip_prefix(root) + .map_err(|_| format!("Invalid override path: {}", entry.name()))?; + Ok(Some(relative.to_owned())) +} + +pub(super) fn override_files(path: &Path, roots: &[&str]) -> Result, String> { + let file = std::fs::File::open(path).map_err(|error| error.to_string())?; + let mut archive = zip::ZipArchive::new(file).map_err(|error| error.to_string())?; + let mut files = Vec::new(); + for index in 0..archive.len() { + let entry = archive.by_index(index).map_err(|error| error.to_string())?; + if entry.is_dir() { + continue; + } + for root in roots { + if let Some(relative) = relative_path(&entry, root)? + && !relative.as_os_str().is_empty() + { + files.push(relative); + break; + } + } + } + Ok(files) +} + +pub(super) fn extract_overrides( + path: &Path, + destination: &Path, + roots: &[&str], +) -> Result<(), Box> { + let file = std::fs::File::open(path)?; + let mut archive = zip::ZipArchive::new(file)?; + // Later roots override earlier ones, independently of ZIP entry order. + for root in roots { + for index in 0..archive.len() { + let mut entry = archive.by_index(index)?; + let Some(relative) = relative_path(&entry, root)? else { + continue; + }; + let target = destination.join(relative); + if entry.is_dir() { + std::fs::create_dir_all(&target)?; + continue; + } + if let Some(parent) = target.parent() { + std::fs::create_dir_all(parent)?; + } + let mut file = std::fs::File::create(&target)?; + let size = std::io::copy(&mut entry, &mut file)?; + tracing::trace!( + "Extracted {} to {} ({} bytes)", + entry.name(), + target.display(), + size + ); + } + } + Ok(()) +} diff --git a/src/instance/import/curseforge.rs b/src/instance/import/curseforge.rs index 542dc88..29d1c50 100644 --- a/src/instance/import/curseforge.rs +++ b/src/instance/import/curseforge.rs @@ -1,9 +1,6 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// curseforge modpack archives: manifest.json references provider file ids, -// while the overrides directory contains configs and other bundled files. - use std::path::Path; use serde::Deserialize; @@ -97,7 +94,7 @@ fn loader(manifest: &Manifest) -> (ModLoader, Option) { pub fn build_summary(path: &Path) -> Result { let manifest = parse(path)?; let (loader, loader_version) = loader(&manifest); - let override_count = count_overrides(path, &manifest.overrides)?; + let override_count = super::override_files(path, &[&manifest.overrides])?.len(); Ok(ImportSummary { name: manifest.name, pack_version: manifest.version, @@ -131,15 +128,18 @@ async fn download_files( manifest: &Manifest, minecraft_dir: &Path, ) -> Result<(), Box> { - let api_key = - crate::net::curseforge::api_key().ok_or("CurseForge API key is not configured")?; - let client = crate::net::HttpClient::new(); let ids = manifest .files .iter() .filter(|file| file.required) .map(|file| file.file_id) .collect::>(); + if ids.is_empty() { + return Ok(()); + } + let api_key = + crate::net::curseforge::api_key().ok_or("CurseForge API key is not configured")?; + let client = crate::net::HttpClient::new(); let versions = crate::net::curseforge::fetch_file_versions(&client, api_key, &ids).await?; if versions.len() != ids.len() { return Err(format!( @@ -218,53 +218,13 @@ pub(super) async fn owned_files(path: &Path) -> Result, Ok(files) } -fn count_overrides(path: &Path, root: &str) -> Result { - let root = root.trim_matches('/'); - if root.is_empty() { - return Ok(0); - } - let file = std::fs::File::open(path).map_err(|error| error.to_string())?; - let archive = zip::ZipArchive::new(file).map_err(|error| error.to_string())?; - let prefix = format!("{root}/"); - Ok(archive - .file_names() - .filter(|name| name.starts_with(&prefix) && !name.ends_with('/')) - .count()) -} - fn extract_overrides( path: &Path, minecraft_dir: &Path, root: &str, ) -> Result<(), Box> { progress::set_action("Extracting overrides..."); - let file = std::fs::File::open(path)?; - let mut archive = zip::ZipArchive::new(file)?; - let root = root.trim_matches('/'); - if root.is_empty() { - return Ok(()); - } - for index in 0..archive.len() { - let mut entry = archive.by_index(index)?; - let enclosed = entry.enclosed_name().ok_or("Unsafe override path")?; - let Ok(relative) = enclosed.strip_prefix(root) else { - continue; - }; - if relative.as_os_str().is_empty() { - continue; - } - let destination = minecraft_dir.join(relative); - if entry.is_dir() { - std::fs::create_dir_all(destination)?; - continue; - } - if let Some(parent) = destination.parent() { - std::fs::create_dir_all(parent)?; - } - let mut destination = std::fs::File::create(destination)?; - std::io::copy(&mut entry, &mut destination)?; - } - Ok(()) + super::archive::extract_overrides(path, minecraft_dir, &[root]) } #[cfg(test)] diff --git a/src/instance/import/mmc.rs b/src/instance/import/mmc.rs index b531a20..02a5253 100644 --- a/src/instance/import/mmc.rs +++ b/src/instance/import/mmc.rs @@ -233,12 +233,9 @@ fn instance_name_from_cfg(path: &Path) -> Option { } fn find_archive_prefix(archive: &zip::ZipArchive) -> String { - for name in archive.file_names() { - if name.ends_with("mmc-pack.json") { - return name.strip_suffix("mmc-pack.json").unwrap_or("").to_string(); - } - } - String::new() + find_entry(archive, "mmc-pack.json") + .and_then(|name| name.strip_suffix("mmc-pack.json").map(str::to_owned)) + .unwrap_or_default() } // looks for a file at root or one level deep (some archives nest everything diff --git a/src/instance/import/mod.rs b/src/instance/import/mod.rs index 830b5c8..0fa02a3 100644 --- a/src/instance/import/mod.rs +++ b/src/instance/import/mod.rs @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only +mod archive; pub mod curseforge; pub mod mmc; pub mod mrpack; @@ -8,21 +9,7 @@ pub mod refresh; use std::path::{Path, PathBuf}; -const MAX_PACK_MANIFEST_BYTES: u64 = 8 * 1024 * 1024; - -fn read_pack_manifest(reader: impl std::io::Read) -> Result, String> { - use std::io::Read; - - let mut bytes = Vec::new(); - reader - .take(MAX_PACK_MANIFEST_BYTES + 1) - .read_to_end(&mut bytes) - .map_err(|error| error.to_string())?; - if bytes.len() as u64 > MAX_PACK_MANIFEST_BYTES { - return Err("Pack manifest exceeds 8 MiB".to_owned()); - } - Ok(bytes) -} +use archive::{override_files, read_pack_manifest}; use crate::instance::manager::InstanceManager; use crate::instance::models::ModLoader; @@ -152,7 +139,8 @@ pub fn unique_instance_name(base: &str, instances_dir: &Path) -> String { tracing::trace!("Import instance name '{}' is available", candidate); return candidate; } - for n in 2..100 { + let mut n = 2; + loop { let candidate = format!("{base} ({n})"); if !instances_dir.join(&candidate).exists() { tracing::debug!( @@ -162,12 +150,8 @@ pub fn unique_instance_name(base: &str, instances_dir: &Path) -> String { ); return candidate; } + n += 1; } - tracing::warn!( - "Import instance name '{}' had many collisions; using fallback suffix", - base - ); - format!("{base} (import)") } pub async fn execute_import( @@ -286,34 +270,6 @@ async fn owned_files(summary: &ImportSummary) -> Result, String> { } } -fn override_files(path: &Path, roots: &[&str]) -> Result, String> { - let file = std::fs::File::open(path).map_err(|error| error.to_string())?; - let mut archive = zip::ZipArchive::new(file).map_err(|error| error.to_string())?; - let mut files = Vec::new(); - for index in 0..archive.len() { - let entry = archive.by_index(index).map_err(|error| error.to_string())?; - if entry.is_dir() { - continue; - } - let Some(root) = roots - .iter() - .find(|root| entry.name().starts_with(&format!("{root}/"))) - else { - continue; - }; - let relative = entry - .enclosed_name() - .ok_or_else(|| format!("Unsafe override path: {}", entry.name()))? - .strip_prefix(root) - .map_err(|error| error.to_string())? - .to_owned(); - if !relative.as_os_str().is_empty() { - files.push(relative); - } - } - Ok(files) -} - fn cleanup_failed_import(manager: &InstanceManager, name: &str) { let instance_dir = manager.instances_dir.join(name); if let Err(error) = std::fs::remove_dir_all(&instance_dir) diff --git a/src/instance/import/mrpack.rs b/src/instance/import/mrpack.rs index f0c0c85..e2e39f1 100644 --- a/src/instance/import/mrpack.rs +++ b/src/instance/import/mrpack.rs @@ -35,11 +35,23 @@ pub struct MrpackFile { pub path: String, #[serde(default)] pub hashes: HashMap, + #[serde(default)] + pub env: HashMap, pub downloads: Vec, #[serde(rename = "fileSize")] pub file_size: u64, } +impl MrpackIndex { + fn client_files(&self) -> impl Iterator { + self.files.iter().filter(|file| { + file.env + .get("client") + .is_none_or(|support| support != "unsupported") + }) + } +} + pub fn parse_mrpack(path: &Path) -> Result { tracing::debug!("Parsing .mrpack manifest from {}", path.display()); let file = std::fs::File::open(path).map_err(|e| format!("Cannot open .mrpack: {e}"))?; @@ -50,6 +62,12 @@ pub fn parse_mrpack(path: &Path) -> Result { let raw = super::read_pack_manifest(entry)?; let index: MrpackIndex = serde_json::from_slice(&raw).map_err(|e| format!("Invalid manifest JSON: {e}"))?; + if index.format_version != 1 || index.game != "minecraft" { + return Err(format!( + "Unsupported .mrpack format {} for game '{}'", + index.format_version, index.game + )); + } tracing::debug!( "Parsed .mrpack '{}' version_id={} files={} deps={}", index.name, @@ -104,7 +122,7 @@ pub fn build_summary(path: &Path) -> Result { let (loader_opt, loader_version) = loader_from_dependencies(&index.dependencies); let loader = loader_opt.unwrap_or(ModLoader::Vanilla); - let override_count = count_overrides(path).unwrap_or(0); + let override_count = super::override_files(path, &["overrides", "client-overrides"])?.len(); tracing::trace!( ".mrpack summary: game_version={} loader={:?} loader_version={:?} overrides={}", game_version, @@ -119,7 +137,7 @@ pub fn build_summary(path: &Path) -> Result { game_version, loader, loader_version, - mod_count: index.files.len(), + mod_count: index.client_files().count(), override_count, format: PackFormat::Mrpack, archive_path: path.to_path_buf(), @@ -127,19 +145,6 @@ pub fn build_summary(path: &Path) -> Result { }) } -fn count_overrides(mrpack_path: &Path) -> Result { - let file = std::fs::File::open(mrpack_path).map_err(|e| e.to_string())?; - let archive = zip::ZipArchive::new(file).map_err(|e| e.to_string())?; - let count = archive - .file_names() - .filter(|name| { - (name.starts_with("overrides/") || name.starts_with("client-overrides/")) - && !name.ends_with('/') - }) - .count(); - Ok(count) -} - pub async fn execute_import( summary: &ImportSummary, manager: &InstanceManager, @@ -173,8 +178,6 @@ pub async fn execute_import( Ok(()) } -// downloads all mod files listed in the mrpack index, capped at 10 concurrent -// downloads to avoid getting rate-limited into oblivion async fn download_mod_files( index: &MrpackIndex, minecraft_dir: &Path, @@ -183,7 +186,7 @@ async fn download_mod_files( use std::sync::atomic::{AtomicUsize, Ordering}; let client = crate::net::HttpClient::new(); - let total = index.files.len(); + let total = index.client_files().count(); let completed = Arc::new(AtomicUsize::new(0)); tracing::debug!( "Downloading {} file(s) from .mrpack '{}' into {}", @@ -194,60 +197,14 @@ async fn download_mod_files( progress::set_action(format!("Downloading mods... 0/{total}")); - // bounded concurrency via manual JoinSet draining: seed with max_concurrent - // tasks, then spawn a new one each time one finishes let mut tasks = tokio::task::JoinSet::new(); - let max_concurrent = 10; - let mut file_iter = index.files.iter(); - for _ in 0..max_concurrent { - if let Some(file) = file_iter.next() { - let client = client.clone(); - let relative = safe_mrpack_path(&file.path)?; - let dest = minecraft_dir.join(relative); - let url = file.downloads.first().cloned().ok_or_else(|| { - crate::net::NetError::Parse(format!( - ".mrpack file '{}' has no download URL", - file.path - )) - })?; - let filename = file - .path - .rsplit('/') - .next() - .unwrap_or(&file.path) - .to_string(); - let hashes = file.hashes.clone(); - let file_size = file.file_size; - let completed = completed.clone(); - tasks.spawn(async move { - if let Some(parent) = dest.parent() - && let Err(error) = tokio::fs::create_dir_all(parent).await - { - return Err(crate::net::NetError::from(error)); - } - progress::set_sub_action(filename); - tracing::trace!("Downloading .mrpack file to {}", dest.display()); - crate::net::download_file(&client, &url, &dest, |_, _| {}).await?; - if !verify_mrpack_file(&dest, file_size, &hashes)? { - let _ = tokio::fs::remove_file(&dest).await; - return Err(crate::net::NetError::Parse(format!( - "Downloaded .mrpack file '{}' failed its size or hash verification", - dest.display() - ))); - } - let done = completed.fetch_add(1, Ordering::Relaxed) + 1; - progress::set_action(format!("Downloading mods... {done}/{total}")); - Ok::<(), crate::net::NetError>(()) - }); - } - } - - for file in file_iter { - if let Some(result) = tasks.join_next().await { - result - .map_err(|e| -> Box { Box::new(e) })? - .map_err(|e| -> Box { Box::new(e) })?; + for file in index.client_files() { + // Keep at most ten downloads in flight to avoid provider rate limits. + if tasks.len() == 10 + && let Some(result) = tasks.join_next().await + { + result??; } let client = client.clone(); let relative = safe_mrpack_path(&file.path)?; @@ -287,9 +244,7 @@ async fn download_mod_files( } while let Some(result) = tasks.join_next().await { - result - .map_err(|e| -> Box { Box::new(e) })? - .map_err(|e| -> Box { Box::new(e) })?; + result??; } Ok(()) @@ -297,11 +252,7 @@ async fn download_mod_files( fn safe_mrpack_path(path: &str) -> Result { let path = Path::new(path); - if path.as_os_str().is_empty() - || path - .components() - .any(|component| !matches!(component, std::path::Component::Normal(_))) - { + if !crate::storage::safe_relative_path(path) { return Err(crate::net::NetError::Parse(format!( "Unsafe .mrpack file path '{}'", path.display() @@ -311,9 +262,9 @@ fn safe_mrpack_path(path: &str) -> Result { } pub(super) fn owned_files(path: &Path) -> Result, String> { - let mut files: Vec<_> = parse_mrpack(path)? - .files - .into_iter() + let index = parse_mrpack(path)?; + let mut files: Vec<_> = index + .client_files() .map(|file| safe_mrpack_path(&file.path).map_err(|error| error.to_string())) .collect::>()?; files.extend(super::override_files( @@ -346,7 +297,7 @@ fn seed_content_manifest( paths: &InstancePaths, ) -> Result<(), Box> { let mut manifest = ContentManifest::default(); - for file in &index.files { + for file in index.client_files() { let relative_path = Path::new(&file.path); let Some(kind) = mrpack_content_kind(relative_path) else { continue; @@ -429,65 +380,11 @@ fn extract_overrides( progress::set_action("Extracting overrides...".to_string()); progress::set_sub_action(String::new()); - let file = std::fs::File::open(mrpack_path)?; - let mut archive = zip::ZipArchive::new(file)?; - let mut extracted = 0usize; - let mut dirs = 0usize; - - for i in 0..archive.len() { - let mut entry = archive.by_index(i)?; - let entry_name = entry.name().to_string(); - - let root = if entry_name.starts_with("overrides/") { - "overrides" - } else if entry_name.starts_with("client-overrides/") { - "client-overrides" - } else { - continue; - }; - let enclosed = entry.enclosed_name().ok_or_else(|| { - std::io::Error::new( - std::io::ErrorKind::InvalidData, - format!("Unsafe override path: {entry_name}"), - ) - })?; - let relative = enclosed.strip_prefix(root).map_err(|_| { - std::io::Error::new( - std::io::ErrorKind::InvalidData, - format!("Invalid override path: {entry_name}"), - ) - })?; - - if relative.as_os_str().is_empty() || entry_name.ends_with('/') { - let dir = minecraft_dir.join(relative); - std::fs::create_dir_all(dir)?; - dirs += 1; - continue; - } - - let dest = minecraft_dir.join(relative); - if let Some(parent) = dest.parent() { - std::fs::create_dir_all(parent)?; - } - - let mut destination = std::fs::File::create(&dest)?; - let size = std::io::copy(&mut entry, &mut destination)?; - tracing::trace!( - "Extracting .mrpack override {} to {} ({} bytes)", - entry_name, - dest.display(), - size - ); - extracted += 1; - } - - tracing::debug!( - "Extracted {} override files and {} directories from {}", - extracted, - dirs, - mrpack_path.display() - ); - Ok(()) + super::archive::extract_overrides( + mrpack_path, + minecraft_dir, + &["overrides", "client-overrides"], + ) } #[cfg(test)] diff --git a/src/instance/import/refresh.rs b/src/instance/import/refresh.rs index 12aa6ba..7eaa110 100644 --- a/src/instance/import/refresh.rs +++ b/src/instance/import/refresh.rs @@ -75,7 +75,12 @@ pub async fn prepare( .map_err(|error| error.to_string())?; let live = manager.instances_dir.join(&instance.name); let needed = directory_size(&live) - .saturating_add(target.files.iter().map(|file| file.size).sum::()) + .saturating_add( + target + .files + .iter() + .fold(0u64, |size, file| size.saturating_add(file.size)), + ) .saturating_add(64 * 1024 * 1024); let available = fs2::available_space(&manager.instances_dir).map_err(|e| e.to_string())?; if available < needed { @@ -156,6 +161,9 @@ pub fn apply( plan: RefreshPlan, replace_conflicts: &HashSet, ) -> Result { + if crate::instance::runtime::is_active(&plan.instance.name) { + return Err("Stop the instance before changing its modpack".to_owned()); + } let live = plan .stage_root .parent() @@ -188,7 +196,13 @@ pub fn apply( } std::fs::rename(&live, &backup).map_err(|error| error.to_string())?; if let Err(error) = std::fs::rename(&plan.staged_instance, &live) { - let _ = std::fs::rename(&backup, &live); + if let Err(rollback) = std::fs::rename(&backup, &live) { + return Err(format!( + "Could not activate the staged update: {error}; could not restore '{}' from '{}': {rollback}", + live.display(), + backup.display() + )); + } return Err(format!("Could not activate the staged update: {error}")); } if let Err(error) = std::fs::remove_dir_all(&backup) { @@ -284,7 +298,7 @@ fn preserve_refresh_state( let path = &record.relative_path; if !old_owned.contains(path) && !(new_owned.contains(path) && replace_conflicts.contains(path)) - && old.minecraft().join(path).exists() + && std::fs::symlink_metadata(old.minecraft().join(path)).is_ok() { new_manifest.upsert(record.clone()); } @@ -292,7 +306,7 @@ fn preserve_refresh_state( for path in new_owned { if !replace_conflicts.contains(path) && !old_owned.contains(path) - && old.minecraft().join(path).exists() + && std::fs::symlink_metadata(old.minecraft().join(path)).is_ok() && old_manifest.record(path).is_none() { new_manifest.remove(path); @@ -300,7 +314,15 @@ fn preserve_refresh_state( } new_manifest .save(&new.content_manifest()) - .map_err(|e| e.to_string()) + .map_err(|e| e.to_string())?; + let mut state = PackState::load(&new) + .ok_or_else(|| "The staged pack did not record its owned files".to_owned())?; + state.files.retain(|path| { + old_owned.contains(path) + || replace_conflicts.contains(path) + || std::fs::symlink_metadata(old.minecraft().join(path)).is_err() + }); + state.save(&new) } fn preserve_user_files( @@ -332,17 +354,7 @@ fn preserve_user_files( } std::fs::remove_file(&target).map_err(|error| error.to_string())?; } - #[cfg(unix)] - std::os::unix::fs::symlink( - std::fs::read_link(&path).map_err(|error| error.to_string())?, - &target, - ) - .map_err(|error| error.to_string())?; - #[cfg(not(unix))] - return Err(format!( - "Cannot preserve symbolic link '{}' on this platform", - path.display() - )); + crate::storage::copy_symlink(&path, &target).map_err(|error| error.to_string())?; } else if metadata.is_dir() { let target = destination.join(entry.file_name()); std::fs::create_dir_all(&target).map_err(|error| error.to_string())?; @@ -387,9 +399,13 @@ fn collect_files( } fn directory_size(path: &Path) -> u64 { - let mut size = 0; + let mut size = 0u64; let _ = collect_files(path, path, &mut |_, file| { - size += file.metadata().map(|metadata| metadata.len()).unwrap_or(0); + size = size.saturating_add( + std::fs::symlink_metadata(file) + .map(|metadata| metadata.len()) + .unwrap_or(0), + ); Ok(()) }); size @@ -409,6 +425,50 @@ mod tests { use crate::instance::content::manifest::{ContentFileRecord, ContentKind, FileFingerprint}; + #[test] + fn refresh_rechecks_whether_the_instance_started_after_preparation() { + let temp = tempfile::tempdir().unwrap(); + let name = "refresh-became-active"; + let stage_root = temp.path().join(".rmcl-refresh-test"); + let live = temp.path().join(name); + let staged_instance = stage_root.join(name); + std::fs::create_dir_all(live.join("minecraft")).unwrap(); + std::fs::create_dir_all(staged_instance.join("minecraft")).unwrap(); + let instance = serde_json::from_value(serde_json::json!({ + "name": name, "game_version": "1.21", "loader": "vanilla", + "loader_version": null, "created": "2026-01-01T00:00:00Z" + })) + .unwrap(); + let plan = RefreshPlan { + instance, + summary: ImportSummary { + name: name.to_owned(), + pack_version: "2".to_owned(), + game_version: "1.21".to_owned(), + loader: crate::instance::ModLoader::Vanilla, + loader_version: None, + mod_count: 0, + override_count: 0, + format: super::super::PackFormat::Mrpack, + archive_path: stage_root.join("pack.mrpack"), + source: None, + }, + current_version: "1".to_owned(), + target_version: "2".to_owned(), + conflicts: Vec::new(), + stage_root, + staged_instance, + old_owned: HashSet::new(), + new_owned: HashSet::new(), + }; + crate::instance::runtime::set_state(name, crate::instance::runtime::RunState::Running); + let result = apply(plan, &HashSet::new()); + crate::instance::runtime::remove(name); + + assert!(result.unwrap_err().contains("Stop the instance")); + assert!(live.join("minecraft").is_dir()); + } + fn record(path: &str) -> ContentFileRecord { ContentFileRecord { relative_path: path.into(), @@ -446,6 +506,20 @@ mod tests { let mut staged = ContentManifest::default(); staged.upsert(record("mods/pack.jar")); staged.save(&new.content_manifest()).unwrap(); + PackState { + source: ProviderProject { + provider: "modrinth".to_owned(), + project_id: "pack".to_owned(), + version_id: "2".to_owned(), + }, + files: vec![ + "mods/pack.jar".into(), + "mods/user.jar".into(), + "mods/replace.jar".into(), + ], + } + .save(&new) + .unwrap(); preserve_refresh_state( old.root(), @@ -453,6 +527,7 @@ mod tests { &HashSet::new(), &HashSet::from([ PathBuf::from("mods/pack.jar"), + PathBuf::from("mods/user.jar"), PathBuf::from("mods/replace.jar"), ]), &HashSet::from([PathBuf::from("mods/replace.jar")]), @@ -467,6 +542,13 @@ mod tests { assert!(manifest.record(Path::new("mods/user.jar")).is_some()); assert!(manifest.record(Path::new("mods/pack.jar")).is_some()); assert!(manifest.record(Path::new("mods/replace.jar")).is_none()); + assert_eq!( + PackState::load(&new).unwrap().files, + vec![ + PathBuf::from("mods/pack.jar"), + PathBuf::from("mods/replace.jar") + ] + ); } #[cfg(unix)] diff --git a/src/instance/tests/import/curseforge.rs b/src/instance/tests/import/curseforge.rs index 6804df6..3845496 100644 --- a/src/instance/tests/import/curseforge.rs +++ b/src/instance/tests/import/curseforge.rs @@ -87,4 +87,7 @@ async fn override_only_pack_tracks_files_under_its_configured_root() { owned_files(&path).await.unwrap(), vec![std::path::PathBuf::from("config/pack.toml")] ); + download_files(&parse(&path).unwrap(), &temp.path().join("minecraft")) + .await + .unwrap(); } diff --git a/src/instance/tests/import/format_detection.rs b/src/instance/tests/import/format_detection.rs index c2d7ad3..6354be3 100644 --- a/src/instance/tests/import/format_detection.rs +++ b/src/instance/tests/import/format_detection.rs @@ -36,8 +36,6 @@ fn detect_format_recognises_mrpack() { #[test] fn detect_format_recognises_mmc_flat() { - // mmc-pack.json at the zip root - the flat layout that some mmc - // archives use. let tmp = tempfile::tempdir().unwrap(); let path = make_pack_zip(tmp.path(), "pack.zip", &[("mmc-pack.json", b"{}")]); assert_eq!(detect_format(&path), Ok(PackFormat::Mmc)); @@ -45,8 +43,6 @@ fn detect_format_recognises_mmc_flat() { #[test] fn detect_format_recognises_mmc_nested() { - // mmc-pack.json one directory deep - the more common layout where - // the archive wraps everything in a named directory. let tmp = tempfile::tempdir().unwrap(); let path = make_pack_zip(tmp.path(), "pack.zip", &[("MyPack/mmc-pack.json", b"{}")]); assert_eq!(detect_format(&path), Ok(PackFormat::Mmc)); @@ -54,8 +50,6 @@ fn detect_format_recognises_mmc_nested() { #[test] fn detect_format_prefers_mrpack_when_both_markers_present() { - // a zip with both markers should resolve to Mrpack since the - // detector checks modrinth.index.json first. let tmp = tempfile::tempdir().unwrap(); let path = make_pack_zip( tmp.path(), @@ -121,6 +115,17 @@ fn unique_name_multiple_collisions() { assert_eq!(name, "TestPack (4)"); } +#[test] +fn unique_name_keeps_searching_after_ninety_nine_collisions() { + let tmp = tempfile::tempdir().unwrap(); + std::fs::create_dir(tmp.path().join("Pack")).unwrap(); + for suffix in 2..=100 { + std::fs::create_dir(tmp.path().join(format!("Pack ({suffix})"))).unwrap(); + } + std::fs::create_dir(tmp.path().join("Pack (import)")).unwrap(); + assert_eq!(unique_instance_name("Pack", tmp.path()), "Pack (101)"); +} + #[test] fn parse_project_url() { assert_eq!( diff --git a/src/instance/tests/import/mmc.rs b/src/instance/tests/import/mmc.rs index ebe206a..6460c62 100644 --- a/src/instance/tests/import/mmc.rs +++ b/src/instance/tests/import/mmc.rs @@ -3,6 +3,32 @@ use super::*; +#[test] +fn minecraft_prefix_comes_from_the_manifest_used_for_import() { + use std::io::Write; + + let tmp = tempfile::tempdir().unwrap(); + let archive_path = tmp.path().join("pack.zip"); + let mut zip = zip::ZipWriter::new(std::fs::File::create(&archive_path).unwrap()); + let options = zip::write::SimpleFileOptions::default(); + zip.start_file("Decoy/mmc-pack.json", options).unwrap(); + zip.write_all(b"{}").unwrap(); + zip.start_file("mmc-pack.json", options).unwrap(); + zip.write_all(br#"{"components":[{"uid":"net.minecraft","version":"1.21"}]}"#) + .unwrap(); + zip.start_file(".minecraft/options.txt", options).unwrap(); + zip.write_all(b"correct").unwrap(); + zip.finish().unwrap(); + + let destination = tmp.path().join("minecraft"); + assert_eq!(build_summary(&archive_path).unwrap().override_count, 1); + extract_mmc_archive(&archive_path, &destination).unwrap(); + assert_eq!( + std::fs::read(destination.join("options.txt")).unwrap(), + b"correct" + ); +} + #[test] fn parse_mmc_pack_json() { let json = r#"{ diff --git a/src/instance/tests/import/mrpack.rs b/src/instance/tests/import/mrpack.rs index 9932ce2..e0553ff 100644 --- a/src/instance/tests/import/mrpack.rs +++ b/src/instance/tests/import/mrpack.rs @@ -108,6 +108,7 @@ fn extraction_merges_both_override_roots() { &[ ("overrides/config/test.toml", b"config"), ("client-overrides/options.txt", b"options"), + ("overrides/options.txt", b"generic"), ], ); let minecraft = tmp.path().join("minecraft"); @@ -124,6 +125,63 @@ fn extraction_merges_both_override_roots() { ); } +#[test] +fn server_only_files_are_excluded_from_client_imports() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("server-only.mrpack"); + let mut zip = zip::ZipWriter::new(std::fs::File::create(&path).unwrap()); + zip.start_file( + "modrinth.index.json", + zip::write::SimpleFileOptions::default(), + ) + .unwrap(); + zip.write_all(br#"{ + "formatVersion": 1, "game": "minecraft", "versionId": "1", "name": "Pack", + "dependencies": {"minecraft": "1.21"}, + "files": [ + {"path": "mods/server.jar", "env": {"client": "unsupported"}, "downloads": [], "fileSize": 0}, + {"path": "mods/client.jar", "downloads": [], "fileSize": 0} + ] + }"#).unwrap(); + zip.finish().unwrap(); + + assert_eq!(build_summary(&path).unwrap().mod_count, 1); + assert_eq!( + owned_files(&path).unwrap(), + vec![PathBuf::from("mods/client.jar")] + ); +} + +#[test] +fn unsupported_pack_format_or_game_is_rejected() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("unsupported.mrpack"); + for (from, to) in [ + ("\"formatVersion\": 1", "\"formatVersion\": 2"), + ("\"game\": \"minecraft\"", "\"game\": \"other\""), + ] { + let mut zip = zip::ZipWriter::new(std::fs::File::create(&path).unwrap()); + zip.start_file( + "modrinth.index.json", + zip::write::SimpleFileOptions::default(), + ) + .unwrap(); + zip.write_all( + std::str::from_utf8(INDEX) + .unwrap() + .replace(from, to) + .as_bytes(), + ) + .unwrap(); + zip.finish().unwrap(); + assert!( + parse_mrpack(&path) + .unwrap_err() + .contains("Unsupported .mrpack") + ); + } +} + #[test] fn extraction_rejects_path_traversal() { let tmp = tempfile::tempdir().unwrap(); @@ -150,7 +208,7 @@ fn mod_files_download_to_their_manifest_paths() { Mock::given(method("GET")) .and(path("/first.jar")) .respond_with(ResponseTemplate::new(200).set_body_bytes(b"first".to_vec())) - .expect(1) + .expect(11) .mount(&server) .await; Mock::given(method("GET")) @@ -159,7 +217,7 @@ fn mod_files_download_to_their_manifest_paths() { .expect(1) .mount(&server) .await; - let index = MrpackIndex { + let mut index = MrpackIndex { format_version: 1, game: "minecraft".to_owned(), version_id: "1".to_owned(), @@ -168,18 +226,27 @@ fn mod_files_download_to_their_manifest_paths() { files: vec![ MrpackFile { path: "mods/first.jar".to_owned(), + env: Default::default(), hashes: Default::default(), downloads: vec![format!("{}/first.jar", server.uri())], file_size: 5, }, MrpackFile { path: "resourcepacks/second.jar".to_owned(), + env: Default::default(), hashes: Default::default(), downloads: vec![format!("{}/second.jar", server.uri())], file_size: 6, }, ], }; + index.files.extend((2..12).map(|number| MrpackFile { + path: format!("mods/extra-{number}.jar"), + env: Default::default(), + hashes: Default::default(), + downloads: vec![format!("{}/first.jar", server.uri())], + file_size: 5, + })); let tmp = tempfile::tempdir().unwrap(); download_mod_files(&index, tmp.path()).await.unwrap(); @@ -192,6 +259,12 @@ fn mod_files_download_to_their_manifest_paths() { std::fs::read(tmp.path().join("resourcepacks/second.jar")).unwrap(), b"second" ); + for number in 2..12 { + assert_eq!( + std::fs::read(tmp.path().join(format!("mods/extra-{number}.jar"))).unwrap(), + b"first" + ); + } crate::feedback::progress::clear(); }); } @@ -206,7 +279,7 @@ fn mod_file_without_a_download_url_fails_without_creating_a_file() { .build() .unwrap(); runtime.block_on(async { - let index = MrpackIndex { + let mut index = MrpackIndex { format_version: 1, game: "minecraft".to_owned(), version_id: "1".to_owned(), @@ -214,6 +287,7 @@ fn mod_file_without_a_download_url_fails_without_creating_a_file() { dependencies: Default::default(), files: vec![MrpackFile { path: "mods/missing.jar".to_owned(), + env: Default::default(), hashes: Default::default(), downloads: Vec::new(), file_size: 0, @@ -223,6 +297,11 @@ fn mod_file_without_a_download_url_fails_without_creating_a_file() { assert!(download_mod_files(&index, tmp.path()).await.is_err()); assert!(!tmp.path().join("mods/missing.jar").exists()); + index.files[0] + .env + .insert("client".to_owned(), "unsupported".to_owned()); + download_mod_files(&index, tmp.path()).await.unwrap(); + assert!(!tmp.path().join("mods/missing.jar").exists()); crate::feedback::progress::clear(); }); } @@ -247,6 +326,7 @@ fn mod_file_rejects_paths_outside_the_instance() { dependencies: Default::default(), files: vec![MrpackFile { path: "../escape.jar".to_owned(), + env: Default::default(), hashes: Default::default(), downloads: vec!["https://example.invalid/escape.jar".to_owned()], file_size: 1, @@ -286,6 +366,7 @@ fn mod_file_removes_downloads_with_invalid_metadata() { dependencies: Default::default(), files: vec![MrpackFile { path: "mods/corrupt.jar".to_owned(), + env: Default::default(), hashes: Default::default(), downloads: vec![format!("{}/corrupt.jar", server.uri())], file_size: 1, @@ -320,6 +401,7 @@ fn import_seeds_exact_modrinth_content_identity() { dependencies: Default::default(), files: vec![MrpackFile { path: relative_path.to_string_lossy().into_owned(), + env: Default::default(), hashes: HashMap::from([("sha512".to_owned(), sha512)]), downloads: vec![ "https://cdn.modrinth.com/data/project/versions/version/example.zip".to_owned(), diff --git a/src/layout_migration.rs b/src/layout_migration.rs index 05b9e1a..2027de7 100644 --- a/src/layout_migration.rs +++ b/src/layout_migration.rs @@ -136,6 +136,7 @@ pub fn run( let metadata = MetadataPaths::new(meta_dir); if marker_version(&metadata.layout_marker()) == Some(LAYOUT_VERSION) && metadata.cache_rebuild_pending().exists() + && !metadata.migration_journal().exists() && !has_legacy_instances(instances_dir) && !has_legacy_shared_data(meta_dir) { @@ -150,7 +151,7 @@ pub fn run( fs::create_dir_all(metadata.state())?; fs::write(metadata.cache_rebuild_pending(), LAYOUT_VERSION.to_string())?; - let mut journal = load_or_create_journal(instances_dir, &metadata)?; + let mut journal = load_or_create_journal(&metadata)?; let instances = instance_directories(instances_dir)?; let total = instances.len() as u64 + 8; let mut current = journal.completed.len() as u64; @@ -554,7 +555,7 @@ fn copy_dir_recursive_with_progress( let file_type = entry.file_type()?; let target = destination.join(entry.file_name()); if file_type.is_symlink() { - copy_symlink(&entry.path(), &target)?; + crate::storage::copy_symlink(&entry.path(), &target)?; } else if file_type.is_dir() { copy_dir_recursive_with_progress(&entry.path(), &target, report)?; } else { @@ -566,25 +567,7 @@ fn copy_dir_recursive_with_progress( Ok(()) } -#[cfg(unix)] -fn copy_symlink(source: &Path, destination: &Path) -> io::Result<()> { - std::os::unix::fs::symlink(fs::read_link(source)?, destination) -} - -#[cfg(windows)] -fn copy_symlink(source: &Path, destination: &Path) -> io::Result<()> { - let target = fs::read_link(source)?; - if source.is_dir() { - std::os::windows::fs::symlink_dir(target, destination) - } else { - std::os::windows::fs::symlink_file(target, destination) - } -} - -fn load_or_create_journal( - _instances_dir: &Path, - metadata: &MetadataPaths, -) -> Result { +fn load_or_create_journal(metadata: &MetadataPaths) -> Result { let legacy_journal = metadata.state().join("migration-v2.json"); if metadata.migration_journal().exists() { return Ok(serde_json::from_slice(&fs::read( @@ -597,7 +580,7 @@ fn load_or_create_journal( fs::remove_file(legacy_journal)?; return Ok(journal); } - let timestamp = chrono::Local::now().format("%Y%m%d-%H%M%S").to_string(); + let timestamp = chrono::Local::now().format("%Y%m%d-%H%M%S-%f").to_string(); let journal = MigrationJournal { version: LAYOUT_VERSION, backup_dir: metadata.backups().join(format!("backup-{timestamp}")), diff --git a/src/migrate.rs b/src/migrate.rs index 8098e5d..fc85b77 100644 --- a/src/migrate.rs +++ b/src/migrate.rs @@ -93,7 +93,9 @@ fn copy_dir_recursive(src: &Path, dst: &Path) -> io::Result<()> { let entry = entry?; let ty = entry.file_type()?; let dst_path = dst.join(entry.file_name()); - if ty.is_dir() { + if ty.is_symlink() { + crate::storage::copy_symlink(&entry.path(), &dst_path)?; + } else if ty.is_dir() { copy_dir_recursive(&entry.path(), &dst_path)?; } else { fs::copy(entry.path(), &dst_path)?; diff --git a/src/net/mod.rs b/src/net/mod.rs index 67ba14b..4f4546b 100644 --- a/src/net/mod.rs +++ b/src/net/mod.rs @@ -333,7 +333,7 @@ async fn download_file_once( } file.flush().await?; drop(file); - crate::storage::replace_file(&temporary, dest)?; + tokio::fs::rename(&temporary, dest).await?; Ok(()) } .await; diff --git a/src/storage.rs b/src/storage.rs index a9e7b64..83c67f2 100644 --- a/src/storage.rs +++ b/src/storage.rs @@ -3,9 +3,10 @@ use std::io; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; -static TEMP_FILE_ID: AtomicU64 = AtomicU64::new(1); +mod filesystem; +pub(crate) use filesystem::copy_symlink; +pub use filesystem::{write_atomic, write_atomic_private}; pub const MINECRAFT_DIR_NAME: &str = "minecraft"; pub const INSTANCE_STATE_DIR_NAME: &str = "rmcl"; @@ -161,68 +162,6 @@ pub fn safe_relative_path(path: &Path) -> bool { && components.all(|part| matches!(part, std::path::Component::Normal(_))) } -pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { - write_atomic_with_mode(path, bytes, false) -} - -pub fn write_atomic_private(path: &Path, bytes: &[u8]) -> io::Result<()> { - write_atomic_with_mode(path, bytes, true) -} - -fn write_atomic_with_mode(path: &Path, bytes: &[u8], private: bool) -> io::Result<()> { - let parent = path - .parent() - .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no parent"))?; - std::fs::create_dir_all(parent)?; - let id = TEMP_FILE_ID.fetch_add(1, Ordering::Relaxed); - let name = path - .file_name() - .and_then(|name| name.to_str()) - .unwrap_or("data"); - let temporary = parent.join(format!(".{name}.{}.{}.tmp", std::process::id(), id)); - let result = (|| { - use std::io::Write; - - let mut options = std::fs::OpenOptions::new(); - options.create_new(true).write(true); - #[cfg(unix)] - if private { - use std::os::unix::fs::OpenOptionsExt; - options.mode(0o600); - } - #[cfg(not(unix))] - let _ = private; - let mut file = options.open(&temporary)?; - file.write_all(bytes)?; - file.sync_all()?; - replace_file(&temporary, path) - })(); - if result.is_err() { - let _ = std::fs::remove_file(&temporary); - } - result -} - -#[cfg(not(windows))] -pub(crate) fn replace_file(source: &Path, destination: &Path) -> io::Result<()> { - std::fs::rename(source, destination) -} - -#[cfg(windows)] -pub(crate) fn replace_file(source: &Path, destination: &Path) -> io::Result<()> { - if !destination.exists() { - return std::fs::rename(source, destination); - } - let id = TEMP_FILE_ID.fetch_add(1, Ordering::Relaxed); - let backup = destination.with_extension(format!("rmcl-replaced-{id}")); - std::fs::rename(destination, &backup)?; - if let Err(error) = std::fs::rename(source, destination) { - let _ = std::fs::rename(&backup, destination); - return Err(error); - } - std::fs::remove_file(backup) -} - #[cfg(test)] #[path = "tests/storage.rs"] mod tests; diff --git a/src/storage/filesystem.rs b/src/storage/filesystem.rs new file mode 100644 index 0000000..80ad07d --- /dev/null +++ b/src/storage/filesystem.rs @@ -0,0 +1,66 @@ +// SPDX-FileCopyrightText: 2026 Constantin Bauer +// SPDX-License-Identifier: GPL-3.0-only + +use std::io; +use std::path::Path; +use std::sync::atomic::{AtomicU64, Ordering}; + +static TEMP_FILE_ID: AtomicU64 = AtomicU64::new(1); + +pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { + write_atomic_with_mode(path, bytes, false) +} + +pub fn write_atomic_private(path: &Path, bytes: &[u8]) -> io::Result<()> { + write_atomic_with_mode(path, bytes, true) +} + +fn write_atomic_with_mode(path: &Path, bytes: &[u8], private: bool) -> io::Result<()> { + let parent = path + .parent() + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no parent"))?; + std::fs::create_dir_all(parent)?; + let id = TEMP_FILE_ID.fetch_add(1, Ordering::Relaxed); + let name = path + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or("data"); + let temporary = parent.join(format!(".{name}.{}.{}.tmp", std::process::id(), id)); + let result = (|| { + use std::io::Write; + + let mut options = std::fs::OpenOptions::new(); + options.create_new(true).write(true); + #[cfg(unix)] + if private { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + #[cfg(not(unix))] + let _ = private; + let mut file = options.open(&temporary)?; + file.write_all(bytes)?; + file.sync_all()?; + drop(file); + std::fs::rename(&temporary, path) + })(); + if result.is_err() { + let _ = std::fs::remove_file(&temporary); + } + result +} + +#[cfg(unix)] +pub(crate) fn copy_symlink(source: &Path, destination: &Path) -> io::Result<()> { + std::os::unix::fs::symlink(std::fs::read_link(source)?, destination) +} + +#[cfg(windows)] +pub(crate) fn copy_symlink(source: &Path, destination: &Path) -> io::Result<()> { + let target = std::fs::read_link(source)?; + if source.is_dir() { + std::os::windows::fs::symlink_dir(target, destination) + } else { + std::os::windows::fs::symlink_file(target, destination) + } +} diff --git a/src/tests/layout_migration.rs b/src/tests/layout_migration.rs index 44e0a96..1de38cc 100644 --- a/src/tests/layout_migration.rs +++ b/src/tests/layout_migration.rs @@ -49,6 +49,44 @@ fn migrated_layout_detects_newly_copied_shared_data() { ); } +#[test] +fn incomplete_migration_is_not_skipped_after_legacy_directories_were_renamed() { + let temp = tempfile::tempdir().unwrap(); + let instances = temp.path().join("instances"); + let meta = temp.path().join("meta"); + let config = temp.path().join("config.toml"); + let state = instances.join("Copied/.rmcl"); + fs::create_dir_all(state.join("config-sync/local-config")).unwrap(); + fs::create_dir_all(state.join("content/config")).unwrap(); + fs::write(state.join("config-sync/local-config/options.txt"), b"old").unwrap(); + fs::write(state.join("content/config/options.txt"), b"current").unwrap(); + initialize_new_layout(&meta).unwrap(); + + assert!(run(&instances, &meta, &config, |_| {}).is_err()); + assert!(!state.exists()); + assert!(MetadataPaths::new(&meta).migration_journal().exists()); + assert!(run(&instances, &meta, &config, |_| {}).is_err()); + assert_eq!( + fs::read(instances.join("Copied/rmcl/content/config/options.txt")).unwrap(), + b"current" + ); +} + +#[test] +fn repeated_migrations_create_separate_backups() { + let temp = tempfile::tempdir().unwrap(); + let instances = temp.path().join("instances"); + let meta = temp.path().join("meta"); + let config = temp.path().join("config.toml"); + fs::create_dir_all(instances.join("First/.minecraft")).unwrap(); + let first = run(&instances, &meta, &config, |_| {}).unwrap(); + fs::create_dir_all(instances.join("Second/.minecraft")).unwrap(); + let second = run(&instances, &meta, &config, |_| {}).unwrap(); + + assert_ne!(first, second); + assert!(second.join("instances/Second/.minecraft").is_dir()); +} + #[test] fn migration_backs_up_and_renames_instance_directories() { let temp = tempfile::tempdir().unwrap(); diff --git a/src/tests/migrate.rs b/src/tests/migrate.rs index a09c481..1294a38 100644 --- a/src/tests/migrate.rs +++ b/src/tests/migrate.rs @@ -123,3 +123,25 @@ fn copy_dir_recursive_copies_nested_tree() { b"inner" ); } + +#[cfg(unix)] +#[test] +fn cross_device_copy_preserves_links_without_following_directory_cycles() { + let tmp = tempfile::tempdir().unwrap(); + let source = tmp.path().join("old"); + let destination = tmp.path().join("new"); + fs::create_dir(&source).unwrap(); + fs::write(source.join("data.txt"), b"data").unwrap(); + std::os::unix::fs::symlink("data.txt", source.join("linked.txt")).unwrap(); + std::os::unix::fs::symlink(".", source.join("cycle")).unwrap(); + + copy_dir_recursive(&source, &destination).unwrap(); + assert_eq!( + fs::read_link(destination.join("linked.txt")).unwrap(), + Path::new("data.txt") + ); + assert_eq!( + fs::read_link(destination.join("cycle")).unwrap(), + Path::new(".") + ); +} diff --git a/src/tests/storage.rs b/src/tests/storage.rs index 9d06657..f8f751e 100644 --- a/src/tests/storage.rs +++ b/src/tests/storage.rs @@ -68,3 +68,15 @@ fn atomic_write_replaces_existing_file() { write_atomic(&path, b"new").unwrap(); assert_eq!(std::fs::read(path).unwrap(), b"new"); } + +#[test] +fn failed_atomic_replacement_keeps_the_destination_and_removes_staging() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("state.json"); + std::fs::create_dir(&path).unwrap(); + std::fs::write(path.join("keep"), b"old").unwrap(); + + assert!(write_atomic(&path, b"new").is_err()); + assert_eq!(std::fs::read(path.join("keep")).unwrap(), b"old"); + assert_eq!(std::fs::read_dir(temp.path()).unwrap().count(), 1); +} From 500d72a473eaa92c2f8fbdc5a111367ee5e79de5 Mon Sep 17 00:00:00 2001 From: objz Date: Thu, 1 Oct 2026 22:07:15 +0200 Subject: [PATCH 10/34] style: remove unused installer and asset narration --- assets/icon.svg | 1 - pkg/wix/main.wxs | 72 ------------------------------------------------ 2 files changed, 73 deletions(-) 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(); @@ -140,12 +132,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/tests/event.rs b/src/tui/tests/event.rs index cd0e76b..56c0e3c 100644 --- a/src/tui/tests/event.rs +++ b/src/tui/tests/event.rs @@ -4,6 +4,555 @@ use super::*; use crate::tui::tests::harness::UiHarness; +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() { + 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(); + config.ui.error_auto_dismiss_ms += 1; + let timeout = config.ui.error_auto_dismiss_ms; + 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 + ); + + 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(); @@ -363,7 +912,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"), ["nvim", "-u", "NONE"]); + 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 b524704..61949c1 100644 --- a/src/tui/tests/flows.rs +++ b/src/tui/tests/flows.rs @@ -7,7 +7,7 @@ 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(); @@ -1164,6 +1233,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')); @@ -1249,6 +1319,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(), @@ -1267,11 +1342,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(), }, @@ -1293,6 +1364,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..88b6406 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, @@ -109,6 +112,7 @@ impl UiHarness { throbber_tick: 0, error_effects: HashMap::new(), pending_editor: None, + edited_config_watches: Vec::new(), reconciliation_for: None, content_manifest: None, content_update_snapshot: None, @@ -164,15 +168,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 +193,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/content/discovery.rs b/src/tui/tests/widgets/content/discovery.rs index 6d811a5..69558c5 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; @@ -1332,6 +1344,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 +1402,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(), diff --git a/src/tui/tests/widgets/content/list.rs b/src/tui/tests/widgets/content/list.rs index 78b55f4..c3b1d6e 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, 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/logs_viewer.rs b/src/tui/tests/widgets/logs_viewer.rs index 179c39a..e227dea 100644 --- a/src/tui/tests/widgets/logs_viewer.rs +++ b/src/tui/tests/widgets/logs_viewer.rs @@ -48,3 +48,58 @@ 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 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)); +} 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/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/state.rs b/src/tui/tests/widgets/popups/new_instance/state.rs index 3638f47..42d73f3 100644 --- a/src/tui/tests/widgets/popups/new_instance/state.rs +++ b/src/tui/tests/widgets/popups/new_instance/state.rs @@ -11,6 +11,61 @@ fn key(code: KeyCode) -> KeyEvent { KeyEvent::new(code, KeyModifiers::NONE) } +#[test] +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()); diff --git a/src/tui/tests/widgets/search.rs b/src/tui/tests/widgets/search.rs index a6e328a..77774f3 100644 --- a/src/tui/tests/widgets/search.rs +++ b/src/tui/tests/widgets/search.rs @@ -53,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 58d1070..2972bba 100644 --- a/src/tui/tests/widgets/settings.rs +++ b/src/tui/tests/widgets/settings.rs @@ -6,13 +6,21 @@ use super::*; #[test] fn narrow_settings_shows_the_selected_pane() { 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")); 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(); - state.java_key = Some("test-java".to_owned()); + let environment = crate::instance::java::merge_environment( + &SETTINGS.read().defaults.environment, + &instance.environment, + ); + state.java_key = Some(java_path_key( + "test-java", + &state.instances_dir.join("Test/minecraft"), + &environment, + )); state.java_label = "jdk17".to_owned(); let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(35, 8)).unwrap(); @@ -62,7 +70,7 @@ fn narrow_settings_shows_the_selected_pane() { #[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); @@ -77,7 +85,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!( @@ -85,3 +93,45 @@ fn info_pane_does_not_bind_desktop_toggle() { SettingsAction::None )); } + +#[cfg(unix)] +#[test] +fn instance_java_labels_use_their_cwd_and_environment_and_discard_previous_results() { + 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\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 first = instance("first", "21"); + wait_for_label(&mut state, &first, "jdk21"); + let old_pending = state.pending_java.clone(); + let second = instance("second", "25"); + state.update_for_instance(Some(&second)); + *old_pending.lock().unwrap() = Some("stale label".to_owned()); + wait_for_label(&mut state, &second, "jdk25"); +} diff --git a/src/tui/widgets/content/discovery.rs b/src/tui/widgets/content/discovery.rs index 7308867..3326070 100644 --- a/src/tui/widgets/content/discovery.rs +++ b/src/tui/widgets/content/discovery.rs @@ -1364,11 +1364,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; } @@ -2645,6 +2642,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()) diff --git a/src/tui/widgets/content/list.rs b/src/tui/widgets/content/list.rs index dc175fc..888e624 100644 --- a/src/tui/widgets/content/list.rs +++ b/src/tui/widgets/content/list.rs @@ -578,7 +578,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(); @@ -875,8 +875,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; @@ -1808,8 +1806,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; @@ -2694,9 +2690,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, diff --git a/src/tui/widgets/content/tabs.rs b/src/tui/widgets/content/tabs.rs index 6e49e07..6c099bf 100644 --- a/src/tui/widgets/content/tabs.rs +++ b/src/tui/widgets/content/tabs.rs @@ -597,7 +597,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 @@ -643,8 +642,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( diff --git a/src/tui/widgets/logs_viewer.rs b/src/tui/widgets/logs_viewer.rs index acf5633..571d4f2 100644 --- a/src/tui/widgets/logs_viewer.rs +++ b/src/tui/widgets/logs_viewer.rs @@ -76,6 +76,7 @@ impl LogsState { 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(); @@ -99,33 +100,38 @@ 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; } pub fn try_rescan(&mut self) { @@ -448,7 +454,6 @@ 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 { @@ -468,7 +473,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) { @@ -558,15 +563,9 @@ fn render_list(frame: &mut Frame, area: Rect, state: &mut LogsState, is_focused: ); } -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); + let is_live = state.is_live_selected(); let all_lines: Vec = if is_live { let name = state.loaded_for.as_deref().unwrap_or(""); 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() { diff --git a/src/tui/widgets/popups/global_settings.rs b/src/tui/widgets/popups/global_settings.rs index 3dcb2c8..4a14c86 100644 --- a/src/tui/widgets/popups/global_settings.rs +++ b/src/tui/widgets/popups/global_settings.rs @@ -14,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}, @@ -22,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, }; @@ -96,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, @@ -238,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), @@ -563,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, @@ -579,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(); @@ -586,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; @@ -617,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) { @@ -687,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) { @@ -1318,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(); @@ -1550,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/state.rs b/src/tui/widgets/popups/import_modpack/state.rs index a49167a..921a1c3 100644 --- a/src/tui/widgets/popups/import_modpack/state.rs +++ b/src/tui/widgets/popups/import_modpack/state.rs @@ -120,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(); diff --git a/src/tui/widgets/popups/instance_settings.rs b/src/tui/widgets/popups/instance_settings.rs index 249dad8..f18e476 100644 --- a/src/tui/widgets/popups/instance_settings.rs +++ b/src/tui/widgets/popups/instance_settings.rs @@ -16,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, @@ -30,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, @@ -92,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, @@ -111,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, ) } @@ -121,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 { @@ -158,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, @@ -405,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(); } @@ -770,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; @@ -937,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() => { @@ -964,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 { @@ -1106,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)> { @@ -1740,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(), @@ -2231,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] @@ -2296,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/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/state.rs b/src/tui/widgets/popups/new_instance/state.rs index 9a69cfe..c2255dd 100644 --- a/src/tui/widgets/popups/new_instance/state.rs +++ b/src/tui/widgets/popups/new_instance/state.rs @@ -116,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, diff --git a/src/tui/widgets/popups/settings_controls.rs b/src/tui/widgets/popups/settings_controls.rs index 921e33a..92b04b2 100644 --- a/src/tui/widgets/popups/settings_controls.rs +++ b/src/tui/widgets/popups/settings_controls.rs @@ -2,7 +2,7 @@ // SPDX-License-Identifier: GPL-3.0-only use std::{ - collections::{BTreeMap, BTreeSet}, + collections::BTreeMap, path::{Path, PathBuf}, sync::{ Arc, Mutex, @@ -21,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}, }, @@ -204,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)] @@ -225,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, @@ -298,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), @@ -315,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; } } @@ -342,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); } } @@ -363,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}"); } @@ -737,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; @@ -995,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)? { @@ -1118,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)); @@ -1147,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> { @@ -1303,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() { @@ -1387,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()), @@ -1401,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()); @@ -1483,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())); @@ -1495,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"]); @@ -1538,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"] ); } @@ -1560,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/search.rs b/src/tui/widgets/search.rs index 4b54685..3f93e7e 100644 --- a/src/tui/widgets/search.rs +++ b/src/tui/widgets/search.rs @@ -57,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 { diff --git a/src/tui/widgets/settings.rs b/src/tui/widgets/settings.rs index 0458e6e..2e3baa8 100644 --- a/src/tui/widgets/settings.rs +++ b/src/tui/widgets/settings.rs @@ -44,14 +44,16 @@ 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, + pending_java: std::sync::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() @@ -62,10 +64,12 @@ 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(), + pending_java: Default::default(), }; state.select_active(); state @@ -116,15 +120,53 @@ impl SettingsState { self.select_active(); } - let java_key = instance.map(java_path_key); + let context = instance.map(|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, + ); + (java, cwd, environment) + }); + let java_key = context + .as_ref() + .map(|(java, cwd, environment)| java_path_key(java, cwd, environment)); 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.pending_java = Default::default(); + self.java_label = "unknown".to_owned(); + if let Some((java, cwd, environment)) = context { + let pending = self.pending_java.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(); + }); + } self.java_key = java_key; } + if let Some(label) = self + .pending_java + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take() + { + self.java_label = label; + } } } @@ -137,38 +179,25 @@ 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 { + format!( + "{java}:{}", + crate::instance::java::probe_context_key(cwd, environment) + ) } -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)); @@ -445,15 +474,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 { From 7ead3706a296084696bb11152941532df790bb04 Mon Sep 17 00:00:00 2001 From: objz Date: Thu, 1 Oct 2026 23:48:06 +0200 Subject: [PATCH 21/34] fix(ci): scope async-trait lint compatibility to generated traits --- src/instance/content/provider.rs | 4 ++++ src/instance/loader/mod.rs | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/src/instance/content/provider.rs b/src/instance/content/provider.rs index cb0efba..35e9fc3 100644 --- a/src/instance/content/provider.rs +++ b/src/instance/content/provider.rs @@ -61,6 +61,10 @@ pub struct ResolvedFile { pub project: ProviderProject, } +#[allow( + clippy::double_must_use, + reason = "async_trait adds #[must_use] to generated futures" +)] #[async_trait] pub trait ContentProvider: Send + Sync { fn id(&self) -> &'static str; diff --git a/src/instance/loader/mod.rs b/src/instance/loader/mod.rs index 5c17800..38ce2e1 100644 --- a/src/instance/loader/mod.rs +++ b/src/instance/loader/mod.rs @@ -42,6 +42,10 @@ pub struct GameVersion { pub stable: bool, } +#[allow( + clippy::double_must_use, + reason = "async_trait adds #[must_use] to generated futures" +)] #[async_trait] pub trait ModLoaderInstaller: Send + Sync { fn loader_type(&self) -> ModLoader; From 8998139934a9520dcd34ab3b4bf015d10b078081 Mon Sep 17 00:00:00 2001 From: objz Date: Fri, 2 Oct 2026 00:02:56 +0200 Subject: [PATCH 22/34] test: make native runner fixtures use platform paths and literal arguments --- src/instance/tests/config_sync.rs | 2 +- src/instance/tests/loader/installers.rs | 7 +++++-- src/launch_profile/tests/templates.rs | 11 ++++++++++- src/tui/tests/widgets/settings.rs | 5 ++++- 4 files changed, 20 insertions(+), 5 deletions(-) diff --git a/src/instance/tests/config_sync.rs b/src/instance/tests/config_sync.rs index aecb07f..fec7853 100644 --- a/src/instance/tests/config_sync.rs +++ b/src/instance/tests/config_sync.rs @@ -1258,7 +1258,7 @@ fn dangling_payload_links_remain_internal_but_non_payload_referents_stay_anchore ); assert_eq!( std::fs::read_link(replay.join("optionsexternal.txt")).unwrap(), - source.join("custom.txt") + source.canonicalize().unwrap().join("custom.txt") ); assert_eq!( std::fs::read(replay.join("optionsdirectory.txt")).unwrap(), diff --git a/src/instance/tests/loader/installers.rs b/src/instance/tests/loader/installers.rs index cc042bd..a514e96 100644 --- a/src/instance/tests/loader/installers.rs +++ b/src/instance/tests/loader/installers.rs @@ -186,7 +186,7 @@ fn recording_java(temp: &Path) -> String { "installer java.sh" }); #[cfg(windows)] - std::fs::write(&path, "@echo off\r\n(echo %~1\r\necho %~2\r\necho %~3\r\necho %~4\r\n)>installer-args.txt\r\necho %CD%>installer-cwd.txt\r\n(echo %INSTALLER_CONTEXT%\r\necho %INSTALLER_GLOBAL%\r\n)>installer-env.txt\r\n").unwrap(); + std::fs::write(&path, "@echo off\r\n(echo %~1\r\necho %~2\r\necho %~3\r\necho(%~4\r\n)>installer-args.txt\r\necho %CD%>installer-cwd.txt\r\n(echo %INSTALLER_CONTEXT%\r\necho %INSTALLER_GLOBAL%\r\n)>installer-env.txt\r\n").unwrap(); #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; @@ -249,7 +249,10 @@ async fn installers_use_merged_environment_and_minecraft_cwd(#[case] neoforge: b if neoforge { assert_eq!(args[3], minecraft.to_string_lossy()); } else { - assert!(args[3..].iter().all(|arg| arg.trim().is_empty())); + assert!( + args[3..].iter().all(|arg| arg.trim().is_empty()), + "{args:?}" + ); } let cwd = std::fs::read_to_string(minecraft.join("installer-cwd.txt")).unwrap(); assert_eq!( diff --git a/src/launch_profile/tests/templates.rs b/src/launch_profile/tests/templates.rs index 54811f5..34dce37 100644 --- a/src/launch_profile/tests/templates.rs +++ b/src/launch_profile/tests/templates.rs @@ -137,5 +137,14 @@ fn legacy_164_arguments_resolve_session_and_virtual_assets() { ); assert!(!args.contains("${")); assert!(args.contains("--session token:token:00000000000000000000000000000000")); - assert!(args.contains(&fixture.assets.join("virtual/legacy").display().to_string())); + assert!( + args.contains( + &fixture + .assets + .join("virtual") + .join("legacy") + .display() + .to_string() + ) + ); } diff --git a/src/tui/tests/widgets/settings.rs b/src/tui/tests/widgets/settings.rs index 2972bba..1e14c69 100644 --- a/src/tui/tests/widgets/settings.rs +++ b/src/tui/tests/widgets/settings.rs @@ -18,7 +18,10 @@ fn narrow_settings_shows_the_selected_pane() { ); state.java_key = Some(java_path_key( "test-java", - &state.instances_dir.join("Test/minecraft"), + &state + .instances_dir + .join("Test") + .join(crate::storage::MINECRAFT_DIR_NAME), &environment, )); state.java_label = "jdk17".to_owned(); From 3479a05e63cf39bf0e4e1494079e84f45b6ec388 Mon Sep 17 00:00:00 2001 From: objz Date: Fri, 2 Oct 2026 00:18:53 +0200 Subject: [PATCH 23/34] test: observe partial downloads through file contents on Windows --- tests/net_retry.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tests/net_retry.rs b/tests/net_retry.rs index 645c763..31ba676 100644 --- a/tests/net_retry.rs +++ b/tests/net_retry.rs @@ -234,7 +234,11 @@ async fn cancelled_downloads_preserve_the_destination_and_remove_all_staging_fil loop { if std::fs::read_dir(temp.path()).unwrap().any(|entry| { let entry = entry.unwrap(); - entry.path() != destination && entry.metadata().unwrap().len() == 1 + // 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; } From 7cbfe9cd0d035ad9ebad0a5838ca272f8441ebf6 Mon Sep 17 00:00:00 2001 From: objz Date: Fri, 2 Oct 2026 00:38:10 +0200 Subject: [PATCH 24/34] fix(instance): release locks explicitly across all instance operations --- src/instance/content/manifest.rs | 12 ++---------- src/instance/runtime.rs | 16 ++++++++++++++-- src/instance/tests/content/manifest.rs | 3 +-- src/instance/tests/runtime.rs | 14 ++++++++++++++ 4 files changed, 31 insertions(+), 14 deletions(-) diff --git a/src/instance/content/manifest.rs b/src/instance/content/manifest.rs index 41f7715..24ae03b 100644 --- a/src/instance/content/manifest.rs +++ b/src/instance/content/manifest.rs @@ -14,7 +14,7 @@ const MANIFEST_VERSION: u32 = 1; pub(crate) struct ContentLock { file: File, - instance_lock: Option, + _instance_lock: Option, path: PathBuf, } @@ -69,7 +69,7 @@ impl ContentLock { } Ok(Self { file, - instance_lock, + _instance_lock: instance_lock, path: path.to_owned(), }) } @@ -105,14 +105,6 @@ impl Drop for ContentLock { self.path.display() ); } - if let Some(file) = &self.instance_lock - && let Err(error) = file.unlock() - { - tracing::warn!( - "Could not release instance lock for '{}': {error}", - self.path.display() - ); - } } } diff --git a/src/instance/runtime.rs b/src/instance/runtime.rs index 605fdb9..29058df 100644 --- a/src/instance/runtime.rs +++ b/src/instance/runtime.rs @@ -111,10 +111,22 @@ pub fn cleanup_kill_sender(name: &str) { } } +pub(crate) struct InstanceLock(std::fs::File); + +impl Drop for InstanceLock { + fn drop(&mut self) { + // A concurrent fork can retain a descriptor until exec; closing our copy + // alone would leave the instance locked during that interval. + if let Err(error) = self.0.unlock() { + tracing::warn!("Could not release instance lock: {error}"); + } + } +} + pub(crate) fn lock_instance( root: &std::path::Path, name: &str, -) -> Result { +) -> Result { crate::instance::manager::validate_name(name)?; let locks = root.join(".rmcl-locks"); std::fs::create_dir_all(&locks)?; @@ -125,7 +137,7 @@ pub(crate) fn lock_instance( .write(true) .open(locks.join(format!("{name}.lock")))?; match file.try_lock() { - Ok(()) => Ok(file), + Ok(()) => Ok(InstanceLock(file)), Err(std::fs::TryLockError::WouldBlock) => Err( crate::instance::manager::InstanceError::InstanceRunning(name.to_owned()), ), diff --git a/src/instance/tests/content/manifest.rs b/src/instance/tests/content/manifest.rs index 9341888..d58305d 100644 --- a/src/instance/tests/content/manifest.rs +++ b/src/instance/tests/content/manifest.rs @@ -22,12 +22,11 @@ fn content_lock_excludes_independent_handles_until_drop() { } #[test] -fn dropping_guard_releases_locks_with_duplicated_handles() { +fn dropping_guard_releases_the_content_lock_with_a_duplicated_handle() { let temp = tempfile::tempdir().unwrap(); let path = temp.path().join("instance/rmcl/content/manifest.json"); let lock = ContentLock::acquire(&path).unwrap(); let _manifest_handle = lock.file.try_clone().unwrap(); - let _instance_handle = lock.instance_lock.as_ref().unwrap().try_clone().unwrap(); drop(lock); ContentLock::acquire(&path).unwrap(); } diff --git a/src/instance/tests/runtime.rs b/src/instance/tests/runtime.rs index 09a393c..7fc709b 100644 --- a/src/instance/tests/runtime.rs +++ b/src/instance/tests/runtime.rs @@ -3,6 +3,20 @@ use super::*; +#[test] +fn dropping_an_instance_lock_releases_it_even_with_a_duplicated_descriptor() { + let temp = tempfile::tempdir().unwrap(); + let lock = lock_instance(temp.path(), "duplicated").unwrap(); + let duplicate = lock.0.try_clone().unwrap(); + drop(lock); + let next = lock_instance(temp.path(), "duplicated"); + drop(duplicate); + assert!( + next.is_ok(), + "A duplicate descriptor retained the released instance lock" + ); +} + #[test] fn set_and_get_state() { set_state("run_test_1", RunState::Starting); From f5068d09d2735e4e8dbce48e54affd16bca830e3 Mon Sep 17 00:00:00 2001 From: objz Date: Fri, 2 Oct 2026 00:39:19 +0200 Subject: [PATCH 25/34] fix(tui): restore session content caches and stream prioritized update checks --- src/instance/content/reconcile.rs | 50 ++-- src/instance/content/updates.rs | 305 ++++++++++++--------- src/instance/tests/content/dependencies.rs | 163 +++++++++++ src/instance/tests/content/reconcile.rs | 92 ++++++- src/tui/app.rs | 81 ++++-- src/tui/event.rs | 157 +++++++---- src/tui/input.rs | 50 +++- src/tui/render.rs | 3 + src/tui/tests/event.rs | 172 ++++++++++++ src/tui/tests/harness.rs | 3 + src/tui/widgets/content/list.rs | 17 +- 11 files changed, 842 insertions(+), 251 deletions(-) diff --git a/src/instance/content/reconcile.rs b/src/instance/content/reconcile.rs index 2611029..36717e5 100644 --- a/src/instance/content/reconcile.rs +++ b/src/instance/content/reconcile.rs @@ -174,26 +174,30 @@ async fn reconcile(job: ReconcileJob, task: &ProgressTask) -> ReconcileResult { match inventory { Ok(Ok((mut inventory, manifest_path))) => { - let registry = ProviderRegistry::configured(client); - task.set_action(format!("Identifying content for {instance_name}")); - task.set_sub_action(format!("{} file(s) need matching", inventory.queries.len())); - if !inventory.queries.is_empty() { - task.set_progress(0, inventory.queries.len() as u64); - } - let resolution_result = - resolve_queries(®istry, &inventory.queries, &mut inventory.manifest).await; - if !inventory.queries.is_empty() { - task.set_progress( - inventory.queries.len() as u64, - inventory.queries.len() as u64, - ); - } + let resolution_result = if inventory.queries.is_empty() { + Ok(()) + } else { + let registry = ProviderRegistry::configured(client); + task.set_action(format!("Identifying content for {instance_name}")); + resolve_queries( + ®istry, + &inventory.queries, + &mut inventory.manifest, + &task.handle(), + ) + .await + }; + task.set_action(format!("Saving content index for {instance_name}")); + task.set_sub_action("Validating content files"); + task.set_progress(0, inventory.manifest.files.len() as u64); + let save_progress = task.handle(); let saved = tokio::task::spawn_blocking(move || { save_reconciled_manifest( &manifest_path, &minecraft_dir, inventory.manifest, &inventory.previous, + &save_progress, ) }) .await @@ -235,6 +239,7 @@ fn save_reconciled_manifest( minecraft_dir: &Path, reconciled: ContentManifest, previous: &ContentManifest, + task: &impl InventoryProgress, ) -> Result { ContentManifest::update(manifest_path, |current| { for record in current.files.clone() { @@ -247,7 +252,11 @@ fn save_reconciled_manifest( Err(error) => return Err(error.into()), } } - for mut record in reconciled.files { + let total = reconciled.files.len() as u64; + task.set_progress(0, total); + for (index, mut record) in reconciled.files.into_iter().enumerate() { + task.set_sub_action(record.relative_path.to_string_lossy().as_ref()); + task.set_progress(index as u64, total); let path = minecraft_dir.join(&record.relative_path); relative_path(minecraft_dir, &path)?; if current.record(&record.relative_path) != previous.record(&record.relative_path) { @@ -289,6 +298,7 @@ fn save_reconciled_manifest( current.upsert(record); } } + task.set_progress(total, total); Ok(current.clone()) }) } @@ -496,6 +506,7 @@ async fn resolve_queries( registry: &ProviderRegistry, queries: &[FingerprintQuery], manifest: &mut ContentManifest, + task: &impl InventoryProgress, ) -> Result<(), crate::net::NetError> { if queries.is_empty() { return Ok(()); @@ -503,8 +514,14 @@ async fn resolve_queries( let mut matches: HashMap> = HashMap::new(); let mut checked = Vec::new(); let mut last_error = None; - for provider in registry.providers() { + let total = (queries.len() * registry.providers().len()) as u64; + task.set_progress(0, total); + for (index, provider) in registry.providers().iter().enumerate() { let provider_id = provider.id(); + task.set_sub_action(&format!( + "{} file(s) need matching ({provider_id})", + queries.len() + )); match tokio::time::timeout( std::time::Duration::from_secs(10), provider.resolve_files(queries), @@ -533,6 +550,7 @@ async fn resolve_queries( last_error = Some(format!("{provider_id} content matching timed out")); } } + task.set_progress(((index + 1) * queries.len()) as u64, total); } if checked.is_empty() { return Err(crate::net::NetError::TaskFailed(last_error.unwrap_or_else( diff --git a/src/instance/content/updates.rs b/src/instance/content/updates.rs index 56bb1ef..e49a2df 100644 --- a/src/instance/content/updates.rs +++ b/src/instance/content/updates.rs @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only +use std::collections::HashMap; use std::sync::{Arc, LazyLock, Mutex}; use serde::{Deserialize, Serialize}; @@ -109,17 +110,6 @@ impl UpdateSnapshot { >= RECHECK_AFTER_SECONDS } - /// Keeps known updates for entries whose check failed this round so a flaky - /// network or a rate limited provider does not drop labels that were correct. - fn carry_over(&mut self, previous: &Self) { - for failure in &self.failures { - if let Some(update) = previous.update_for(&failure.installed) { - self.updates.push(update.clone()); - } - } - sort_updates(&mut self.updates); - } - pub fn update_for(&self, installed: &ProviderProject) -> Option<&AvailableUpdate> { self.updates.iter().find(|update| { update.installed.provider == installed.provider @@ -129,31 +119,75 @@ impl UpdateSnapshot { } } -pub fn spawn(instance: InstanceConfig, manifest: ContentManifest, path: std::path::PathBuf) { +pub fn spawn( + instance: InstanceConfig, + manifest: ContentManifest, + path: std::path::PathBuf, + priority: Vec, +) { tokio::spawn(async move { let previous = UpdateSnapshot::load(&path).filter(|previous| previous.applies_to(&instance)); - let mut snapshot = scan(&instance, &manifest).await; - if let Some(previous) = previous { - snapshot.carry_over(&previous); - } + let registry = Arc::new(super::provider::ProviderRegistry::configured( + crate::net::HttpClient::new(), + )); + let snapshot = scan_with_registry( + &instance, + &manifest, + &priority, + registry, + previous.as_ref(), + |snapshot| publish_snapshot(&instance, snapshot.clone()), + ) + .await; if let Ok(bytes) = serde_json::to_vec_pretty(&snapshot) && let Err(error) = crate::storage::write_atomic(&path, &bytes) { tracing::debug!("Could not cache content update snapshot: {error}"); } - if let Ok(mut pending) = PENDING_UPDATE_SNAPSHOTS.lock() { - pending.push(PendingUpdateSnapshot { - instance_name: instance.name, - instance_created: instance.created, - snapshot, - }); - crate::feedback::request_redraw(); - } + publish_snapshot(&instance, snapshot); }); } +fn publish_snapshot(instance: &InstanceConfig, snapshot: UpdateSnapshot) { + if let Ok(mut pending) = PENDING_UPDATE_SNAPSHOTS.lock() { + pending.retain(|pending| { + pending.instance_name != instance.name + || pending.instance_created != instance.created + || pending.snapshot.game_version != snapshot.game_version + || pending.snapshot.loader != snapshot.loader + }); + pending.push(PendingUpdateSnapshot { + instance_name: instance.name.clone(), + instance_created: instance.created, + snapshot, + }); + crate::feedback::request_redraw(); + } +} + pub async fn scan(instance: &InstanceConfig, manifest: &ContentManifest) -> UpdateSnapshot { + scan_with_registry( + instance, + manifest, + &[], + Arc::new(super::provider::ProviderRegistry::configured( + crate::net::HttpClient::new(), + )), + None, + |_| {}, + ) + .await +} + +pub(super) async fn scan_with_registry( + instance: &InstanceConfig, + manifest: &ContentManifest, + priority: &[ProviderProject], + registry: Arc, + previous: Option<&UpdateSnapshot>, + mut publish: impl FnMut(&UpdateSnapshot), +) -> UpdateSnapshot { let mut projects = manifest .files .iter() @@ -176,91 +210,128 @@ pub async fn scan(instance: &InstanceConfig, manifest: &ContentManifest) -> Upda && left.0.project_id == right.0.project_id && left.0.version_id == right.0.version_id }); - let inventory = projects + let inventory = resolved_inventory(manifest); + let priority = priority .iter() - .map(|(project, _)| project.clone()) - .collect(); - - let slots = Arc::new(tokio::sync::Semaphore::new(8)); - let registry = Arc::new( - crate::instance::content::provider::ProviderRegistry::configured( - crate::net::HttpClient::new(), - ), - ); - let mut tasks = tokio::task::JoinSet::new(); - for (installed, kind) in projects { - let slots = slots.clone(); - let registry = registry.clone(); - let game_version = instance.game_version.clone(); - let loader = instance.loader; - tasks.spawn(async move { - let result = async { - let _permit = slots - .acquire_owned() - .await - .map_err(|error| error.to_string())?; - let provider = registry.get(&installed.provider).ok_or_else(|| { - format!("{} content provider is unavailable", installed.provider) - })?; - let versions = provider - .compatible_versions(&installed.project_id, kind, &game_version, loader) - .await - .map_err(|error| error.to_string())?; - let Some(newest) = crate::instance::content::provider::newest_version(&versions) - else { - return Ok(None); - }; - // a modpack pins files that are often not tagged for the exact - // game version of the instance, so the installed version can be - // missing from the compatible list. asking the provider for it - // directly is the only way to tell "up to date" from "unknown". - let current = match versions + .enumerate() + .rev() + .map(|(index, project)| { + ( + (&project.provider, &project.project_id, &project.version_id), + index, + ) + }) + .collect::>(); + projects.sort_by_key(|(project, _)| { + priority + .get(&(&project.provider, &project.project_id, &project.version_id)) + .copied() + .unwrap_or(usize::MAX) + }); + let mut snapshot = UpdateSnapshot { + game_version: instance.game_version.clone(), + loader: instance.loader, + inventory, + checked_at: 0, + updates: previous + .into_iter() + .flat_map(|previous| previous.updates.iter()) + .filter(|update| { + projects .iter() - .find(|version| version.id == installed.version_id) - { - Some(current) => current.clone(), - None => provider - .version(&installed.version_id) - .await - .map_err(|error| error.to_string())?, - }; - let target = crate::instance::content::provider::is_newer(newest, ¤t) - .then(|| newest.clone()); - Ok::<_, String>(target.map(|target| (Some(current), target))) - } - .await; - (installed, kind, result) - }); + .any(|(installed, _)| installed == &update.installed) + }) + .cloned() + .collect(), + failures: Vec::new(), + }; + if projects.is_empty() { + snapshot.checked_at = chrono::Utc::now().timestamp(); + return snapshot; } - - let mut updates = Vec::new(); - let mut failures = Vec::new(); - while let Some(result) = tasks.join_next().await { + let total = projects.len() as u64; + let progress = crate::feedback::progress::ProgressTask::start(format!( + "Checking content updates for {}", + instance.name + )); + progress.set_progress(0, total); + let mut completed = 0; + let mut projects = projects.into_iter(); + let mut tasks = tokio::task::JoinSet::new(); + loop { + while tasks.len() < 8 { + let Some((installed, kind)) = projects.next() else { + break; + }; + let registry = registry.clone(); + let game_version = instance.game_version.clone(); + let loader = instance.loader; + tasks.spawn(async move { + let result = async { + let provider = registry.get(&installed.provider).ok_or_else(|| { + format!("{} content provider is unavailable", installed.provider) + })?; + let versions = provider + .compatible_versions(&installed.project_id, kind, &game_version, loader) + .await + .map_err(|error| error.to_string())?; + let Some(newest) = + crate::instance::content::provider::newest_version(&versions) + else { + return Ok(None); + }; + // Packs can pin versions omitted from the compatible list. + let current = match versions + .iter() + .find(|version| version.id == installed.version_id) + { + Some(current) => current.clone(), + None => provider + .version(&installed.version_id) + .await + .map_err(|error| error.to_string())?, + }; + let target = + super::provider::is_newer(newest, ¤t).then(|| newest.clone()); + Ok::<_, String>(target.map(|target| (Some(current), target))) + } + .await; + (installed, kind, result) + }); + } + let Some(result) = tasks.join_next().await else { + break; + }; + if let Ok((installed, _, Ok(_))) = &result { + snapshot + .updates + .retain(|update| &update.installed != installed); + } match result { - Ok((installed, kind, Ok(Some((current, target))))) => updates.push(AvailableUpdate { - installed, - current, - target, - kind, - }), + Ok((installed, kind, Ok(Some((current, target))))) => { + snapshot.updates.push(AvailableUpdate { + installed, + current, + target, + kind, + }) + } Ok((_, _, Ok(None))) => {} - Ok((installed, kind, Err(reason))) => failures.push(UpdateCheckFailure { + Ok((installed, kind, Err(reason))) => snapshot.failures.push(UpdateCheckFailure { installed, kind, reason, }), Err(error) => tracing::debug!("Content update task failed: {error}"), } + completed += 1; + progress.set_sub_action(format!("{completed}/{total} item(s) checked")); + progress.set_progress(completed, total); + publish(&snapshot); } - sort_updates(&mut updates); - UpdateSnapshot { - game_version: instance.game_version.clone(), - loader: instance.loader, - inventory, - checked_at: chrono::Utc::now().timestamp(), - updates, - failures, - } + sort_updates(&mut snapshot.updates); + snapshot.checked_at = chrono::Utc::now().timestamp(); + snapshot } fn sort_updates(updates: &mut [AvailableUpdate]) { @@ -542,46 +613,6 @@ mod tests { assert!(expired.is_stale(&manifest)); } - #[test] - fn failed_checks_keep_the_previously_known_update() { - let installed = ProviderProject { - provider: "modrinth".to_owned(), - project_id: "project".to_owned(), - version_id: "old".to_owned(), - }; - let previous = UpdateSnapshot { - game_version: "1.21.1".to_owned(), - loader: ModLoader::Fabric, - inventory: vec![installed.clone()], - checked_at: 0, - updates: vec![AvailableUpdate { - installed: installed.clone(), - current: Some(version("old")), - target: version("new"), - kind: ContentKind::Mod, - }], - failures: Vec::new(), - }; - let mut offline = UpdateSnapshot { - updates: Vec::new(), - failures: vec![UpdateCheckFailure { - installed: installed.clone(), - kind: ContentKind::Mod, - reason: "request timed out".to_owned(), - }], - ..previous.clone() - }; - - offline.carry_over(&previous); - - assert_eq!( - offline - .update_for(&installed) - .map(|update| &update.target.id), - Some(&"new".to_owned()) - ); - } - #[test] fn bulk_planning_projects_other_selected_updates() { let minecraft = std::path::Path::new("/instance/minecraft"); diff --git a/src/instance/tests/content/dependencies.rs b/src/instance/tests/content/dependencies.rs index 09fc06b..61b65c6 100644 --- a/src/instance/tests/content/dependencies.rs +++ b/src/instance/tests/content/dependencies.rs @@ -129,6 +129,8 @@ struct FakeProvider { download_barrier: Option>, download_pause: Option>, download_filename: Option, + compatible_started: Option>, + compatible_pause: HashMap>, } impl FakeProvider { @@ -223,6 +225,12 @@ impl ContentProvider for FakeProvider { _game_version: &str, _loader: ModLoader, ) -> Result, NetError> { + if let Some(started) = &self.compatible_started { + let _ = started.send(project_id.to_owned()); + } + if let Some(pause) = self.compatible_pause.get(project_id) { + pause.acquire().await.unwrap().forget(); + } Ok(self .compatible .get(project_id) @@ -404,9 +412,164 @@ fn provider(versions: Vec) -> FakeProvider { download_barrier: None, download_pause: None, download_filename: None, + compatible_started: None, + compatible_pause: HashMap::new(), } } +#[test] +fn update_checks_prioritize_list_rows_and_publish_before_the_rest_finish() { + use crate::instance::content::updates::{AvailableUpdate, UpdateSnapshot, scan_with_registry}; + let _guard = crate::tests::TEST_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .block_on(async { + let mut manifest = ContentManifest::default(); + let mut versions = Vec::new(); + let mut pauses = HashMap::new(); + for index in 0..12 { + let project = format!("project-{index:02}"); + let old = format!("{project}-old"); + manifest.files.push(installed_record(&project, &old, true)); + for (suffix, date) in [ + ("old", "2026-01-01T00:00:00Z"), + ("new", "2026-02-01T00:00:00Z"), + ] { + versions.push(version( + &format!("{project}-{suffix}"), + &project, + VersionType::Release, + date, + Vec::new(), + )); + } + pauses.insert(project, std::sync::Arc::new(tokio::sync::Semaphore::new(0))); + } + let priority = manifest + .files + .iter() + .rev() + .map(|record| record.resolved_project().unwrap().clone()) + .collect::>(); + let first = priority[0].clone(); + let known = priority.last().unwrap().clone(); + let previous = UpdateSnapshot { + game_version: "1.21.1".to_owned(), + loader: ModLoader::Fabric, + inventory: priority.clone(), + checked_at: 0, + updates: vec![AvailableUpdate { + installed: known.clone(), + current: None, + target: versions + .iter() + .find(|version| version.id == format!("{}-new", known.project_id)) + .unwrap() + .clone(), + kind: ContentKind::Mod, + }], + failures: Vec::new(), + }; + let (started, mut requests) = tokio::sync::mpsc::unbounded_channel(); + let (published, mut results) = tokio::sync::mpsc::unbounded_channel(); + let mut provider = provider(versions); + provider + .compatible + .insert(known.project_id.clone(), vec![known.version_id.clone()]); + provider.compatible_started = Some(started); + provider.compatible_pause = pauses.clone(); + let registry = std::sync::Arc::new(provider.registry()); + let expected = priority[..8] + .iter() + .map(|project| project.project_id.clone()) + .collect::>(); + let scan = tokio::spawn(async move { + let complete = scan_with_registry( + &instance(), + &manifest, + &priority, + registry, + Some(&previous), + |snapshot| { + published.send(snapshot.clone()).unwrap(); + }, + ) + .await; + let offline = scan_with_registry( + &instance(), + &manifest, + &priority, + std::sync::Arc::new(ProviderRegistry::new(Vec::new())), + Some(&complete), + |_| {}, + ) + .await; + assert_eq!(offline.updates.len(), complete.updates.len()); + assert_eq!(offline.failures.len(), 12); + complete + }); + let mut requested = HashSet::new(); + for _ in 0..8 { + requested.insert( + tokio::time::timeout(std::time::Duration::from_secs(5), requests.recv()) + .await + .unwrap() + .unwrap(), + ); + } + assert_eq!(requested, expected); + assert!(requests.try_recv().is_err()); + assert_eq!( + crate::feedback::progress::PROGRESS.lock().unwrap().progress, + Some((0, 12)) + ); + pauses[&first.project_id].add_permits(1); + let partial = tokio::time::timeout(std::time::Duration::from_secs(5), results.recv()) + .await + .unwrap() + .unwrap(); + assert!(!scan.is_finished()); + assert!(partial.update_for(&first).is_some()); + assert!(partial.update_for(&known).is_some()); + assert_eq!(partial.checked_at, 0); + assert_eq!( + crate::feedback::progress::PROGRESS.lock().unwrap().progress, + Some((1, 12)) + ); + let mut terminal = + ratatui::Terminal::new(ratatui::backend::TestBackend::new(50, 5)).unwrap(); + terminal + .draw(|frame| { + crate::tui::widgets::status::render( + frame, + frame.area(), + crate::tui::app::FocusedArea::Overview, + &mut throbber_widgets_tui::ThrobberState::default(), + None, + ) + }) + .unwrap(); + let overview = terminal.backend().to_string(); + assert!(overview.contains("8%")); + assert!(overview.contains("1/12 item(s) checked")); + for pause in pauses.values() { + pause.add_permits(1); + } + let complete = tokio::time::timeout(std::time::Duration::from_secs(5), scan) + .await + .unwrap() + .unwrap(); + assert_eq!(complete.updates.len(), 11); + assert!(complete.failures.is_empty()); + assert!(complete.checked_at > 0); + assert!(complete.update_for(&known).is_none()); + }); +} + #[tokio::test] async fn datapack_dependencies_are_routed_to_the_world_or_instance_by_kind() { let temp = tempfile::tempdir().unwrap(); diff --git a/src/instance/tests/content/reconcile.rs b/src/instance/tests/content/reconcile.rs index 2910944..1bfd798 100644 --- a/src/instance/tests/content/reconcile.rs +++ b/src/instance/tests/content/reconcile.rs @@ -45,6 +45,50 @@ impl InventoryProgress for NoopProgress { fn set_progress(&self, _current: u64, _total: u64) {} } +#[test] +fn saving_an_identified_inventory_reports_progress_for_the_actual_files() { + #[derive(Default)] + struct Counts(std::cell::RefCell>); + impl InventoryProgress for Counts { + fn set_sub_action(&self, _text: &str) {} + fn set_progress(&self, current: u64, total: u64) { + self.0.borrow_mut().push((current, total)); + } + } + let temp = tempfile::tempdir().unwrap(); + let minecraft = temp.path().join("minecraft"); + let manifest_path = temp.path().join("manifest.json"); + let mut previous = ContentManifest::default(); + for name in ["alpha.jar", "bravo.jar"] { + let mut record = resolved_record(); + record.relative_path = PathBuf::from("mods").join(name); + let path = minecraft.join(&record.relative_path); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, name).unwrap(); + record.fingerprint = fingerprint(&path).unwrap(); + record.provider_checks = vec!["modrinth".to_owned(), "curseforge".to_owned()]; + previous.files.push(record); + } + previous.save(&manifest_path).unwrap(); + let counts = Counts::default(); + let inventory = reconcile_inventory(&manifest_path, &minecraft, 24, 512, &counts).unwrap(); + assert!(inventory.queries.is_empty()); + counts.0.borrow_mut().clear(); + let saved = save_reconciled_manifest( + &manifest_path, + &minecraft, + inventory.manifest, + &inventory.previous, + &counts, + ) + .unwrap(); + assert_eq!(saved.files, previous.files); + let reported = counts.0.borrow(); + assert_eq!(reported.first(), Some(&(0, 2))); + assert!(reported.contains(&(1, 2))); + assert_eq!(reported.last(), Some(&(2, 2))); +} + fn resolved_record() -> ContentFileRecord { ContentFileRecord { relative_path: PathBuf::from("mods/example.jar"), @@ -207,8 +251,14 @@ fn reconciliation_keeps_newer_provider_ownership_for_unchanged_bytes() { }; current.files[0].provider_aliases = vec![record.resolved_project().unwrap().clone()]; current.save(&manifest_path).unwrap(); - let saved = - save_reconciled_manifest(&manifest_path, &minecraft, previous.clone(), &previous).unwrap(); + let saved = save_reconciled_manifest( + &manifest_path, + &minecraft, + previous.clone(), + &previous, + &NoopProgress, + ) + .unwrap(); assert_eq!(saved.files, current.files); } @@ -236,6 +286,7 @@ fn reconciliation_revalidates_hashes_after_provider_matching() { &minecraft, inventory.manifest, &inventory.previous, + &NoopProgress, ) .unwrap(); assert!(saved.files.is_empty()); @@ -289,6 +340,7 @@ fn reconciliation_saves_provider_aliases_for_an_existing_resolution() { files: vec![enriched.clone()], }, ¤t, + &NoopProgress, ) .unwrap(); @@ -298,25 +350,43 @@ fn reconciliation_saves_provider_aliases_for_an_existing_resolution() { managed.files[0].automatic_dependency = true; managed.files[0].cleanup_eligible = true; managed.save(&manifest_path).unwrap(); - let merged = - save_reconciled_manifest(&manifest_path, &minecraft, stale.clone(), &stale).unwrap(); + let merged = save_reconciled_manifest( + &manifest_path, + &minecraft, + stale.clone(), + &stale, + &NoopProgress, + ) + .unwrap(); assert!(merged.files[0].automatic_dependency); std::fs::write(&path, b"replacement").unwrap(); let mut newer = merged.clone(); newer.files[0].fingerprint = fingerprint(&path).unwrap(); newer.save(&manifest_path).unwrap(); assert_eq!( - save_reconciled_manifest(&manifest_path, &minecraft, stale.clone(), &stale) - .unwrap() - .files, + save_reconciled_manifest( + &manifest_path, + &minecraft, + stale.clone(), + &stale, + &NoopProgress + ) + .unwrap() + .files, newer.files ); std::fs::remove_file(path).unwrap(); assert!( - save_reconciled_manifest(&manifest_path, &minecraft, stale.clone(), &stale) - .unwrap() - .files - .is_empty() + save_reconciled_manifest( + &manifest_path, + &minecraft, + stale.clone(), + &stale, + &NoopProgress + ) + .unwrap() + .files + .is_empty() ); } diff --git a/src/tui/app.rs b/src/tui/app.rs index 8a13a47..3c3275f 100644 --- a/src/tui/app.rs +++ b/src/tui/app.rs @@ -55,10 +55,13 @@ pub struct App { pub(super) error_effects: HashMap, pub(super) pending_editor: Option, pub(super) edited_config_watches: Vec, + pub(super) content_for: Option, + pub(super) cached_instance_content: HashMap, pub(super) reconciliation_for: Option<(String, chrono::DateTime)>, pub(super) content_manifest: Option<(String, crate::instance::ContentManifest)>, pub(super) content_update_snapshot: Option<(String, crate::instance::content::updates::UpdateSnapshot)>, + pub(super) content_update_check_pending: bool, pub(super) content_update_popup: Option, pub(super) modpack_versions_state: Option, pub(super) modpack_update_popup: Option, @@ -66,6 +69,59 @@ pub struct App { pub(super) dismissed_provider_conflicts: HashSet, } +#[derive(Clone, PartialEq, Eq, Hash)] +pub(super) struct InstanceContentKey { + pub root: PathBuf, + pub name: String, + pub created: chrono::DateTime, + pub game_version: String, + pub loader: crate::instance::ModLoader, +} + +#[derive(Default)] +pub(super) struct CachedInstanceContent { + mods: widgets::content::ContentListState, + resource_packs: widgets::content::ContentListState, + shaders: widgets::content::ContentListState, + worlds: widgets::content::ContentListState, + world_datapacks: widgets::content::ContentListState, + open_world_datapacks: Option<(String, PathBuf)>, + screenshots: widgets::screenshots_grid::ScreenshotsState, + logs: widgets::logs_viewer::LogsState, + pub(super) reconciliation_for: Option<(String, chrono::DateTime)>, + manifest: Option<(String, crate::instance::ContentManifest)>, + updates: Option<(String, crate::instance::content::updates::UpdateSnapshot)>, + pub(super) update_check_pending: bool, + dismissed_provider_conflicts: HashSet, +} + +impl CachedInstanceContent { + pub fn swap(&mut self, app: &mut App) { + std::mem::swap(&mut self.mods, &mut app.mods_state); + std::mem::swap(&mut self.resource_packs, &mut app.resource_packs_state); + std::mem::swap(&mut self.shaders, &mut app.shaders_state); + std::mem::swap(&mut self.worlds, &mut app.worlds_state); + std::mem::swap(&mut self.world_datapacks, &mut app.world_datapacks_state); + std::mem::swap( + &mut self.open_world_datapacks, + &mut app.open_world_datapacks, + ); + std::mem::swap(&mut self.screenshots, &mut app.screenshots_state); + std::mem::swap(&mut self.logs, &mut app.logs_state); + std::mem::swap(&mut self.reconciliation_for, &mut app.reconciliation_for); + std::mem::swap(&mut self.manifest, &mut app.content_manifest); + std::mem::swap(&mut self.updates, &mut app.content_update_snapshot); + std::mem::swap( + &mut self.update_check_pending, + &mut app.content_update_check_pending, + ); + std::mem::swap( + &mut self.dismissed_provider_conflicts, + &mut app.dismissed_provider_conflicts, + ); + } +} + pub(super) struct ProviderConflictState { pub relative_path: PathBuf, pub candidates: Vec, @@ -138,20 +194,6 @@ impl App { instances::spawn_modpack_update_checks(&instances); let instances_state = instances::State::with_instances(instances); - let mut mods_state = widgets::content::list::ContentListState::default(); - let mut resource_packs_state = widgets::content::list::ContentListState::default(); - let mut shaders_state = widgets::content::list::ContentListState::default(); - let mut world_datapacks_state = widgets::content::list::ContentListState::default(); - let provider_icon_client = crate::net::HttpClient::new(); - for state in [ - &mut mods_state, - &mut resource_packs_state, - &mut shaders_state, - &mut world_datapacks_state, - ] { - state.enable_provider_icons(manager.meta_dir.clone(), provider_icon_client.clone()); - } - App { exit: false, focused: FocusedArea::default(), @@ -159,15 +201,15 @@ impl App { content_tab: widgets::content::ContentTab::default(), content_mode: widgets::content::ContentMode::default(), instances_state, - mods_state, + mods_state: widgets::content::ContentListState::default(), mods_discovery_state: widgets::content::DiscoveryState::new( crate::instance::ContentKind::Mod, ), - resource_packs_state, + resource_packs_state: widgets::content::ContentListState::default(), resource_packs_discovery_state: widgets::content::DiscoveryState::new( crate::instance::ContentKind::ResourcePack, ), - shaders_state, + shaders_state: widgets::content::ContentListState::default(), shaders_discovery_state: widgets::content::DiscoveryState::new( crate::instance::ContentKind::Shader, ), @@ -175,7 +217,7 @@ impl App { crate::instance::ContentKind::DataPack, ), worlds_state: widgets::content::list::ContentListState::default(), - world_datapacks_state, + world_datapacks_state: widgets::content::ContentListState::default(), open_world_datapacks: None, world_quick_play_support: None, logs_state: widgets::logs_viewer::LogsState::default(), @@ -202,9 +244,12 @@ impl App { 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, diff --git a/src/tui/event.rs b/src/tui/event.rs index b090ced..772f8bb 100644 --- a/src/tui/event.rs +++ b/src/tui/event.rs @@ -28,6 +28,7 @@ impl App { let mut drawn_image_skips = Vec::new(); let mut image_redraw_marker = false; while !self.exit { + self.sync_instance_content(); let redraw_requested = crate::feedback::take_redraw_request(); let edited_config_changed = self.drain_edited_configs(); if let Some(params) = new_instance::take_result() { @@ -83,10 +84,9 @@ impl App { self.instances_state.modpack_updates.remove(&name); widgets::instances::spawn_modpack_update_check(&instance); self.modpack_update_popup = None; - self.reconciliation_for = None; - self.content_manifest = None; - self.content_update_snapshot = None; + self.forget_instance_content(&name); } + self.sync_instance_content(); let mut local_streamed = false; let mut content_changed = false; let mut toggles = Vec::new(); @@ -160,6 +160,21 @@ impl App { if local_streamed { self.apply_cached_content_manifest(); } + if self.content_update_check_pending + && ![ + &self.mods_state, + &self.resource_packs_state, + &self.shaders_state, + &self.world_datapacks_state, + ] + .iter() + .any(|state| state.is_scanning()) + { + self.content_update_check_pending = false; + if crate::config::SETTINGS.read().general.check_content_updates { + self.spawn_selected_content_update_check(); + } + } self.ensure_provider_conflict_popup(); self.ensure_active_discovery_loaded(); let progress_active = progress::is_active(); @@ -289,7 +304,77 @@ impl App { !complete } + pub(super) fn sync_instance_content(&mut self) { + let key = self.instances_state.selected_instance().map(|instance| { + super::app::InstanceContentKey { + root: self.instance_manager.instances_dir.clone(), + name: instance.name.clone(), + created: instance.created, + game_version: instance.game_version.clone(), + loader: instance.loader, + } + }); + if self.content_for == key { + return; + } + if let Some(previous) = self.content_for.take() { + let mut cached = super::app::CachedInstanceContent::default(); + cached.swap(self); + self.cached_instance_content.insert(previous, cached); + } + self.cached_instance_content.retain(|cached, _| { + cached.root == self.instance_manager.instances_dir + && self.instances_state.instances.iter().any(|instance| { + instance.name == cached.name + && instance.created == cached.created + && instance.game_version == cached.game_version + && instance.loader == cached.loader + }) + }); + let cached = key + .as_ref() + .and_then(|key| self.cached_instance_content.remove(key)); + if let Some(mut cached) = cached { + cached.swap(self); + } else if key.is_some() { + let client = crate::net::HttpClient::new(); + for state in [ + &mut self.mods_state, + &mut self.resource_packs_state, + &mut self.shaders_state, + &mut self.world_datapacks_state, + ] { + state.enable_provider_icons(self.instance_manager.meta_dir.clone(), client.clone()); + } + let font_size = self.picker.font_size(); + self.screenshots_state.font_size = (font_size.width, font_size.height); + } + self.content_for = key; + self.provider_conflict = None; + if let Some(instance) = self.instances_state.selected_instance() { + let minecraft = crate::storage::InstancePaths::new( + self.instance_manager.instances_dir.join(&instance.name), + ) + .minecraft(); + let empty = crate::instance::ContentManifest::default(); + let manifest = self + .content_manifest + .as_ref() + .map_or(&empty, |(_, manifest)| manifest); + for discovery in [ + &mut self.mods_discovery_state, + &mut self.resource_packs_discovery_state, + &mut self.shaders_discovery_state, + &mut self.datapacks_discovery_state, + ] { + discovery.refresh_installed_manifest(manifest, &minecraft); + } + } + self.apply_cached_content_manifest(); + } + fn ensure_content_reconciliation(&mut self, changed: bool) { + self.sync_instance_content(); let Some(instance) = self.instances_state.selected_instance().cloned() else { self.reconciliation_for = None; self.content_manifest = None; @@ -299,27 +384,6 @@ impl App { if !changed && self.reconciliation_for.as_ref() == Some(&instance_id) { return; } - let instance_changed = self.reconciliation_for.as_ref() != Some(&instance_id); - if instance_changed { - self.provider_conflict = None; - self.dismissed_provider_conflicts.clear(); - self.content_manifest = None; - self.content_update_snapshot = None; - for discovery in [ - &mut self.mods_discovery_state, - &mut self.resource_packs_discovery_state, - &mut self.shaders_discovery_state, - &mut self.datapacks_discovery_state, - ] { - discovery.refresh_installed_manifest( - &crate::instance::ContentManifest::default(), - &crate::storage::InstancePaths::new( - self.instance_manager.instances_dir.join(&instance.name), - ) - .minecraft(), - ); - } - } self.reconciliation_for = Some(instance_id); if changed { crate::instance::content::reconcile::spawn_after_change( @@ -436,13 +500,8 @@ impl App { cached.map(|snapshot| (result.instance_name.clone(), snapshot)); self.content_manifest = Some((result.instance_name.clone(), result.manifest.clone())); self.apply_content_update_snapshot(); - if stale && crate::config::SETTINGS.read().general.check_content_updates { - crate::instance::content::updates::spawn( - selected, - result.manifest, - paths.content_updates(), - ); - } + self.content_update_check_pending = + stale && crate::config::SETTINGS.read().general.check_content_updates; } fn apply_cached_content_manifest(&mut self) { @@ -491,11 +550,10 @@ impl App { .rposition(|pending| { pending.instance_name == selected.name && pending.instance_created == selected.created + && pending.snapshot.applies_to(selected) }) .map(|index| pending.remove(index)); - // every scan also writes its result to disk, so whatever is left - // here is recovered on the next reconciliation of that instance - pending.clear(); + pending.retain(|pending| pending.instance_name != selected.name); latest } Err(_) => return, @@ -974,7 +1032,7 @@ impl App { ); } if outcome.content_updates_enabled { - self.spawn_selected_content_update_check(); + self.queue_content_update_checks(); } if outcome.restart_required { error_buffer::push_error(error_buffer::ErrorEvent { @@ -1181,28 +1239,19 @@ impl App { } pub(super) fn forget_instance_content(&mut self, instance_name: &str) { - for state in [ - &mut self.mods_state, - &mut self.resource_packs_state, - &mut self.shaders_state, - &mut self.worlds_state, - &mut self.world_datapacks_state, - ] { - state.forget_instance(instance_name); + self.cached_instance_content + .retain(|key, _| key.name != instance_name); + if self + .content_for + .as_ref() + .is_some_and(|key| key.name != instance_name) + { + return; } - if self.logs_state.loaded_for.as_deref() == Some(instance_name) { - self.logs_state.loaded_for = None; - } - if self.screenshots_state.loaded_for.as_deref() == Some(instance_name) { - self.screenshots_state.loaded_for = None; - } - self.reconciliation_for = None; - self.content_manifest = None; - self.content_update_snapshot = None; + super::app::CachedInstanceContent::default().swap(self); + self.content_for = None; self.content_update_popup = None; self.provider_conflict = None; - self.dismissed_provider_conflicts.clear(); - self.apply_content_update_snapshot(); } fn drain_pending_last_played(&mut self) { diff --git a/src/tui/input.rs b/src/tui/input.rs index 0c7380e..086f29e 100644 --- a/src/tui/input.rs +++ b/src/tui/input.rs @@ -2255,7 +2255,7 @@ impl App { ); } if outcome.content_updates_enabled { - self.spawn_selected_content_update_check(); + self.queue_content_update_checks(); } if outcome.restart_required && outcome.restart_changed { error_buffer::push_message( @@ -2357,6 +2357,10 @@ impl App { } pub(super) fn reset_discovery_states(&mut self) { + self.reconciliation_for = None; + for cached in self.cached_instance_content.values_mut() { + cached.reconciliation_for = None; + } self.mods_discovery_state = widgets::content::DiscoveryState::new(crate::instance::ContentKind::Mod); self.resource_packs_discovery_state = @@ -2367,6 +2371,13 @@ impl App { widgets::content::DiscoveryState::new(crate::instance::ContentKind::DataPack); } + pub(super) fn queue_content_update_checks(&mut self) { + self.content_update_check_pending = true; + for cached in self.cached_instance_content.values_mut() { + cached.update_check_pending = true; + } + } + pub(super) fn spawn_selected_content_update_check(&self) { let Some(instance) = self.instances_state.selected_instance().cloned() else { return; @@ -2381,7 +2392,42 @@ impl App { self.instance_manager.instances_dir.join(&instance.name), ) .content_updates(); - crate::instance::content::updates::spawn(instance, manifest.clone(), path); + crate::instance::content::updates::spawn( + instance, + manifest.clone(), + path, + self.content_update_priority(), + ); + } + + pub(super) fn content_update_priority(&self) -> Vec { + let active = match self.content_tab { + widgets::content::ContentTab::ResourcePacks => &self.resource_packs_state, + widgets::content::ContentTab::Shaders => &self.shaders_state, + widgets::content::ContentTab::Worlds => &self.world_datapacks_state, + _ => &self.mods_state, + }; + [ + active, + &self.mods_state, + &self.resource_packs_state, + &self.shaders_state, + &self.world_datapacks_state, + ] + .into_iter() + .flat_map(|state| { + state + .filtered_indices() + .into_iter() + .filter_map(|index| state.entries[index].provider_project.clone()) + .chain( + state + .entries + .iter() + .filter_map(|entry| entry.provider_project.clone()), + ) + }) + .collect() } } diff --git a/src/tui/render.rs b/src/tui/render.rs index f434f09..88e2df2 100644 --- a/src/tui/render.rs +++ b/src/tui/render.rs @@ -29,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())), diff --git a/src/tui/tests/event.rs b/src/tui/tests/event.rs index 56c0e3c..434ea01 100644 --- a/src/tui/tests/event.rs +++ b/src/tui/tests/event.rs @@ -4,6 +4,178 @@ 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()); +} + fn key_kind(code: KeyCode, kind: KeyEventKind) -> KeyEvent { KeyEvent::new_with_kind(code, KeyModifiers::NONE, kind) } diff --git a/src/tui/tests/harness.rs b/src/tui/tests/harness.rs index 88b6406..63c2ce3 100644 --- a/src/tui/tests/harness.rs +++ b/src/tui/tests/harness.rs @@ -113,9 +113,12 @@ impl UiHarness { 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, diff --git a/src/tui/widgets/content/list.rs b/src/tui/widgets/content/list.rs index 888e624..8a389af 100644 --- a/src/tui/widgets/content/list.rs +++ b/src/tui/widgets/content/list.rs @@ -350,6 +350,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() } @@ -1667,19 +1671,6 @@ async fn load_installed_version( } impl ContentListState { - pub fn forget_instance(&mut self, instance_name: &str) { - let world_prefix = format!("{instance_name}:"); - 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(); - } - } - pub fn start_load( &mut self, content_dir: &Path, From ce0bb344013082e495b3ca447a0fcc155486ba52 Mon Sep 17 00:00:00 2001 From: objz Date: Fri, 2 Oct 2026 01:06:06 +0200 Subject: [PATCH 26/34] fix(tui): retain per-instance Java labels across switches Cache completed and in-flight Java inspections by instance and execution context, refresh changed executables and settings, and cover cached rendering and configuration changes. Remove instance names from Overview activity labels. --- src/instance/content/reconcile.rs | 6 +- src/instance/content/updates.rs | 5 +- src/instance/import/mod.rs | 2 +- src/instance/manager.rs | 5 +- src/instance/tests/content/dependencies.rs | 2 + src/tui/event.rs | 6 +- src/tui/input.rs | 4 +- src/tui/tests/event.rs | 58 ++++++++ src/tui/tests/widgets/settings.rs | 163 ++++++++++++++++++--- src/tui/widgets/settings.rs | 77 ++++++---- 10 files changed, 266 insertions(+), 62 deletions(-) diff --git a/src/instance/content/reconcile.rs b/src/instance/content/reconcile.rs index 36717e5..de03f6d 100644 --- a/src/instance/content/reconcile.rs +++ b/src/instance/content/reconcile.rs @@ -145,7 +145,7 @@ async fn reconcile(job: ReconcileJob, task: &ProgressTask) -> ReconcileResult { } = job; let instance_name = instance.name; let instance_created = instance.created; - task.set_action(format!("Checking content for {instance_name}")); + task.set_action("Checking content"); task.set_sub_action("Reading saved content index"); task.set_progress(0, 1); let paths = InstancePaths::new(instances_dir.join(&instance_name)); @@ -178,7 +178,7 @@ async fn reconcile(job: ReconcileJob, task: &ProgressTask) -> ReconcileResult { Ok(()) } else { let registry = ProviderRegistry::configured(client); - task.set_action(format!("Identifying content for {instance_name}")); + task.set_action("Identifying content"); resolve_queries( ®istry, &inventory.queries, @@ -187,7 +187,7 @@ async fn reconcile(job: ReconcileJob, task: &ProgressTask) -> ReconcileResult { ) .await }; - task.set_action(format!("Saving content index for {instance_name}")); + task.set_action("Saving content index"); task.set_sub_action("Validating content files"); task.set_progress(0, inventory.manifest.files.len() as u64); let save_progress = task.handle(); diff --git a/src/instance/content/updates.rs b/src/instance/content/updates.rs index e49a2df..a63f865 100644 --- a/src/instance/content/updates.rs +++ b/src/instance/content/updates.rs @@ -250,10 +250,7 @@ pub(super) async fn scan_with_registry( return snapshot; } let total = projects.len() as u64; - let progress = crate::feedback::progress::ProgressTask::start(format!( - "Checking content updates for {}", - instance.name - )); + let progress = crate::feedback::progress::ProgressTask::start("Checking content updates"); progress.set_progress(0, total); let mut completed = 0; let mut projects = projects.into_iter(); diff --git a/src/instance/import/mod.rs b/src/instance/import/mod.rs index 8c0883a..c92589d 100644 --- a/src/instance/import/mod.rs +++ b/src/instance/import/mod.rs @@ -178,7 +178,7 @@ pub async fn execute_import( ); let name = unique_instance_name(&summary.name, &manager.instances_dir) .inspect_err(|_| crate::feedback::progress::clear())?; - crate::feedback::progress::set_action(format!("Importing '{name}'...")); + crate::feedback::progress::set_action("Importing instance..."); crate::feedback::progress::set_sub_action(format!( "{} {}", summary.game_version, summary.loader diff --git a/src/instance/manager.rs b/src/instance/manager.rs index a29c24c..ab28933 100644 --- a/src/instance/manager.rs +++ b/src/instance/manager.rs @@ -315,10 +315,7 @@ impl InstanceManager { &minecraft_dir, &environment, ); - let task = crate::feedback::progress::ProgressTask::start(format!( - "Rebuilding runtime for '{}'", - config.name - )); + let task = crate::feedback::progress::ProgressTask::start("Rebuilding runtime"); task.set_sub_action(format!("Minecraft {}", config.game_version)); let metadata_paths = crate::storage::MetadataPaths::new(&self.meta_dir); for directory in [ diff --git a/src/instance/tests/content/dependencies.rs b/src/instance/tests/content/dependencies.rs index 61b65c6..b5c41c0 100644 --- a/src/instance/tests/content/dependencies.rs +++ b/src/instance/tests/content/dependencies.rs @@ -556,6 +556,8 @@ fn update_checks_prioritize_list_rows_and_publish_before_the_rest_finish() { let overview = terminal.backend().to_string(); assert!(overview.contains("8%")); assert!(overview.contains("1/12 item(s) checked")); + assert!(overview.contains("Checking content updates")); + assert!(!overview.contains(&instance().name)); for pause in pauses.values() { pause.add_permits(1); } diff --git a/src/tui/event.rs b/src/tui/event.rs index 772f8bb..e7edc46 100644 --- a/src/tui/event.rs +++ b/src/tui/event.rs @@ -793,7 +793,7 @@ impl App { let pending_instances = PENDING_INSTANCES.clone(); tokio::spawn(async move { - progress::set_action(format!("Creating instance '{}'...", params.name)); + progress::set_action("Creating instance..."); progress::set_sub_action(format!("{} {}", params.game_version, params.loader)); let manager = InstanceManager::new(instances_dir, meta_dir); @@ -836,7 +836,7 @@ impl App { let completed_updates = COMPLETED_INSTANCE_SETTINGS_UPDATES.clone(); tokio::spawn(async move { - progress::set_action(format!("Updating instance '{}'...", updated.name)); + progress::set_action("Updating instance..."); progress::set_sub_action(format!("{} {}", updated.game_version, updated.loader)); let manager = InstanceManager::new(&instances_dir, &meta_dir); updated = match apply_instance_settings_update(&manager, &previous, updated).await { @@ -1239,6 +1239,8 @@ impl App { } pub(super) fn forget_instance_content(&mut self, instance_name: &str) { + self.settings_state + .invalidate_java_cache(Some(instance_name)); self.cached_instance_content .retain(|key, _| key.name != instance_name); if self diff --git a/src/tui/input.rs b/src/tui/input.rs index 086f29e..141bcb5 100644 --- a/src/tui/input.rs +++ b/src/tui/input.rs @@ -339,6 +339,7 @@ impl App { match crate::storage::clear_disposable_caches(&meta_dir) { Ok(()) => { self.reset_discovery_states(); + self.settings_state.invalidate_java_cache(None); if let Some(state) = self.global_settings.as_mut() { state.invalidate_java_cache(); } @@ -1303,8 +1304,7 @@ impl App { widgets::popups::modpack_update::Action::Reinstall => "reinstall", }; let progress = crate::feedback::progress::ProgressTask::start(format!( - "Preparing modpack {action} for {}", - instance.name + "Preparing modpack {action}" )); let manager = crate::instance::InstanceManager::new(instances_dir, meta_dir); let result = diff --git a/src/tui/tests/event.rs b/src/tui/tests/event.rs index 434ea01..4a05dc3 100644 --- a/src/tui/tests/event.rs +++ b/src/tui/tests/event.rs @@ -665,6 +665,8 @@ fn gui_editor_saves_reload_after_handoff_and_atomic_replacement_only_when_bytes_ #[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; } @@ -678,14 +680,70 @@ fn launcher_config_save_process() { 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"); theme.theme = "dracula".to_owned(); theme.border_style = crate::config::theme::BorderStyle::Thick; diff --git a/src/tui/tests/widgets/settings.rs b/src/tui/tests/widgets/settings.rs index 1e14c69..05f32be 100644 --- a/src/tui/tests/widgets/settings.rs +++ b/src/tui/tests/widgets/settings.rs @@ -3,8 +3,41 @@ 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!({ @@ -12,19 +45,7 @@ fn narrow_settings_shows_the_selected_pane() { "loader_version": null, "created": "2026-01-01T00:00:00Z", "java_path": "test-java" })) .unwrap(); - let environment = crate::instance::java::merge_environment( - &SETTINGS.read().defaults.environment, - &instance.environment, - ); - state.java_key = Some(java_path_key( - "test-java", - &state - .instances_dir - .join("Test") - .join(crate::storage::MINECRAFT_DIR_NAME), - &environment, - )); - state.java_label = "jdk17".to_owned(); + cache_java_result(&mut state, &instance, Some("jdk17")); let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(35, 8)).unwrap(); terminal @@ -70,6 +91,70 @@ fn narrow_settings_shows_the_selected_pane() { 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(); @@ -99,7 +184,7 @@ fn info_pane_does_not_bind_desktop_toggle() { #[cfg(unix)] #[test] -fn instance_java_labels_use_their_cwd_and_environment_and_discard_previous_results() { +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() @@ -107,7 +192,7 @@ fn instance_java_labels_use_their_cwd_and_environment_and_discard_previous_resul 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\nread -r expected < marker || exit 1\n[ \"$RMCL_TEST_JAVA_VERSION\" = \"$expected\" ] || exit 1\nprintf 'java.version = %s\\n' \"$expected\"\n").unwrap(); + 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 { @@ -130,11 +215,53 @@ fn instance_java_labels_use_their_cwd_and_environment_and_discard_previous_resul } panic!("Expected {expected}, found {}", state.java_label); } - let first = instance("first", "21"); + let mut first = instance("first", "21"); wait_for_label(&mut state, &first, "jdk21"); - let old_pending = state.pending_java.clone(); let second = instance("second", "25"); state.update_for_instance(Some(&second)); - *old_pending.lock().unwrap() = Some("stale label".to_owned()); 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/settings.rs b/src/tui/widgets/settings.rs index 2e3baa8..4659d10 100644 --- a/src/tui/widgets/settings.rs +++ b/src/tui/widgets/settings.rs @@ -1,7 +1,11 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -use std::path::{Path, PathBuf}; +use std::{ + collections::HashMap, + path::{Path, PathBuf}, + sync::{Arc, Mutex}, +}; use crossterm::event::{KeyCode, KeyEvent}; use ratatui::{ @@ -47,9 +51,14 @@ pub struct SettingsState { instances_dir: PathBuf, active_profile: Option, instance_name: Option, - java_key: Option, java_label: String, - pending_java: std::sync::Arc>>, + java_cache: HashMap, +} + +#[derive(Default)] +struct CachedJavaLabel { + key: Option<(chrono::DateTime, String)>, + result: Arc>>, } impl SettingsState { @@ -67,9 +76,8 @@ impl SettingsState { instances_dir, active_profile: None, instance_name: None, - java_key: None, java_label: "unknown".to_string(), - pending_java: Default::default(), + java_cache: HashMap::new(), }; state.select_active(); state @@ -108,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()); @@ -120,7 +136,7 @@ impl SettingsState { self.select_active(); } - let context = instance.map(|instance| { + self.java_label = if let Some(instance) = instance { let settings = SETTINGS.read(); let cwd = self .instances_dir @@ -139,16 +155,12 @@ impl SettingsState { &cwd, &environment, ); - (java, cwd, environment) - }); - let java_key = context - .as_ref() - .map(|(java, cwd, environment)| java_path_key(java, cwd, environment)); - if self.java_key != java_key { - self.pending_java = Default::default(); - self.java_label = "unknown".to_owned(); - if let Some((java, cwd, environment)) = context { - let pending = self.pending_java.clone(); + 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 @@ -157,16 +169,15 @@ impl SettingsState { crate::feedback::request_redraw(); }); } - self.java_key = java_key; - } - if let Some(label) = self - .pending_java - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .take() - { - self.java_label = label; - } + cached + .result + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + .unwrap_or_else(|| "unknown".to_owned()) + } else { + "unknown".to_owned() + }; } } @@ -184,9 +195,19 @@ fn java_path_key( 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}:{}", - crate::instance::java::probe_context_key(cwd, environment) + "{java}:{}:{:?}:{metadata:?}", + crate::instance::java::probe_context_key(cwd, environment), + std::fs::canonicalize(path).ok(), ) } From 65edd0b31b9fcb60833630877d3743316e8b14b4 Mon Sep 17 00:00:00 2001 From: objz Date: Fri, 2 Oct 2026 11:58:27 +0200 Subject: [PATCH 27/34] Stream update badges during content index validation Publish the fingerprinted inventory before the validating save pass so checks start while validation continues, and keep streamed badges through the final save without duplicate scans. Deduplicate running scans by exact inventory, guard retired workers from overwriting successors, and cancel scoped checks on forget/reset. Rename the long phase to Validating content files. --- src/instance/content/dependencies.rs | 2 +- src/instance/content/reconcile.rs | 55 +++- src/instance/content/updates.rs | 134 ++++++++- src/instance/tests/content/dependencies.rs | 11 + src/tui/event.rs | 60 ++-- src/tui/input.rs | 17 +- src/tui/tests/event.rs | 329 +++++++++++++++++++++ 7 files changed, 555 insertions(+), 53 deletions(-) diff --git a/src/instance/content/dependencies.rs b/src/instance/content/dependencies.rs index 3b5ac2f..ac40c41 100644 --- a/src/instance/content/dependencies.rs +++ b/src/instance/content/dependencies.rs @@ -1529,4 +1529,4 @@ fn planned_install( #[cfg(test)] #[path = "../tests/content/dependencies.rs"] -mod tests; +pub(crate) mod tests; diff --git a/src/instance/content/reconcile.rs b/src/instance/content/reconcile.rs index de03f6d..b9b11c0 100644 --- a/src/instance/content/reconcile.rs +++ b/src/instance/content/reconcile.rs @@ -20,6 +20,7 @@ pub struct ReconcileResult { pub instance_name: String, pub instance_created: chrono::DateTime, pub manifest: ContentManifest, + pub complete: bool, pub error: Option, } @@ -118,14 +119,15 @@ async fn reconcile_worker() { }; let instance = (job.instance.name.clone(), job.instance.created); let rerun_job = job.clone(); - let result = reconcile(job, &task).await; - if let Ok(mut results) = PENDING_RECONCILIATIONS.lock() { - results.retain(|pending| { - (pending.instance_name.as_str(), pending.instance_created) - != (instance.0.as_str(), instance.1) - }); - results.push(result); - } + let result = reconcile( + job.instance, + job.instances_dir, + job.client, + &task, + publish_reconciliation, + ) + .await; + publish_reconciliation(result); if let Ok(mut coordinator) = RECONCILE_COORDINATOR.lock() { if coordinator.rerun.remove(&instance) { coordinator.queue.push_back(rerun_job); @@ -133,16 +135,27 @@ async fn reconcile_worker() { coordinator.scheduled.remove(&instance); } } + } +} + +pub(crate) fn publish_reconciliation(result: ReconcileResult) { + if let Ok(mut results) = PENDING_RECONCILIATIONS.lock() { + results.retain(|pending| { + pending.instance_name != result.instance_name + || pending.instance_created != result.instance_created + }); + results.push(result); crate::feedback::request_redraw(); } } -async fn reconcile(job: ReconcileJob, task: &ProgressTask) -> ReconcileResult { - let ReconcileJob { - instance, - instances_dir, - client, - } = job; +pub(crate) async fn reconcile( + instance: InstanceConfig, + instances_dir: PathBuf, + client: crate::net::HttpClient, + task: &ProgressTask, + mut publish: impl FnMut(ReconcileResult), +) -> ReconcileResult { let instance_name = instance.name; let instance_created = instance.created; task.set_action("Checking content"); @@ -187,9 +200,16 @@ async fn reconcile(job: ReconcileJob, task: &ProgressTask) -> ReconcileResult { ) .await }; - task.set_action("Saving content index"); - task.set_sub_action("Validating content files"); + task.set_action("Validating content files"); + task.set_sub_action("Rechecking local files"); task.set_progress(0, inventory.manifest.files.len() as u64); + publish(ReconcileResult { + instance_name: instance_name.clone(), + instance_created, + manifest: inventory.manifest.clone(), + complete: false, + error: None, + }); let save_progress = task.handle(); let saved = tokio::task::spawn_blocking(move || { save_reconciled_manifest( @@ -216,6 +236,7 @@ async fn reconcile(job: ReconcileJob, task: &ProgressTask) -> ReconcileResult { instance_name, instance_created, manifest: saved.unwrap_or_default(), + complete: true, error, } } @@ -223,12 +244,14 @@ async fn reconcile(job: ReconcileJob, task: &ProgressTask) -> ReconcileResult { instance_name, instance_created, manifest: ContentManifest::default(), + complete: true, error: Some(error.to_string()), }, Err(error) => ReconcileResult { instance_name, instance_created, manifest: ContentManifest::default(), + complete: true, error: Some(error.to_string()), }, } diff --git a/src/instance/content/updates.rs b/src/instance/content/updates.rs index a63f865..dd76916 100644 --- a/src/instance/content/updates.rs +++ b/src/instance/content/updates.rs @@ -83,6 +83,24 @@ pub struct BulkUpdatePlan { pub static PENDING_UPDATE_SNAPSHOTS: LazyLock>>> = LazyLock::new(|| Arc::new(Mutex::new(Vec::new()))); +struct RunningCheck { + instance: InstanceConfig, + inventory: Vec, + task: tokio::task::JoinHandle<()>, +} + +impl RunningCheck { + fn matches(&self, instance: &InstanceConfig, manifest: &ContentManifest) -> bool { + self.instance.created == instance.created + && self.instance.game_version == instance.game_version + && self.instance.loader == instance.loader + && self.inventory == resolved_inventory(manifest) + } +} + +static RUNNING_CHECKS: LazyLock>> = + LazyLock::new(|| Mutex::new(HashMap::new())); + impl UpdateSnapshot { pub fn load(path: &std::path::Path) -> Option { std::fs::read(path) @@ -124,29 +142,121 @@ pub fn spawn( manifest: ContentManifest, path: std::path::PathBuf, priority: Vec, + previous: Option, ) { - tokio::spawn(async move { - let previous = - UpdateSnapshot::load(&path).filter(|previous| previous.applies_to(&instance)); - let registry = Arc::new(super::provider::ProviderRegistry::configured( + spawn_with_registry( + instance, + manifest, + path, + priority, + previous, + Arc::new(super::provider::ProviderRegistry::configured( crate::net::HttpClient::new(), - )); + )), + ); +} + +pub(crate) fn is_running( + instance: &InstanceConfig, + manifest: &ContentManifest, + path: &std::path::Path, +) -> bool { + RUNNING_CHECKS.lock().is_ok_and(|checks| { + checks + .get(path) + .is_some_and(|check| !check.task.is_finished() && check.matches(instance, manifest)) + }) +} + +pub(crate) fn cancel(path: Option<&std::path::Path>) { + if let Ok(mut checks) = RUNNING_CHECKS.lock() { + checks.retain(|check_path, check| { + if path.is_none_or(|path| path == check_path) { + check.task.abort(); + if let Ok(mut pending) = PENDING_UPDATE_SNAPSHOTS.lock() { + pending.retain(|pending| { + pending.instance_name != check.instance.name + || pending.instance_created != check.instance.created + }); + } + false + } else { + true + } + }); + } +} + +pub(crate) fn spawn_with_registry( + instance: InstanceConfig, + manifest: ContentManifest, + path: std::path::PathBuf, + priority: Vec, + previous: Option, + registry: Arc, +) -> bool { + let Ok(mut checks) = RUNNING_CHECKS.lock() else { + return false; + }; + if let Some(check) = checks.get(&path) { + if !check.task.is_finished() && check.matches(&instance, &manifest) { + return false; + } + check.task.abort(); + } + let check_path = path.clone(); + let check_instance = instance.clone(); + let inventory = resolved_inventory(&manifest); + let task = tokio::spawn(async move { + let previous = previous + .or_else(|| UpdateSnapshot::load(&path)) + .filter(|previous| previous.applies_to(&instance)); let snapshot = scan_with_registry( &instance, &manifest, &priority, registry, previous.as_ref(), - |snapshot| publish_snapshot(&instance, snapshot.clone()), + |snapshot| publish_current_snapshot(&instance, snapshot.clone(), &path, false), ) .await; - if let Ok(bytes) = serde_json::to_vec_pretty(&snapshot) - && let Err(error) = crate::storage::write_atomic(&path, &bytes) - { - tracing::debug!("Could not cache content update snapshot: {error}"); - } - publish_snapshot(&instance, snapshot); + publish_current_snapshot(&instance, snapshot, &path, true); }); + checks.insert( + check_path, + RunningCheck { + instance: check_instance, + inventory, + task, + }, + ); + true +} + +fn publish_current_snapshot( + instance: &InstanceConfig, + snapshot: UpdateSnapshot, + path: &std::path::Path, + complete: bool, +) { + let Ok(checks) = RUNNING_CHECKS.lock() else { + return; + }; + if checks + .get(path) + .is_none_or(|check| check.task.id() != tokio::task::id()) + { + return; + } + // Hold the check registry through persistence and publication so a replaced + // worker cannot overwrite its successor's snapshot. + if complete + && let Ok(bytes) = serde_json::to_vec_pretty(&snapshot) + && let Err(error) = crate::storage::write_atomic(path, &bytes) + { + tracing::debug!("Could not cache content update snapshot: {error}"); + } + publish_snapshot(instance, snapshot); } fn publish_snapshot(instance: &InstanceConfig, snapshot: UpdateSnapshot) { diff --git a/src/instance/tests/content/dependencies.rs b/src/instance/tests/content/dependencies.rs index b5c41c0..abce1a5 100644 --- a/src/instance/tests/content/dependencies.rs +++ b/src/instance/tests/content/dependencies.rs @@ -417,6 +417,17 @@ fn provider(versions: Vec) -> FakeProvider { } } +pub(crate) fn controlled_update_registry( + versions: Vec, + started: tokio::sync::mpsc::UnboundedSender, + pauses: HashMap>, +) -> ProviderRegistry { + let mut provider = provider(versions); + provider.compatible_started = Some(started); + provider.compatible_pause = pauses; + provider.registry() +} + #[test] fn update_checks_prioritize_list_rows_and_publish_before_the_rest_finish() { use crate::instance::content::updates::{AvailableUpdate, UpdateSnapshot, scan_with_registry}; diff --git a/src/tui/event.rs b/src/tui/event.rs index e7edc46..d619e63 100644 --- a/src/tui/event.rs +++ b/src/tui/event.rs @@ -160,16 +160,7 @@ impl App { if local_streamed { self.apply_cached_content_manifest(); } - if self.content_update_check_pending - && ![ - &self.mods_state, - &self.resource_packs_state, - &self.shaders_state, - &self.world_datapacks_state, - ] - .iter() - .any(|state| state.is_scanning()) - { + if self.content_update_check_ready() { self.content_update_check_pending = false; if crate::config::SETTINGS.read().general.check_content_updates { self.spawn_selected_content_update_check(); @@ -423,7 +414,9 @@ impl App { let Some(mut result) = result else { return; }; - self.reconciliation_for = Some((result.instance_name.clone(), result.instance_created)); + if result.complete { + self.reconciliation_for = Some((result.instance_name.clone(), result.instance_created)); + } if let Some(error) = &result.error { tracing::warn!( "Content reconciliation for {} was incomplete: {}", @@ -490,18 +483,30 @@ impl App { .instances_dir .join(&result.instance_name), ); - let cached = - crate::instance::content::updates::UpdateSnapshot::load(&paths.content_updates()) - .filter(|snapshot| snapshot.applies_to(&selected)); - let stale = cached + if self.content_update_snapshot.is_none() { + self.content_update_snapshot = + crate::instance::content::updates::UpdateSnapshot::load(&paths.content_updates()) + .filter(|snapshot| snapshot.applies_to(&selected)) + .map(|snapshot| (result.instance_name.clone(), snapshot)); + } + let stale = self + .content_update_snapshot .as_ref() - .is_none_or(|snapshot| snapshot.is_stale(&result.manifest)); - self.content_update_snapshot = - cached.map(|snapshot| (result.instance_name.clone(), snapshot)); + .is_none_or(|(_, snapshot)| snapshot.is_stale(&result.manifest)); + let running = crate::instance::content::updates::is_running( + &selected, + &result.manifest, + &paths.content_updates(), + ); self.content_manifest = Some((result.instance_name.clone(), result.manifest.clone())); self.apply_content_update_snapshot(); - self.content_update_check_pending = - stale && crate::config::SETTINGS.read().general.check_content_updates; + self.content_update_check_pending |= + stale && !running && crate::config::SETTINGS.read().general.check_content_updates; + } + + fn content_update_check_ready(&self) -> bool { + let active = self.active_installed_content_state(); + self.content_update_check_pending && !(active.is_scanning() && active.entries.is_empty()) } fn apply_cached_content_manifest(&mut self) { @@ -561,6 +566,15 @@ impl App { let Some(snapshot) = snapshot else { return; }; + if self + .content_manifest + .as_ref() + .is_some_and(|(name, manifest)| { + name == &snapshot.instance_name && !snapshot.snapshot.is_stale(manifest) + }) + { + self.content_update_check_pending = false; + } self.content_update_snapshot = Some((snapshot.instance_name, snapshot.snapshot)); self.apply_content_update_snapshot(); } @@ -1239,6 +1253,12 @@ impl App { } pub(super) fn forget_instance_content(&mut self, instance_name: &str) { + crate::instance::content::updates::cancel(Some( + &crate::storage::InstancePaths::new( + self.instance_manager.instances_dir.join(instance_name), + ) + .content_updates(), + )); self.settings_state .invalidate_java_cache(Some(instance_name)); self.cached_instance_content diff --git a/src/tui/input.rs b/src/tui/input.rs index 141bcb5..b70ccd2 100644 --- a/src/tui/input.rs +++ b/src/tui/input.rs @@ -2357,6 +2357,7 @@ impl App { } pub(super) fn reset_discovery_states(&mut self) { + crate::instance::content::updates::cancel(None); self.reconciliation_for = None; for cached in self.cached_instance_content.values_mut() { cached.reconciliation_for = None; @@ -2397,18 +2398,26 @@ impl App { manifest.clone(), path, self.content_update_priority(), + self.content_update_snapshot + .as_ref() + .map(|(_, snapshot)| snapshot.clone()), ); } - pub(super) fn content_update_priority(&self) -> Vec { - let active = match self.content_tab { + pub(super) fn active_installed_content_state( + &self, + ) -> &widgets::content::list::ContentListState { + match self.content_tab { widgets::content::ContentTab::ResourcePacks => &self.resource_packs_state, widgets::content::ContentTab::Shaders => &self.shaders_state, widgets::content::ContentTab::Worlds => &self.world_datapacks_state, _ => &self.mods_state, - }; + } + } + + pub(super) fn content_update_priority(&self) -> Vec { [ - active, + self.active_installed_content_state(), &self.mods_state, &self.resource_packs_state, &self.shaders_state, diff --git a/src/tui/tests/event.rs b/src/tui/tests/event.rs index 4a05dc3..f0aa413 100644 --- a/src/tui/tests/event.rs +++ b/src/tui/tests/event.rs @@ -176,6 +176,334 @@ fn partial_update_snapshots_label_rows_immediately_and_keep_inactive_results() { 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) } @@ -744,6 +1072,7 @@ fn launcher_config_save_process() { .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; From 9c54e8f3219143d2487e2e1fbb95a67460bb2a26 Mon Sep 17 00:00:00 2001 From: objz Date: Fri, 2 Oct 2026 13:16:35 +0200 Subject: [PATCH 28/34] Fix screenshot bug bash: badges, update flow, logs, opener Keep selected-row badges in their own colors, report preparing-updates progress per item, lock and cancel the checking phase, drop the redundant review badge, warn-style conflict reasons, defer busy-manifest reconciliation silently, share log level colors, filter log levels, page without snap-back scrolling, drag-to-copy log lines, and surface opener failures with the missing logs shortcut. --- Cargo.lock | 1 + Cargo.toml | 1 + src/instance/content/reconcile.rs | 52 ++- src/instance/content/updates.rs | 28 ++ src/instance/tests/content/dependencies.rs | 2 + src/instance/tests/content/reconcile.rs | 45 +++ src/tui/app.rs | 14 + src/tui/event.rs | 9 +- src/tui/input.rs | 219 +++++++++- src/tui/logging.rs | 9 +- src/tui/render.rs | 68 +++- src/tui/tests/flows.rs | 154 ++++++- src/tui/tests/harness.rs | 7 + src/tui/tests/widgets/content/list.rs | 41 ++ ...ts__update_review_reuses_content_rows.snap | 2 +- src/tui/tests/widgets/content/update.rs | 3 + src/tui/tests/widgets/logs_viewer.rs | 140 +++++++ src/tui/widgets/content/list.rs | 16 +- src/tui/widgets/content/tabs.rs | 9 +- src/tui/widgets/content/update.rs | 43 +- src/tui/widgets/logs_viewer.rs | 377 +++++++++++++++--- src/tui/widgets/popups/select_list.rs | 26 ++ src/tui/widgets/screenshots_grid.rs | 16 +- 23 files changed, 1178 insertions(+), 104 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e3c07f0..0f83cfc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3859,6 +3859,7 @@ name = "rmcl" version = "0.5.1" dependencies = [ "async-trait", + "base64", "chrono", "clap", "color-eyre", diff --git a/Cargo.toml b/Cargo.toml index 9dea4db..fadfbb8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,6 +24,7 @@ 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" diff --git a/src/instance/content/reconcile.rs b/src/instance/content/reconcile.rs index b9b11c0..f2a7f5b 100644 --- a/src/instance/content/reconcile.rs +++ b/src/instance/content/reconcile.rs @@ -9,8 +9,8 @@ use super::local::{current_fingerprint, directory_fingerprint_metadata, relative use crate::feedback::progress::{ProgressTask, ProgressTaskHandle}; use crate::instance::InstanceConfig; use crate::instance::content::manifest::{ - ContentFileRecord, ContentKind, ContentLock, ContentManifest, ProviderProject, Resolution, - fingerprint, fingerprint_metadata, + ContentFileRecord, ContentKind, ContentLock, ContentManifest, ManifestError, ProviderProject, + Resolution, fingerprint, fingerprint_metadata, }; use crate::instance::content::provider::{FingerprintQuery, ProviderRegistry}; use crate::storage::InstancePaths; @@ -224,6 +224,22 @@ pub(crate) async fn reconcile( .unwrap_or_else(|error| { Err(std::io::Error::other(format!("Content save task failed: {error}")).into()) }); + if matches!(saved, Err(ManifestError::Busy(_))) { + // Another operation (for example a reinstall commit) holds the + // manifest lock. It triggers its own reconciliation when done, + // so stay silent instead of warning on every reinstall. + tracing::debug!( + "Content reconciliation for {instance_name} deferred: manifest busy" + ); + let manifest = ContentManifest::load(&paths.content_manifest()).unwrap_or_default(); + return ReconcileResult { + instance_name, + instance_created, + manifest, + complete: true, + error: None, + }; + } let error = match (resolution_result, &saved) { (Ok(()), Ok(_)) => None, (Err(error), Ok(_)) => Some(error.to_string()), @@ -240,13 +256,31 @@ pub(crate) async fn reconcile( error, } } - Ok(Err(error)) => ReconcileResult { - instance_name, - instance_created, - manifest: ContentManifest::default(), - complete: true, - error: Some(error.to_string()), - }, + Ok(Err(error)) => { + if error + .downcast_ref::() + .is_some_and(|error| matches!(error, ManifestError::Busy(_))) + { + tracing::debug!( + "Content reconciliation for {instance_name} deferred: manifest busy" + ); + let manifest = ContentManifest::load(&paths.content_manifest()).unwrap_or_default(); + return ReconcileResult { + instance_name, + instance_created, + manifest, + complete: true, + error: None, + }; + } + ReconcileResult { + instance_name, + instance_created, + manifest: ContentManifest::default(), + complete: true, + error: Some(error.to_string()), + } + } Err(error) => ReconcileResult { instance_name, instance_created, diff --git a/src/instance/content/updates.rs b/src/instance/content/updates.rs index dd76916..327d53a 100644 --- a/src/instance/content/updates.rs +++ b/src/instance/content/updates.rs @@ -471,6 +471,7 @@ pub async fn plan_bulk( minecraft_dir: &std::path::Path, requests: Vec, conflicts: Vec, + progress: Option<&crate::feedback::progress::ProgressTaskHandle>, ) -> BulkUpdatePlan { let registry = crate::instance::content::provider::ProviderRegistry::configured( crate::net::HttpClient::new(), @@ -482,6 +483,7 @@ pub async fn plan_bulk( minecraft_dir, requests, conflicts, + progress, ) .await } @@ -493,9 +495,16 @@ pub(super) async fn plan_bulk_with_registry( minecraft_dir: &std::path::Path, mut requests: Vec, mut conflicts: Vec, + progress: Option<&crate::feedback::progress::ProgressTaskHandle>, ) -> BulkUpdatePlan { loop { let request_count = requests.len(); + if let Some(progress) = progress + && request_count > 0 + { + progress.set_progress(0, request_count as u64); + } + let mut completed = 0; let projected_manifest = project_updates(manifest, minecraft_dir, &requests); let mut accepted = Vec::new(); let mut survivors = Vec::new(); @@ -505,6 +514,13 @@ pub(super) async fn plan_bulk_with_registry( optional_dependencies: 0, }; for request in requests { + if let Some(progress) = progress { + progress.set_sub_action(format!( + "Checking {} ({}/{request_count})", + request.title, + completed + 1 + )); + } let root = InstallRoot { provider: request.update.installed.provider.clone(), project_id: request.update.installed.project_id.clone(), @@ -541,6 +557,10 @@ pub(super) async fn plan_bulk_with_registry( installed_path: request.installed_path, reason: error.to_string(), }); + completed += 1; + if let Some(progress) = progress { + progress.set_progress(completed, request_count as u64); + } continue; } }; @@ -562,11 +582,19 @@ pub(super) async fn plan_bulk_with_registry( installed_path: request.installed_path, reason: error.to_string(), }); + completed += 1; + if let Some(progress) = progress { + progress.set_progress(completed, request_count as u64); + } continue; } } accepted.push(plan); survivors.push(request); + completed += 1; + if let Some(progress) = progress { + progress.set_progress(completed, request_count as u64); + } } if survivors.len() != request_count { requests = survivors; diff --git a/src/instance/tests/content/dependencies.rs b/src/instance/tests/content/dependencies.rs index abce1a5..3dc0eaa 100644 --- a/src/instance/tests/content/dependencies.rs +++ b/src/instance/tests/content/dependencies.rs @@ -1709,6 +1709,7 @@ async fn rejected_bulk_roots_are_removed_from_survivor_projections() { minecraft, requests, Vec::new(), + None, ) .await; assert_eq!(plan.roots.len(), 1); @@ -1763,6 +1764,7 @@ async fn accepted_bulk_dependencies_keep_actual_old_ownership_and_replace_files( &minecraft, requests, Vec::new(), + None, ) .await; assert!(plan.conflicts.is_empty()); diff --git a/src/instance/tests/content/reconcile.rs b/src/instance/tests/content/reconcile.rs index 1bfd798..e4bb784 100644 --- a/src/instance/tests/content/reconcile.rs +++ b/src/instance/tests/content/reconcile.rs @@ -144,6 +144,51 @@ fn job(name: &str) -> ReconcileJob { } } +#[tokio::test] +async fn busy_manifest_defers_reconciliation_without_an_error() { + let temp = tempfile::tempdir().unwrap(); + let instances_dir = temp.path().join("instances"); + let paths = crate::storage::InstancePaths::new(instances_dir.join("Busy")); + let path = paths.minecraft().join("mods/example.jar"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, b"example").unwrap(); + let mut record = resolved_record(); + record.relative_path = PathBuf::from("mods/example.jar"); + record.fingerprint = fingerprint(&path).unwrap(); + ContentManifest { + version: 1, + files: vec![record], + } + .save(&paths.content_manifest()) + .unwrap(); + // Hold the manifest lock the way an install commit does. + let _lock = ContentLock::acquire(&paths.content_manifest()).unwrap(); + assert!( + reconcile_inventory( + &paths.content_manifest(), + &paths.minecraft(), + 24, + 512, + &NoopProgress, + ) + .is_err() + ); + + let task = crate::feedback::progress::ProgressTask::start("test reconcile"); + let result = super::reconcile( + job("Busy").instance, + instances_dir, + crate::net::HttpClient::new(), + &task, + |_| {}, + ) + .await; + + assert!(result.complete); + assert!(result.error.is_none()); + assert_eq!(result.manifest.files.len(), 1); +} + #[test] fn coordinator_queues_instances_once_and_preserves_order() { let mut coordinator = ReconcileCoordinator::default(); diff --git a/src/tui/app.rs b/src/tui/app.rs index 3c3275f..01971ca 100644 --- a/src/tui/app.rs +++ b/src/tui/app.rs @@ -48,6 +48,13 @@ pub struct App { pub(super) instance_manager: InstanceManager, pub(super) log_overlay_scroll: usize, pub(super) log_overlay_max_scroll: usize, + pub(super) log_overlay_page: usize, + pub(super) log_filter_open: bool, + pub(super) log_filter_selected: usize, + pub(super) log_hidden_levels: Vec, + pub(super) log_selection: Option<(usize, usize)>, + pub(super) log_selecting: bool, + pub(super) log_overlay_inner: ratatui::layout::Rect, pub(super) log_overlay_search: widgets::search::SearchState, pub(super) log_overlay_scrollbar: ratatui::widgets::ScrollbarState, pub(super) throbber_state: throbber_widgets_tui::ThrobberState, @@ -237,6 +244,13 @@ impl App { instance_manager: manager, log_overlay_scroll: 0, log_overlay_max_scroll: 0, + log_overlay_page: 0, + log_filter_open: false, + log_filter_selected: 0, + log_hidden_levels: Vec::new(), + log_selection: None, + log_selecting: false, + 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(), diff --git a/src/tui/event.rs b/src/tui/event.rs index d619e63..5a81831 100644 --- a/src/tui/event.rs +++ b/src/tui/event.rs @@ -57,8 +57,9 @@ impl App { .selected_instance() .map(|instance| instance.name.as_str()) != Some(update.instance_name.as_str()) - }) { - self.content_update_popup = None; + }) && let Some(popup) = self.content_update_popup.take() + { + popup.cancel(); } let content_update_completed = self.content_update_popup.as_mut().and_then(|update| { update.drain(); @@ -1272,7 +1273,9 @@ impl App { } super::app::CachedInstanceContent::default().swap(self); self.content_for = None; - self.content_update_popup = None; + if let Some(popup) = self.content_update_popup.take() { + popup.cancel(); + } self.provider_conflict = None; } diff --git a/src/tui/input.rs b/src/tui/input.rs index b70ccd2..7600b5d 100644 --- a/src/tui/input.rs +++ b/src/tui/input.rs @@ -24,6 +24,9 @@ impl App { } return; } + if self.handle_log_selection_mouse(event) { + return; + } if event.kind != MouseEventKind::Down(MouseButton::Left) { return; } @@ -58,6 +61,135 @@ impl App { } } + fn handle_log_selection_mouse(&mut self, event: MouseEvent) -> bool { + use ratatui::layout::Position; + let at = Position::new(event.column, event.row); + if self.focused == FocusedArea::OverviewExpanded && !self.log_filter_open { + let area = self.log_overlay_inner; + match event.kind { + MouseEventKind::Down(MouseButton::Left) => { + if area.is_empty() || !area.contains(at) { + return false; + } + let count = self.overlay_filtered_lines().len(); + if count == 0 { + return false; + } + let index = (self.log_overlay_scroll + + usize::from(event.row.saturating_sub(area.y))) + .min(count - 1); + self.log_selecting = true; + self.log_selection = Some((index, index)); + true + } + MouseEventKind::Drag(MouseButton::Left) => { + if !self.log_selecting { + return false; + } + let count = self.overlay_filtered_lines().len(); + if count == 0 { + return false; + } + let relative = usize::from(event.row.saturating_sub(area.y)) + .min(usize::from(area.height.saturating_sub(1))); + let index = (self.log_overlay_scroll + relative).min(count - 1); + if let Some(selection) = self.log_selection.as_mut() { + selection.1 = index; + } + true + } + MouseEventKind::Up(MouseButton::Left) => { + if !self.log_selecting { + return false; + } + self.log_selecting = false; + true + } + _ => false, + } + } else if self.focused == FocusedArea::Content + && self.content_tab == widgets::content::ContentTab::Logs + && !self.logs_state.filter_open + { + let area = self.logs_state.viewer_area; + match event.kind { + MouseEventKind::Down(MouseButton::Left) => { + if area.is_empty() || !area.contains(at) { + return false; + } + let count = widgets::logs_viewer::filtered_viewer_line_count(&self.logs_state); + if count == 0 { + return false; + } + let index = (self.logs_state.viewer_scroll + + usize::from(event.row.saturating_sub(area.y))) + .min(count - 1); + self.logs_state.selecting = true; + self.logs_state.selection = Some((index, index)); + true + } + MouseEventKind::Drag(MouseButton::Left) => { + if !self.logs_state.selecting { + return false; + } + let count = widgets::logs_viewer::filtered_viewer_line_count(&self.logs_state); + if count == 0 { + return false; + } + let relative = usize::from(event.row.saturating_sub(area.y)) + .min(usize::from(area.height.saturating_sub(1))); + let index = (self.logs_state.viewer_scroll + relative).min(count - 1); + if let Some(selection) = self.logs_state.selection.as_mut() { + selection.1 = index; + } + true + } + MouseEventKind::Up(MouseButton::Left) => { + if !self.logs_state.selecting { + return false; + } + self.logs_state.selecting = false; + true + } + _ => false, + } + } else { + false + } + } + + fn yank_overlay_selection(&mut self) { + let Some((from, to)) = self + .log_selection + .map(|(first, second)| (first.min(second), first.max(second))) + else { + error_buffer::push_message( + tracing::Level::INFO, + "Drag across log lines to select them, then press y to copy", + ); + return; + }; + let lines = self.overlay_filtered_lines(); + if lines.is_empty() { + return; + } + let end = to.min(lines.len() - 1); + if from > end { + return; + } + match widgets::logs_viewer::copy_to_clipboard(&lines[from..=end].join("\n")) { + Some((count, false)) => error_buffer::push_message( + tracing::Level::INFO, + format!("Copied {count} line(s) to the clipboard"), + ), + Some((count, true)) => error_buffer::push_message( + tracing::Level::WARN, + format!("Copied the first {count} lines; the selection was truncated"), + ), + None => {} + } + } + pub(super) fn handle_key_event(&mut self, key_event: KeyEvent) -> color_eyre::Result<()> { if self.content_update_popup.as_ref().is_some_and(|update| { update.phase != widgets::content::update::Phase::Applying @@ -66,8 +198,9 @@ impl App { .selected_instance() .map(|instance| instance.name.as_str()) != Some(update.instance_name.as_str()) - }) { - self.content_update_popup = None; + }) && let Some(popup) = self.content_update_popup.take() + { + popup.cancel(); return Ok(()); } if self @@ -165,10 +298,40 @@ impl App { // log overlay eats all input when open, including its own search sub-mode if self.focused == FocusedArea::OverviewExpanded { + if self.log_filter_open { + match key_event.code { + KeyCode::Esc | KeyCode::Char('f') => { + self.log_filter_open = false; + } + KeyCode::Char('j') | KeyCode::Down => { + self.log_filter_selected = (self.log_filter_selected + 1).min( + crate::tui::widgets::logs_viewer::LOG_LEVEL_FILTER_ORDER.len() - 1, + ); + } + KeyCode::Char('k') | KeyCode::Up => { + self.log_filter_selected = self.log_filter_selected.saturating_sub(1); + } + KeyCode::Enter | KeyCode::Char(' ') => { + crate::tui::widgets::logs_viewer::toggle_hidden_level( + &mut self.log_hidden_levels, + self.log_filter_selected, + ); + self.log_selection = None; + self.log_overlay_scroll = 0; + } + KeyCode::Char('r') => { + self.log_hidden_levels.clear(); + } + _ => {} + } + return Ok(()); + } if self.log_overlay_search.active { match key_event.code { KeyCode::Enter => { self.log_overlay_search.confirm(); + self.log_selection = None; + self.log_overlay_scroll = 0; } KeyCode::Esc => { self.log_overlay_search.deactivate(); @@ -185,6 +348,10 @@ impl App { } match key_event.code { KeyCode::Char('O') | KeyCode::Esc => { + if self.log_selection.take().is_some() { + self.log_selecting = false; + return Ok(()); + } self.focused = self.pre_overlay_focused; self.log_overlay_search.deactivate(); return Ok(()); @@ -199,18 +366,39 @@ impl App { self.log_overlay_scroll = self.log_overlay_scroll.saturating_sub(1); return Ok(()); } - KeyCode::Char('G') => { + KeyCode::Char('G') | KeyCode::End => { self.log_overlay_scroll = self.log_overlay_max_scroll; return Ok(()); } - KeyCode::Char('g') => { + KeyCode::Char('g') | KeyCode::Home => { self.log_overlay_scroll = 0; return Ok(()); } + KeyCode::PageDown => { + let page = self.log_overlay_page.max(1); + self.log_overlay_scroll = + (self.log_overlay_scroll + page).min(self.log_overlay_max_scroll); + return Ok(()); + } + KeyCode::PageUp => { + let page = self.log_overlay_page.max(1); + self.log_overlay_scroll = self.log_overlay_scroll.saturating_sub(page); + return Ok(()); + } KeyCode::Char('/') => { self.log_overlay_search.activate(); return Ok(()); } + KeyCode::Char('f') => { + self.log_filter_open = true; + self.log_filter_selected = 0; + return Ok(()); + } + KeyCode::Char('y') => { + self.log_selecting = false; + self.yank_overlay_selection(); + return Ok(()); + } _ => { return Ok(()); } @@ -1088,8 +1276,12 @@ impl App { .instances_dir .join(&instance.name) .join(crate::storage::MINECRAFT_DIR_NAME); - if let Err(e) = open::that_detached(&dir) { - tracing::error!("Failed to open instance directory: {}", e); + if let Err(error) = open::that_detached(&dir) { + tracing::error!("Failed to open instance directory: {}", error); + error_buffer::push_message( + tracing::Level::ERROR, + format!("Could not open {}: {error}", dir.display()), + ); } } } @@ -1521,15 +1713,14 @@ impl App { { return; } - let state = widgets::content::update::State::checking( + let mut state = widgets::content::update::State::checking( instance.name.clone(), kind, target_world.clone(), source_entries, ); let pending = state.pending.clone(); - self.content_update_popup = Some(state); - tokio::spawn(async move { + let task = tokio::spawn(async move { let progress = crate::feedback::progress::ProgressTask::start("Preparing updates"); let snapshot = cached_snapshot.expect("checked above"); let target_directory = target_world @@ -1581,6 +1772,7 @@ impl App { &paths.minecraft(), requests, conflicts, + Some(&progress.handle()), ) .await; progress.finish(); @@ -1591,6 +1783,8 @@ impl App { crate::feedback::request_redraw(); } }); + state.abort_handle = Some(task.abort_handle()); + self.content_update_popup = Some(state); } fn handle_content_update_key(&mut self, key_event: KeyEvent) { @@ -1598,8 +1792,11 @@ impl App { return; }; match (state.phase, key_event.code) { - (widgets::content::update::Phase::Checking, KeyCode::Esc) - | (widgets::content::update::Phase::Review, KeyCode::Esc) + (widgets::content::update::Phase::Checking, KeyCode::Esc) => { + state.cancel(); + self.content_update_popup = None; + } + (widgets::content::update::Phase::Review, KeyCode::Esc) | (widgets::content::update::Phase::Conflicts, KeyCode::Esc) => { self.content_update_popup = None; } diff --git a/src/tui/logging.rs b/src/tui/logging.rs index 31eac30..881625b 100644 --- a/src/tui/logging.rs +++ b/src/tui/logging.rs @@ -27,7 +27,14 @@ pub fn get_app_logs() -> Vec { APP_LOG_LINES.lock().map(|l| l.clone()).unwrap_or_default() } -fn push_app_log(line: String) { +#[cfg(test)] +pub(crate) fn clear_app_logs() { + if let Ok(mut lines) = APP_LOG_LINES.lock() { + lines.clear(); + } +} + +pub(crate) fn push_app_log(line: String) { if let Ok(mut lines) = APP_LOG_LINES.lock() { lines.push(line); if lines.len() > 5000 { diff --git a/src/tui/render.rs b/src/tui/render.rs index 88e2df2..d2e671a 100644 --- a/src/tui/render.rs +++ b/src/tui/render.rs @@ -217,9 +217,18 @@ impl App { } } + 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| { + !super::widgets::logs_viewer::level_hidden(&self.log_hidden_levels, 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}, @@ -233,15 +242,13 @@ 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); + self.log_overlay_page = visible_height; + // 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 { self.log_overlay_scroll = self.log_overlay_max_scroll; @@ -250,17 +257,28 @@ impl App { ratatui::widgets::ScrollbarState::new(self.log_overlay_max_scroll) .position(self.log_overlay_scroll); + let title = if self.log_hidden_levels.is_empty() { + " Logs ".to_owned() + } else { + format!(" Logs · {} hidden ", self.log_hidden_levels.len()) + }; 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(&[ + ("O", " close"), + ("f", " filter"), + ("y", " copy"), + ("PgUp/PgDn", " page"), + ("/", " search"), + ]) + .alignment(Alignment::Right), ) .border_type(BORDER_STYLE.to_border_type()) .border_style(Style::default().fg(theme.accent())) @@ -272,22 +290,22 @@ impl App { let inner = block.inner(overlay); frame.render_widget(block, overlay); + self.log_overlay_inner = inner; let search = &self.log_overlay_search; + let selected = self + .log_selection + .map(|(from, to)| (from.min(to), from.max(to))); 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()) - }; + .map(|(index, line)| { + let mut style = super::widgets::logs_viewer::line_level_style(line); + if selected.is_some_and(|(from, to)| index >= from && index <= to) { + style = style.add_modifier(Modifier::REVERSED); + } search.highlight_line(line, style) }) .collect(); @@ -305,6 +323,14 @@ impl App { scrollbar_area, &mut self.log_overlay_scrollbar, ); + if self.log_filter_open { + super::widgets::logs_viewer::render_level_filter( + frame, + overlay, + self.log_filter_selected, + &self.log_hidden_levels, + ); + } } fn sync_error_effects(&mut self, events: &[error_buffer::ErrorEvent]) { diff --git a/src/tui/tests/flows.rs b/src/tui/tests/flows.rs index 61949c1..be119dd 100644 --- a/src/tui/tests/flows.rs +++ b/src/tui/tests/flows.rs @@ -1,7 +1,7 @@ // 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; @@ -772,6 +772,158 @@ fn switching_instances_discards_another_instances_update_review() { 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_pages_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, 0); + ui.key(KeyCode::PageDown); + assert_eq!(ui.app.log_overlay_scroll, 14); + 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_toggles_and_closes() { + use crate::instance::launch::parser::LogLevel; + let mut ui = UiHarness::new(); + ui.app.focused = FocusedArea::OverviewExpanded; + + ui.key(KeyCode::Char('f')); + assert!(ui.app.log_filter_open); + ui.draw(); + assert!(ui.screen().contains("Log levels")); + ui.key(KeyCode::Enter); + assert_eq!(ui.app.log_hidden_levels, vec![LogLevel::Error]); + ui.draw(); + assert!(ui.screen().contains("1 hidden")); + ui.key(KeyCode::Esc); + assert!(!ui.app.log_filter_open); + assert_eq!(ui.app.log_hidden_levels, vec![LogLevel::Error]); +} + +#[test] +fn mouse_drag_selects_viewer_lines_for_yank() { + 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(); + 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)); + 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, Some((0, 1))); + assert!(!ui.app.logs_state.selecting); +} + +#[test] +fn mouse_drag_selects_overlay_lines_for_yank() { + 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, Some((0, 2))); + ui.key(KeyCode::Char('y')); + assert!( + crate::feedback::errors::peek_all_errors() + .iter() + .any(|event| event.message.contains("Copied 3 line(s)")) + ); + clear_app_logs(); +} + #[test] fn settings_panel_routes_legacy_edit_keys_to_tui_popups() { let mut ui = UiHarness::new(); diff --git a/src/tui/tests/harness.rs b/src/tui/tests/harness.rs index 63c2ce3..d5b9f2d 100644 --- a/src/tui/tests/harness.rs +++ b/src/tui/tests/harness.rs @@ -106,6 +106,13 @@ impl UiHarness { instance_manager, log_overlay_scroll: 0, log_overlay_max_scroll: 0, + log_overlay_page: 0, + log_filter_open: false, + log_filter_selected: 0, + log_hidden_levels: Vec::new(), + log_selection: None, + log_selecting: false, + 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(), diff --git a/src/tui/tests/widgets/content/list.rs b/src/tui/tests/widgets/content/list.rs index c3b1d6e..2d76624 100644 --- a/src/tui/tests/widgets/content/list.rs +++ b/src/tui/tests/widgets/content/list.rs @@ -1204,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"); 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/update.rs b/src/tui/tests/widgets/content/update.rs index 3d2b4f6..7aa35c2 100644 --- a/src/tui/tests/widgets/content/update.rs +++ b/src/tui/tests/widgets/content/update.rs @@ -89,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] @@ -118,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/logs_viewer.rs b/src/tui/tests/widgets/logs_viewer.rs index e227dea..88207eb 100644 --- a/src/tui/tests/widgets/logs_viewer.rs +++ b/src/tui/tests/widgets/logs_viewer.rs @@ -49,6 +49,78 @@ fn list_and_viewer_navigation_loads_and_scrolls_the_selected_log() { 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_pages_by_visible_height() { + let mut state = LogsState { + viewer_focused: true, + viewer_max_scroll: 30, + viewer_page: 10, + ..Default::default() + }; + let page = |code| KeyEvent::new(code, KeyModifiers::NONE); + assert!(handle_key(&page(KeyCode::PageDown), &mut state)); + assert_eq!(state.viewer_scroll, 10); + assert!(handle_key(&page(KeyCode::PageDown), &mut state)); + assert_eq!(state.viewer_scroll, 20); + assert!(handle_key(&page(KeyCode::PageUp), &mut state)); + assert_eq!(state.viewer_scroll, 10); + 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_the_selected_viewer_lines() { + let mut state = LogsState { + viewer_lines: vec!["first".to_owned(), "second".to_owned(), "third".to_owned()], + selection: Some((2, 0)), + ..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("Copied 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("[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(); @@ -103,3 +175,71 @@ fn rescans_and_runtime_changes_keep_the_selected_log_and_viewer_in_sync() { assert_eq!(state.viewer_lines, ["newer content"]); assert_eq!(state.selected_path, Some(newer.path)); } + +#[test] +fn unclassified_lines_have_no_level_and_are_never_filtered() { + 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) + ); + assert!(!level_hidden(&[LogLevel::Debug], "just some output")); +} + +#[test] +fn level_filter_panel_toggles_resets_and_closes() { + use crate::instance::launch::parser::LogLevel; + 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.hidden_levels, vec![LogLevel::Error]); + assert!(handle_key(&press(KeyCode::Char('j')), &mut state)); + assert!(handle_key(&press(KeyCode::Enter), &mut state)); + assert_eq!(state.hidden_levels, vec![LogLevel::Error, LogLevel::Warn]); + assert!(handle_key(&press(KeyCode::Enter), &mut state)); + assert_eq!(state.hidden_levels, vec![LogLevel::Error]); + assert!(handle_key(&press(KeyCode::Char('r')), &mut state)); + assert!(state.hidden_levels.is_empty()); + assert!(handle_key(&press(KeyCode::Esc), &mut state)); + assert!(!state.filter_open); +} + +#[test] +fn level_filter_hides_matching_lines_but_keeps_unclassified_ones() { + use crate::instance::launch::parser::LogLevel; + 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.hidden_levels.push(LogLevel::Debug); + let shown = rendered(&mut state); + assert!(!shown.contains("fetching versions")); + assert!(shown.contains("done")); + assert!(shown.contains("plain line")); +} diff --git a/src/tui/widgets/content/list.rs b/src/tui/widgets/content/list.rs index 8a389af..1ffdbfd 100644 --- a/src/tui/widgets/content/list.rs +++ b/src/tui/widgets/content/list.rs @@ -276,6 +276,7 @@ pub struct ContentListState { images_dirty: bool, display_metadata: HashMap, pub search: crate::tui::widgets::search::SearchState, + pub warning_descriptions: bool, filter_search: bool, sort_metadata: RefCell>, filtered_cache: RefCell>, @@ -329,6 +330,7 @@ impl Default for ContentListState { images_dirty: true, display_metadata: HashMap::new(), search: crate::tui::widgets::search::SearchState::default(), + warning_descriptions: false, filter_search: true, sort_metadata: RefCell::new(HashMap::new()), filtered_cache: RefCell::new(None), @@ -2003,9 +2005,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 } @@ -2089,6 +2095,7 @@ pub fn render( let local_game_version = state.local_game_version.clone(); 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| { @@ -2119,7 +2126,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()) @@ -2149,6 +2156,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) diff --git a/src/tui/widgets/content/tabs.rs b/src/tui/widgets/content/tabs.rs index 6c099bf..589aafb 100644 --- a/src/tui/widgets/content/tabs.rs +++ b/src/tui/widgets/content/tabs.rs @@ -453,6 +453,9 @@ pub fn render( if logs_state.viewer_focused { &[ ("j/k", " scroll"), + ("PgUp/PgDn", " page"), + ("f", " filter"), + ("y", " copy"), ("g/G", " top/bottom"), ("d", " delete"), ("Esc", " back"), @@ -464,6 +467,8 @@ pub fn render( ("j/k", " navigate"), ("⏎", " view"), ("d", " delete"), + ("Shift+⏎", " open dir"), + ("f", " filter"), ("h/l", " tabs"), ("/", " search"), ("Tab", " discovery"), @@ -1624,7 +1629,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, diff --git a/src/tui/widgets/content/update.rs b/src/tui/widgets/content/update.rs index b5702c6..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; @@ -39,6 +41,7 @@ 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, } @@ -60,6 +63,7 @@ impl State { target_world, completed: false, applied: false, + abort_handle: None, list: super::list::ContentListState::default(), source_entries: entries .into_iter() @@ -68,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::>(), @@ -116,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 { @@ -164,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(), @@ -175,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); } @@ -211,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/logs_viewer.rs b/src/tui/widgets/logs_viewer.rs index 571d4f2..7fdf76c 100644 --- a/src/tui/widgets/logs_viewer.rs +++ b/src/tui/widgets/logs_viewer.rs @@ -29,6 +29,13 @@ pub struct LogsState { pub viewer_lines: Vec, pub viewer_scroll: usize, pub viewer_max_scroll: usize, + pub viewer_page: usize, + pub filter_open: bool, + pub filter_selected: usize, + pub hidden_levels: Vec, + pub selection: Option<(usize, usize)>, + pub selecting: bool, + pub viewer_area: Rect, pub scrollbar_state: ScrollbarState, pub viewer_scrollbar_state: ScrollbarState, pub search: super::search::SearchState, @@ -51,6 +58,13 @@ impl Default for LogsState { viewer_lines: Vec::new(), viewer_scroll: 0, viewer_max_scroll: 0, + viewer_page: 0, + filter_open: false, + filter_selected: 0, + hidden_levels: Vec::new(), + selection: None, + selecting: false, + viewer_area: Rect::default(), scrollbar_state: ScrollbarState::default(), viewer_scrollbar_state: ScrollbarState::default(), search: super::search::SearchState::default(), @@ -306,11 +320,37 @@ 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 { + match key_event.code { + KeyCode::Esc | KeyCode::Char('f') => { + state.filter_open = false; + } + KeyCode::Char('j') | KeyCode::Down => { + state.filter_selected = + (state.filter_selected + 1).min(LOG_LEVEL_FILTER_ORDER.len() - 1); + } + KeyCode::Char('k') | KeyCode::Up => { + state.filter_selected = state.filter_selected.saturating_sub(1); + } + KeyCode::Enter | KeyCode::Char(' ') => { + toggle_hidden_level(&mut state.hidden_levels, state.filter_selected); + state.selection = None; + state.viewer_scroll = 0; + } + KeyCode::Char('r') => { + state.hidden_levels.clear(); + } + _ => {} + } + return true; + } + if state.viewer_focused { if state.viewer_search.active { match key_event.code { KeyCode::Enter => { state.viewer_search.confirm(); + state.selection = None; state.viewer_scroll = 0; } KeyCode::Esc => { @@ -336,6 +376,12 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool { 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 { @@ -351,22 +397,43 @@ 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::PageDown => { + state.viewer_scroll = + (state.viewer_scroll + state.viewer_page.max(1)).min(state.viewer_max_scroll); + state.viewer_scrollbar_state = + ScrollbarState::new(state.viewer_max_scroll).position(state.viewer_scroll); + true + } + KeyCode::PageUp => { + state.viewer_scroll = state.viewer_scroll.saturating_sub(state.viewer_page.max(1)); + state.viewer_scrollbar_state = + ScrollbarState::new(state.viewer_max_scroll).position(state.viewer_scroll); + true + } KeyCode::Esc => { + if state.selection.take().is_some() { + return true; + } state.viewer_focused = false; true } + KeyCode::Char('y') => { + state.selecting = false; + yank_viewer_selection(state); + true + } KeyCode::Char('H') | KeyCode::Left if shift => { state.viewer_focused = false; true @@ -378,6 +445,7 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool { match key_event.code { KeyCode::Enter => { state.search.confirm(); + state.selection = None; state.list_state.selected = Some(0); state.load_selected_content(); state.update_scrollbar(); @@ -412,6 +480,12 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool { 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 => { @@ -431,6 +505,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 @@ -439,6 +528,15 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool { state.viewer_focused = true; true } + KeyCode::Esc if state.selection.is_some() => { + state.selection = None; + true + } + KeyCode::Char('y') => { + state.selecting = false; + yank_viewer_selection(state); + true + } _ => false, } } @@ -565,9 +663,126 @@ fn render_list(frame: &mut Frame, area: Rect, state: &mut LogsState, is_focused: fn render_viewer(frame: &mut Frame, area: Rect, state: &mut LogsState) { let theme = THEME.as_ref(); + 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; + state.viewer_page = visible_height; + // 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.viewer_scroll = state.viewer_max_scroll; + state.viewer_scrollbar_state = + ScrollbarState::new(state.viewer_max_scroll).position(state.viewer_scroll); + } + + if lines.is_empty() { + if state.filter_open { + render_level_filter(frame, area, state.filter_selected, &state.hidden_levels); + } + return; + } + + let search = &state.viewer_search; + let selected = state.selection.map(ordered_selection); + let styled_lines: Vec = lines + .iter() + .enumerate() + .skip(state.viewer_scroll) + .take(visible_height) + .map(|(index, line)| { + let mut style = line + .level + .map(log_level_style) + .unwrap_or_else(|| line_level_style(&line.text)); + if selected.is_some_and(|(from, to)| index >= from && index <= to) { + style = style.add_modifier(Modifier::REVERSED); + } + search.highlight_line(&line.text, style) + }) + .collect(); + + frame.render_widget(Paragraph::new(styled_lines), area); + + if state.filter_open { + render_level_filter(frame, area, state.filter_selected, &state.hidden_levels); + } + + 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 + } +} + +/// Whether a line is hidden by the level filter. Lines without a +/// recognizable level are always shown. +pub(crate) fn level_hidden(hidden: &[LogLevel], text: &str) -> bool { + level_of_line(text).is_some_and(|level| hidden.contains(&level)) +} + +pub(crate) fn toggle_hidden_level(hidden: &mut Vec, selected: usize) { + if let Some(level) = LOG_LEVEL_FILTER_ORDER.get(selected) { + if hidden.contains(level) { + hidden.retain(|kept| kept != level); + } else { + hidden.push(*level); + } + } +} + +fn ordered_selection(selection: (usize, usize)) -> (usize, usize) { + (selection.0.min(selection.1), selection.0.max(selection.1)) +} + +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() @@ -584,56 +799,126 @@ fn render_viewer(frame: &mut Frame, area: Rect, state: &mut LogsState) { .map(|text| ViewerLine { text, level: None }) .collect() }; + all_lines + .into_iter() + .filter(|line| state.viewer_search.matches(&line.text)) + .filter(|line| match line.level { + Some(level) => !state.hidden_levels.contains(&level), + None => !level_hidden(&state.hidden_levels, &line.text), + }) + .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); - } +pub(crate) fn filtered_viewer_line_count(state: &LogsState) -> usize { + filtered_viewer_lines(state).len() +} +pub(crate) fn yank_viewer_selection(state: &mut LogsState) { + let Some(selection) = state.selection.map(ordered_selection) else { + crate::feedback::errors::push_message( + tracing::Level::INFO, + "Drag across log lines to select them, then press y to copy", + ); + return; + }; + let lines = filtered_viewer_lines(state); if lines.is_empty() { return; } - - let search = &state.viewer_search; - let styled_lines: Vec = lines + let end = selection.1.min(lines.len() - 1); + if selection.0 > end { + return; + } + let text = lines[selection.0..=end] .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)), - ) + .map(|line| line.text.as_str()) + .collect::>() + .join("\n"); + match copy_to_clipboard(&text) { + Some((count, false)) => crate::feedback::errors::push_message( + tracing::Level::INFO, + format!("Copied {count} line(s) to the clipboard"), + ), + Some((count, true)) => crate::feedback::errors::push_message( + tracing::Level::WARN, + format!("Copied 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.lines().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].join("\n")); + let sequence = format!("\x1b]52;c;{encoded}\x07"); + use std::io::Write; + std::io::stdout() + .write_all(sequence.as_bytes()) + .and_then(|_| std::io::stdout().flush()) + .ok()?; + Some((count, truncated)) +} + +pub(crate) fn render_level_filter( + frame: &mut Frame, + area: Rect, + selected: usize, + hidden: &[LogLevel], +) { + use ratatui::layout::Constraint; + use ratatui::widgets::Widget; + let theme = THEME.as_ref(); + let popup = area.centered(Constraint::Length(26), Constraint::Length(9)); + let rows = LOG_LEVEL_FILTER_ORDER + .iter() + .enumerate() + .map(|(index, level)| { + let marker = if hidden.contains(level) { "[ ]" } else { "[x]" }; + let prefix = if index == selected { "▶ " } else { " " }; + Line::from(vec![ + Span::styled( + prefix, + Style::default().fg(if index == selected { + theme.accent() + } else { + theme.text() + }), + ), + Span::styled( + format!("{marker} {}", level_label(*level)), + Style::default().fg(theme.text()), + ), + ]) }) - .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), + .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(super::popups::keybind_line(&[ + ("Enter", " toggle"), + ("r", " reset"), + ("Esc", " close"), + ])), + search_line: None, + content: Box::new(move |area, buffer| { + Paragraph::new(rows.clone()).render(area, buffer); + }), }; - frame.render_stateful_widget( - super::scrollbar(theme.accent()), - scrollbar_area, - &mut state.viewer_scrollbar_state, - ); + frame.render_widget(frame_widget, popup); } struct ViewerLine { @@ -651,7 +936,7 @@ fn log_level_style(level: LogLevel) -> Style { } } -fn line_level_style(line: &str) -> Style { +pub(crate) 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]") { diff --git a/src/tui/widgets/popups/select_list.rs b/src/tui/widgets/popups/select_list.rs index fcfa8a5..ca65dc2 100644 --- a/src/tui/widgets/popups/select_list.rs +++ b/src/tui/widgets/popups/select_list.rs @@ -89,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/screenshots_grid.rs b/src/tui/widgets/screenshots_grid.rs index cbe2c5f..ebd3607 100644 --- a/src/tui/widgets/screenshots_grid.rs +++ b/src/tui/widgets/screenshots_grid.rs @@ -290,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 } @@ -300,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 } From 8adadf75a866447f5b3b9ef942935bc958c42a43 Mon Sep 17 00:00:00 2001 From: objz Date: Fri, 2 Oct 2026 13:45:12 +0200 Subject: [PATCH 29/34] Fix discovery version popup dead end on filtered empty results When a filtered versions fetch comes back empty, retry unfiltered and open the Minecraft version picker instead of showing No compatible versions found. --- src/tui/input.rs | 107 +++++++++++++-------- src/tui/tests/widgets/content/discovery.rs | 62 ++++++++++++ src/tui/widgets/content/discovery.rs | 59 ++++++++++++ 3 files changed, 187 insertions(+), 41 deletions(-) diff --git a/src/tui/input.rs b/src/tui/input.rs index 7600b5d..18847ef 100644 --- a/src/tui/input.rs +++ b/src/tui/input.rs @@ -2026,49 +2026,66 @@ impl App { let registry = crate::instance::content::provider::ProviderRegistry::configured( crate::net::HttpClient::new(), ); + let primary_version = if request.game_version_overrides.len() == 1 { + request.game_version_overrides[0].clone() + } else if request.all_game_versions { + String::new() + } else { + instance.game_version.clone() + }; + let current_version_id = request.current_version_id.clone(); + let mut fallback = false; let result = match registry.get(&request.provider) { - Some(provider) => match provider - .compatible_versions( + Some(provider) => { + let mut primary = widgets::content::discovery::fetch_popup_versions( + provider, &request.project_id, kind, - if request.game_version_overrides.len() == 1 { - &request.game_version_overrides[0] - } else if request.all_game_versions { - "" - } else { - &instance.game_version - }, + &primary_version, instance.loader, + current_version_id.as_deref(), ) - .await - { - Ok(mut versions) => { - if request.game_version_overrides.len() > 1 { - versions.retain(|version| { - version.game_versions.iter().any(|game_version| { - request.game_version_overrides.contains(game_version) - }) - }); - } - if let Some(current) = request.current_version_id.as_deref() - && !versions.iter().any(|version| version.id == current) - && let Ok(version) = provider.version(current).await - { - versions.push(version); - } - if let Ok(bytes) = serde_json::to_vec_pretty(&versions) { - let _ = crate::storage::write_atomic(&version_cache, &bytes); - } - Ok(versions) - } - Err(error) => match std::fs::read(&version_cache) - .ok() - .and_then(|bytes| serde_json::from_slice(&bytes).ok()) + .await; + if let Ok(versions) = &mut primary + && request.game_version_overrides.len() > 1 { - Some(versions) => Ok(versions), - None => Err(error.to_string()), - }, - }, + versions.retain(|version| { + version.game_versions.iter().any(|game_version| { + request.game_version_overrides.contains(game_version) + }) + }); + } + if let Ok(versions) = &primary + && let Ok(bytes) = serde_json::to_vec_pretty(versions) + { + let _ = crate::storage::write_atomic(&version_cache, &bytes); + } + match primary { + // The list facet matched but no file fits this + // version/loader: retry unfiltered so the popup offers + // the version picker instead of a dead end. + Ok(versions) if versions.is_empty() && !request.all_game_versions => { + fallback = true; + widgets::content::discovery::fetch_popup_versions( + provider, + &request.project_id, + kind, + "", + instance.loader, + current_version_id.as_deref(), + ) + .await + } + Ok(versions) => Ok(versions), + Err(error) => match std::fs::read(&version_cache) + .ok() + .and_then(|bytes| serde_json::from_slice(&bytes).ok()) + { + Some(versions) => Ok(versions), + None => Err(error), + }, + } + } None => Err(format!( "{} content provider is unavailable", request.provider @@ -2076,10 +2093,18 @@ impl App { }; widgets::content::DiscoveryState::push_action_result( &request.pending, - widgets::content::discovery::DiscoveryActionResult::Versions { - request_id: request.request_id, - project_id: request.project_id, - result, + if fallback { + widgets::content::discovery::DiscoveryActionResult::VersionsUnfiltered { + request_id: request.request_id, + project_id: request.project_id, + result, + } + } else { + widgets::content::discovery::DiscoveryActionResult::Versions { + request_id: request.request_id, + project_id: request.project_id, + result, + } }, ); }); diff --git a/src/tui/tests/widgets/content/discovery.rs b/src/tui/tests/widgets/content/discovery.rs index 69558c5..5e28b2d 100644 --- a/src/tui/tests/widgets/content/discovery.rs +++ b/src/tui/tests/widgets/content/discovery.rs @@ -423,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); diff --git a/src/tui/widgets/content/discovery.rs b/src/tui/widgets/content/discovery.rs index 3326070..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, @@ -2547,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, @@ -3016,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, From b5c680ed557b7a533b40eb010ee1239dea8957ce Mon Sep 17 00:00:00 2001 From: objz Date: Sun, 4 Oct 2026 12:12:11 +0200 Subject: [PATCH 30/34] fix(tui): refine log selection and filters, label unlinked content --- src/tui/app.rs | 12 +- src/tui/input.rs | 204 ++++------------- src/tui/render.rs | 49 +++-- src/tui/tests/flows.rs | 155 +++++++++++-- src/tui/tests/harness.rs | 6 +- src/tui/tests/widgets/content/list.rs | 86 ++++++++ src/tui/tests/widgets/log_selection.rs | 157 +++++++++++++ src/tui/tests/widgets/logs_viewer.rs | 75 +++++-- src/tui/widgets/content/list.rs | 44 +++- src/tui/widgets/content/tabs.rs | 33 ++- src/tui/widgets/log_selection.rs | 158 ++++++++++++++ src/tui/widgets/logs_viewer.rs | 291 ++++++++++++++----------- src/tui/widgets/mod.rs | 1 + 13 files changed, 906 insertions(+), 365 deletions(-) create mode 100644 src/tui/tests/widgets/log_selection.rs create mode 100644 src/tui/widgets/log_selection.rs diff --git a/src/tui/app.rs b/src/tui/app.rs index 01971ca..5bc009c 100644 --- a/src/tui/app.rs +++ b/src/tui/app.rs @@ -48,12 +48,10 @@ pub struct App { pub(super) instance_manager: InstanceManager, pub(super) log_overlay_scroll: usize, pub(super) log_overlay_max_scroll: usize, - pub(super) log_overlay_page: usize, pub(super) log_filter_open: bool, pub(super) log_filter_selected: usize, - pub(super) log_hidden_levels: Vec, - pub(super) log_selection: Option<(usize, usize)>, - pub(super) log_selecting: bool, + pub(super) log_level_filters: widgets::logs_viewer::LevelFilters, + pub(super) log_selection: widgets::log_selection::LogSelection, pub(super) log_overlay_inner: ratatui::layout::Rect, pub(super) log_overlay_search: widgets::search::SearchState, pub(super) log_overlay_scrollbar: ratatui::widgets::ScrollbarState, @@ -244,12 +242,10 @@ impl App { instance_manager: manager, log_overlay_scroll: 0, log_overlay_max_scroll: 0, - log_overlay_page: 0, log_filter_open: false, log_filter_selected: 0, - log_hidden_levels: Vec::new(), - log_selection: None, - log_selecting: false, + 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(), diff --git a/src/tui/input.rs b/src/tui/input.rs index 18847ef..1b2bf84 100644 --- a/src/tui/input.rs +++ b/src/tui/input.rs @@ -62,134 +62,43 @@ impl App { } fn handle_log_selection_mouse(&mut self, event: MouseEvent) -> bool { - use ratatui::layout::Position; - let at = Position::new(event.column, event.row); + if !matches!( + event.kind, + MouseEventKind::Down(MouseButton::Left) + | MouseEventKind::Drag(MouseButton::Left) + | MouseEventKind::Up(MouseButton::Left) + ) { + return false; + } + if self + .content_update_popup + .as_ref() + .is_some_and(widgets::content::update::State::visible) + || self.provider_conflict.is_some() + || self.modpack_versions_state.is_some() + || self.modpack_update_popup.is_some() + { + return false; + } if self.focused == FocusedArea::OverviewExpanded && !self.log_filter_open { - let area = self.log_overlay_inner; - match event.kind { - MouseEventKind::Down(MouseButton::Left) => { - if area.is_empty() || !area.contains(at) { - return false; - } - let count = self.overlay_filtered_lines().len(); - if count == 0 { - return false; - } - let index = (self.log_overlay_scroll - + usize::from(event.row.saturating_sub(area.y))) - .min(count - 1); - self.log_selecting = true; - self.log_selection = Some((index, index)); - true - } - MouseEventKind::Drag(MouseButton::Left) => { - if !self.log_selecting { - return false; - } - let count = self.overlay_filtered_lines().len(); - if count == 0 { - return false; - } - let relative = usize::from(event.row.saturating_sub(area.y)) - .min(usize::from(area.height.saturating_sub(1))); - let index = (self.log_overlay_scroll + relative).min(count - 1); - if let Some(selection) = self.log_selection.as_mut() { - selection.1 = index; - } - true - } - MouseEventKind::Up(MouseButton::Left) => { - if !self.log_selecting { - return false; - } - self.log_selecting = false; - true - } - _ => false, - } + let lines = self.overlay_filtered_lines(); + self.log_selection.handle_mouse( + event, + self.log_overlay_inner, + self.log_overlay_scroll, + &lines, + ) } else if self.focused == FocusedArea::Content && self.content_tab == widgets::content::ContentTab::Logs + && self.content_mode == widgets::content::ContentMode::Installed && !self.logs_state.filter_open { - let area = self.logs_state.viewer_area; - match event.kind { - MouseEventKind::Down(MouseButton::Left) => { - if area.is_empty() || !area.contains(at) { - return false; - } - let count = widgets::logs_viewer::filtered_viewer_line_count(&self.logs_state); - if count == 0 { - return false; - } - let index = (self.logs_state.viewer_scroll - + usize::from(event.row.saturating_sub(area.y))) - .min(count - 1); - self.logs_state.selecting = true; - self.logs_state.selection = Some((index, index)); - true - } - MouseEventKind::Drag(MouseButton::Left) => { - if !self.logs_state.selecting { - return false; - } - let count = widgets::logs_viewer::filtered_viewer_line_count(&self.logs_state); - if count == 0 { - return false; - } - let relative = usize::from(event.row.saturating_sub(area.y)) - .min(usize::from(area.height.saturating_sub(1))); - let index = (self.logs_state.viewer_scroll + relative).min(count - 1); - if let Some(selection) = self.logs_state.selection.as_mut() { - selection.1 = index; - } - true - } - MouseEventKind::Up(MouseButton::Left) => { - if !self.logs_state.selecting { - return false; - } - self.logs_state.selecting = false; - true - } - _ => false, - } + widgets::logs_viewer::handle_selection_mouse(event, &mut self.logs_state) } else { false } } - fn yank_overlay_selection(&mut self) { - let Some((from, to)) = self - .log_selection - .map(|(first, second)| (first.min(second), first.max(second))) - else { - error_buffer::push_message( - tracing::Level::INFO, - "Drag across log lines to select them, then press y to copy", - ); - return; - }; - let lines = self.overlay_filtered_lines(); - if lines.is_empty() { - return; - } - let end = to.min(lines.len() - 1); - if from > end { - return; - } - match widgets::logs_viewer::copy_to_clipboard(&lines[from..=end].join("\n")) { - Some((count, false)) => error_buffer::push_message( - tracing::Level::INFO, - format!("Copied {count} line(s) to the clipboard"), - ), - Some((count, true)) => error_buffer::push_message( - tracing::Level::WARN, - format!("Copied the first {count} lines; the selection was truncated"), - ), - None => {} - } - } - pub(super) fn handle_key_event(&mut self, key_event: KeyEvent) -> color_eyre::Result<()> { if self.content_update_popup.as_ref().is_some_and(|update| { update.phase != widgets::content::update::Phase::Applying @@ -299,38 +208,22 @@ impl App { // log overlay eats all input when open, including its own search sub-mode if self.focused == FocusedArea::OverviewExpanded { if self.log_filter_open { - match key_event.code { - KeyCode::Esc | KeyCode::Char('f') => { - self.log_filter_open = false; - } - KeyCode::Char('j') | KeyCode::Down => { - self.log_filter_selected = (self.log_filter_selected + 1).min( - crate::tui::widgets::logs_viewer::LOG_LEVEL_FILTER_ORDER.len() - 1, - ); - } - KeyCode::Char('k') | KeyCode::Up => { - self.log_filter_selected = self.log_filter_selected.saturating_sub(1); - } - KeyCode::Enter | KeyCode::Char(' ') => { - crate::tui::widgets::logs_viewer::toggle_hidden_level( - &mut self.log_hidden_levels, - self.log_filter_selected, - ); - self.log_selection = None; - self.log_overlay_scroll = 0; - } - KeyCode::Char('r') => { - self.log_hidden_levels.clear(); - } - _ => {} + if widgets::logs_viewer::handle_level_filter_key( + &key_event, + &mut self.log_filter_open, + &mut self.log_filter_selected, + &mut self.log_level_filters, + ) { + self.log_selection.clear(); + self.log_overlay_scroll = 0; } return Ok(()); } if self.log_overlay_search.active { + self.log_selection.clear(); match key_event.code { KeyCode::Enter => { self.log_overlay_search.confirm(); - self.log_selection = None; self.log_overlay_scroll = 0; } KeyCode::Esc => { @@ -348,10 +241,7 @@ impl App { } match key_event.code { KeyCode::Char('O') | KeyCode::Esc => { - if self.log_selection.take().is_some() { - self.log_selecting = false; - return Ok(()); - } + self.log_selection.clear(); self.focused = self.pre_overlay_focused; self.log_overlay_search.deactivate(); return Ok(()); @@ -374,18 +264,8 @@ impl App { self.log_overlay_scroll = 0; return Ok(()); } - KeyCode::PageDown => { - let page = self.log_overlay_page.max(1); - self.log_overlay_scroll = - (self.log_overlay_scroll + page).min(self.log_overlay_max_scroll); - return Ok(()); - } - KeyCode::PageUp => { - let page = self.log_overlay_page.max(1); - self.log_overlay_scroll = self.log_overlay_scroll.saturating_sub(page); - return Ok(()); - } KeyCode::Char('/') => { + self.log_selection.clear(); self.log_overlay_search.activate(); return Ok(()); } @@ -395,8 +275,11 @@ impl App { return Ok(()); } KeyCode::Char('y') => { - self.log_selecting = false; - self.yank_overlay_selection(); + self.log_selection.finish(); + widgets::logs_viewer::yank_selection( + &self.log_selection, + &self.overlay_filtered_lines(), + ); return Ok(()); } _ => { @@ -776,6 +659,7 @@ impl App { } else if self.focused == FocusedArea::Content { if self.content_tab == widgets::content::ContentTab::Logs { if key_event.code == KeyCode::Char('d') + && !self.logs_state.filter_open && !self.logs_state.search.active && !self.logs_state.viewer_search.active { diff --git a/src/tui/render.rs b/src/tui/render.rs index d2e671a..d70bf96 100644 --- a/src/tui/render.rs +++ b/src/tui/render.rs @@ -222,7 +222,10 @@ impl App { .into_iter() .filter(|line| self.log_overlay_search.matches(line)) .filter(|line| { - !super::widgets::logs_viewer::level_hidden(&self.log_hidden_levels, line) + widgets::logs_viewer::level_matches( + &self.log_level_filters, + widgets::logs_viewer::level_of_line(line), + ) }) .collect() } @@ -245,23 +248,34 @@ impl App { let filtered = self.overlay_filtered_lines(); let visible_height = overlay.height.saturating_sub(2) as usize; - self.log_overlay_page = visible_height; // 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 title = if self.log_hidden_levels.is_empty() { + let active_filters = self.log_level_filters.iter().flatten().count(); + let title = if active_filters == 0 { " Logs ".to_owned() } else { - format!(" Logs · {} hidden ", self.log_hidden_levels.len()) + 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(title).style( @@ -271,14 +285,7 @@ impl App { ), ) .title_bottom( - crate::tui::widgets::popups::keybind_line(&[ - ("O", " close"), - ("f", " filter"), - ("y", " copy"), - ("PgUp/PgDn", " page"), - ("/", " 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())) @@ -293,20 +300,18 @@ impl App { self.log_overlay_inner = inner; let search = &self.log_overlay_search; - let selected = self - .log_selection - .map(|(from, to)| (from.min(to), from.max(to))); let styled: Vec = filtered .iter() .enumerate() .skip(self.log_overlay_scroll) .take(visible_height) .map(|(index, line)| { - let mut style = super::widgets::logs_viewer::line_level_style(line); - if selected.is_some_and(|(from, to)| index >= from && index <= to) { - style = style.add_modifier(Modifier::REVERSED); - } - search.highlight_line(line, style) + self.log_selection.highlight_line( + index, + line, + search, + widgets::logs_viewer::line_level_style(line), + ) }) .collect(); @@ -328,7 +333,7 @@ impl App { frame, overlay, self.log_filter_selected, - &self.log_hidden_levels, + &self.log_level_filters, ); } } diff --git a/src/tui/tests/flows.rs b/src/tui/tests/flows.rs index be119dd..30aa715 100644 --- a/src/tui/tests/flows.rs +++ b/src/tui/tests/flows.rs @@ -795,7 +795,7 @@ fn checking_popup_locks_input_until_cancelled() { } #[test] -fn log_overlay_pages_and_stays_put_while_reading_history() { +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(); @@ -809,9 +809,13 @@ fn log_overlay_pages_and_stays_put_while_reading_history() { assert_eq!(ui.app.log_overlay_scroll, 14); ui.key(KeyCode::PageUp); - assert_eq!(ui.app.log_overlay_scroll, 0); + 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')); } @@ -833,26 +837,44 @@ fn log_overlay_pages_and_stays_put_while_reading_history() { } #[test] -fn log_overlay_level_filter_opens_toggles_and_closes() { - use crate::instance::launch::parser::LogLevel; +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_hidden_levels, vec![LogLevel::Error]); + assert_eq!(ui.app.log_level_filters[0], Some(CategoryFilter::Include)); ui.draw(); - assert!(ui.screen().contains("1 hidden")); + 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_hidden_levels, vec![LogLevel::Error]); + 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_lines_for_yank() { +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(); @@ -871,6 +893,7 @@ fn mouse_drag_selects_viewer_lines_for_yank() { 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 { @@ -881,16 +904,36 @@ fn mouse_drag_selects_viewer_lines_for_yank() { }; 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, Some((0, 1))); - assert!(!ui.app.logs_state.selecting); + 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_lines_for_yank() { +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(); @@ -914,16 +957,102 @@ fn mouse_drag_selects_overlay_lines_for_yank() { .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, Some((0, 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("Copied 3 line(s)")) + .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; + 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.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")); + ui.key(KeyCode::Esc); + assert!(!ui.app.logs_state.filter_open); +} + +#[test] +fn selected_unlinked_content_explains_why_versions_are_unavailable() { + 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; 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(); diff --git a/src/tui/tests/harness.rs b/src/tui/tests/harness.rs index d5b9f2d..d29cce8 100644 --- a/src/tui/tests/harness.rs +++ b/src/tui/tests/harness.rs @@ -106,12 +106,10 @@ impl UiHarness { instance_manager, log_overlay_scroll: 0, log_overlay_max_scroll: 0, - log_overlay_page: 0, log_filter_open: false, log_filter_selected: 0, - log_hidden_levels: Vec::new(), - log_selection: None, - log_selecting: false, + 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(), diff --git a/src/tui/tests/widgets/content/list.rs b/src/tui/tests/widgets/content/list.rs index 2d76624..6c3caa8 100644 --- a/src/tui/tests/widgets/content/list.rs +++ b/src/tui/tests/widgets/content/list.rs @@ -1391,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.selected_is_unlinked()); + 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.text_dim()); + assert_eq!(buffer[(x, 0)].bg, theme.surface()); + 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.selected_is_unlinked()); + } + 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/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 88207eb..05cf62a 100644 --- a/src/tui/tests/widgets/logs_viewer.rs +++ b/src/tui/tests/widgets/logs_viewer.rs @@ -58,20 +58,16 @@ fn shift_enter_without_a_selected_log_is_swallowed_without_opening() { } #[test] -fn viewer_pages_by_visible_height() { +fn viewer_ignores_page_keys_and_keeps_top_bottom_navigation() { let mut state = LogsState { viewer_focused: true, viewer_max_scroll: 30, - viewer_page: 10, ..Default::default() }; let page = |code| KeyEvent::new(code, KeyModifiers::NONE); - assert!(handle_key(&page(KeyCode::PageDown), &mut state)); - assert_eq!(state.viewer_scroll, 10); - assert!(handle_key(&page(KeyCode::PageDown), &mut state)); - assert_eq!(state.viewer_scroll, 20); - assert!(handle_key(&page(KeyCode::PageUp), &mut state)); - assert_eq!(state.viewer_scroll, 10); + 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)); @@ -79,10 +75,14 @@ fn viewer_pages_by_visible_height() { } #[test] -fn yank_copies_the_selected_viewer_lines() { +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: Some((2, 0)), + 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); @@ -90,7 +90,7 @@ fn yank_copies_the_selected_viewer_lines() { assert!( crate::feedback::errors::peek_all_errors() .iter() - .any(|event| event.message.contains("Copied 3 line(s)")) + .any(|event| event.message.contains("Yanked 3 line(s)")) ); } @@ -113,8 +113,16 @@ fn log_levels_share_one_color_mapping_in_viewer_and_overlay() { } assert_eq!( line_level_style("12:17:28:DEBUG:rmcl::net: fetching").fg, + Some(theme.info()) + ); + assert_eq!( + line_level_style("12:17:28:TRACE:rmcl::net: fetching").fg, Some(theme.text_dim()) ); + 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()) @@ -177,7 +185,7 @@ fn rescans_and_runtime_changes_keep_the_selected_log_and_viewer_in_sync() { } #[test] -fn unclassified_lines_have_no_level_and_are_never_filtered() { +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!( @@ -188,32 +196,40 @@ fn unclassified_lines_have_no_level_and_are_never_filtered() { level_of_line("tracing trace message"), Some(LogLevel::Trace) ); - assert!(!level_hidden(&[LogLevel::Debug], "just some output")); + 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_toggles_resets_and_closes() { - use crate::instance::launch::parser::LogLevel; +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.hidden_levels, vec![LogLevel::Error]); + 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.hidden_levels, vec![LogLevel::Error, LogLevel::Warn]); + assert_eq!(state.level_filters[1], Some(CategoryFilter::Include)); assert!(handle_key(&press(KeyCode::Enter), &mut state)); - assert_eq!(state.hidden_levels, vec![LogLevel::Error]); + assert_eq!(state.level_filters[1], Some(CategoryFilter::Exclude)); assert!(handle_key(&press(KeyCode::Char('r')), &mut state)); - assert!(state.hidden_levels.is_empty()); + assert_eq!(state.level_filters, [None; 5]); assert!(handle_key(&press(KeyCode::Esc), &mut state)); assert!(!state.filter_open); } #[test] fn level_filter_hides_matching_lines_but_keeps_unclassified_ones() { - use crate::instance::launch::parser::LogLevel; fn rendered(state: &mut LogsState) -> String { let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(70, 6)).unwrap(); @@ -237,9 +253,26 @@ fn level_filter_hides_matching_lines_but_keeps_unclassified_ones() { ..Default::default() }; assert!(rendered(&mut state).contains("fetching versions")); - state.hidden_levels.push(LogLevel::Debug); + 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/widgets/content/list.rs b/src/tui/widgets/content/list.rs index 1ffdbfd..6bbcf29 100644 --- a/src/tui/widgets/content/list.rs +++ b/src/tui/widgets/content/list.rs @@ -265,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, @@ -316,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, @@ -405,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 { @@ -742,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(); @@ -1178,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(), @@ -1201,11 +1222,13 @@ impl ContentListState { 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() @@ -1278,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; @@ -1626,6 +1650,12 @@ impl ContentListState { .is_some_and(|entry| entry.provider_project.is_some()) } + pub(crate) fn selected_is_unlinked(&self) -> bool { + self.selected_entry().is_some_and(|entry| { + entry.provider_project.is_none() && self.unlinked_paths.contains(&entry.path) + }) + } + pub(crate) fn clamp_selected_index(&mut self) { let count = self.filtered_indices().len(); self.list_state.selected = @@ -1828,6 +1858,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 @@ -2093,6 +2124,7 @@ 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; @@ -2109,7 +2141,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 @@ -2169,7 +2205,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") { + Style::default().fg(theme.text_dim()).bg(theme.surface()) + } 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() diff --git a/src/tui/widgets/content/tabs.rs b/src/tui/widgets/content/tabs.rs index 589aafb..94198f7 100644 --- a/src/tui/widgets/content/tabs.rs +++ b/src/tui/widgets/content/tabs.rs @@ -352,6 +352,16 @@ pub fn render( } _ => false, }; + let selected_unlinked = mode == ContentMode::Installed + && match tab { + ContentTab::Mods => mods_state.selected_is_unlinked(), + ContentTab::ResourcePacks => resource_packs_state.selected_is_unlinked(), + ContentTab::Shaders => shaders_state.selected_is_unlinked(), + ContentTab::Worlds if open_world_datapacks.is_some() => { + world_datapacks_state.selected_is_unlinked() + } + _ => false, + }; let kb: Option<&[(&str, &str)]> = if is_focused { Some(match (mode, tab) { @@ -453,9 +463,7 @@ pub fn render( if logs_state.viewer_focused { &[ ("j/k", " scroll"), - ("PgUp/PgDn", " page"), ("f", " filter"), - ("y", " copy"), ("g/G", " top/bottom"), ("d", " delete"), ("Esc", " back"), @@ -495,6 +503,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!( @@ -536,8 +551,20 @@ pub fn render( area.width.saturating_sub(2), )); - let content_area = block.inner(area); + let mut content_area = block.inner(area); frame.render_widget(block, area); + if is_focused && selected_unlinked && content_area.height > 1 { + content_area.height -= 1; + frame.render_widget( + Paragraph::new(" No online source linked; version switching unavailable.") + .style(Style::default().fg(theme.text_dim())), + Rect { + y: content_area.bottom(), + height: 1, + ..content_area + }, + ); + } let downloadable_state = match tab { ContentTab::Mods => Some((mods_state, mods_discovery_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 7fdf76c..b8cf7aa 100644 --- a/src/tui/widgets/logs_viewer.rs +++ b/src/tui/widgets/logs_viewer.rs @@ -14,10 +14,14 @@ use ratatui::{ }; 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 { @@ -29,12 +33,10 @@ pub struct LogsState { pub viewer_lines: Vec, pub viewer_scroll: usize, pub viewer_max_scroll: usize, - pub viewer_page: usize, pub filter_open: bool, pub filter_selected: usize, - pub hidden_levels: Vec, - pub selection: Option<(usize, usize)>, - pub selecting: bool, + pub(crate) level_filters: LevelFilters, + pub(crate) selection: LogSelection, pub viewer_area: Rect, pub scrollbar_state: ScrollbarState, pub viewer_scrollbar_state: ScrollbarState, @@ -58,12 +60,10 @@ impl Default for LogsState { viewer_lines: Vec::new(), viewer_scroll: 0, viewer_max_scroll: 0, - viewer_page: 0, filter_open: false, filter_selected: 0, - hidden_levels: Vec::new(), - selection: None, - selecting: false, + level_filters: [None; 5], + selection: LogSelection::default(), viewer_area: Rect::default(), scrollbar_state: ScrollbarState::default(), viewer_scrollbar_state: ScrollbarState::default(), @@ -87,6 +87,7 @@ impl LogsState { 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; @@ -240,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; @@ -255,6 +259,7 @@ impl LogsState { return; } self.selected_path = path.clone(); + self.selection.clear(); self.viewer_scroll = 0; if let Some(path) = path { @@ -309,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(); @@ -321,36 +327,24 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool { let shift = key_event.modifiers.contains(KeyModifiers::SHIFT); if state.filter_open { - match key_event.code { - KeyCode::Esc | KeyCode::Char('f') => { - state.filter_open = false; - } - KeyCode::Char('j') | KeyCode::Down => { - state.filter_selected = - (state.filter_selected + 1).min(LOG_LEVEL_FILTER_ORDER.len() - 1); - } - KeyCode::Char('k') | KeyCode::Up => { - state.filter_selected = state.filter_selected.saturating_sub(1); - } - KeyCode::Enter | KeyCode::Char(' ') => { - toggle_hidden_level(&mut state.hidden_levels, state.filter_selected); - state.selection = None; - state.viewer_scroll = 0; - } - KeyCode::Char('r') => { - state.hidden_levels.clear(); - } - _ => {} + 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(); - state.selection = None; state.viewer_scroll = 0; } KeyCode::Esc => { @@ -371,6 +365,7 @@ 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; @@ -409,28 +404,13 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool { ScrollbarState::new(state.viewer_max_scroll).position(state.viewer_scroll); true } - KeyCode::PageDown => { - state.viewer_scroll = - (state.viewer_scroll + state.viewer_page.max(1)).min(state.viewer_max_scroll); - state.viewer_scrollbar_state = - ScrollbarState::new(state.viewer_max_scroll).position(state.viewer_scroll); - true - } - KeyCode::PageUp => { - state.viewer_scroll = state.viewer_scroll.saturating_sub(state.viewer_page.max(1)); - state.viewer_scrollbar_state = - ScrollbarState::new(state.viewer_max_scroll).position(state.viewer_scroll); - true - } KeyCode::Esc => { - if state.selection.take().is_some() { - return true; - } + state.selection.clear(); state.viewer_focused = false; true } KeyCode::Char('y') => { - state.selecting = false; + state.selection.finish(); yank_viewer_selection(state); true } @@ -442,10 +422,10 @@ 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(); - state.selection = None; state.list_state.selected = Some(0); state.load_selected_content(); state.update_scrollbar(); @@ -474,6 +454,7 @@ 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(); @@ -528,12 +509,12 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool { state.viewer_focused = true; true } - KeyCode::Esc if state.selection.is_some() => { - state.selection = None; + KeyCode::Esc if state.selection.range.is_some() => { + state.selection.clear(); true } KeyCode::Char('y') => { - state.selecting = false; + state.selection.finish(); yank_viewer_selection(state); true } @@ -545,20 +526,28 @@ 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, ); + if state.filter_open { + render_level_filter(frame, area, state.filter_selected, &state.level_filters); + } return; } 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, ); + if state.filter_open { + render_level_filter(frame, area, state.filter_selected, &state.level_filters); + } return; } @@ -669,13 +658,12 @@ fn render_viewer(frame: &mut Frame, area: Rect, state: &mut LogsState) { let lines = filtered_viewer_lines(state); let visible_height = area.height as usize; - state.viewer_page = visible_height; // 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 { + 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); @@ -683,34 +671,32 @@ fn render_viewer(frame: &mut Frame, area: Rect, state: &mut LogsState) { if lines.is_empty() { if state.filter_open { - render_level_filter(frame, area, state.filter_selected, &state.hidden_levels); + render_level_filter(frame, area, state.filter_selected, &state.level_filters); } return; } let search = &state.viewer_search; - let selected = state.selection.map(ordered_selection); let styled_lines: Vec = lines .iter() .enumerate() .skip(state.viewer_scroll) .take(visible_height) .map(|(index, line)| { - let mut style = line + let style = line .level .map(log_level_style) .unwrap_or_else(|| line_level_style(&line.text)); - if selected.is_some_and(|(from, to)| index >= from && index <= to) { - style = style.add_modifier(Modifier::REVERSED); - } - search.highlight_line(&line.text, style) + state + .selection + .highlight_line(index, &line.text, search, style) }) .collect(); frame.render_widget(Paragraph::new(styled_lines), area); if state.filter_open { - render_level_filter(frame, area, state.filter_selected, &state.hidden_levels); + render_level_filter(frame, area, state.filter_selected, &state.level_filters); } let scrollbar_area = Rect { @@ -761,24 +747,41 @@ pub(crate) fn level_of_line(line: &str) -> Option { } } -/// Whether a line is hidden by the level filter. Lines without a -/// recognizable level are always shown. -pub(crate) fn level_hidden(hidden: &[LogLevel], text: &str) -> bool { - level_of_line(text).is_some_and(|level| hidden.contains(&level)) +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 toggle_hidden_level(hidden: &mut Vec, selected: usize) { - if let Some(level) = LOG_LEVEL_FILTER_ORDER.get(selected) { - if hidden.contains(level) { - hidden.retain(|kept| kept != level); - } else { - hidden.push(*level); +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; + } + _ => {} } -} - -fn ordered_selection(selection: (usize, usize)) -> (usize, usize) { - (selection.0.min(selection.1), selection.0.max(selection.1)) + false } fn filtered_viewer_lines(state: &LogsState) -> Vec { @@ -802,46 +805,47 @@ fn filtered_viewer_lines(state: &LogsState) -> Vec { all_lines .into_iter() .filter(|line| state.viewer_search.matches(&line.text)) - .filter(|line| match line.level { - Some(level) => !state.hidden_levels.contains(&level), - None => !level_hidden(&state.hidden_levels, &line.text), + .filter(|line| { + level_matches( + &state.level_filters, + line.level.or_else(|| level_of_line(&line.text)), + ) }) .collect() } -pub(crate) fn filtered_viewer_line_count(state: &LogsState) -> usize { - filtered_viewer_lines(state).len() +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 } pub(crate) fn yank_viewer_selection(state: &mut LogsState) { - let Some(selection) = state.selection.map(ordered_selection) else { - crate::feedback::errors::push_message( - tracing::Level::INFO, - "Drag across log lines to select them, then press y to copy", - ); + 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; }; - let lines = filtered_viewer_lines(state); - if lines.is_empty() { - return; - } - let end = selection.1.min(lines.len() - 1); - if selection.0 > end { - return; - } - let text = lines[selection.0..=end] - .iter() - .map(|line| line.text.as_str()) - .collect::>() - .join("\n"); match copy_to_clipboard(&text) { Some((count, false)) => crate::feedback::errors::push_message( tracing::Level::INFO, - format!("Copied {count} line(s) to the clipboard"), + format!("Yanked {count} line(s) to the clipboard"), ), Some((count, true)) => crate::feedback::errors::push_message( tracing::Level::WARN, - format!("Copied the first {count} lines; the selection was truncated"), + format!("Yanked the first {count} lines; the selection was truncated"), ), None => {} } @@ -852,19 +856,25 @@ pub(crate) fn yank_viewer_selection(state: &mut LogsState) { pub(crate) fn copy_to_clipboard(text: &str) -> Option<(usize, bool)> { use base64::Engine; const MAX_LINES: usize = 2000; - let lines: Vec<&str> = text.lines().take(MAX_LINES + 1).collect(); + 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].join("\n")); + let encoded = base64::engine::general_purpose::STANDARD.encode(lines[..count].concat()); let sequence = format!("\x1b]52;c;{encoded}\x07"); use std::io::Write; - std::io::stdout() + if let Err(error) = std::io::stdout() .write_all(sequence.as_bytes()) .and_then(|_| std::io::stdout().flush()) - .ok()?; + { + crate::feedback::errors::push_message( + tracing::Level::ERROR, + format!("Could not yank to the terminal clipboard: {error}"), + ); + return None; + } Some((count, truncated)) } @@ -872,32 +882,54 @@ pub(crate) fn render_level_filter( frame: &mut Frame, area: Rect, selected: usize, - hidden: &[LogLevel], + filters: &LevelFilters, ) { use ratatui::layout::Constraint; use ratatui::widgets::Widget; let theme = THEME.as_ref(); - let popup = area.centered(Constraint::Length(26), Constraint::Length(9)); + let keybinds = super::popups::keybind_line(&[ + ("j/k", " navigate"), + ("Enter", " toggle"), + ("r", " reset"), + ("Esc", " close"), + ]); + let popup = 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 marker = if hidden.contains(level) { "[ ]" } else { "[x]" }; - let prefix = if index == selected { "▶ " } else { " " }; + 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( - prefix, - Style::default().fg(if index == selected { - theme.accent() - } else { - theme.text() - }), + if index == selected { "▌ " } else { " " }, + Style::default().fg(theme.accent()), ), Span::styled( - format!("{marker} {}", level_label(*level)), - Style::default().fg(theme.text()), + 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 { @@ -908,11 +940,7 @@ pub(crate) fn render_level_filter( ), border_color: theme.accent(), bg: Some(theme.surface()), - keybinds: Some(super::popups::keybind_line(&[ - ("Enter", " toggle"), - ("r", " reset"), - ("Esc", " close"), - ])), + keybinds: Some(keybinds), search_line: None, content: Box::new(move |area, buffer| { Paragraph::new(rows.clone()).render(area, buffer); @@ -926,28 +954,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.info()), + LogLevel::Trace => Style::default().fg(theme.text_dim()), LogLevel::Info => Style::default().fg(theme.text()), } } pub(crate) 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()) - } + 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/mod.rs b/src/tui/widgets/mod.rs index 9ca60b1..2f11cac 100644 --- a/src/tui/widgets/mod.rs +++ b/src/tui/widgets/mod.rs @@ -12,6 +12,7 @@ use ratatui::{ pub mod account; pub mod content; pub mod instances; +pub(crate) mod log_selection; pub mod logs_viewer; pub mod markdown; pub mod popups; From 41707c8a09d4702706e72a4dc232242f5c62c84c Mon Sep 17 00:00:00 2001 From: objz Date: Sun, 4 Oct 2026 12:51:44 +0200 Subject: [PATCH 31/34] fix(tui): polish log filters and unlinked badge styling --- src/tui/render.rs | 25 +++++++++++------ src/tui/tests/flows.rs | 22 +++++++++++---- src/tui/tests/widgets/content/list.rs | 10 +++---- src/tui/tests/widgets/logs_viewer.rs | 21 +++++++++++++-- src/tui/widgets/content/list.rs | 8 +----- src/tui/widgets/content/tabs.rs | 24 +---------------- src/tui/widgets/logs_viewer.rs | 39 +++++++-------------------- 7 files changed, 70 insertions(+), 79 deletions(-) diff --git a/src/tui/render.rs b/src/tui/render.rs index d70bf96..8a211d1 100644 --- a/src/tui/render.rs +++ b/src/tui/render.rs @@ -147,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 @@ -328,14 +345,6 @@ impl App { scrollbar_area, &mut self.log_overlay_scrollbar, ); - if self.log_filter_open { - super::widgets::logs_viewer::render_level_filter( - frame, - overlay, - self.log_filter_selected, - &self.log_level_filters, - ); - } } fn sync_error_effects(&mut self, events: &[error_buffer::ErrorEvent]) { diff --git a/src/tui/tests/flows.rs b/src/tui/tests/flows.rs index 30aa715..b9ed533 100644 --- a/src/tui/tests/flows.rs +++ b/src/tui/tests/flows.rs @@ -985,6 +985,7 @@ fn mouse_drag_selects_overlay_characters_for_yank_and_escape_closes() { #[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; @@ -995,6 +996,7 @@ fn log_level_popup_does_not_delete_logs_or_leave_on_tab() { 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); @@ -1004,12 +1006,24 @@ fn log_level_popup_does_not_delete_logs_or_leave_on_tab() { 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_explains_why_versions_are_unavailable() { +fn selected_unlinked_content_shows_only_the_badge() { let mut ui = UiHarness::new(); ui.add_instance("A"); let minecraft = ui @@ -1037,10 +1051,8 @@ fn selected_unlinked_content_explains_why_versions_are_unavailable() { ui.app.focused = FocusedArea::Content; ui.draw(); assert!(ui.screen().contains("Unlinked")); - assert!( - ui.screen() - .contains("No online source linked; version switching unavailable.") - ); + 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()); diff --git a/src/tui/tests/widgets/content/list.rs b/src/tui/tests/widgets/content/list.rs index 6c3caa8..1de4e35 100644 --- a/src/tui/tests/widgets/content/list.rs +++ b/src/tui/tests/widgets/content/list.rs @@ -1424,7 +1424,7 @@ fn unlinked_badge_is_subdued_and_requires_a_completed_unmatched_lookup() { }); state.apply_manifest(&manifest, &minecraft, ContentKind::Mod); state.apply_update_snapshot(None); - assert!(state.selected_is_unlinked()); + 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(); @@ -1447,9 +1447,9 @@ fn unlinked_badge_is_subdued_and_requires_a_completed_unmatched_lookup() { 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.text_dim()); - assert_eq!(buffer[(x, 0)].bg, theme.surface()); - assert!(!buffer[(x, 0)].modifier.contains(Modifier::BOLD)); + 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 [ @@ -1471,7 +1471,7 @@ fn unlinked_badge_is_subdued_and_requires_a_completed_unmatched_lookup() { ] { manifest.files[0].resolution = resolution; state.apply_manifest(&manifest, &minecraft, ContentKind::Mod); - assert!(!state.selected_is_unlinked()); + assert!(state.unlinked_paths.is_empty()); } state.apply_manifest(&ContentManifest::default(), &minecraft, ContentKind::Mod); assert!(state.unlinked_paths.is_empty()); diff --git a/src/tui/tests/widgets/logs_viewer.rs b/src/tui/tests/widgets/logs_viewer.rs index 05cf62a..fb40706 100644 --- a/src/tui/tests/widgets/logs_viewer.rs +++ b/src/tui/tests/widgets/logs_viewer.rs @@ -113,11 +113,11 @@ fn log_levels_share_one_color_mapping_in_viewer_and_overlay() { } assert_eq!( line_level_style("12:17:28:DEBUG:rmcl::net: fetching").fg, - Some(theme.info()) + Some(theme.text_dim()) ); assert_eq!( line_level_style("12:17:28:TRACE:rmcl::net: fetching").fg, - Some(theme.text_dim()) + Some(theme.border()) ); assert_ne!( log_level_style(LogLevel::Debug).fg, @@ -228,6 +228,23 @@ fn level_filter_panel_cycles_neutral_include_exclude_resets_and_closes() { 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 { diff --git a/src/tui/widgets/content/list.rs b/src/tui/widgets/content/list.rs index 6bbcf29..f1dfd61 100644 --- a/src/tui/widgets/content/list.rs +++ b/src/tui/widgets/content/list.rs @@ -1650,12 +1650,6 @@ impl ContentListState { .is_some_and(|entry| entry.provider_project.is_some()) } - pub(crate) fn selected_is_unlinked(&self) -> bool { - self.selected_entry().is_some_and(|entry| { - entry.provider_project.is_none() && self.unlinked_paths.contains(&entry.path) - }) - } - pub(crate) fn clamp_selected_index(&mut self) { let count = self.filtered_indices().len(); self.list_state.selected = @@ -2206,7 +2200,7 @@ pub fn render( } }); let title_suffix_style = if title_suffix == Some("Unlinked") { - Style::default().fg(theme.text_dim()).bg(theme.surface()) + crate::tui::widgets::status_badge_style(theme.text_dim()) } else { crate::tui::widgets::status_badge_style(title_suffix_color) }; diff --git a/src/tui/widgets/content/tabs.rs b/src/tui/widgets/content/tabs.rs index 94198f7..8608ded 100644 --- a/src/tui/widgets/content/tabs.rs +++ b/src/tui/widgets/content/tabs.rs @@ -352,16 +352,6 @@ pub fn render( } _ => false, }; - let selected_unlinked = mode == ContentMode::Installed - && match tab { - ContentTab::Mods => mods_state.selected_is_unlinked(), - ContentTab::ResourcePacks => resource_packs_state.selected_is_unlinked(), - ContentTab::Shaders => shaders_state.selected_is_unlinked(), - ContentTab::Worlds if open_world_datapacks.is_some() => { - world_datapacks_state.selected_is_unlinked() - } - _ => false, - }; let kb: Option<&[(&str, &str)]> = if is_focused { Some(match (mode, tab) { @@ -551,20 +541,8 @@ pub fn render( area.width.saturating_sub(2), )); - let mut content_area = block.inner(area); + let content_area = block.inner(area); frame.render_widget(block, area); - if is_focused && selected_unlinked && content_area.height > 1 { - content_area.height -= 1; - frame.render_widget( - Paragraph::new(" No online source linked; version switching unavailable.") - .style(Style::default().fg(theme.text_dim())), - Rect { - y: content_area.bottom(), - height: 1, - ..content_area - }, - ); - } let downloadable_state = match tab { ContentTab::Mods => Some((mods_state, mods_discovery_state)), diff --git a/src/tui/widgets/logs_viewer.rs b/src/tui/widgets/logs_viewer.rs index b8cf7aa..5186d00 100644 --- a/src/tui/widgets/logs_viewer.rs +++ b/src/tui/widgets/logs_viewer.rs @@ -531,9 +531,6 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut LogsState, is_focused: Paragraph::new("Loading logs...").style(Style::default().fg(theme.text_dim())), area, ); - if state.filter_open { - render_level_filter(frame, area, state.filter_selected, &state.level_filters); - } return; } @@ -545,9 +542,6 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut LogsState, is_focused: Paragraph::new("No logs yet.").style(Style::default().fg(theme.text_dim())), area, ); - if state.filter_open { - render_level_filter(frame, area, state.filter_selected, &state.level_filters); - } return; } @@ -670,9 +664,6 @@ fn render_viewer(frame: &mut Frame, area: Rect, state: &mut LogsState) { } if lines.is_empty() { - if state.filter_open { - render_level_filter(frame, area, state.filter_selected, &state.level_filters); - } return; } @@ -695,10 +686,6 @@ fn render_viewer(frame: &mut Frame, area: Rect, state: &mut LogsState) { frame.render_widget(Paragraph::new(styled_lines), area); - if state.filter_open { - render_level_filter(frame, area, state.filter_selected, &state.level_filters); - } - let scrollbar_area = Rect { x: area.x + area.width.saturating_sub(0), y: area.y + 1, @@ -878,22 +865,12 @@ pub(crate) fn copy_to_clipboard(text: &str) -> Option<(usize, bool)> { Some((count, truncated)) } -pub(crate) fn render_level_filter( - frame: &mut Frame, - area: Rect, - selected: usize, - filters: &LevelFilters, -) { +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(&[ - ("j/k", " navigate"), - ("Enter", " toggle"), - ("r", " reset"), - ("Esc", " close"), - ]); - let popup = area.centered( + 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), ); @@ -943,7 +920,11 @@ pub(crate) fn render_level_filter( keybinds: Some(keybinds), search_line: None, content: Box::new(move |area, buffer| { - Paragraph::new(rows.clone()).render(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); @@ -965,8 +946,8 @@ fn log_level_style(level: LogLevel) -> Style { match level { LogLevel::Error => Style::default().fg(theme.error()), LogLevel::Warn => Style::default().fg(theme.warning()), - LogLevel::Debug => Style::default().fg(theme.info()), - 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()), } } From ad039cab05dfc45960ca8d4dbd831fa849f55902 Mon Sep 17 00:00:00 2001 From: objz Date: Sun, 4 Oct 2026 12:56:21 +0200 Subject: [PATCH 32/34] chore: add GitHub Sponsors funding link --- .github/FUNDING.yml | 1 + 1 file changed, 1 insertion(+) create mode 100644 .github/FUNDING.yml 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 From c2e039e41286181628856fef7165df42d53ef2e0 Mon Sep 17 00:00:00 2001 From: objz Date: Sun, 4 Oct 2026 13:11:24 +0200 Subject: [PATCH 33/34] feat(curseforge): enable source builds with a default API key --- README.md | 14 +++++++++++++- src/net/curseforge.rs | 15 ++++++++++++--- src/net/tests/curseforge.rs | 13 +++++++++++++ 3 files changed, 38 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index a5211f3..68fd6cf 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, MultiMC, Prism, and GTNH packs directly. Direct imports accept a file, Modrinth URL, or project slug. CurseForge requires a build-time [API key](#curseforge-api). Able to use multiple Microsoft accounts and offline accounts aswell. --- @@ -53,6 +53,18 @@ 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 `DEFAULT_API_KEY` in `src/net/curseforge.rs` +unless `CURSEFORGE_API_KEY` is set at compile time. The source default is currently +empty, so a nonempty key must be supplied to enable CurseForge. An explicitly +empty or whitespace-only override disables CurseForge, even when a default is set. + +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) diff --git a/src/net/curseforge.rs b/src/net/curseforge.rs index 48f509b..ec75c50 100644 --- a/src/net/curseforge.rs +++ b/src/net/curseforge.rs @@ -18,10 +18,19 @@ const SHADERS_CLASS_ID: u32 = 6552; const DATA_PACKS_CLASS_ID: u32 = 6945; pub const MODPACKS_CLASS_ID: u32 = 4471; +// Keys supplied for rmcl must not be reused by forks or rebranded applications +const DEFAULT_API_KEY: &str = "$2a$10$j2eThhfsaLOAJIMwP7RbwO4D/Tp2NUE16LNalqguv04T7I5jGu8H2"; + pub fn api_key() -> Option<&'static str> { - option_env!("CURSEFORGE_API_KEY") - .map(str::trim) - .filter(|key| !key.is_empty()) + select_api_key(option_env!("CURSEFORGE_API_KEY"), DEFAULT_API_KEY) +} + +fn select_api_key( + build_key: Option<&'static str>, + default_key: &'static str, +) -> Option<&'static str> { + let key = build_key.unwrap_or(default_key).trim(); + (!key.is_empty()).then_some(key) } #[derive(Debug, Deserialize)] diff --git a/src/net/tests/curseforge.rs b/src/net/tests/curseforge.rs index 614c5c3..fc1abcb 100644 --- a/src/net/tests/curseforge.rs +++ b/src/net/tests/curseforge.rs @@ -3,6 +3,19 @@ use super::*; +#[test] +fn build_key_overrides_the_default_and_empty_values_disable_curseforge() { + for (build_key, default_key, expected) in [ + (None, "", None), + (None, " default-key ", Some("default-key")), + (Some(" override-key "), "default-key", Some("override-key")), + (Some(""), "default-key", None), + (Some(" \n\t"), "default-key", None), + ] { + assert_eq!(select_api_key(build_key, default_key), expected); + } +} + #[tokio::test(start_paused = true)] async fn authenticated_requests_retry_transient_failures_with_the_api_key() { use std::sync::Arc; From 526db91665650d9eb102351543d79bb1742e213b Mon Sep 17 00:00:00 2001 From: objz Date: Sun, 4 Oct 2026 13:36:47 +0200 Subject: [PATCH 34/34] docs: refresh contribution guide and correct README details --- CONTRIBUTING.md | 108 ++++++++++++++++++++++++++++++++++-------------- README.md | 27 ++++++------ 2 files changed, 90 insertions(+), 45 deletions(-) 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/README.md b/README.md index 68fd6cf..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. CurseForge requires a build-time [API key](#curseforge-api). 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. --- @@ -55,11 +55,7 @@ Authentication is performed through Microsoft’s official services. ## CurseForge API -Git, source, and Cargo builds use `DEFAULT_API_KEY` in `src/net/curseforge.rs` -unless `CURSEFORGE_API_KEY` is set at compile time. The source default is currently -empty, so a nonempty key must be supplied to enable CurseForge. An explicitly -empty or whitespace-only override disables CurseForge, even when a default is set. - +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 @@ -147,14 +143,19 @@ settings, accounts, instances, and cached game metadata. | 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\` | +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`. + each instance has an `instance.json` for its config and a `minecraft/` directory with the actual game files. -Launcher settings can be edited from the TUI or in `config.toml`. Changes to -`instances_dir`, `meta_dir`, and `image_protocol` apply after restarting rmcl; -other launcher settings apply immediately. Omitting `java_path` enables automatic -Java selection. Global JVM arguments and environment variables are applied before -per-instance values. Instances can explicitly inherit the launcher window mode -and resolution defaults. +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] @@ -256,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. ---