Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions .cargo/mutants.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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$",
]
30 changes: 8 additions & 22 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ impl TerminalPrompt {
impl Prompt for TerminalPrompt {
fn select(&self, prompt: &str, items: &[String], default: usize) -> Result<usize> {
self.with_stderr_colors(|| {
Ok(Select::with_theme(&prompt_theme())
Ok(Select::with_theme(&ColorfulTheme::default())
.with_prompt(prompt)
.items(items)
.default(default)
Expand All @@ -126,7 +126,7 @@ impl Prompt for TerminalPrompt {
defaults: &[bool],
) -> Result<Vec<usize>> {
self.with_stderr_colors(|| {
Ok(MultiSelect::with_theme(&prompt_theme())
Ok(MultiSelect::with_theme(&ColorfulTheme::default())
.with_prompt(prompt)
.items(items)
.defaults(defaults)
Expand All @@ -136,7 +136,7 @@ impl Prompt for TerminalPrompt {

fn confirm(&self, prompt: &str, default: bool) -> Result<bool> {
self.with_stderr_colors(|| {
Ok(Confirm::with_theme(&prompt_theme())
Ok(Confirm::with_theme(&ColorfulTheme::default())
.with_prompt(prompt)
.default(default)
.interact()?)
Expand Down Expand Up @@ -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>,
Expand Down Expand Up @@ -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
}

Expand Down
37 changes: 37 additions & 0 deletions src/cli_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<usize> {
Ok(default)
}

fn multi_select(
&self,
_prompt: &str,
_items: &[String],
_defaults: &[bool],
) -> anyhow::Result<Vec<usize>> {
Ok(Vec::new())
}

fn confirm(&self, _prompt: &str, default: bool) -> anyhow::Result<bool> {
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| {
Expand Down
8 changes: 8 additions & 0 deletions src/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
24 changes: 22 additions & 2 deletions src/external/download.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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)));
}
Expand Down
18 changes: 18 additions & 0 deletions src/ui/app_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(&[]);
Expand Down
25 changes: 25 additions & 0 deletions src/ui/dialogs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
28 changes: 19 additions & 9 deletions src/ui/setup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand All @@ -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 => {
Expand Down Expand Up @@ -1496,6 +1502,10 @@ fn prefetch_order(mods: &[ModEntry], index: Option<usize>, 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.
Expand Down
43 changes: 43 additions & 0 deletions src/ui/setup_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> = 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"]);
Expand Down
Loading