diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml index 25ee60f..f48e32e 100644 --- a/.cargo/mutants.toml +++ b/.cargo/mutants.toml @@ -21,8 +21,13 @@ exclude_re = [ "\\bpaint_backdrops\\b", # src/ui/theme.rs "\\bpaint_background\\b", - # src/ui/motion.rs: the button press offset - "in press$", + # src/ui/motion.rs: the hover and press animations. Their values only + # tint and offset what is painted. Both forms of the name: "in press" for + # a change inside, "replace press ->" for its return value. + "^src/ui/motion\\.rs:\\d+:\\d+: replace (highlight|press)\\b", + "^src/ui/motion\\.rs:.* in (highlight|press)$", + # The focus outline and the card frame: color, radius and shadow. + "^src/ui/widgets\\.rs:.*\\b(focus_ring|card)\\b", # src/ui/setup.rs "\\bshow_cover\\b", "\\bspinner\\b", @@ -31,4 +36,10 @@ exclude_re = [ # src/ui/images.rs: an image exactly MAX_WIDTH wide is resized to the # same size. "replace > with >= in decode$", + # src/ui/welcome.rs: when the image and the area have the same shape, + # both branches give the whole image. + "replace > with >= in cover_uv$", + # src/setup/common.rs: an archive exactly MAX_CACHED_ARCHIVE_AGE old, to + # the nanosecond, is kept or dropped; no test can make that age. + "replace > with >= in discard_stale_archive$", ] diff --git a/src/cli.rs b/src/cli.rs index e62b68c..661070b 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -111,7 +111,7 @@ impl TerminalPrompt { impl Prompt for TerminalPrompt { fn select(&self, prompt: &str, items: &[String], default: usize) -> Result { self.with_stderr_colors(|| { - Ok(Select::with_theme(&prompt_theme()) + Ok(Select::with_theme(&ColorfulTheme::default()) .with_prompt(prompt) .items(items) .default(default) @@ -126,7 +126,7 @@ impl Prompt for TerminalPrompt { defaults: &[bool], ) -> Result> { self.with_stderr_colors(|| { - Ok(MultiSelect::with_theme(&prompt_theme()) + Ok(MultiSelect::with_theme(&ColorfulTheme::default()) .with_prompt(prompt) .items(items) .defaults(defaults) @@ -136,7 +136,7 @@ impl Prompt for TerminalPrompt { fn confirm(&self, prompt: &str, default: bool) -> Result { self.with_stderr_colors(|| { - Ok(Confirm::with_theme(&prompt_theme()) + Ok(Confirm::with_theme(&ColorfulTheme::default()) .with_prompt(prompt) .default(default) .interact()?) @@ -806,10 +806,6 @@ fn persist_cli_language_selection( ); } -fn prompt_theme() -> ColorfulTheme { - ColorfulTheme::default() -} - fn resolve_game_kind_rich( args: &SetupArgs, detected: Option<&DetectionResult>, @@ -1292,29 +1288,19 @@ fn gui_flag_requires_value(arg: &str) -> bool { } fn has_only_gui_flags(args: &[String]) -> bool { - let mut index = 1; - - while index < args.len() { - let arg = &args[index]; + let mut rest = args.iter().skip(1); + while let Some(arg) = rest.next() { if arg == "--no-color" { - index += 1; continue; } - if !arg.starts_with('-') || !is_known_gui_flag(arg) { return false; } - - if gui_flag_requires_value(arg) { - index += 1; - if index >= args.len() { - return false; - } + // The value is the next argument, which must be there. + if gui_flag_requires_value(arg) && rest.next().is_none() { + return false; } - - index += 1; } - true } diff --git a/src/cli_tests.rs b/src/cli_tests.rs index 5e1b10b..caf1179 100644 --- a/src/cli_tests.rs +++ b/src/cli_tests.rs @@ -2182,6 +2182,43 @@ fn game_path_flag_is_validated_instead_of_detected() { ); } +/// Answers every list with the option the prompt marks as the default. +struct DefaultPrompt; + +impl Prompt for DefaultPrompt { + fn select(&self, _prompt: &str, _items: &[String], default: usize) -> anyhow::Result { + Ok(default) + } + + fn multi_select( + &self, + _prompt: &str, + _items: &[String], + _defaults: &[bool], + ) -> anyhow::Result> { + Ok(Vec::new()) + } + + fn confirm(&self, _prompt: &str, default: bool) -> anyhow::Result { + Ok(default) + } +} + +#[test] +fn language_prompts_start_on_the_saved_choices() { + with_test_settings(|settings| { + set_string(settings, "sadx-subtitle-language", "german"); + set_string(settings, "sadx-voice-language", "english"); + + let selection = + resolve_setup_languages(&empty_setup_args(), GameKind::SADX, Some(&DefaultPrompt)) + .unwrap(); + + assert_eq!(selection.subtitle, SubtitleLanguage::German); + assert_eq!(selection.voice, VoiceLanguage::English); + }); +} + #[test] fn voice_language_keeps_the_saved_choice_without_flag_or_prompt() { with_test_settings(|settings| { diff --git a/src/display.rs b/src/display.rs index da4169e..4f488fb 100644 --- a/src/display.rs +++ b/src/display.rs @@ -177,6 +177,14 @@ mod tests { ); assert_eq!(preferred_resolution([(1080, 1920)]), Some((1080, 1920))); assert_eq!(preferred_resolution([]), None); + // A monitor with no width or no height is not a monitor. + assert_eq!(preferred_resolution([(0, 1080)]), None); + assert_eq!(preferred_resolution([(1920, 0)]), None); + // The biggest area wins, not the longest sides. + assert_eq!( + preferred_resolution([(3000, 100), (1920, 1080)]), + Some((1920, 1080)) + ); } #[test] diff --git a/src/external/download.rs b/src/external/download.rs index ec9cafa..258fde5 100644 --- a/src/external/download.rs +++ b/src/external/download.rs @@ -36,7 +36,8 @@ const SPEED_WINDOW: std::time::Duration = if cfg!(test) { /// [`SPEED_WINDOW`] (about 256 KiB/s) asks for the file again, so the host /// can pick another mirror. GameBanana picks one per request, and some are /// much slower than others. -const SLOW_WINDOW_BYTES: u64 = if cfg!(test) { 5 } else { 20 * 256 * 1024 }; +// 20 × 256 KiB, written out: tests use 5, so no test could check the math. +const SLOW_WINDOW_BYTES: u64 = if cfg!(test) { 5 } else { 5_242_880 }; /// How many times one download may ask for another mirror. const MIRROR_RETRIES: usize = 3; @@ -647,6 +648,9 @@ mod tests { ranged_file(request, "\"v1\"").header("Accept-Ranges", "bytes") } "/slow" => trickle(request, true), + "/stall" => ranged_file(request, "\"v1\"") + .header("Accept-Ranges", "bytes") + .pause_after(1, STALL_TIMEOUT * 3), _ => trickle(request, false), }); let asked = std::sync::atomic::AtomicUsize::new(0); @@ -684,6 +688,20 @@ mod tests { ); } + #[test] + fn another_mirror_that_stops_responding_still_fails() { + // The client for other mirrors keeps the stall timeout of the shared one. + init(); + let (url, mirror_log, _) = mirrored_file("/stall", usize::MAX); + let tmp = tempfile::tempdir().unwrap(); + let dest = tmp.path().join("file.7z"); + + let err = download_file_resumable(&url, &dest, None).unwrap_err(); + + assert!(err.to_string().contains("stopped responding"), "{err:#}"); + assert_eq!(mirror_log.lock().unwrap().len(), MIRROR_RETRIES + 1); + } + #[test] fn a_mirror_that_stays_slow_is_kept_after_a_few_tries() { init(); @@ -1073,8 +1091,10 @@ mod tests { .unwrap_err(); assert_eq!(err.to_string(), "cancelled"); + // The server answers after 3 stall timeouts. The cancel comes at the first + // heartbeat, so a slow, busy machine still stops well before that. let elapsed = started.elapsed(); - assert!(elapsed < STALL_TIMEOUT, "{elapsed:?}"); + assert!(elapsed < STALL_TIMEOUT * 3, "{elapsed:?}"); // Before the answer, progress counts the kept bytes with no total. assert_eq!(seen, Some((2, None))); } diff --git a/src/ui/app_tests.rs b/src/ui/app_tests.rs index 8b07de6..519367a 100644 --- a/src/ui/app_tests.rs +++ b/src/ui/app_tests.rs @@ -749,6 +749,24 @@ fn a_window_bigger_than_its_monitor_shrinks_to_fit() { assert!(inner_size_commands(&harness).is_empty()); } +#[test] +fn a_zoomed_window_bigger_than_its_monitor_shrinks_to_fit() { + // The monitor is known only after the UI zoomed, as on Wayland. + let fixture = Fixture::new(&[]); + let mut app = fixture.app(); + app.window.saved = true; + let layout = Vec2::new(super::super::LAYOUT_WIDTH, super::super::LAYOUT_HEIGHT); + let mut harness = harness_on_monitor(app, Vec2::new(640.0, 360.0), layout); + harness.ctx.set_zoom_factor(2.0); + harness.step(); + // At zoom 2 the monitor is 1280 by 720 on screen. The window keeps its + // width and loses height, then goes back to points. + assert_eq!( + inner_size_commands(&harness), + vec![Vec2::new(layout.x / 2.0, 360.0)] + ); +} + #[test] fn the_first_window_is_sized_for_its_monitor() { let fixture = Fixture::new(&[]); diff --git a/src/ui/dialogs.rs b/src/ui/dialogs.rs index b1b47c3..1cc8316 100644 --- a/src/ui/dialogs.rs +++ b/src/ui/dialogs.rs @@ -300,6 +300,31 @@ mod tests { assert!(!filled(&harness, "English")); } + #[test] + fn long_choice_lists_scroll_and_keep_cancel_on_screen() { + let options = (1..=40).map(|n| format!("Option {n}")).collect(); + let dialog = ChoiceDialog::new("long", "Many", options, None); + let harness = Harness::builder() + .with_size(egui::vec2(800.0, 600.0)) + .build_ui_state( + |ui, dialog: &mut ChoiceDialog| { + // Nothing is clicked, so the dialog gives no answer. + let _ = dialog.show(ui.ctx()); + }, + dialog, + ); + + let title = harness.get_by_label("Many").rect(); + let cancel = harness.get_by_label("Cancel").rect(); + assert!(title.top() >= 0.0, "{title:?}"); + assert!(cancel.bottom() <= 600.0, "{cancel:?}"); + // The list takes at most 60% of the window. + assert!( + cancel.top() - title.bottom() <= 600.0 * 0.6 + 40.0, + "{title:?} {cancel:?}" + ); + } + #[test] fn choice_dialogs_can_be_cancelled() { let mut harness = choice_harness(); diff --git a/src/ui/setup.rs b/src/ui/setup.rs index b5864ea..4dec33b 100644 --- a/src/ui/setup.rs +++ b/src/ui/setup.rs @@ -644,13 +644,17 @@ impl SetupFlow { let Some(last) = self.steps.len().checked_sub(1) else { return start; }; - let mut index = start; // Never skip the last step, the finish screen. - while index < last && (self.work.is_step_complete)(self.steps[index].id, &self.game) { - tracing::info!("Auto-skipping completed step: {}", self.steps[index].id); - index += 1; - } - index + (start..last) + .find(|&index| { + let id = self.steps[index].id; + let complete = (self.work.is_step_complete)(id, &self.game); + if complete { + tracing::info!("Auto-skipping completed step: {id}"); + } + !complete + }) + .unwrap_or(last.max(start)) } fn steam_status(&mut self) -> &SteamConfigStatus { @@ -1185,7 +1189,7 @@ impl SetupFlow { .expect("work steps always have an install view"); let busy = self.task.is_some(); centered(ui, |ui| { - ui.set_max_width(620.0); + ui.set_max_width(INSTALL_CARD_WIDTH); widgets::card().inner_margin(8).show(ui, |ui| { ui.set_width(ui.available_width()); for task in &install.tasks { @@ -1198,8 +1202,10 @@ impl SetupFlow { ui.label(RichText::new(task.title).strong()); widgets::caption(ui, task.subtitle()); }); - let (rect, response) = - ui.allocate_exact_size(Vec2::splat(36.0), egui::Sense::hover()); + let (rect, response) = ui.allocate_exact_size( + Vec2::splat(STATUS_ICON_SIZE), + egui::Sense::hover(), + ); match task.state { TaskState::Pending => {} TaskState::Running => { @@ -1496,6 +1502,10 @@ fn prefetch_order(mods: &[ModEntry], index: Option, page: usize) -> Vec<& /// The most of the preview panel's height its picture takes: its share in /// the layout's window size, where the description and links fit under it. const PICTURE_SHARE: f32 = 0.47; +/// The width of the install card, in points. +const INSTALL_CARD_WIDTH: f32 = 620.0; +/// The size of the status icon at the end of each install row, in points. +const STATUS_ICON_SIZE: f32 = 36.0; /// 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. diff --git a/src/ui/setup_tests.rs b/src/ui/setup_tests.rs index 85b3449..6199f49 100644 --- a/src/ui/setup_tests.rs +++ b/src/ui/setup_tests.rs @@ -736,6 +736,49 @@ fn cancelling_the_mod_download_waits_for_it_and_goes_back() { assert!(!dir.path().join("installed.txt").exists()); } +#[test] +fn install_texts_leave_room_for_the_status_icons() { + let dir = game_dir(&["proton-ready", "hold-mods"]); + 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, "mods downloading", |state| { + step_id(state) == StepId::DownloadMods + }); + let texts: Vec = harness + .state() + .flow + .install + .as_ref() + .unwrap() + .tasks + .iter() + .flat_map(|task| [task.title.to_owned(), task.subtitle().to_owned()]) + .collect(); + // The card is in the middle of the 1280-point window. Each row has 8 + 16 + // points of margins and the status icon on the right. + let icons_left = 640.0 + INSTALL_CARD_WIDTH / 2.0 - 8.0 - 16.0 - STATUS_ICON_SIZE; + let mut checked = 0; + for shape in &harness.output().shapes { + if let egui::Shape::Text(text) = &shape.shape + && texts.iter().any(|t| t == text.galley.text()) + { + checked += 1; + let bounds = text.visual_bounding_rect(); + assert!( + bounds.right() <= icons_left, + "{:?} {bounds:?}", + text.galley.text() + ); + } + } + assert!(checked >= texts.len(), "{checked} of {texts:?}"); + let _ = std::fs::remove_file(dir.path().join("hold-mods")); +} + #[test] fn cancelling_while_the_prefetch_finishes_installs_nothing() { let dir = game_dir(&["proton-ready", "hold-prefetch"]); diff --git a/src/ui/widgets.rs b/src/ui/widgets.rs index 98f32dd..c8e399e 100644 --- a/src/ui/widgets.rs +++ b/src/ui/widgets.rs @@ -253,16 +253,6 @@ fn banner_with(ui: &mut Ui, tone: Tone, content: impl FnOnce(&mut Ui)) -> Respon .response } -/// A colored dot with a short state label, such as "Mods installed". -pub fn status_dot(ui: &mut Ui, tone: Tone, label: &str) { - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 8.0; - let (dot, _) = ui.allocate_exact_size(Vec2::splat(14.0), Sense::hover()); - ui.painter().circle_filled(dot.center(), 6.0, tone.color()); - ui.label(RichText::new(label).strong().color(tone.color())); - }); -} - /// Dimmed, smaller text that wraps. pub fn caption(ui: &mut Ui, text: &str) -> Response { ui.add( @@ -664,6 +654,37 @@ mod tests { assert!(!*harness.state(), "Enter on the focused row flips it back"); } + #[test] + fn toggle_row_texts_wrap_inside_the_row() { + let subtitle = "Restores the look of the Dreamcast version, with its \ + original menus, models, textures and lighting in every stage"; + let harness = Harness::builder() + .with_size(egui::vec2(360.0, 300.0)) + .build_ui(|ui| { + theme::apply_ui(ui); + toggle_row(ui, &mut false, "Dreamcast Conversion", subtitle); + }); + + let row = harness.get_by_label("Dreamcast Conversion").rect(); + let texts: Vec = harness + .output() + .shapes + .iter() + .filter_map(|shape| match &shape.shape { + egui::Shape::Text(text) => Some(text.visual_bounding_rect()), + _ => None, + }) + .collect(); + assert_eq!(texts.len(), 2, "{texts:?}"); + for text in texts { + assert!( + text.left() >= row.left() + TOGGLE_TEXT_LEFT - 1.0, + "{text:?} {row:?}" + ); + assert!(text.right() <= row.right() - 16.0, "{text:?} {row:?}"); + } + } + #[test] fn every_widget_renders_in_and_out_of_focus() { let mut harness = Harness::new_ui_state( @@ -682,7 +703,6 @@ mod tests { clicks.push("Voices"); } banner(ui, Tone::Warning, "Needs access"); - status_dot(ui, Tone::Success, "Mods installed"); caption(ui, "Small print"); pad_hint(ui, "A", theme::SUCCESS, "Select"); status_page(ui, "✔", Tone::Success, "Proton Is Ready", "All set");