//! Settings, shortcuts, palette and first run: what changes, what is undone, what is kept, and what the keyboard does. #[path = "main/fixture.rs"] mod fixture; use eframe::egui::{Event, Key, Modifiers, PointerButton, Pos2, Vec2, vec2}; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use fixture::{all, lists, many, shot, view}; use medlar_app::app::App; use medlar_app::bridge::Bridge; use medlar_app::desktop::Sources; use medlar_app::keys::{self, Action, Shortcut}; use medlar_app::views::firstrun::FirstRun; use medlar_app::views::list::layout::Form; use medlar_app::views::main::Wish; use medlar_app::views::settings::rows::{self, Kind, Page}; use medlar_app::views::settings::{View, read_backup, site_of, write_backup}; use medlar_core::manager::Command; use medlar_core::model::State; use medlar_core::paths::Paths; use medlar_core::settings::{Appearance, Mode, Motion, Settings}; use medlar_core::site::Site; use medlar_core::strings::Catalogue; use std::path::{Path, PathBuf}; use std::time::Instant; type H = Harness<'static, Option>; fn nowhere() -> Sources { Sources { caelestia: "/nonexistent".into(), kde: "/nonexistent".into() } } fn harness_with(size: Vec2, sources: Sources, set: impl Fn(&mut App) + 'static) -> H { let frame = move |ui: &mut eframe::egui::Ui, s: &mut Option| { let Some(app) = s else { let settings = Settings { motion: Motion::Off, ..Settings::default() }; let mut app = App::new(ui.ctx(), settings, sources.clone()); app.main.bridge = Bridge::still(shot(all()), lists()); set(&mut app); *s = Some(app); ui.ctx().request_repaint(); return; }; app.show(ui); }; let mut h = Harness::builder().with_size(size).with_step_dt(1.0 / 60.0).build_ui_state(frame, None); h.run_steps(20); h } fn harness(set: impl Fn(&mut App) + 'static) -> H { harness_with(vec2(1080.0, 1000.0), nowhere(), set) } fn at(page: Page) -> H { harness(move |app| app.open_settings(page)) } fn app(h: &mut H) -> &mut App { h.state_mut().as_mut().unwrap() } fn s(h: &mut H) -> &mut Settings { &mut app(h).settings } fn click_at(h: &mut H, pos: Pos2) { for pressed in [true, false] { h.input_mut().events.push(Event::PointerMoved(pos)); h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); h.step(); } h.run_steps(30); } fn click(h: &mut H, label: &str) { // A field's name stands above it, and is drawn first. let pos = h.query_all_by_label(label).last().unwrap_or_else(|| panic!("no {label}")).rect().center(); click_at(h, pos); } fn key(h: &mut H, m: Modifiers, k: Key) { h.key_press_modifiers(m, k); h.run_steps(4); } fn text(h: &mut H, what: &str) { h.input_mut().events.push(Event::Text(what.into())); h.run_steps(4); } fn there(h: &H, label: &str) -> bool { h.query_by_label(label).is_some() } fn caelestia(dir: &Path) -> Sources { let file = dir.join("scheme.json"); std::fs::write(&file, r#"{"mode": "dark", "colours": {"primary": "5a8f3c"}}"#).unwrap(); Sources { caelestia: file, kde: "/nonexistent".into() } } // The registry. #[test] fn every_row_has_its_texts_and_real_keys() { let english = Catalogue::english(); let has = |key: &str| english.text(key, &[]) != key; let known = serde_json::to_value(Settings::default()).unwrap(); let mut ids = std::collections::HashSet::new(); for r in rows::all() { for k in r.keys { assert!(known.get(k).is_some(), "{}: no setting {k}", r.id); } if let Kind::Shortcut(_) = r.kind { continue; } assert!(ids.insert(r.id), "{} twice", r.id); assert!(has(&format!("set.{}", r.id)) && has(&format!("set.{}.why", r.id)), "{}", r.id); assert!(r.group.is_empty() || has(&format!("set.group.{}", r.group)), "{}", r.group); if let Kind::Choice { options, .. } = r.kind { options.iter().for_each(|o| assert!(has(&format!("set.{}.{o}", r.id)), "{}.{o}", r.id)); } } assert!(Page::ALL.iter().all(|p| has(&format!("page.{}", p.id())))); } /// What the user can change has a row. The others are named here, with who has them. #[test] fn every_setting_has_a_row() { let Ok(serde_json::Value::Object(all)) = serde_json::to_value(Settings::default()) else { panic!() }; let there: Vec<&str> = rows::all().flat_map(|r| r.keys.iter().copied()).collect(); // Edited on their own screens: the speed grid in the schedule view (S022). let elsewhere = ["mode_grid"]; for key in all.keys().filter(|k| !elsewhere.contains(&k.as_str())) { assert!(there.contains(&key.as_str()), "no row for {key}"); } } #[test] fn values_go_in_and_come_out_the_same() { let mut s = Settings::default(); for r in rows::all() { match r.kind { Kind::Switch { get, set } => { let was = get(&s); set(&mut s, !was); assert_eq!(get(&s), !was, "{}", r.id); } Kind::Choice { options, get, set } => { for i in (0..options.len()).rev() { set(&mut s, i); assert_eq!(get(&s), i, "{}", r.id); } } Kind::Number { range, get, set, .. } => { for v in [*range.start(), *range.end()] { set(&mut s, v); assert_eq!(get(&s), v, "{}", r.id); } } _ => {} } } } #[test] fn snail_remembers_the_mode_before_it() { let mut s = Settings { mode: Mode::Medium, ..Settings::default() }; let Some(Kind::Choice { set, .. }) = rows::all().find(|r| r.id == "mode").map(|r| r.kind) else { panic!() }; set(&mut s, 3); assert_eq!((s.mode, s.before_snail), (Mode::Snail, Mode::Medium)); s.toggle_snail(); assert_eq!(s.mode, Mode::Medium); set(&mut s, 3); set(&mut s, 0); assert_eq!(s.mode, Mode::Low); } // The screen. #[test] fn the_screen_opens_closes_and_shows_every_page() { let mut h = harness(|_| {}); key(&mut h, Modifiers::COMMAND, Key::Comma); for page in Page::shown() { click(&mut h, &page.label()); let first = page.rows().next().unwrap().name(); assert!(h.query_all_by_label(&first).count() > 0 || page == Page::Look || page == Page::Shortcuts || page == Page::Sites || page == Page::Backup || page == Page::Network, "{page:?}"); assert_eq!(app(&mut h).screen.as_ref().unwrap().page(), page); } key(&mut h, Modifiers::NONE, Key::Escape); assert!(app(&mut h).screen.is_none()); click(&mut h, "Settings"); assert!(app(&mut h).screen.is_some()); click(&mut h, "Back to downloads"); assert!(app(&mut h).screen.is_none()); } #[test] fn changes_count_at_once_and_a_page_is_undone_alone() { let mut h = at(Page::Look); assert!(!there(&h, "Undo changes")); click(&mut h, "Light"); assert_eq!(s(&mut h).appearance, Appearance::Light); assert!(!app(&mut h).theme.dark); click(&mut h, "Downloads"); click(&mut h, "Go on after a restart"); assert!(!s(&mut h).auto_resume); click(&mut h, "Undo changes"); assert!(s(&mut h).auto_resume); assert!(!there(&h, "Undo changes")); assert_eq!(s(&mut h).appearance, Appearance::Light); click(&mut h, "Look"); click(&mut h, "Undo changes"); assert_eq!(s(&mut h).appearance, Appearance::Auto); } #[test] fn search_finds_rows_of_any_page_and_they_work_there() { let mut h = at(Page::Look); key(&mut h, Modifiers::COMMAND, Key::F); text(&mut h, "restart"); assert!(there(&h, "Go on after a restart")); click(&mut h, "Go on after a restart"); assert!(!s(&mut h).auto_resume); key(&mut h, Modifiers::COMMAND, Key::F); key(&mut h, Modifiers::COMMAND, Key::A); text(&mut h, "zzz"); assert!(!there(&h, "Go on after a restart")); key(&mut h, Modifiers::NONE, Key::Escape); assert!(app(&mut h).screen.is_some(), "Escape empties the search first"); } #[test] fn a_bad_folder_is_not_taken() { let mut h = at(Page::Downloads); click(&mut h, "Download folder"); text(&mut h, "relative"); assert_eq!(s(&mut h).download_folder, ""); key(&mut h, Modifiers::COMMAND, Key::A); text(&mut h, "/tmp"); assert_eq!(s(&mut h).download_folder, "/tmp"); assert!(rows::folder_error("/etc/passwd").is_some()); } #[test] fn an_own_proxy_counts_only_once_it_can() { let mut h = at(Page::Network); click(&mut h, "Own"); assert_eq!(s(&mut h).proxy, "system"); click(&mut h, "Address"); text(&mut h, "socks5://127.0.0"); let half = s(&mut h).proxy.clone(); text(&mut h, ".1:1080"); assert_eq!(s(&mut h).proxy, "socks5://127.0.0.1:1080"); assert!(half == "system" || half.starts_with("socks5://127")); click(&mut h, "None"); assert_eq!(s(&mut h).proxy, "direct"); assert!(!there(&h, "Address")); } #[test] fn sites_are_added_changed_removed_and_come_back() { let mut h = at(Page::Sites); click(&mut h, "Add site"); h.run_steps(30); text(&mut h, "files.example.org"); click(&mut h, "User name"); text(&mut h, "me"); click(&mut h, "Password"); text(&mut h, "pw"); click(&mut h, "Save"); let site = s(&mut h).sites[0].clone(); assert_eq!((site.pattern.as_str(), site.secret.as_deref()), ("files.example.org", Some("site:files.example.org"))); assert!(!serde_json::to_string(s(&mut h)).unwrap().contains("pw")); click(&mut h, "Change files.example.org"); h.run_steps(30); click(&mut h, "Own user agent"); text(&mut h, "Agent"); click(&mut h, "Save"); let site = s(&mut h).sites[0].clone(); assert_eq!((site.user_agent.as_deref(), site.secret.is_some()), (Some("Agent"), true)); click(&mut h, "Remove files.example.org"); assert!(s(&mut h).sites.is_empty()); click(&mut h, "Undo"); assert_eq!(s(&mut h).sites.len(), 1); } #[test] fn a_login_for_anyone_is_refused() { let mut h = at(Page::Sites); click(&mut h, "Add site"); h.run_steps(30); let first = h.query_all_by_label("More").next().unwrap().rect(); assert!(first.right() < h.query_all_by_label("Speed limit").last().unwrap().rect().left(), "the numbers stand beside each other"); text(&mut h, "*.com"); click(&mut h, "User name"); text(&mut h, "me"); assert!(h.get_by_label("Save").accesskit_node().is_disabled()); } #[test] fn signing_in_makes_a_rule_and_resumes() { let mut h = harness(|app| app.main.wish = Some(Wish::SignIn("https://me@files.example.org:8443/a/b.zip?x".into(), vec![7, 9]))); h.run_steps(30); click(&mut h, "User name"); text(&mut h, "me"); h.run_steps(2); key(&mut h, Modifiers::NONE, Key::Enter); let site: Site = s(&mut h).sites[0].clone(); assert_eq!((site.pattern.as_str(), site.secret.as_deref()), ("files.example.org:8443", Some("site:files.example.org:8443"))); let sent = app(&mut h).main.bridge.take_sent(); assert!(matches!(sent[..], [Command::Resume(7), Command::Resume(9)])); assert_eq!((site_of("x"), site_of("http://[::1]:80/")), (None, Some("[::1]:80".into()))); } #[test] fn changed_settings_are_written_and_read_again() { let dir = tempfile::tempdir().unwrap(); let paths = paths(dir.path()); let file = paths.settings(); let mut h = harness(move |app| { app.paths = Some(paths.clone()); app.open_settings(Page::Downloads); }); click(&mut h, "Go on after a restart"); h.run_steps(60); app(&mut h).finish(); assert!(!Settings::load(&file).0.auto_resume); click(&mut h, "Go on after a restart"); // At once when the window closes. app(&mut h).finish(); assert!(Settings::load(&file).0.auto_resume); } fn paths(dir: &Path) -> Paths { let sub = |n: &str| dir.join(n); let paths = Paths { config: sub("config"), data: sub("data"), state: sub("state"), cache: sub("cache"), portable: false }; paths.create().unwrap(); paths } // Colour. #[test] fn both_colour_sources_are_equal_choices() { let dir = tempfile::tempdir().unwrap(); let mut h = harness_with(vec2(1080.0, 1000.0), caelestia(dir.path()), |app| app.open_settings(Page::Look)); let (desk, own) = (h.get_by_label("Follow desktop").rect(), h.get_by_label("Own colour").rect()); assert_eq!((desk.size(), desk.top()), (own.size(), own.top())); assert!(desk.right() < own.left()); let followed = app(&mut h).theme.clone(); assert!(!there(&h, "Hue")); click(&mut h, "Own colour"); assert_eq!(s(&mut h).desktop_colors, Some(false)); assert_ne!(app(&mut h).theme, followed); let before = s(&mut h).own_color.clone(); let hue = h.get_by_label("Hue").rect(); click_at(&mut h, hue.center()); assert_ne!(s(&mut h).own_color, before); click(&mut h, "Follow desktop"); assert_eq!((s(&mut h).desktop_colors, app(&mut h).theme == followed), (Some(true), true)); } #[test] fn without_desktop_colours_the_own_one_is_there() { let mut h = at(Page::Look); assert!(there(&h, "Hue")); click(&mut h, "Follow desktop"); assert_eq!(s(&mut h).desktop_colors, None); click(&mut h, "Colour #3d6fc4"); let now = s(&mut h).clone(); assert_eq!((now.own_color.as_str(), now.desktop_colors), ("#3d6fc4", Some(false))); click(&mut h, "Colour code"); key(&mut h, Modifiers::COMMAND, Key::A); text(&mut h, "00ff0"); assert_eq!(s(&mut h).own_color, "#3d6fc4"); text(&mut h, "0"); assert_eq!(s(&mut h).own_color, "#00ff00"); } #[test] fn the_preview_runs_for_a_moment_and_then_rests() { let mut h = harness(|app| { app.settings.motion = Motion::Expressive; app.open_settings(Page::Look); }); assert!(there(&h, "Pause")); h.run_steps(60 * 6); assert!(there(&h, "Run")); h.run_steps(60); assert!(!medlar_app::motion::busy()); } // Shortcuts. #[test] fn a_shortcut_is_recorded_collides_moves_and_is_reset() { let mut h = at(Page::Shortcuts); click(&mut h, "Search downloads: Ctrl+F"); key(&mut h, Modifiers::COMMAND | Modifiers::SHIFT, Key::F); assert_eq!(keys::of(s(&mut h), Action::Find), Shortcut::parse("Ctrl+Shift+F")); click(&mut h, "Search downloads: Ctrl+Shift+F"); // Taken: nothing is added, nothing changes until the user says so. key(&mut h, Modifiers::COMMAND, Key::N); assert_eq!(keys::of(s(&mut h), Action::Find), Shortcut::parse("Ctrl+Shift+F")); click(&mut h, "Use it here instead"); assert_eq!((keys::of(s(&mut h), Action::Find), keys::of(s(&mut h), Action::Add)), (Shortcut::parse("Ctrl+N"), None)); click(&mut h, "Reset Add links"); assert_eq!(keys::conflicts(s(&mut h), Action::Add), [Action::Find]); click(&mut h, "Search downloads: Ctrl+N"); key(&mut h, Modifiers::NONE, Key::Escape); assert!(app(&mut h).screen.is_some(), "Escape only ends the recording"); click(&mut h, "Search downloads: Ctrl+N"); key(&mut h, Modifiers::NONE, Key::Backspace); assert_eq!(keys::of(s(&mut h), Action::Find), None); click(&mut h, "Reset all"); assert!(s(&mut h).shortcuts.is_empty()); click(&mut h, "Copy links: Ctrl+C"); h.input_mut().events.push(Event::Paste("x".into())); h.run_steps(4); assert_eq!(keys::of(s(&mut h), Action::Copy), Shortcut::parse("Ctrl+C")); } #[test] fn own_shortcuts_work_and_the_old_ones_no_longer_do() { let mut h = harness(|app| { app.settings.shortcuts.insert("settings".into(), "F9".into()); app.settings.shortcuts.insert("select_all".into(), "F8".into()); app.main.bridge = Bridge::still(shot(vec![view(1, "a.zip", "a.org", State::Paused, 10, 0.0)]), lists()); }); key(&mut h, Modifiers::COMMAND, Key::Comma); assert!(app(&mut h).screen.is_none()); key(&mut h, Modifiers::COMMAND, Key::A); assert!(app(&mut h).main.list.selected.is_empty()); key(&mut h, Modifiers::NONE, Key::F8); assert_eq!(app(&mut h).main.list.chosen(), [1]); key(&mut h, Modifiers::NONE, Key::F9); assert!(app(&mut h).screen.is_some()); } /// Every action does something when it is asked for by name. #[test] fn every_action_is_reachable() { for e in keys::ALL { let mut h = harness(|app| { let mut v = view(2, "b.zip", "a.org", State::Paused, 10, 0.0); let mut task = (*v.task).clone(); task.source_page = Some("https://a.org/".into()); v.task = task.into(); let more = [view(1, "a.zip", "a.org", State::Paused, 10, 0.0), view(3, "c.zip", "a.org", State::Running, 10, 0.5)]; app.main.bridge = Bridge::still(shot(more.into_iter().chain([v]).collect()), lists()); app.main.outside = |what| OUTSIDE.with_borrow_mut(|o| o.push(what.into())); }); OUTSIDE.with_borrow_mut(Vec::clear); app(&mut h).main.list.selected = [2].into(); h.run_steps(2); let before = labels(&h); let (list, settings) = (app(&mut h).main.list.form, s(&mut h).clone()); app(&mut h).palette.toggle(); h.run_steps(3); text(&mut h, &e.label()); if e.action != Action::Palette { key(&mut h, Modifiers::NONE, Key::Enter); } h.run_steps(20); let sent = app(&mut h).main.bridge.take_sent(); let outside = OUTSIDE.with_borrow_mut(std::mem::take); let did = !sent.is_empty() || !outside.is_empty() || labels(&h) != before || s(&mut h).clone() != settings || app(&mut h).main.list.form != list || app(&mut h).main.list.selected.len() != 1 || matches!(e.action, Action::Find | Action::Quit | Action::Copy); assert!(did, "{}", e.id); assert!(e.action == Action::Palette || !app(&mut h).palette.is_open()); } } thread_local!(static OUTSIDE: std::cell::RefCell> = const { std::cell::RefCell::new(vec![]) }); fn labels(h: &H) -> Vec { h.root().children_recursive().filter_map(|n| n.accesskit_node().label()).collect() } // Palette. #[test] fn the_palette_is_there_at_once_and_picks_with_the_keyboard() { let mut h = harness(|app| { app.settings.motion = Motion::Expressive; app.main.list.form = Form::Compact; }); h.key_press_modifiers(Modifiers::COMMAND, Key::K); h.run_steps(2); let first = h.get_by_label("Add links").rect(); h.run_steps(30); assert_eq!(h.get_by_label("Add links").rect(), first, "it doesn't move"); text(&mut h, "cards"); key(&mut h, Modifiers::NONE, Key::Enter); assert_eq!(app(&mut h).main.list.form, Form::Cards); key(&mut h, Modifiers::COMMAND, Key::K); text(&mut h, "contrast"); key(&mut h, Modifiers::NONE, Key::Enter); h.run_steps(10); assert_eq!(app(&mut h).screen.as_ref().unwrap().page(), Page::Look); key(&mut h, Modifiers::COMMAND, Key::K); key(&mut h, Modifiers::COMMAND, Key::K); assert!(!app(&mut h).palette.is_open()); key(&mut h, Modifiers::COMMAND, Key::K); key(&mut h, Modifiers::NONE, Key::Escape); assert!(!app(&mut h).palette.is_open() && app(&mut h).screen.is_some()); } #[test] fn the_palette_finds_a_download_among_many_fast() { let mut h = harness(|app| app.main.bridge = Bridge::still(many(10_000, 1), lists())); let name = { let medlar_app::bridge::Data::Ready(shot, _) = app(&mut h).main.bridge.data() else { panic!() }; shot.get(7_777).unwrap().task.name.clone() }; key(&mut h, Modifiers::COMMAND, Key::K); let begun = Instant::now(); text(&mut h, &name); assert!(begun.elapsed().as_secs_f32() < 2.0, "{:?}", begun.elapsed()); key(&mut h, Modifiers::NONE, Key::Enter); h.run_steps(5); assert_eq!(app(&mut h).main.list.chosen().len(), 1); assert!(there(&h, &name)); } // First run. #[test] fn first_run_takes_three_screens_and_prefers_the_desktop() { let dir = tempfile::tempdir().unwrap(); let mut h = harness_with(vec2(1080.0, 720.0), caelestia(dir.path()), |app| app.first = Some(FirstRun::default())); click(&mut h, "Next"); assert!(there(&h, "Follow desktop")); click(&mut h, "Next"); click(&mut h, "Take links from the browser"); click(&mut h, "Start"); assert!(app(&mut h).first.is_none()); assert_eq!((s(&mut h).desktop_colors, s(&mut h).connector), (Some(true), false)); } #[test] fn first_run_can_be_skipped_and_decides_on_an_own_colour_without_a_desktop() { for size in [vec2(1080.0, 720.0), vec2(480.0, 360.0)] { let mut h = harness_with(size, nowhere(), |app| app.first = Some(FirstRun::default())); click(&mut h, "Next"); click(&mut h, "Skip"); assert!(app(&mut h).first.is_none()); assert_eq!(s(&mut h).desktop_colors, Some(false)); } let mut h = harness_with(vec2(480.0, 360.0), nowhere(), |app| app.first = Some(FirstRun::default())); click(&mut h, "Skip"); assert!(app(&mut h).first.is_none()); } // Backup. #[test] fn a_backup_comes_back_whole_and_nothing_else_is_taken() { let dir = tempfile::tempdir().unwrap(); let mut s = Settings { tries: 3, own_color: "#123456".into(), ..Settings::default() }; keys::change(&mut s, Action::Find, None); s.unknown.insert("from_the_future".into(), 1.into()); let one = write_backup(&s, &dir.path().join("new")).unwrap(); let two = write_backup(&s, &dir.path().join("new")).unwrap(); assert_ne!(one, two); assert_eq!(read_backup(&one).unwrap(), (s, vec![])); let file = |name: &str, text: &str| -> PathBuf { let path = dir.path().join(name); std::fs::write(&path, text).unwrap(); path }; for bad in [file("a", ""), file("b", "{}"), file("c", "[1]"), dir.path().into(), dir.path().join("none")] { assert!(read_backup(&bad).is_err(), "{bad:?}"); } let text = std::fs::read_to_string(&one).unwrap().replace("\"tries\": 3", "\"tries\": \"x\""); let damaged = file("d", &text); let (back, lost) = read_backup(&damaged).unwrap(); assert_eq!((back.tries, back.own_color.as_str(), lost), (10, "#123456", vec!["tries".to_string()])); assert_eq!(std::fs::read_to_string(&damaged).unwrap(), text, "the backup itself is not touched"); } #[test] fn backup_and_restore_from_the_screen_with_undo() { let dir = tempfile::tempdir().unwrap(); let paths = paths(dir.path()); let folder = paths.data.join("backups"); let mut h = harness(move |app| { app.paths = Some(paths.clone()); app.settings.tries = 7; app.open_settings(Page::Backup); }); click(&mut h, "Save a backup"); let file = std::fs::read_dir(&folder).unwrap().next().unwrap().unwrap().file_name().into_string().unwrap(); s(&mut h).tries = 1; h.run_steps(60); click(&mut h, &format!("Restore {file}")); assert_eq!(s(&mut h).tries, 7); click(&mut h, "Undo"); assert_eq!(s(&mut h).tries, 1); } #[test] fn undo_leaves_keys_of_other_pages_alone() { let mut s = Settings::default(); let mut v = View::open(&s, Page::Look); s.tries = 99; s.motion = Motion::Off; assert!(v.changed(&s, Page::Look) && v.changed(&s, Page::Downloads) && !v.changed(&s, Page::Network)); v.undo(&mut s, Page::Look); assert_eq!((s.motion, s.tries), (Motion::Expressive, 99)); }