From bc9299b8b7c0909c87c7e824ef9f3022472370e6 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:21:27 -0300 Subject: [PATCH 1/8] test: catch the missed mutants from the weekly run --- .cargo/mutants.toml | 8 +++ src/banner.rs | 6 +- src/cli.rs | 14 +++- src/cli_tests.rs | 55 ++++++++++++++-- src/external/download.rs | 36 ++++++++++- src/external/proton.rs | 21 ++++-- src/external/proton_scenarios_tests.rs | 32 ++++++++++ src/main.rs | 25 +++++++- src/setup/common.rs | 15 ++--- src/setup/common_tests.rs | 14 ++++ src/setup/pipeline.rs | 36 +++++------ src/steam/library.rs | 2 +- src/steam/library_tests.rs | 70 ++++++++++++++++++++ src/steam/vdf.rs | 36 ++++------- src/ui/app.rs | 20 ++++-- src/ui/app_tests.rs | 47 ++++++++++++++ src/ui/images.rs | 33 +++++++--- src/ui/motion.rs | 15 ++++- src/ui/progress.rs | 7 ++ src/ui/setup.rs | 64 ++++++++++++------- src/ui/setup_tests.rs | 88 ++++++++++++++++++++++++++ src/ui/theme.rs | 8 +++ src/ui/welcome.rs | 52 ++++++++++++--- src/ui/widgets.rs | 37 ++++++++++- 24 files changed, 622 insertions(+), 119 deletions(-) diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index 2dac307..783fb9f 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -10,10 +10,14 @@ additional_cargo_args = ["--locked"] exclude_re = [ # src/ui/widgets.rs "\\bpaint_button\\b", + "\\bpaint_choice_row\\b", "\\bpaint_toggle_row\\b", "\\bpaint_progress\\b", + # The chevron of the Back button. + "\\bback_button\\b", # src/ui/welcome.rs "\\bpaint_tile\\b", + "\\bpaint_backdrops\\b", # src/ui/theme.rs "\\bpaint_background\\b", # src/ui/motion.rs: the button press offset @@ -22,4 +26,8 @@ exclude_re = [ "\\bshow_cover\\b", "\\bspinner\\b", "in icon$", + # Equivalent mutants: no test can tell them apart from the real code. + # src/ui/images.rs: an image exactly MAX_WIDTH wide is resized to the + # same size. + "replace > with >= in decode$", ] diff --git a/src/banner.rs b/src/banner.rs index aa0fd34..644cb2b 100644 --- a/src/banner.rs +++ b/src/banner.rs @@ -50,12 +50,16 @@ mod tests { #[test] fn print_banner_formats_each_line_when_color_is_enabled() { + // console leaves out the colors when stdout is not a terminal, as in + // tests. Each test runs in its own process under nextest. + console::set_colors_enabled(true); let mut output = Vec::new(); print_banner(&mut output, true).unwrap(); let output = String::from_utf8(output).unwrap(); - assert!(!output.is_empty()); + assert_eq!(output.lines().count(), SONIC_BANNER.lines().count()); + assert!(output.lines().all(|line| line.starts_with('\x1b'))); } #[test] diff --git a/src/cli.rs b/src/cli.rs index 584b9ef..e62b68c 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -485,9 +485,17 @@ fn run_setup(args: SetupArgs, out: &mut CliOutput) -> Result<()> { } fn use_rich_prompts(args: &SetupArgs) -> bool { - std::io::stdin().is_terminal() - && std::io::stdout().is_terminal() - && !setup_is_fully_specified(args) + rich_prompts_fit( + std::io::stdin().is_terminal(), + std::io::stdout().is_terminal(), + args, + ) +} + +/// Menus need a person at a terminal on both ends, and only when the flags +/// leave a choice open. +fn rich_prompts_fit(stdin_is_terminal: bool, stdout_is_terminal: bool, args: &SetupArgs) -> bool { + stdin_is_terminal && stdout_is_terminal && !setup_is_fully_specified(args) } fn setup_is_fully_specified(args: &SetupArgs) -> bool { diff --git a/src/cli_tests.rs b/src/cli_tests.rs index 3faf3a2..5e1b10b 100644 --- a/src/cli_tests.rs +++ b/src/cli_tests.rs @@ -9,7 +9,7 @@ use super::{ detect_games_with_saved_libraries, not_detected_error, parse_xrandr_resolution, persist_cli_language_selection, resolve_game_kind_rich, resolve_game_path_rich, resolve_mods_flag, resolve_setup_languages, resolve_setup_mods, resolve_setup_mods_rich, - run_from_args_with_io, run_with_io, setup_is_fully_specified, + rich_prompts_fit, run_from_args_with_io, run_with_io, setup_is_fully_specified, }; use crate::config::APP_ID; use crate::settings::{Settings, Value}; @@ -809,6 +809,40 @@ fn setup_is_fully_specified_with_explicit_flags() { assert!(setup_is_fully_specified(&args)); } +#[test] +fn a_preset_or_all_mods_alone_is_a_mod_choice() { + let chosen = |preset: Option<&str>, all_mods: bool| SetupArgs { + game: Some("sa2".to_string()), + game_path: Some(PathBuf::from("/tmp/sa2")), + preset: preset.map(str::to_string), + all_mods, + ..empty_setup_args() + }; + + assert!(!setup_is_fully_specified(&chosen(None, false))); + assert!(setup_is_fully_specified(&chosen( + Some("recommended"), + false + ))); + assert!(setup_is_fully_specified(&chosen(None, true))); +} + +#[test] +fn rich_prompts_need_a_terminal_on_both_ends_and_an_open_choice() { + let open = empty_setup_args(); + let full = SetupArgs { + game: Some("sa2".to_string()), + game_path: Some(PathBuf::from("/tmp/sa2")), + all_mods: true, + ..empty_setup_args() + }; + + assert!(rich_prompts_fit(true, true, &open)); + assert!(!rich_prompts_fit(false, true, &open)); + assert!(!rich_prompts_fit(true, false, &open)); + assert!(!rich_prompts_fit(true, true, &full)); +} + #[test] fn setup_is_not_fully_specified_without_mod_choice() { let args = SetupArgs { @@ -1539,7 +1573,12 @@ fn game_resolution_handles_detection_errors_and_cardinality() { ..empty_setup_args() }; assert!(super::resolve_game_kind(&empty).is_err()); - assert!(super::resolve_game_path(&empty, GameKind::SA2).is_err()); + assert_eq!( + super::resolve_game_path(&empty, GameKind::SA2) + .unwrap_err() + .to_string(), + "Sonic Adventure 2 was not detected. Pass --game-path." + ); let mut output = Vec::new(); run_with_io( @@ -1652,10 +1691,14 @@ fn download_progress_and_summary_cover_cli_output_paths() { } #[test] -fn detect_resolution_uses_a_safe_fallback() { - let (width, height) = super::detect_resolution(); - assert!(width > 0); - assert!(height > 0); +fn detect_resolution_asks_the_display_server_then_xrandr() { + let mut xrandr = ProcessCommand::new("xrandr"); + xrandr.arg("--current"); + let expected = + super::detect_resolution_with(crate::display::resolution_from_display_server, xrandr); + + assert_eq!(super::detect_resolution(), expected); + assert!(expected.0 > 1 && expected.1 > 1); } #[test] diff --git a/src/external/download.rs b/src/external/download.rs index d922078..ec9cafa 100644 --- a/src/external/download.rs +++ b/src/external/download.rs @@ -289,7 +289,7 @@ async fn download_attempt( loop { if tokio::time::Instant::now() >= window_end { let window_bytes = downloaded - window_start_bytes; - if may_switch_mirror && window_bytes < SLOW_WINDOW_BYTES { + if may_switch_mirror && too_slow(window_bytes) { tracing::info!( "{mirror} sent only {window_bytes} bytes of {url} in {} seconds, asking for another mirror", SPEED_WINDOW.as_secs() @@ -323,6 +323,12 @@ async fn download_attempt( Ok(Attempt::Done(validator)) } +/// Whether a mirror that sent `window_bytes` in one [`SPEED_WINDOW`] is too +/// slow to keep. [`SLOW_WINDOW_BYTES`] itself is fast enough. +fn too_slow(window_bytes: u64) -> bool { + window_bytes < SLOW_WINDOW_BYTES +} + /// Whether the server says it can send part of the file. fn accepts_ranges(response: &Response) -> bool { response @@ -568,6 +574,34 @@ mod tests { assert_eq!(log.lock().unwrap().len(), 1); } + #[test] + fn an_empty_partial_file_starts_over_without_asking_for_a_range() { + init(); + let ranges = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let seen = ranges.clone(); + let (base, _) = serve(move |request| { + seen.lock() + .unwrap() + .push(request.header("Range").map(str::to_owned)); + ranged_file(request, "\"v1\"") + }); + let tmp = tempfile::tempdir().unwrap(); + let dest = tmp.path().join("file.7z"); + seed_partial(&dest, b"", Some("\"v1\"")); + + download_file_resumable(&format!("{base}/file"), &dest, None).unwrap(); + + assert_eq!(std::fs::read(&dest).unwrap(), BODY); + assert_eq!(*ranges.lock().unwrap(), [None]); + } + + #[test] + fn a_mirror_is_slow_only_below_the_window_minimum() { + assert!(too_slow(0)); + assert!(too_slow(SLOW_WINDOW_BYTES - 1)); + assert!(!too_slow(SLOW_WINDOW_BYTES)); + } + /// Long enough to look slow, short enough not to count as a stall. const TRICKLE_PAUSE: std::time::Duration = std::time::Duration::from_millis(700); diff --git a/src/external/proton.rs b/src/external/proton.rs index b8cd108..bc6c60e 100644 --- a/src/external/proton.rs +++ b/src/external/proton.rs @@ -424,10 +424,10 @@ fn proton_tag_major(text: &str) -> Option { /// Split leading ASCII digits off `text`. fn split_number(text: &str) -> (Option, &str) { - let end = text - .find(|c: char| !c.is_ascii_digit()) - .unwrap_or(text.len()); - (text[..end].parse().ok(), &text[end..]) + // The rest always starts after the digits, so callers that loop on it + // move forward. + let rest = text.trim_start_matches(|c: char| c.is_ascii_digit()); + (text[..text.len() - rest.len()].parse().ok(), rest) } fn configured_tool_from_config( @@ -456,9 +456,8 @@ fn configured_tool_from_config( best_failure = ConfiguredToolLookup::ConfiguredToolUnavailable { name }; } Err(other) => { - if failure_priority(&other) > failure_priority(&best_failure) { - best_failure = other; - } + // On a tie the two are the same failure. + best_failure = std::cmp::max_by_key(best_failure, other, failure_priority); } } } @@ -889,6 +888,14 @@ fn parse_proton_dir_name(name: &str) -> Option { mod tests { use super::*; + #[test] + fn split_number_splits_off_the_leading_digits() { + assert_eq!(split_number("10.0-4b"), (Some(10), ".0-4b")); + assert_eq!(split_number("11"), (Some(11), "")); + assert_eq!(split_number("x10"), (None, "x10")); + assert_eq!(split_number(""), (None, "")); + } + #[test] fn major_from_label_reads_dotted_versions_and_numbered_tags() { assert_eq!(major_from_label("10.1000-105"), Some(10)); diff --git a/src/external/proton_scenarios_tests.rs b/src/external/proton_scenarios_tests.rs index c52c657..f09ac7d 100644 --- a/src/external/proton_scenarios_tests.rs +++ b/src/external/proton_scenarios_tests.rs @@ -359,6 +359,38 @@ fn switching_to_a_wine_11_build_on_another_drive_is_caught_before_launch() { ); } +#[test] +fn switching_to_proton_hotfix_is_caught_before_launch() { + let steam = Steam::new(); + let game = steam.install_game(&steam.root); + let proton = steam.install(&steam.root, PROTON_10); + steam.install(&steam.root, PROTON_HOTFIX); + steam.launch(&game, PROTON_10, &proton); + // Steam stores `proton_hotfix`, but the folder is `Proton Hotfix`. + steam.force(PROTON_HOTFIX); + + assert_eq!( + steam.state(&game), + PrefixState::UnsupportedConfiguredProton { + tool_name: "Proton Hotfix".to_owned(), + major: 11, + } + ); +} + +#[test] +fn a_proton_10_steam_still_has_to_download_is_not_refused() { + let steam = Steam::new(); + let game = steam.install_game(&steam.root); + let ge = steam.install(&steam.root, GE_PROTON_10); + steam.launch(&game, GE_PROTON_10, &ge); + // Forced, but not installed anywhere yet. Proton 10 is supported. + steam.force(PROTON_10); + + let state = steam.state(&game); + assert_eq!(state, PrefixState::Ready); +} + #[test] fn a_custom_tool_is_found_by_its_registered_name_not_its_folder() { let steam = Steam::new(); diff --git a/src/main.rs b/src/main.rs index 7b15529..a7b9d0a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -122,6 +122,29 @@ mod tests { assert_eq!(options.viewport.fullscreen, Some(true)); assert_eq!(options.viewport.clamp_size_to_monitor_size, Some(false)); assert_eq!(options.viewport.app_id.as_deref(), Some(config::APP_ID)); - let _ = in_game_mode(); + } + + #[test] + fn either_gamescope_or_the_steam_gamepad_ui_means_game_mode() { + // nextest runs each test in its own process, so the variables do not + // leak into other tests. + let set = |gamescope: bool, gamepad_ui: bool| { + for (name, on) in [ + ("GAMESCOPE_WAYLAND_DISPLAY", gamescope), + ("SteamGamepadUI", gamepad_ui), + ] { + if on { + unsafe { std::env::set_var(name, "1") }; + } else { + unsafe { std::env::remove_var(name) }; + } + } + in_game_mode() + }; + + assert!(!set(false, false)); + assert!(set(true, false)); + assert!(set(false, true)); + assert!(set(true, true)); } } diff --git a/src/setup/common.rs b/src/setup/common.rs index 0ffcf00..39ae8ce 100644 --- a/src/setup/common.rs +++ b/src/setup/common.rs @@ -883,15 +883,14 @@ fn download_cache_dir() -> std::path::PathBuf { .join("downloads") } -#[cfg(not(test))] fn default_cache_dir() -> Option { - dirs::cache_dir().map(|dir| dir.join("adventure-mods")) -} - -/// Tests must not write to the user's real download cache. -#[cfg(test)] -fn default_cache_dir() -> Option { - Some(std::env::temp_dir().join("adventure-mods-tests")) + // Tests must not write to the user's real download cache. + let base = if cfg!(test) { + Some(std::env::temp_dir().join("adventure-mods-tests")) + } else { + dirs::cache_dir() + }; + base.map(|dir| dir.join("adventure-mods")) } fn cached_archive_path(url: &str) -> std::path::PathBuf { diff --git a/src/setup/common_tests.rs b/src/setup/common_tests.rs index 1174d54..e884f0b 100644 --- a/src/setup/common_tests.rs +++ b/src/setup/common_tests.rs @@ -1,5 +1,19 @@ use super::*; +#[test] +fn downloads_are_cached_in_the_app_folder_of_the_cache_dir() { + let _guard = crate::test_env::lock(); + let base = std::env::temp_dir().join("adventure-mods-tests"); + + assert_eq!(default_cache_dir(), Some(base.join("adventure-mods"))); + // SAFETY: the lock keeps other tests from reading the environment now. + unsafe { std::env::remove_var("ADVENTURE_MODS_CACHE_DIR") }; + assert_eq!( + download_cache_dir(), + base.join("adventure-mods").join("downloads") + ); +} + #[test] fn gamebanana_item_dl_base_override() { use std::io::{Read, Write}; diff --git a/src/setup/pipeline.rs b/src/setup/pipeline.rs index 210c341..31eba3f 100644 --- a/src/setup/pipeline.rs +++ b/src/setup/pipeline.rs @@ -99,8 +99,7 @@ fn prefetch_with_retries( report: &(dyn Fn(&'static str, PrefetchEvent) + Sync), ) { let name = mod_entry.name; - let mut attempt = 1; - loop { + for attempt in 1..=MAX_MOD_INSTALL_ATTEMPTS { let mut progress = |downloaded: u64, total: Option| { ensure_not_cancelled(cancelled)?; report(name, PrefetchEvent::Downloading { downloaded, total }); @@ -119,8 +118,12 @@ fn prefetch_with_retries( return report(name, PrefetchEvent::Failed); } tracing::info!("Prefetching '{name}' failed, trying again: {err:#}"); - attempt += 1; - report(name, PrefetchEvent::Retrying { attempt }); + report( + name, + PrefetchEvent::Retrying { + attempt: attempt + 1, + }, + ); thread::sleep(RETRY_PAUSE); } } @@ -198,8 +201,8 @@ fn install_mods_and_generate_config( let mod_entry = selected_mods[job_index]; let _ = tx.send(WorkerMessage::InstallingMod { job_index }); - let mut attempt = 0; - let result = loop { + let mut result = Ok(()); + for attempt in 1..=MAX_MOD_INSTALL_ATTEMPTS { let mut download_progress = |downloaded: u64, total_bytes: Option| { ensure_not_cancelled(&cancelled)?; @@ -214,24 +217,19 @@ fn install_mods_and_generate_config( ensure_not_cancelled(&cancelled) }; - let result = common::install_mod_with_progress( + result = common::install_mod_with_progress( game_path, mod_entry, Some(&mut download_progress), ); - - attempt += 1; - match result { - Ok(()) => break Ok(()), - Err(e) if attempt < MAX_MOD_INSTALL_ATTEMPTS => { - if cancelled.load(Ordering::Relaxed) { - break Err(e); - } - std::thread::sleep(RETRY_PAUSE); - } - Err(e) => break Err(e), + if result.is_ok() + || attempt == MAX_MOD_INSTALL_ATTEMPTS + || cancelled.load(Ordering::Relaxed) + { + break; } - }; + std::thread::sleep(RETRY_PAUSE); + } match result { Ok(()) => { diff --git a/src/steam/library.rs b/src/steam/library.rs index f9e7dc7..51953c4 100644 --- a/src/steam/library.rs +++ b/src/steam/library.rs @@ -61,7 +61,7 @@ pub(crate) fn document_portal_host_path(path: &Path) -> Option { return None; } buf.truncate(len as usize); - while buf.last() == Some(&0) { + while let Some(&0) = buf.last() { buf.pop(); } if buf.is_empty() { diff --git a/src/steam/library_tests.rs b/src/steam/library_tests.rs index 636f418..6e14d6d 100644 --- a/src/steam/library_tests.rs +++ b/src/steam/library_tests.rs @@ -1179,6 +1179,39 @@ fn library_detection_logs_found_stale_and_unmounted_libraries() { assert!(logs.contains(&format!("at {} is inaccessible", unmounted.display()))); } +#[test] +fn only_a_game_that_is_nowhere_is_logged_as_not_found() { + let tmp = tempfile::tempdir().unwrap(); + let library = tmp.path().join("library"); + let unmounted = tmp.path().join("unmounted"); + make_steam_library(&library, GameKind::SA2); + let text = format!( + "\"libraryfolders\" {{ \"0\" {{ \"path\" \"{}\" \"apps\" {{ \"{}\" \"0\" }} }} }}", + library.display(), + GameKind::SA2.app_id() + ); + let only_sa2 = vdf::parse(&text).unwrap(); + // SADX is listed too, but on a drive that is not there. + let text = format!( + "\"libraryfolders\" {{ \"0\" {{ \"path\" \"{}\" \"apps\" {{ \"{}\" \"0\" }} }} }}", + unmounted.display(), + GameKind::SADX.app_id() + ); + let unmounted_sadx = vdf::parse(&text).unwrap(); + let not_found = |kind: GameKind| format!("{} not found", kind.name()); + + let (result, logs) = + capture_logs(|| detect_games_from_parsed_vdfs(std::slice::from_ref(&only_sa2), &[])); + assert_eq!(result.games.len(), 1); + assert!(logs.contains(¬_found(GameKind::SADX)), "{logs}"); + assert!(!logs.contains(¬_found(GameKind::SA2)), "{logs}"); + + let (result, logs) = + capture_logs(|| detect_games_from_parsed_vdfs(&[only_sa2, unmounted_sadx], &[])); + assert_eq!(result.inaccessible.len(), 1); + assert!(!logs.contains(¬_found(GameKind::SADX)), "{logs}"); +} + #[test] fn home_scan_logs_unreadable_library_file() { let home = tempfile::tempdir().unwrap(); @@ -1627,6 +1660,43 @@ fn a_blocked_steam_folder_lists_each_game_once() { assert_eq!(result.inaccessible[0].library_path, steam); } +#[test] +fn a_blocked_steam_folder_offers_a_game_another_list_missed() { + let home = tempfile::tempdir().unwrap(); + let steam = home_with_blocked_steam(home.path()); + make_steam_library(&steam, GameKind::SA2); + // The Flatpak's Steam lists the folder with SADX only, so only SADX comes + // from a library list. + let flatpak = home + .path() + .join(".var/app/com.valvesoftware.Steam/.local/share/Steam/steamapps"); + std::fs::create_dir_all(&flatpak).unwrap(); + std::fs::write( + flatpak.join("libraryfolders.vdf"), + format!( + "\"libraryfolders\"\n{{\n\"0\"\n{{\n\"path\" \"{}\"\n\"apps\"\n{{\n\"71250\" \"0\"\n}}\n}}\n}}\n", + steam.display() + ), + ) + .unwrap(); + let game_dir = steam.join("steamapps/common/Sonic Adventure DX"); + set_mode(&game_dir, 0o555); + + let result = in_a_snap(home.path(), || detect_games_with_extra_libraries(&[])); + set_mode(&game_dir, 0o755); + set_mode(&steam.join("steamapps/libraryfolders.vdf"), 0o644); + + let listed: Vec<_> = result + .inaccessible + .iter() + .map(|game| (game.kind, game.library_path.clone())) + .collect(); + assert_eq!( + listed, + vec![(GameKind::SADX, steam.clone()), (GameKind::SA2, steam)] + ); +} + #[cfg(target_os = "linux")] #[test] fn granting_the_blocked_steam_folder_clears_the_report() { diff --git a/src/steam/vdf.rs b/src/steam/vdf.rs index 2fabb48..8790d93 100644 --- a/src/steam/vdf.rs +++ b/src/steam/vdf.rs @@ -61,23 +61,18 @@ impl<'a> Parser<'a> { fn parse_quoted_string(&mut self) -> Option { self.skip_whitespace(); - if self.pos >= self.input.len() || self.input.as_bytes()[self.pos] != b'"' { - return None; - } - self.pos += 1; - + let mut chars = self.input[self.pos..].strip_prefix('"')?.chars(); let mut result = String::new(); - let mut start = self.pos; - while self.pos < self.input.len() { - let ch = self.input.as_bytes()[self.pos]; - if ch == b'\\' && self.pos + 1 < self.input.len() { - result.push_str(&self.input[start..self.pos]); - self.pos += 1; - // The escaped character may be several bytes long, so step - // over all of it to stay on a character boundary. - let escaped = self.input[self.pos..].chars().next()?; - match escaped { + // The iterator always moves forward, so the loop ends at the closing + // quote or at the end of the input. + while let Some(ch) = chars.next() { + match ch { + '"' => { + self.pos = self.input.len() - chars.as_str().len(); + return Some(result); + } + '\\' => match chars.next()? { 'n' => result.push('\n'), 't' => result.push('\t'), '\\' => result.push('\\'), @@ -86,15 +81,8 @@ impl<'a> Parser<'a> { result.push('\\'); result.push(other); } - } - self.pos += escaped.len_utf8(); - start = self.pos; - } else if ch == b'"' { - result.push_str(&self.input[start..self.pos]); - self.pos += 1; - return Some(result); - } else { - self.pos += 1; + }, + other => result.push(other), } } None diff --git a/src/ui/app.rs b/src/ui/app.rs index 44b659b..883cd7e 100644 --- a/src/ui/app.rs +++ b/src/ui/app.rs @@ -22,6 +22,8 @@ use crate::steam::library::{DetectionResult, resolve_granted_steam_library}; use crate::{tr, trf}; const TOAST_SECONDS: f64 = 4.0; +/// Toasts sit this far above the bottom of the window, clear of the footer. +const TOAST_OFFSET: Vec2 = Vec2::new(0.0, -110.0); const ISSUES_URL: &str = "https://github.com/astrovm/AdventureMods/issues"; /// Everything the app does outside itself. Tests swap these for fakes. @@ -124,6 +126,16 @@ struct Toast { until: f64, } +impl Toast { + /// From 0 to 1 while it appears, 1 while shown, and back to 0 as it + /// leaves. + fn fade(&self, now: f64) -> f32 { + let shown = now - (self.until - TOAST_SECONDS); + let left = self.until - now; + (shown.min(left) / motion::SCREEN).clamp(0.0, 1.0) as f32 + } +} + /// A scan of the Steam libraries running in the background. struct Scan { id: u64, @@ -744,15 +756,11 @@ impl AdventureModsApp { } let now = ctx.input(|input| input.time); egui::Area::new(egui::Id::unique("toasts")) - .anchor(Align2::CENTER_BOTTOM, Vec2::new(0.0, -110.0)) + .anchor(Align2::CENTER_BOTTOM, TOAST_OFFSET) .interactable(false) .show(ctx, |ui| { for toast in &self.toasts { - // Fade in when shown and out before leaving. - let shown = now - (toast.until - TOAST_SECONDS); - let left = toast.until - now; - let fade = (shown.min(left) / motion::SCREEN).clamp(0.0, 1.0) as f32; - ui.set_opacity(motion::ease_out(fade)); + ui.set_opacity(motion::ease_out(toast.fade(now))); egui::Frame::new() .fill(theme::CARD_RAISED) .corner_radius(24) diff --git a/src/ui/app_tests.rs b/src/ui/app_tests.rs index 006bd4b..4a5968c 100644 --- a/src/ui/app_tests.rs +++ b/src/ui/app_tests.rs @@ -613,6 +613,53 @@ fn the_window_size_is_saved_unless_maximized() { without.save_window_state(); } +#[test] +fn a_window_size_counts_as_saved_only_with_both_sides() { + let dir = tempfile::tempdir().unwrap(); + let mut settings = Settings::load_from(dir.path(), &|| None); + settings.set(WINDOW_WIDTH_KEY, Value::Int(1111)); + + let half = WindowState::load(Some(&settings)); + assert_eq!(half.size, Vec2::new(1111.0, super::super::DEFAULT_HEIGHT)); + assert!(!half.saved); + + settings.set(WINDOW_HEIGHT_KEY, Value::Int(777)); + assert!(WindowState::load(Some(&settings)).saved); +} + +#[test] +fn a_toast_fades_in_stays_and_fades_out() { + let toast = Toast { + text: String::new(), + until: 10.0 + TOAST_SECONDS, + }; + let half = motion::SCREEN / 2.0; + let near = |a: f32, b: f32| (a - b).abs() < 1e-3; + + assert_eq!(toast.fade(10.0), 0.0); + assert!(near(toast.fade(10.0 + half), 0.5)); + assert_eq!(toast.fade(12.0), 1.0); + assert!(near(toast.fade(10.0 + TOAST_SECONDS - half), 0.5)); + assert_eq!(toast.fade(10.0 + TOAST_SECONDS), 0.0); +} + +#[test] +fn a_toast_stays_for_a_few_seconds_and_keeps_the_window_repainting() { + let fixture = Fixture::new(&[]); + let mut harness = fixture.harness(); + run_until(&mut harness, "scan", scanned); + harness.run_steps(5); + assert_eq!(repaint_delay(&harness), Duration::MAX, "idle"); + + let ctx = harness.ctx.clone(); + let now = ctx.input(|input| input.time); + harness.state_mut().toast(&ctx, "Hello"); + assert_eq!(harness.state().toasts[0].until, now + TOAST_SECONDS); + harness.run_steps(2); + harness.get_by_label("Hello"); + assert_eq!(repaint_delay(&harness), Duration::from_millis(100)); +} + fn inner_size_commands(harness: &Harness<'_, AdventureModsApp>) -> Vec { harness.output().viewport_output[&egui::ViewportId::ROOT] .commands diff --git a/src/ui/images.rs b/src/ui/images.rs index ee92866..e3055d1 100644 --- a/src/ui/images.rs +++ b/src/ui/images.rs @@ -140,11 +140,8 @@ impl ImageCache { ctx: &egui::Context, decode: fn(&str) -> anyhow::Result, ) -> Self { - // Leave a core for the UI. - let workers = std::thread::available_parallelism() - .map_or(1, |cores| cores.get() - 1) - .clamp(1, MAX_WORKERS); - Self::with_workers(ctx, decode, workers) + let cores = std::thread::available_parallelism().map_or(1, usize::from); + Self::with_workers(ctx, decode, worker_count(cores)) } fn with_workers( @@ -318,11 +315,28 @@ fn is_cover(resource: &str) -> bool { resource.contains("/covers/") } +/// Decoding threads for a machine with `cores`: one core stays for the UI, +/// but there is always at least one worker. +fn worker_count(cores: usize) -> usize { + cores.saturating_sub(1).clamp(1, MAX_WORKERS) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn one_core_is_left_for_the_ui() { + assert_eq!(worker_count(1), 1); + assert_eq!(worker_count(2), 1); + assert_eq!(worker_count(3), 2); + assert_eq!(worker_count(64), MAX_WORKERS); + } + const SCREENSHOT: &str = "/io/github/astrovm/AdventureMods/resources/images/sadx/dreamcast_conversion/dreamcast_conversion_before.jpg"; + /// 1600 pixels wide, more than [`MAX_WIDTH`]. + const WIDE_SCREENSHOT: &str = + "/io/github/astrovm/AdventureMods/resources/images/sadx/super_sonic/sadx-super-sonic_5.jpg"; /// Move on to the next frame, which may upload more screenshots. fn next_frame(ctx: &egui::Context) { @@ -384,9 +398,11 @@ mod tests { #[test] fn large_screenshots_are_shrunk_when_decoded() { - let image = decode(SCREENSHOT).unwrap(); - assert!(image.size[0] <= MAX_WIDTH as usize); + let image = decode(WIDE_SCREENSHOT).unwrap(); + assert_eq!(image.size[0], MAX_WIDTH as usize); assert!(image.size[1] > 0); + // A narrower one keeps its size. + assert_eq!(decode(SCREENSHOT).unwrap().size[0], 1024); let cover = decode(cover_resource(GameKind::SA2)).unwrap(); assert_eq!(cover.size, [460, 215]); @@ -450,9 +466,10 @@ mod tests { assert!(cache.get(&ctx, next).is_some(), "no wait when shown"); assert!(cache.get(&ctx, SCREENSHOT).is_some()); - // Asking again keeps what is decoded. + // Asking again keeps what is decoded, even what is not asked for. cache.prefetch(&ctx, &[next]); assert!(matches!(cache.slots.get(next), Some(Slot::Ready(_)))); + assert!(matches!(cache.slots.get(SCREENSHOT), Some(Slot::Ready(_)))); } #[test] diff --git a/src/ui/motion.rs b/src/ui/motion.rs index 96bb591..62ac450 100644 --- a/src/ui/motion.rs +++ b/src/ui/motion.rs @@ -64,11 +64,17 @@ impl ScreenTransition { pub fn show(&mut self, ui: &mut Ui, key: u64, add: impl FnOnce(&mut Ui) -> R) -> R { let t = self.progress(ui.ctx(), key); ui.multiply_opacity(t); - ui.add_space((1.0 - t) * SCREEN_SLIDE); + ui.add_space(slide(t)); add(ui) } } +/// How far below its place a screen is at progress `t`: all of +/// [`SCREEN_SLIDE`] at first, none once settled. +fn slide(t: f32) -> f32 { + (1.0 - t) * SCREEN_SLIDE +} + /// A stable key for `value`, for [`ScreenTransition`]. pub fn key(value: impl std::hash::Hash + std::fmt::Debug) -> u64 { Id::unique(value).value() @@ -79,6 +85,13 @@ mod tests { use super::*; use std::time::Duration; + #[test] + fn a_new_screen_slides_up_into_place() { + assert_eq!(slide(0.0), SCREEN_SLIDE); + assert_eq!(slide(0.5), SCREEN_SLIDE / 2.0); + assert_eq!(slide(1.0), 0.0); + } + #[test] fn ease_out_starts_fast_and_ends_at_one() { assert_eq!(ease_out(-1.0), 0.0); diff --git a/src/ui/progress.rs b/src/ui/progress.rs index a14d5e6..bb0abfc 100644 --- a/src/ui/progress.rs +++ b/src/ui/progress.rs @@ -912,6 +912,13 @@ mod tests { assert!(state.display.as_ref().unwrap().pulse); samples.clear_mod("Alpha"); + let mut one_left = ProgressState::default(); + samples.apply_to(&mut one_left); + assert_eq!( + one_left.active_downloads.keys().collect::>(), + ["Beta"] + ); + samples.clear(); let mut cleared = ProgressState::default(); samples.apply_to(&mut cleared); diff --git a/src/ui/setup.rs b/src/ui/setup.rs index bdc9929..877d31d 100644 --- a/src/ui/setup.rs +++ b/src/ui/setup.rs @@ -709,16 +709,16 @@ impl SetupFlow { let skippable = |step: &SetupStep| { matches!(step.kind, StepKind::Auto) || (self.work.is_step_complete)(step.id, &self.game) }; - let mut previous = self.current - 1; - while previous > 0 && skippable(&self.steps[previous]) { - previous -= 1; - } - // Everything before here could be skipped: leave setup. - if skippable(&self.steps[previous]) { - self.exit(); - } else { - self.current = previous; - self.enter_step(); + let previous = (0..self.current) + .rev() + .find(|&index| !skippable(&self.steps[index])); + match previous { + Some(previous) => { + self.current = previous; + self.enter_step(); + } + // Everything before here could be skipped: leave setup. + None => self.exit(), } } @@ -1266,12 +1266,7 @@ impl SetupFlow { let mods = common::recommended_mods_for_game(self.game.kind); let presets = common::presets_for_game(self.game.kind); let preset = self.matching_preset().map(|index| &presets[index]); - let wide = ui.available_width() >= 900.0; - let column_width = if wide { - (ui.available_width() - 72.0) / 2.0 - } else { - ui.available_width() - 48.0 - }; + let (wide, column_width) = mod_columns(ui.available_width()); let mut open_preset = false; let mut focused = None; let mut hovered = None; @@ -1295,10 +1290,9 @@ impl SetupFlow { widgets::caption(ui, i18n::translate(preset.description)); } } - let list_height = ui.available_height() - 40.0; egui::ScrollArea::vertical() .id_salt("mod-list") - .max_height(list_height.max(120.0)) + .max_height(mod_list_height(ui.available_height())) .auto_shrink([false, true]) .show(ui, |ui| { ui.spacing_mut().item_spacing.y = 8.0; @@ -1370,9 +1364,7 @@ impl SetupFlow { if let Some(picture) = pages.get(self.preview.page) { // In a wide window the picture would grow taller than the room // under it allows, so it stays within a share of the height. - let width = ui.available_width(); - let height = (width * 9.0 / 16.0).min(ui.available_height() * PICTURE_SHARE); - let size = Vec2::new(height * 16.0 / 9.0, height); + let size = picture_size(ui.available_width(), ui.available_height()); let (rect, response) = ui.allocate_exact_size(size, egui::Sense::hover()); ui.painter() .rect_filled(rect, theme::CARD_RADIUS, theme::CARD); @@ -1505,6 +1497,34 @@ fn prefetch_order(mods: &[ModEntry], index: Option, page: usize) -> Vec<& /// the layout's window size, where the description and links fit under it. const PICTURE_SHARE: f32 = 0.47; +/// Whether the mod list and its preview fit side by side in `width`, and how +/// wide each column is: 24 points at both sides, and 24 between two columns. +fn mod_columns(width: f32) -> (bool, f32) { + if width >= 900.0 { + (true, (width - 72.0) / 2.0) + } else { + (false, width - 48.0) + } +} + +/// The mod list leaves 40 points under it, but is never shorter than 120. +fn mod_list_height(room: f32) -> f32 { + (room - 40.0).max(120.0) +} + +/// A 16:9 preview picture as wide as `width`, unless that makes it taller +/// than [`PICTURE_SHARE`] of the `height` below it. +fn picture_size(width: f32, height: f32) -> Vec2 { + let height = (width * 9.0 / 16.0).min(height * PICTURE_SHARE); + Vec2::new(height * 16.0 / 9.0, height) +} + +/// Space above content `content` tall that centers it in `room`, with at +/// least 24 points. +fn centering_space(room: f32, content: f32) -> f32 { + ((room - content) / 2.0).max(24.0) +} + /// A download progress callback that updates the install screen's bar. fn step_progress( tx: async_channel::Sender, @@ -1553,7 +1573,7 @@ fn centered(ui: &mut Ui, add: impl FnOnce(&mut Ui)) { // Centering needs the content's height, so use last frame's. let id = ui.scope_id().with("content-height"); let last = ui.data(|data| data.get_temp::(id)).unwrap_or(0.0); - ui.add_space(((ui.available_height() - last) / 2.0).max(24.0)); + ui.add_space(centering_space(ui.available_height(), last)); let height = ui.vertical_centered(add).response.rect.height(); if (height - last).abs() > 0.5 { ui.data_mut(|data| data.insert_temp(id, height)); diff --git a/src/ui/setup_tests.rs b/src/ui/setup_tests.rs index a9508b0..3dfe990 100644 --- a/src/ui/setup_tests.rs +++ b/src/ui/setup_tests.rs @@ -18,6 +18,9 @@ fn fake_runtimes(path: &Path, _app_id: u32) -> anyhow::Result<()> { if marker(path, "panic-dotnet") { panic!("runtime installer exploded"); } + while marker(path, "hold-dotnet") { + std::thread::sleep(Duration::from_millis(5)); + } if marker(path, "fail-dotnet") { anyhow::bail!("dotnet failed"); } @@ -872,6 +875,8 @@ fn sadx_converts_and_shows_download_progress() { .is_some_and(|install| install.progress.display.is_some()) }); harness.get_by_label_contains("Downloading… - "); + // Only the mod download can be cancelled. + assert_eq!(harness.state().flow.pad_action_label(), None); assert!(dir.path().join("converted").exists()); assert_eq!(harness.state().flow.title().0, "Installing"); assert!(!harness.state().flow.can_go_back()); @@ -1213,6 +1218,89 @@ fn the_preview_follows_the_focused_mod_and_turns_pages() { ); } +#[test] +fn the_previous_page_button_turns_back() { + let dir = game_dir(&["proton-ready"]); + let mut setup = flow(GameKind::SADX, dir.path(), work()); + let mods = common::recommended_mods_for_game(GameKind::SADX); + let index = mods + .iter() + .position(|mod_entry| mod_entry.pictures.len() > 2) + .unwrap(); + let pages = mods[index].pictures.len(); + setup.preview = Preview { + index: Some(index), + page: 1, + }; + + setup.handle_pad(PadButton::PreviousPage); + assert_eq!(setup.preview.page, 0); + setup.handle_pad(PadButton::PreviousPage); + assert_eq!(setup.preview.page, pages - 1); +} + +#[test] +fn a_step_without_a_download_shows_no_progress_bar() { + let dir = game_dir(&["proton-ready", "hold-dotnet"]); + let mut harness = harness(flow(GameKind::SA2, dir.path(), work())); + act(&mut harness, |flow| { + flow.on_next(); + flow.on_next(); + flow.on_next(); + }); + run_until(&mut harness, ".NET step", |state| { + step_id(state) == StepId::Dotnet && state.flow.busy() + }); + harness.run_steps(2); + assert!( + harness + .query_by_role(egui::accesskit::Role::ProgressIndicator) + .is_none() + ); + + std::fs::remove_file(dir.path().join("hold-dotnet")).unwrap(); + run_until(&mut harness, "finished", |state| { + step_id(state) == StepId::Complete + }); +} + +#[test] +fn each_question_has_its_own_screen_and_the_work_shares_one() { + let dir = game_dir(&["proton-ready"]); + let mut setup = flow(GameKind::SA2, dir.path(), work()); + let position = + |setup: &SetupFlow, id: StepId| setup.steps.iter().position(|step| step.id == id).unwrap(); + let key_at = |setup: &mut SetupFlow, id: StepId| { + setup.current = position(setup, id); + setup.screen_key() + }; + + let mods = key_at(&mut setup, StepId::SelectMods); + let languages = key_at(&mut setup, StepId::LanguageOptions); + let dotnet = key_at(&mut setup, StepId::Dotnet); + let manager = key_at(&mut setup, StepId::InstallModManager); + + assert_ne!(mods, languages); + assert_ne!(languages, dotnet); + assert_eq!(dotnet, manager); +} + +#[test] +fn layout_sizes_fit_the_window() { + // Two columns from 900 points on, each with 24 points around it. + assert_eq!(mod_columns(899.0), (false, 851.0)); + assert_eq!(mod_columns(1000.0), (true, 464.0)); + assert_eq!(mod_list_height(500.0), 460.0); + assert_eq!(mod_list_height(100.0), 120.0); + // 16:9 at the full width, unless the room below is short. + assert_eq!(picture_size(320.0, 1000.0), Vec2::new(320.0, 180.0)); + let short = picture_size(1600.0, 200.0); + assert!((short.y - 200.0 * PICTURE_SHARE).abs() < 1e-3); + assert!((short.x - short.y * 16.0 / 9.0).abs() < 1e-3); + assert_eq!(centering_space(500.0, 300.0), 100.0); + assert_eq!(centering_space(300.0, 290.0), 24.0); +} + #[test] fn the_preview_follows_the_mouse_while_a_mod_has_focus() { let dir = game_dir(&["proton-ready"]); diff --git a/src/ui/theme.rs b/src/ui/theme.rs index f41b6ba..ea7629c 100644 --- a/src/ui/theme.rs +++ b/src/ui/theme.rs @@ -245,6 +245,14 @@ fn fonts() -> egui::FontDefinitions { mod tests { use super::*; + #[test] + fn bold_and_heavy_are_their_own_rubik_weights() { + let fonts = fonts(); + assert_eq!(fonts.families[&bold()][0], "rubik-bold"); + assert_eq!(fonts.families[&heavy()][0], "rubik-extrabold"); + assert_eq!(fonts.families[&FontFamily::Proportional][0], "rubik-medium"); + } + #[test] fn theme_uses_large_text_and_targets() { let ctx = egui::Context::default(); diff --git a/src/ui/welcome.rs b/src/ui/welcome.rs index 6b72853..93cdc1b 100644 --- a/src/ui/welcome.rs +++ b/src/ui/welcome.rs @@ -261,7 +261,7 @@ impl WelcomeScreen { let free = ui.available_height() - self.content_height; ui.add_space((free / 2.0).max(16.0)); let content = ui.vertical(|ui| { - let margin = (ui.available_width() * 0.05).clamp(16.0, 48.0); + let margin = side_margin(ui.available_width()); egui::Frame::new() .inner_margin(egui::Margin::symmetric(margin as i8, 0)) .show(ui, |ui| { @@ -342,14 +342,9 @@ impl WelcomeScreen { /// One tile per game; the selected one is larger and outlined in gold. fn show_tiles(&mut self, ui: &mut Ui, images: &mut ImageCache) { - let gap = 24.0; - let count = self.cards.len() as f32; - let room = ui.available_width() - gap * (count - 1.0); - // The selected tile takes a bigger share of the row. - let small = (room / (count + 0.25)).min(560.0); - let large = small * 1.25; + let (small, large) = tile_widths(ui.available_width(), self.cards.len()); ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = gap; + ui.spacing_mut().item_spacing.x = TILE_GAP; ui.with_layout(egui::Layout::left_to_right(egui::Align::Max), |ui| { for index in 0..self.cards.len() { let card = &self.cards[index]; @@ -360,7 +355,7 @@ impl WelcomeScreen { motion::ease_out, ); let width = small + (large - small) * grow; - let size = Vec2::new(width, width * 215.0 / 460.0); + let size = tile_size(width); let (rect, response) = ui.allocate_exact_size(size, egui::Sense::click()); let name = card.kind.name(); response @@ -451,6 +446,29 @@ impl WelcomeScreen { } } +/// Points between game tiles. +const TILE_GAP: f32 = 24.0; + +/// The welcome screen's side margins: 5% of `width`, from 16 to 48 points. +fn side_margin(width: f32) -> f32 { + (width * 0.05).clamp(16.0, 48.0) +} + +/// Widths of an unselected and of the selected tile, when `count` tiles share +/// a row `width` wide. The selected one is a quarter wider, and the row +/// always fits. +fn tile_widths(width: f32, count: usize) -> (f32, f32) { + let count = count as f32; + let room = width - TILE_GAP * (count - 1.0); + let small = (room / (count + 0.25)).min(560.0); + (small, small * 1.25) +} + +/// A tile `width` wide, with the shape of a Steam cover (460 by 215). +fn tile_size(width: f32) -> Vec2 { + Vec2::new(width, width * 215.0 / 460.0) +} + /// A game's cover, dimmed unless selected, outlined in gold as it grows. fn paint_tile( ui: &Ui, @@ -585,6 +603,20 @@ mod tests { use super::*; + #[test] + fn tiles_and_margins_fit_the_window() { + assert_eq!(side_margin(200.0), 16.0); + assert_eq!(side_margin(600.0), 30.0); + assert_eq!(side_margin(2000.0), 48.0); + + // Two tiles: one small, one a quarter wider, and the gap between. + let (small, large) = tile_widths(924.0, 2); + assert_eq!((small, large), (400.0, 500.0)); + assert_eq!(small + large + TILE_GAP, 924.0); + assert_eq!(tile_widths(4000.0, 2), (560.0, 700.0)); + assert_eq!(tile_size(460.0), Vec2::new(460.0, 215.0)); + } + fn game(kind: GameKind, path: &str) -> Game { Game { kind, @@ -920,6 +952,8 @@ mod tests { screen.set_result(result.clone()); screen.cards[0].select(1); screen.cards[0].select(9); + // Two installs: the third does not exist. + screen.cards[0].select(2); screen.set_result(result); assert_eq!(screen.card(GameKind::SADX).selected, 1); diff --git a/src/ui/widgets.rs b/src/ui/widgets.rs index 709ae55..4d6672d 100644 --- a/src/ui/widgets.rs +++ b/src/ui/widgets.rs @@ -401,8 +401,15 @@ pub fn choice_row(ui: &mut Ui, title: &str, value: &str) -> Response { info }); + paint_choice_row(ui, rect, &response, title, value); + response +} + +/// Paints a [`choice_row`]: card, title, value and chevron. Painting only, so +/// mutation testing skips it (`.cargo/mutants.toml`). +fn paint_choice_row(ui: &Ui, rect: egui::Rect, response: &Response, title: &str, value: &str) { // Painting is clipped, so off-screen rows cost little. - let highlight = motion::highlight(ui, &response); + let highlight = motion::highlight(ui, response); let painter = ui.painter(); let fill = theme::CARD.lerp_to_gamma(theme::CARD_RAISED, highlight); painter.rect( @@ -442,7 +449,6 @@ pub fn choice_row(ui: &mut Ui, title: &str, value: &str) -> Response { title, theme::TEXT, ); - response } /// A rounded progress bar with `text` on it. The fill glides to `fraction`; @@ -547,6 +553,33 @@ mod tests { use super::*; + #[test] + fn a_button_grows_with_its_label_and_padding() { + let ctx = egui::Context::default(); + crate::ui::theme::apply(&ctx); + let _ = ctx.run_ui(egui::RawInput::default(), |ui| { + let label = "A label much wider than the smallest button"; + let text_width = WidgetText::from(label) + .into_galley( + ui, + Some(egui::TextWrapMode::Extend), + f32::INFINITY, + TextStyle::Button, + ) + .size() + .x; + let padding = ui.spacing().button_padding.x; + + let long = button_sized(ui, label, ButtonKind::Normal, 0.0); + assert_eq!(long.rect.width(), text_width + 2.0 * padding); + assert_eq!(long.rect.height(), theme::TARGET_HEIGHT); + let short = button_sized(ui, "OK", ButtonKind::Normal, 0.0); + assert_eq!(short.rect.width(), 120.0); + let wide = button_sized(ui, "OK", ButtonKind::Normal, 300.0); + assert_eq!(wide.rect.width(), 300.0); + }); + } + #[test] fn the_progress_pulse_starts_outside_the_track() { let ctx = egui::Context::default(); From 46dd4611c722d9ef8453e2cc02b7000ca873ddd4 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:31:38 -0300 Subject: [PATCH 2/8] test: fix the three new UI tests and drop the redundant toast repaint --- src/ui/app.rs | 3 +-- src/ui/app_tests.rs | 3 ++- src/ui/setup_tests.rs | 8 +++++--- src/ui/widgets.rs | 4 +++- 4 files changed, 11 insertions(+), 7 deletions(-) diff --git a/src/ui/app.rs b/src/ui/app.rs index 883cd7e..0e2185a 100644 --- a/src/ui/app.rs +++ b/src/ui/app.rs @@ -601,8 +601,7 @@ impl AdventureModsApp { let busy = self.scan.is_some() || self.restoring.is_some() || self.granting.is_some() - || self.setup.as_ref().is_some_and(SetupFlow::busy) - || !self.toasts.is_empty(); + || self.setup.as_ref().is_some_and(SetupFlow::busy); if busy { ctx.request_repaint_after(std::time::Duration::from_millis(100)); } diff --git a/src/ui/app_tests.rs b/src/ui/app_tests.rs index 4a5968c..00b92d1 100644 --- a/src/ui/app_tests.rs +++ b/src/ui/app_tests.rs @@ -657,7 +657,8 @@ fn a_toast_stays_for_a_few_seconds_and_keeps_the_window_repainting() { assert_eq!(harness.state().toasts[0].until, now + TOAST_SECONDS); harness.run_steps(2); harness.get_by_label("Hello"); - assert_eq!(repaint_delay(&harness), Duration::from_millis(100)); + // The fade animates on every frame. + assert_eq!(repaint_delay(&harness), Duration::ZERO); } fn inner_size_commands(harness: &Harness<'_, AdventureModsApp>) -> Vec { diff --git a/src/ui/setup_tests.rs b/src/ui/setup_tests.rs index 3dfe990..491a4da 100644 --- a/src/ui/setup_tests.rs +++ b/src/ui/setup_tests.rs @@ -1252,10 +1252,12 @@ fn a_step_without_a_download_shows_no_progress_bar() { step_id(state) == StepId::Dotnet && state.flow.busy() }); harness.run_steps(2); - assert!( + // Only the spinner of the running task: no progress bar under the list. + assert_eq!( harness - .query_by_role(egui::accesskit::Role::ProgressIndicator) - .is_none() + .query_all_by_role(egui::accesskit::Role::ProgressIndicator) + .count(), + 1 ); std::fs::remove_file(dir.path().join("hold-dotnet")).unwrap(); diff --git a/src/ui/widgets.rs b/src/ui/widgets.rs index 4d6672d..98f32dd 100644 --- a/src/ui/widgets.rs +++ b/src/ui/widgets.rs @@ -557,7 +557,7 @@ mod tests { fn a_button_grows_with_its_label_and_padding() { let ctx = egui::Context::default(); crate::ui::theme::apply(&ctx); - let _ = ctx.run_ui(egui::RawInput::default(), |ui| { + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| { let label = "A label much wider than the smallest button"; let text_width = WidgetText::from(label) .into_galley( @@ -578,6 +578,8 @@ mod tests { let wide = button_sized(ui, "OK", ButtonKind::Normal, 300.0); assert_eq!(wide.rect.width(), 300.0); }); + // This test measures widgets without a texture renderer. + output.textures_delta.clear(); } #[test] From 7825a2dc4b18f7c3a98ad7a5e04cac0c767f4043 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:40:59 -0300 Subject: [PATCH 3/8] test: cover the release cache folder with an integration test --- src/setup/common.rs | 15 +++++++------ src/setup/common_tests.rs | 9 +++----- tests/download.rs | 45 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 56 insertions(+), 13 deletions(-) diff --git a/src/setup/common.rs b/src/setup/common.rs index 39ae8ce..0ffcf00 100644 --- a/src/setup/common.rs +++ b/src/setup/common.rs @@ -883,14 +883,15 @@ fn download_cache_dir() -> std::path::PathBuf { .join("downloads") } +#[cfg(not(test))] fn default_cache_dir() -> Option { - // Tests must not write to the user's real download cache. - let base = if cfg!(test) { - Some(std::env::temp_dir().join("adventure-mods-tests")) - } else { - dirs::cache_dir() - }; - base.map(|dir| dir.join("adventure-mods")) + dirs::cache_dir().map(|dir| dir.join("adventure-mods")) +} + +/// Tests must not write to the user's real download cache. +#[cfg(test)] +fn default_cache_dir() -> Option { + Some(std::env::temp_dir().join("adventure-mods-tests")) } fn cached_archive_path(url: &str) -> std::path::PathBuf { diff --git a/src/setup/common_tests.rs b/src/setup/common_tests.rs index e884f0b..f45e0f8 100644 --- a/src/setup/common_tests.rs +++ b/src/setup/common_tests.rs @@ -1,17 +1,14 @@ use super::*; #[test] -fn downloads_are_cached_in_the_app_folder_of_the_cache_dir() { +fn unit_tests_cache_downloads_in_their_own_temporary_folder() { let _guard = crate::test_env::lock(); let base = std::env::temp_dir().join("adventure-mods-tests"); - assert_eq!(default_cache_dir(), Some(base.join("adventure-mods"))); + assert_eq!(default_cache_dir(), Some(base.clone())); // SAFETY: the lock keeps other tests from reading the environment now. unsafe { std::env::remove_var("ADVENTURE_MODS_CACHE_DIR") }; - assert_eq!( - download_cache_dir(), - base.join("adventure-mods").join("downloads") - ); + assert_eq!(download_cache_dir(), base.join("downloads")); } #[test] diff --git a/tests/download.rs b/tests/download.rs index 307b58c..a80aebc 100644 --- a/tests/download.rs +++ b/tests/download.rs @@ -1,6 +1,7 @@ mod support; use adventure_mods::external::download; +use adventure_mods::setup::common::{self, ModEntry, ModSource}; use support::http_server::{Response, TestServer}; @@ -49,3 +50,47 @@ fn download_truncates_http_error_body_snippet() { assert!(message.contains(&"x".repeat(200))); assert!(!message.contains(&"x".repeat(250))); } + +#[test] +fn a_prefetched_mod_waits_in_the_app_folder_of_the_users_cache() { + let _ = rustls::crypto::ring::default_provider().install_default(); + let _env_lock = support::env_lock(); + let server = TestServer::start(std::collections::HashMap::from([( + "/mod.7z", + Response::Ok { + content_type: "application/octet-stream", + body: "archive", + }, + )])); + let tmp = tempfile::tempdir().unwrap(); + let cache = tmp.path().join("cache"); + // The release build caches in the user's cache folder, which + // XDG_CACHE_HOME moves on Linux. Each test runs in its own process under + // nextest, and the lock keeps the other tests here out meanwhile. + unsafe { + std::env::remove_var("ADVENTURE_MODS_CACHE_DIR"); + std::env::set_var("XDG_CACHE_HOME", &cache); + } + let mod_entry = ModEntry { + name: "Cached Mod", + slug: "cached-mod", + source: ModSource::DirectUrl { + url: support::leak_str(server.url("/mod.7z")), + }, + description: "test mod", + full_description: None, + pictures: &[], + dir_name: Some("CachedMod"), + links: &[], + }; + + let result = common::prefetch_mod_archive(&tmp.path().join("game"), &mod_entry, None); + unsafe { std::env::remove_var("XDG_CACHE_HOME") }; + result.unwrap(); + + let downloads = std::fs::read_dir(cache.join("adventure-mods/downloads")) + .unwrap() + .map(|entry| std::fs::read_to_string(entry.unwrap().path()).unwrap()) + .collect::>(); + assert_eq!(downloads, ["archive"]); +} From 36134d7adf6bc2e55641a3a601bb5c7e0a62044a Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:55:03 -0300 Subject: [PATCH 4/8] test: test which game has a backdrop and keep tests from leaking global state --- .cargo/mutants.toml | 1 + src/banner.rs | 4 +++- src/main.rs | 5 +++-- src/ui/welcome.rs | 25 ++++++++++++++++++++++++- tests/download.rs | 2 ++ 5 files changed, 33 insertions(+), 4 deletions(-) diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index 783fb9f..25ee60f 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -17,6 +17,7 @@ exclude_re = [ "\\bback_button\\b", # src/ui/welcome.rs "\\bpaint_tile\\b", + # Which game has a backdrop is in has_backdrop, which is tested. "\\bpaint_backdrops\\b", # src/ui/theme.rs "\\bpaint_background\\b", diff --git a/src/banner.rs b/src/banner.rs index 644cb2b..57b1ff8 100644 --- a/src/banner.rs +++ b/src/banner.rs @@ -51,11 +51,13 @@ mod tests { #[test] fn print_banner_formats_each_line_when_color_is_enabled() { // console leaves out the colors when stdout is not a terminal, as in - // tests. Each test runs in its own process under nextest. + // tests. + let previous = console::colors_enabled(); console::set_colors_enabled(true); let mut output = Vec::new(); print_banner(&mut output, true).unwrap(); + console::set_colors_enabled(previous); let output = String::from_utf8(output).unwrap(); assert_eq!(output.lines().count(), SONIC_BANNER.lines().count()); diff --git a/src/main.rs b/src/main.rs index a7b9d0a..c12a5ca 100644 --- a/src/main.rs +++ b/src/main.rs @@ -126,8 +126,8 @@ mod tests { #[test] fn either_gamescope_or_the_steam_gamepad_ui_means_game_mode() { - // nextest runs each test in its own process, so the variables do not - // leak into other tests. + // No other test in this binary reads these variables, and the test + // leaves both unset. let set = |gamescope: bool, gamepad_ui: bool| { for (name, on) in [ ("GAMESCOPE_WAYLAND_DISPLAY", gamescope), @@ -146,5 +146,6 @@ mod tests { assert!(set(true, false)); assert!(set(false, true)); assert!(set(true, true)); + set(false, false); } } diff --git a/src/ui/welcome.rs b/src/ui/welcome.rs index 93cdc1b..5c4c774 100644 --- a/src/ui/welcome.rs +++ b/src/ui/welcome.rs @@ -295,13 +295,19 @@ impl WelcomeScreen { /// The selected game's blurred cover fills the window, fading between /// games, with the bottom darkened so text stays readable. Call it before /// anything else is drawn, as it paints over the whole window. + /// Only the selected game has its cover behind the screen, and only when + /// the game is there: a missing game has nothing to show yet. + fn has_backdrop(&self, index: usize) -> bool { + index == self.selected && self.cards[index].state != CardState::Missing + } + pub fn paint_backdrops(&mut self, ctx: &egui::Context) { let screen = ctx.content_rect(); let painter = ctx.layer_painter(egui::LayerId::background()); for (index, card) in self.cards.iter().enumerate() { let shown = ctx.animate_bool_with_time_and_easing( egui::Id::unique(("backdrop", card.kind)), - index == self.selected && card.state != CardState::Missing, + self.has_backdrop(index), motion::SCREEN as f32 * 2.0, motion::ease_out, ); @@ -663,6 +669,23 @@ mod tests { ) } + #[test] + fn only_the_selected_game_that_is_there_has_a_backdrop() { + let mut screen = WelcomeScreen::default(); + // SADX is missing, SA2 is found. + screen.set_result(DetectionResult { + games: vec![game(GameKind::SA2, "/games/sa2")], + ..Default::default() + }); + assert_eq!(screen.selected, 1); + assert!(!screen.has_backdrop(0)); + assert!(screen.has_backdrop(1)); + + screen.selected = 0; + assert!(!screen.has_backdrop(0), "missing"); + assert!(!screen.has_backdrop(1), "not selected"); + } + #[test] fn cards_always_include_missing_games() { let cards = build_game_cards(&DetectionResult { diff --git a/tests/download.rs b/tests/download.rs index a80aebc..ae67c15 100644 --- a/tests/download.rs +++ b/tests/download.rs @@ -51,6 +51,8 @@ fn download_truncates_http_error_body_snippet() { assert!(!message.contains(&"x".repeat(250))); } +// XDG_CACHE_HOME moves the user's cache folder only on Linux. +#[cfg(target_os = "linux")] #[test] fn a_prefetched_mod_waits_in_the_app_folder_of_the_users_cache() { let _ = rustls::crypto::ring::default_provider().install_default(); From 95e87ce41eb397f844c14cdbb41846c3eb8583db Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:30:24 -0300 Subject: [PATCH 5/8] test: catch the last missed layout mutants --- src/ui/setup.rs | 8 +++++++- src/ui/setup_tests.rs | 5 +++++ src/ui/welcome.rs | 2 +- 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/ui/setup.rs b/src/ui/setup.rs index 877d31d..b5864ea 100644 --- a/src/ui/setup.rs +++ b/src/ui/setup.rs @@ -1525,6 +1525,12 @@ fn centering_space(room: f32, content: f32) -> f32 { ((room - content) / 2.0).max(24.0) } +/// Whether content `height` differs from `last` frame's by more than half a +/// point, so centering has to measure it again. +fn height_changed(height: f32, last: f32) -> bool { + (height - last).abs() > 0.5 +} + /// A download progress callback that updates the install screen's bar. fn step_progress( tx: async_channel::Sender, @@ -1575,7 +1581,7 @@ fn centered(ui: &mut Ui, add: impl FnOnce(&mut Ui)) { let last = ui.data(|data| data.get_temp::(id)).unwrap_or(0.0); ui.add_space(centering_space(ui.available_height(), last)); let height = ui.vertical_centered(add).response.rect.height(); - if (height - last).abs() > 0.5 { + if height_changed(height, last) { ui.data_mut(|data| data.insert_temp(id, height)); ui.ctx().request_repaint(); } diff --git a/src/ui/setup_tests.rs b/src/ui/setup_tests.rs index 491a4da..ec19f58 100644 --- a/src/ui/setup_tests.rs +++ b/src/ui/setup_tests.rs @@ -1301,6 +1301,11 @@ fn layout_sizes_fit_the_window() { assert!((short.x - short.y * 16.0 / 9.0).abs() < 1e-3); assert_eq!(centering_space(500.0, 300.0), 100.0); assert_eq!(centering_space(300.0, 290.0), 24.0); + // Centering measures again only when the height really changed. + assert!(height_changed(300.0, 0.0)); + assert!(height_changed(300.0, 301.0)); + assert!(!height_changed(300.0, 300.0)); + assert!(!height_changed(300.0, 300.4)); } #[test] diff --git a/src/ui/welcome.rs b/src/ui/welcome.rs index 5c4c774..dcccbdc 100644 --- a/src/ui/welcome.rs +++ b/src/ui/welcome.rs @@ -360,7 +360,7 @@ impl WelcomeScreen { motion::QUICK * 2.0, motion::ease_out, ); - let width = small + (large - small) * grow; + let width = egui::lerp(small..=large, grow); let size = tile_size(width); let (rect, response) = ui.allocate_exact_size(size, egui::Sense::click()); let name = card.kind.name(); From 6d6dc501ca7fe5c2d2bac05a1296fcb6fc60df25 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:42:39 -0300 Subject: [PATCH 6/8] test: name the tile grow time and test the height check at its limit --- src/ui/motion.rs | 2 ++ src/ui/setup_tests.rs | 1 + src/ui/welcome.rs | 2 +- 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/ui/motion.rs b/src/ui/motion.rs index 62ac450..5c1a1c4 100644 --- a/src/ui/motion.rs +++ b/src/ui/motion.rs @@ -5,6 +5,8 @@ use egui::{Context, Id, Response, Ui}; /// How long hover, focus and press effects take, in seconds. pub const QUICK: f32 = 0.12; +/// How long a game tile takes to grow when it is selected, in seconds. +pub const TILE_GROW: f32 = 0.24; /// How long a screen takes to fade and slide in, in seconds. pub const SCREEN: f64 = 0.22; /// How far a new screen slides up while it fades in, in points. diff --git a/src/ui/setup_tests.rs b/src/ui/setup_tests.rs index ec19f58..85b3449 100644 --- a/src/ui/setup_tests.rs +++ b/src/ui/setup_tests.rs @@ -1306,6 +1306,7 @@ fn layout_sizes_fit_the_window() { assert!(height_changed(300.0, 301.0)); assert!(!height_changed(300.0, 300.0)); assert!(!height_changed(300.0, 300.4)); + assert!(!height_changed(300.0, 300.5)); } #[test] diff --git a/src/ui/welcome.rs b/src/ui/welcome.rs index dcccbdc..82aba61 100644 --- a/src/ui/welcome.rs +++ b/src/ui/welcome.rs @@ -357,7 +357,7 @@ impl WelcomeScreen { let grow = ui.ctx().animate_bool_with_time_and_easing( egui::Id::unique(("tile-grow", card.kind)), index == self.selected, - motion::QUICK * 2.0, + motion::TILE_GROW, motion::ease_out, ); let width = egui::lerp(small..=large, grow); From 1398d987f8c38e93b41749a784183b67ab05cd73 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 22 Nov 2026 12:32:02 -0300 Subject: [PATCH 7/8] test: catch the retry, toast offset and tile gap mutants --- src/setup/pipeline_tests.rs | 20 ++++++++++++++++++++ src/ui/app_tests.rs | 9 ++++++++- src/ui/welcome.rs | 4 ++++ 3 files changed, 32 insertions(+), 1 deletion(-) diff --git a/src/setup/pipeline_tests.rs b/src/setup/pipeline_tests.rs index 4c56bfc..bea193d 100644 --- a/src/setup/pipeline_tests.rs +++ b/src/setup/pipeline_tests.rs @@ -453,6 +453,26 @@ fn failing_mods_are_retried_then_reported_by_name() { assert!(!manager_json(&env.game()).exists()); } +#[test] +fn a_mod_that_fails_once_installs_on_the_second_try() { + let env = DownloadEnv::new(); + let requests = std::sync::atomic::AtomicUsize::new(0); + let (base, log) = serve(move |_| match requests.fetch_add(1, Ordering::SeqCst) { + 0 => Reply::ok("busy").status("503 Service Unavailable"), + _ => Reply::ok("Name=Retry Mod"), + }); + let entry = served_mod("Retry Mod", "RetryMod", format!("{base}/retry.7z")); + + install(&env.game(), &[&entry], |_| Ok(())).unwrap(); + + // It stops after the try that works. + assert_eq!(gets(&log), 2); + assert_eq!( + std::fs::read_to_string(env.game().join("mods/RetryMod/mod.ini")).unwrap(), + "Name=Retry Mod" + ); +} + #[test] fn cancelling_during_a_download_stops_without_retrying() { let env = DownloadEnv::new(); diff --git a/src/ui/app_tests.rs b/src/ui/app_tests.rs index 00b92d1..52dcec9 100644 --- a/src/ui/app_tests.rs +++ b/src/ui/app_tests.rs @@ -656,7 +656,14 @@ fn a_toast_stays_for_a_few_seconds_and_keeps_the_window_repainting() { harness.state_mut().toast(&ctx, "Hello"); assert_eq!(harness.state().toasts[0].until, now + TOAST_SECONDS); harness.run_steps(2); - harness.get_by_label("Hello"); + // It sits above the footer, inside the window. + let toast = harness.get_by_label("Hello").rect(); + let window = harness.ctx.content_rect(); + assert!( + toast.bottom() <= window.bottom() + TOAST_OFFSET.y, + "{toast:?} in {window:?}" + ); + assert!(window.contains_rect(toast), "{toast:?} in {window:?}"); // The fade animates on every frame. assert_eq!(repaint_delay(&harness), Duration::ZERO); } diff --git a/src/ui/welcome.rs b/src/ui/welcome.rs index 82aba61..8370c5f 100644 --- a/src/ui/welcome.rs +++ b/src/ui/welcome.rs @@ -620,6 +620,10 @@ mod tests { assert_eq!((small, large), (400.0, 500.0)); assert_eq!(small + large + TILE_GAP, 924.0); assert_eq!(tile_widths(4000.0, 2), (560.0, 700.0)); + // Any count: the tiles and the gaps between them fill the row. + assert_eq!(tile_widths(500.0, 1), (400.0, 500.0)); + assert_eq!(tile_widths(698.0, 3), (200.0, 250.0)); + assert_eq!(200.0 * 2.0 + 250.0 + TILE_GAP * 2.0, 698.0); assert_eq!(tile_size(460.0), Vec2::new(460.0, 215.0)); } From bf221f80b7fc10b81d5ea65630fe5ff0db7aacb9 Mon Sep 17 00:00:00 2001 From: astrovm <5521045+astrovm@users.noreply.github.com> Date: Sun, 22 Nov 2026 12:39:01 -0300 Subject: [PATCH 8/8] refactor(setup): leave the mod install loop at the first success --- src/setup/pipeline.rs | 15 +++++++++------ src/ui/app_tests.rs | 2 +- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/setup/pipeline.rs b/src/setup/pipeline.rs index 31eba3f..ecad879 100644 --- a/src/setup/pipeline.rs +++ b/src/setup/pipeline.rs @@ -222,13 +222,16 @@ fn install_mods_and_generate_config( mod_entry, Some(&mut download_progress), ); - if result.is_ok() - || attempt == MAX_MOD_INSTALL_ATTEMPTS - || cancelled.load(Ordering::Relaxed) - { - break; + match &result { + Ok(()) => break, + Err(_) + if attempt == MAX_MOD_INSTALL_ATTEMPTS + || cancelled.load(Ordering::Relaxed) => + { + break; + } + Err(_) => std::thread::sleep(RETRY_PAUSE), } - std::thread::sleep(RETRY_PAUSE); } match result { diff --git a/src/ui/app_tests.rs b/src/ui/app_tests.rs index 52dcec9..8b07de6 100644 --- a/src/ui/app_tests.rs +++ b/src/ui/app_tests.rs @@ -660,7 +660,7 @@ fn a_toast_stays_for_a_few_seconds_and_keeps_the_window_repainting() { let toast = harness.get_by_label("Hello").rect(); let window = harness.ctx.content_rect(); assert!( - toast.bottom() <= window.bottom() + TOAST_OFFSET.y, + window.bottom() - toast.bottom() >= 100.0, "{toast:?} in {window:?}" ); assert!(window.contains_rect(toast), "{toast:?} in {window:?}");