From 23684c061eb0e103efef4ea7944620d7a571fa61 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 16:15:24 -0500 Subject: [PATCH] pdf-shell-w19: net change of 3 commits - pdf-shell-w19: written from its sheet - pdf-shell-w19: repair 1 - pdf-shell-w19: review fixes (review-1) --- crates/ui-egui/src/bidi/tests.rs | 198 ----- crates/ui-egui/src/i18n/tests.rs | 974 +--------------------- crates/ui-egui/tests/it/open_action.rs | 105 ++- crates/ui-egui/tests/it/reading_colors.rs | 19 +- crates/ui-egui/tests/it/reload.rs | 105 ++- crates/ui-egui/tests/it/ui.rs | 667 +++++---------- crates/ui-egui/tests/it/viewer_prefs.rs | 22 +- 7 files changed, 395 insertions(+), 1695 deletions(-) diff --git a/crates/ui-egui/src/bidi/tests.rs b/crates/ui-egui/src/bidi/tests.rs index e57feebe21..f6993bb61e 100644 --- a/crates/ui-egui/src/bidi/tests.rs +++ b/crates/ui-egui/src/bidi/tests.rs @@ -1,117 +1,5 @@ use super::*; -#[test] -fn text_without_rtl_is_borrowed_unchanged() { - for s in ["", "report.pdf", "日本語の文字.pdf", "a (b) [c]", "caf\u{00E9} \u{200E}x"] { - assert!(matches!(visual(s), Cow::Borrowed(v) if v == s), "{s:?}"); - } -} - -#[test] -fn arabic_words_swap_and_the_extension_stays_last() { - // The reported name: "one two.pdf" in Arabic. - assert_eq!(visual("واحد اثنين.pdf"), "اثنين واحد.pdf"); - assert_eq!(visual("ملف.pdf"), "ملف.pdf"); - assert_eq!(visual("تقرير نهائي جدا.pdf"), "جدا نهائي تقرير.pdf"); -} - -#[test] -fn latin_and_numbers_keep_their_own_order() { - assert_eq!(visual("report واحد اثنين final.pdf"), "report اثنين واحد final.pdf"); - // A number inside right-to-left text reads left to right, to the left of what precedes it. - assert_eq!(visual("ملف 2024.pdf"), "2024 ملف.pdf"); - assert_eq!(visual(r"C:\Users\me\واحد اثنين\a.pdf"), r"C:\Users\me\اثنين واحد\a.pdf"); -} - -#[test] -fn hebrew_and_brackets() { - assert_eq!(visual("שלום עולם.pdf"), "עולם שלום.pdf"); - // Brackets between right-to-left words flip with the direction. - assert_eq!(visual("واحد (اثنين) ثلاثة.pdf"), "ثلاثة (اثنين) واحد.pdf"); -} - -#[test] -fn direction_controls_are_not_drawn() { - assert_eq!(visual("\u{202B}واحد اثنين\u{202C}.pdf"), "اثنين واحد.pdf"); - assert_eq!(visual("\u{200F}واحد\u{061C}"), "واحد"); -} - -#[test] -fn rtl_labels_read_right_to_left() { - // No right-to-left characters: unchanged. - for s in ["", "Save as…", "{n} pages", "日本語"] { - assert_eq!(display_rtl(s), s); - } - assert_eq!(display_rtl("حفظ"), "حفظ"); - // "Save as…": the second word and the ellipsis end up on the left. - assert_eq!(display_rtl("حفظ باسم…"), "…باسم حفظ"); - // Latin words and numbers keep their own order inside the line. - assert_eq!(display_rtl("إنشاء PDF من ملف"), "ملف من PDF إنشاء"); - assert_eq!(display_rtl("تصدير إلى Microsoft Word الآن"), "الآن Microsoft Word إلى تصدير"); - assert_eq!(display_rtl("صالح لمدة 5 سنوات"), "سنوات 5 لمدة صالح"); - // Keyboard shortcuts are not reversed. - assert_eq!(display_rtl("طباعة (⌘P)"), "(⌘P) طباعة"); - assert_eq!(display_rtl("تدوير العرض (⇧⌘+)"), "(⇧⌘+) العرض تدوير"); - assert_eq!(display_rtl("التمرير مع ⌘ أيضًا"), "أيضًا ⌘ مع التمرير"); - assert_eq!(display_rtl("نص (عادي)"), "(عادي) نص"); -} - -#[test] -fn rtl_labels_keep_placeholders_whole() { - // Two placeholders around a colon stay together, left to right: a file name and its error. - assert_eq!(display_rtl("تعذّر فتح {name}: {e}"), "{name}: {e} فتح تعذّر"); - assert_eq!(display_rtl("فشل {label}، السبب {e}"), "{e} السبب ،{label} فشل"); - assert_eq!(display_rtl("{n} صفحات"), "صفحات {n}"); - assert_eq!(display_rtl("الصفحة {p} من {n}"), "{n} من {p} الصفحة"); - // Adjacent placeholders keep their order, as numbers around a slash would. - assert_eq!(display_rtl("جارٍ البحث… {s}/{p}"), "{s}/{p} …البحث جارٍ"); - // Braces that are not a placeholder are ordinary punctuation. - assert_eq!(display_rtl("حرف } واحد"), "واحد { حرف"); - let many = format!("ا {}", "{a} ".repeat(200)); - assert_eq!(display_rtl(&many).matches("{a}").count(), 200); -} - -#[test] -fn rtl_labels_keep_their_edges() { - // Edge spaces and separator dots stay where the code concatenates. - assert_eq!(display_rtl(" (صفحة {p})"), " ({p} صفحة)"); - assert_eq!(display_rtl(" · محمي بكلمة مرور"), " · مرور بكلمة محمي"); - assert_eq!(display_rtl("سلسلة المفاتيح · "), "المفاتيح سلسلة · "); - // A caption's colon stays next to its widget; a sentence's colon ends the sentence. - assert_eq!(display_rtl("الاسم:"), "الاسم:"); - assert_eq!(display_rtl("صادرة عن: "), "عن صادرة: "); - assert_eq!(display_rtl("اختر المعرّف الرقمي الذي تريد استخدامه:"), ":استخدامه تريد الذي الرقمي المعرّف اختر"); - // Each line is its own paragraph. - assert_eq!(display_rtl("تعذّر عرض الصفحة.\n{e}"), ".الصفحة عرض تعذّر\n{e}"); -} - -#[test] -fn rtl_labels_never_panic_on_odd_input() { - let long = "ا {n} ".repeat(20_000); - for s in [ - "ا{", - "ا}", - "ا{}", - "ا{{{", - "}ا{", - "ا\u{E000}{n}", - "⌘", - "ا ⌘", - "⌘ا⌘{", - "ا (⇧⌘", - "\u{064B}:", - ":", - "ا:", - " : ا : ", - "ا\n\n\nب", - "\u{202E}ا{n}", - long.as_str(), - ] { - let v = display_rtl(s); - assert!(v.chars().count() <= s.chars().count(), "{:?}", s.chars().take(12).collect::()); - } -} - /// `wrap` with a width of `n` characters. fn wrap_at(text: &str, n: usize) -> Vec { wrap(text, |s| s.chars().count() <= n) @@ -252,89 +140,3 @@ fn egui_draws_lines_in_reading_order() { assert_eq!(on_screen("See واحد اثنين here"), [format!("See {} {} here", rev("اثنين"), rev("واحد"))]); assert_eq!(on_screen("واحد (اثنين)."), [format!(".({}) {}", rev("اثنين"), rev("واحد"))]); } - -/// A file name keeps its extension at the visual end even when the first strong word is -/// Arabic: with an explicit `LeftToRight` base, `.pdf` is right of every Arabic glyph. -#[test] -fn file_names_are_laid_out_left_to_right() { - if pdfcraft_fonts::ui_arabic_fonts().is_empty() { - return; - } - let ctx = egui::Context::default(); - ctx.set_fonts(crate::theme::font_definitions()); - let mut positions: Vec<(char, f32)> = Vec::new(); - ctx.run_ui(egui::RawInput::default(), |ui| { - let galley = layout_ltr(ui, "واحد اثنين.pdf", egui::FontId::proportional(13.0), egui::Color32::WHITE); - positions = galley.rows.iter().flat_map(|row| row.glyphs.iter().map(|g| (g.chr, g.pos.x))).collect(); - }) - .drop_without_applying_deltas(); - let rightmost_arabic = positions.iter().filter(|(c, _)| is_rtl_script(*c)).map(|(_, x)| *x).fold(f32::MIN, f32::max); - let leftmost_extension = positions.iter().filter(|(c, _)| matches!(*c, '.' | 'p' | 'd' | 'f')).map(|(_, x)| *x).fold(f32::MAX, f32::min); - assert!(rightmost_arabic < leftmost_extension, "the extension must stay to the right: {positions:?}"); - let last = positions.iter().filter(|(c, _)| !c.is_whitespace()).max_by(|a, b| a.1.total_cmp(&b.1)); - assert_eq!(last.map(|(c, _)| *c), Some('f'), "the painted line ends in the extension"); -} - -/// Arabic/Kurdish labels get an explicit right-to-left paragraph, even when their first -/// strong character is Latin. With English the same text stays left to right. -#[test] -fn arabic_ui_labels_use_an_explicit_paragraph_direction() { - if pdfcraft_fonts::ui_arabic_fonts().is_empty() { - return; - } - let previous = crate::i18n::current(); - let ctx = egui::Context::default(); - ctx.set_fonts(crate::theme::font_definitions()); - let read = |lang: &str| { - crate::i18n::set_current(crate::i18n::Lang::from_code(lang).expect("registered language")); - let mut got = None; - ctx.run_ui(egui::RawInput::default(), |ui| { - let galley = layout_ui(ui, "PDF واحد", egui::FontId::proportional(13.0), egui::Color32::WHITE); - let positions: Vec<_> = galley.rows.iter().flat_map(|row| row.glyphs.iter().map(|g| (g.chr, g.pos.x))).collect(); - got = Some((galley.job.direction, positions)); - }) - .drop_without_applying_deltas(); - got.expect("one layout") - }; - let (direction, positions) = read("ar"); - crate::i18n::set_current(previous); - assert_eq!(direction, egui::epaint::text::TextDirection::RightToLeft); - let p = positions.iter().find(|(c, _)| *c == 'P').map(|(_, x)| *x).expect("a Latin P"); - let rightmost_arabic = positions.iter().filter(|(c, _)| is_rtl_script(*c)).map(|(_, x)| *x).fold(f32::MIN, f32::max); - assert!(p > rightmost_arabic, "in an RTL paragraph the first Latin run is at the right: {positions:?}"); - - let (direction, positions) = read("en"); - crate::i18n::set_current(previous); - assert_eq!(direction, egui::epaint::text::TextDirection::Auto); - let p = positions.iter().find(|(c, _)| *c == 'P').map(|(_, x)| *x).expect("a Latin P"); - let leftmost_arabic = positions.iter().filter(|(c, _)| is_rtl_script(*c)).map(|(_, x)| *x).fold(f32::MAX, f32::min); - assert!(p < leftmost_arabic, "with English the Latin run stays at the left: {positions:?}"); -} - -#[test] -fn single_line_with_its_own_direction() { - assert!(matches!(visual_auto("Ada Lovelace"), Cow::Borrowed("Ada Lovelace"))); - assert_eq!(visual_auto("علی رضایی"), "رضایی علی"); - assert_eq!(visual_auto("علی 2"), "2 علی"); - assert_eq!(visual_auto("Team علی رضایی"), "Team رضایی علی"); -} - -#[test] -fn odd_input_never_panics() { - let long = "ا ب ".repeat(20_000); - let odd = [ - "\u{064B}", - "\u{064B}\u{064C} \u{0301}", - "\u{202E}\u{202E}\u{202E}ا", - "\u{2067}ا\u{2066}b", - "ا\nب\r\nج\u{2029}د", - "\u{FEFF}ا\u{0000}ب", - "ا\u{10FFFF}\u{E000}ب", - "((((ا]]]]", - long.as_str(), - ]; - for s in odd { - let v = visual(s); - assert!(v.chars().count() <= s.chars().count(), "{:?}", s.chars().take(12).collect::()); - } -} diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index ce2189ce8e..3b48cfba68 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -32,13 +32,6 @@ fn app_catalog(code: &str) -> &'static str { CRAFT_I18N.iter().find(|(c, ..)| *c == code).map_or("", |(_, _, app)| *app) } -/// Every translation `code`'s embedded catalogs hold, each plural form on its own: the fonts must -/// draw all of them. -fn translations(code: &str) -> String { - let lang = Lang::from_code(code).expect("registered"); - lang.catalog_texts().flat_map(rows).flat_map(|(_, _, t)| t.split('|').map(str::to_owned).collect::>()).collect() -} - #[test] fn the_macos_bundle_declares_every_interface_language() { // AppKit translates its own dialogs (open and save panels) only into the languages the app @@ -249,86 +242,25 @@ fn the_languages_offered_are_the_embedded_ones_of_the_list() { } } +/// Every language in `LANGUAGES` is registered, its bundled catalog loads, and its code survives +/// a save and a restore into a fresh app. A language added to the list without its catalog or +/// without a saved code fails here. #[test] -fn lookups_fall_back_to_english() { - assert_eq!(tr(Lang::EN, "File"), "File"); - assert!(!has(Lang::EN, "Save")); +fn every_language_is_registered_loads_its_catalog_and_persists() { needs_catalogs!(); - assert_eq!(tr(JA(), "no such label"), "no such label"); - assert_eq!(tr(JA(), "File"), "ファイル"); - assert_eq!(tr(JA(), "日本語の文書.pdf"), "日本語の文書.pdf"); - assert_eq!(tr_id(JA(), "no.such.id", "File"), "ファイル"); - assert_eq!(tr_ctx(JA(), "no such context", "File"), "ファイル"); - assert!(has(JA(), "Save")); -} - -#[test] -fn catalog_kinds_are_parsed_and_looked_up() { - let l = fixture_lang( - "ja", - "# c\n\tHello\tこんにちは\n@id\tfile.save\t保存する\nmenu\tWindows\tウィンドウ群\n@plural\t{n} file|{n} files\t{n} 個\n\n", - ); - assert!(l.i18n().check_all().is_empty(), "{:?}", l.i18n().check_all()); - assert_eq!(tr(l, "Hello"), "こんにちは"); - assert_eq!(tr_id(l, "file.save", "Save"), "保存する"); - assert_eq!(tr_ctx(l, "menu", "Windows"), "ウィンドウ群"); - assert_eq!(tr_ctx(l, "other", "Windows"), "Windows"); - assert_eq!(trn(l, 0, "{n} file", "{n} files"), "0 個"); - assert_eq!(trn(l, 5, "{n} file", "{n} files"), "5 個"); -} - -/// A bad line is skipped and reported; the rest of the catalog still loads. -#[test] -fn malformed_lines_are_reported_not_fatal() { - let l = fixture_lang("x-bad", "\tok\tはい\nno tabs here\n\tonly\n\ta\tb\tc\textra\n\t\tempty source\n\tOpen…\tOpen\n"); - assert_eq!(tr(l, "ok"), "はい"); - assert_eq!(tr(l, "Open…"), "Open…", "a row that drops the ellipsis is skipped"); - assert_eq!(l.i18n().check_all().len(), 5, "{:?}", l.i18n().check_all()); -} - -#[test] -fn catalogs_handle_escapes_crlf_and_distinct_contexts() { - let l = - fixture_lang("x-esc", "# comment\r\n\r\n\tLine\\nTab\\tPath\\\\\tOther\\nTab\\tPath\\\\\r\nweight\tLight\tThin\r\ntheme\tLight\tPale\r\n"); - assert!(l.i18n().check_all().is_empty(), "{:?}", l.i18n().check_all()); - assert_eq!(tr(l, "Line\nTab\tPath\\"), "Other\nTab\tPath\\"); - assert_eq!(tr_ctx(l, "weight", "Light"), "Thin"); - assert_eq!(tr_ctx(l, "theme", "Light"), "Pale"); -} - -#[test] -fn broken_catalog_falls_back_to_english() { - let broken = fixture_lang("x-broken", "malformed\n\\"); - assert_eq!(tr(broken, "File"), "File"); - assert_eq!(trn(broken, 2, "{n} page", "{n} pages"), "2 pages"); -} - -#[test] -fn contextual_id_and_plural_lookups_have_english_fallbacks() { - let l = fixture_lang( - "de", - "\tLight\tPlain light\nweight\tLight\tThin\n@id\tfile.open\tOpen dialog…\n@plural\t{n} page|{n} pages\tOne page: {n}|Many pages: {n}\n", - ); - assert_eq!(tr_ctx(l, "weight", "Light"), "Thin"); - assert_eq!(tr_ctx(l, "theme", "Light"), "Plain light"); - assert_eq!(tr_ctx(l, "theme", "Unknown"), "Unknown"); - assert_eq!(tr_id(l, "file.open", "Reworded English…"), "Open dialog…"); - assert_eq!(tr_id(l, "unknown", "Light"), "Plain light"); - assert_eq!(tr_id(l, "unknown", "Unknown"), "Unknown"); - assert_eq!(trn(l, 1, "{n} page", "{n} pages"), "One page: 1"); - assert_eq!(trn(l, 0, "{n} page", "{n} pages"), "Many pages: 0"); - assert_eq!(trn(l, 1234, "{n} page", "{n} pages"), "Many pages: 1234", "no grouping, as before"); - assert_eq!(trn(l, u64::MAX, "{n} page", "{n} pages"), format!("Many pages: {}", u64::MAX)); -} - -#[test] -fn formatting_reorders_parameters_without_reinterpreting_user_text() { - let args = [("file", "日本語-{n}.pdf"), ("n", "2")]; - assert_eq!(fmt("{n}: {file}; {unknown}", &args), "2: 日本語-{n}.pdf; {unknown}"); - assert_eq!(fmt("{file} / {file}", &args), "日本語-{n}.pdf / 日本語-{n}.pdf"); - assert_eq!(fmt("text {unfinished", &args), "text {unfinished"); - assert_eq!(fmt("}{n}{", &args), "}2{"); - assert_eq!(fmt("unchanged", &[]), "unchanged"); + for info in &LANGUAGES { + let lang = Lang::from_code(info.code).unwrap_or_else(|| panic!("{} is not registered", info.code)); + assert_eq!(lang.code(), info.code); + if lang != Lang::EN { + assert!(lang.catalog_texts().any(|text| !rows(text).is_empty()), "{}: its catalog holds no rows", info.code); + } + let mut app = crate::PdfCraftApp::default(); + app.set_option("language", info.code).unwrap(); + assert_eq!(app.language, info.code); + let mut restored = crate::PdfCraftApp::default(); + restored.apply_settings(&app.settings_snapshot()); + assert_eq!(restored.language, info.code, "{}: the saved code is restored", info.code); + } } /// Every literal passed to `tl!(…)` or `crate::i18n::t(…)` in the UI source (test modules @@ -396,31 +328,6 @@ fn signature_appearance_labels_keep_their_separator() { } } -/// With craft-fonts, every Japanese translation has glyphs: with all interface faces (desktop) -/// and with BIZ UDPGothic Regular alone (the web build's only Japanese face). -#[test] -fn japanese_labels_have_glyphs() { - let craft = pdfcraft_fonts::ui_japanese_fonts(); - let Some(web) = craft.iter().find(|f| f.family == "BIZ UDPGothic" && f.style == "Regular") else { - eprintln!("skipping Japanese glyph checks: build with CRAFT_FONTS_DIR to run them"); - return; - }; - needs_catalogs!(); - let labels: String = translations("ja").chars().chain(JA().name().chars()).filter(|c| !c.is_control()).collect(); - let web_name = web.name(); - let mut web_only = crate::theme::font_definitions(); - for family in web_only.families.values_mut() { - family.retain(|name| !pdfcraft_fonts::CRAFT_FONTS.iter().any(|face| face.name() == *name) || *name == web_name); - } - use egui::epaint::text::{Fonts, TextOptions}; - for (build, defs) in [("desktop", crate::theme::font_definitions()), ("web", web_only)] { - let mut fonts = Fonts::new(TextOptions::default(), defs); - for id in [egui::FontId::proportional(13.0), egui::FontId::monospace(13.0), crate::theme::medium(13.0), crate::theme::semibold(17.0)] { - assert!(fonts.has_glyphs(&id, &labels), "{build}: {id:?} lacks a Japanese label glyph"); - } - } -} - #[test] fn history_labels_keep_captured_names() { set_current(Lang::EN); @@ -497,164 +404,7 @@ fn command_ids_and_undo_phrases_come_from_pdfcraft_s_own_rows() { set_current(Lang::EN); } -#[test] -fn current_language_is_per_thread() { - set_current(fixture_lang("x-thread", "\tFile\tファイル\n")); - assert_eq!(t("File"), "ファイル"); - std::thread::spawn(|| assert_eq!(current(), Lang::EN)).join().unwrap(); - set_current(Lang::EN); - assert_eq!(t("File"), "File"); -} - -#[test] -fn plurals_and_placeholders() { - assert_eq!(trn(Lang::EN, 1, "{n} item", "{n} items"), "1 item"); - assert_eq!(trn(Lang::EN, 0, "{n} item", "{n} items"), "0 items"); - assert_eq!(trn(Lang::EN, 7, "{n} item", "{n} items"), "7 items"); - assert_eq!(trn(Lang::EN, 12345, "{n} item", "{n} items"), "12345 items"); - assert_eq!(fmt("{b} before {a}", &[("a", "x"), ("b", "y"), ("c", "z")]), "y before x"); - assert_eq!(fmt("{missing}", &[]), "{missing}"); - needs_catalogs!(); - // No catalog has this `@plural` entry: Japanese falls back to the English forms. - assert_eq!(trn(JA(), 7, "{n} test item", "{n} test items"), "7 test items"); -} - -/// PdfCraft's plural rules before craft-i18n (form index by count), kept to show the crate's -/// CLDR categories pick the same form of the same rows. -fn pdfcraft_plural_rule(code: &str) -> fn(u64) -> usize { - fn one_other(n: u64) -> usize { - usize::from(n != 1) - } - fn none(_: u64) -> usize { - 0 - } - fn zero_one_other(n: u64) -> usize { - usize::from(n > 1) - } - fn ro(n: u64) -> usize { - if n == 1 { - 0 - } else if n == 0 || (1..=19).contains(&(n % 100)) { - 1 - } else { - 2 - } - } - fn lt(n: u64) -> usize { - match (n % 10, n % 100) { - (1, 11) => 2, - (1, _) => 0, - (2..=9, 12..=19) => 2, - (2..=9, _) => 1, - _ => 2, - } - } - fn cs(n: u64) -> usize { - match n { - 1 => 0, - 2..=4 => 1, - _ => 2, - } - } - fn ru_uk(n: u64) -> usize { - match n % 100 { - 11..=14 => 2, - _ => match n % 10 { - 1 => 0, - 2..=4 => 1, - _ => 2, - }, - } - } - fn ar(n: u64) -> usize { - match (n, n % 100) { - (0, _) => 0, - (1, _) => 1, - (2, _) => 2, - (_, 3..=10) => 3, - (_, 11..=99) => 4, - _ => 5, - } - } - fn pl(n: u64) -> usize { - match (n, n % 100, n % 10) { - (1, _, _) => 0, - (_, 12..=14, _) => 2, - (_, _, 2..=4) => 1, - _ => 2, - } - } - fn sl(n: u64) -> usize { - match n % 100 { - 1 => 0, - 2 => 1, - 3 | 4 => 2, - _ => 3, - } - } - match code { - "ja" | "zh-hans" | "zh-hant" | "tr" | "id" | "vi" | "th" | "lo" | "hi" | "ko" => none, - "cs" => cs, - "pt-br" | "fr" | "fa" => zero_one_other, - "ru" | "uk" | "bs" => ru_uk, - "ar" => ar, - "pl" => pl, - "sl" => sl, - "lt" => lt, - "ro" => ro, - _ => one_other, - } -} - -/// The counts the plural checks try: 0..=200, then large ones with every ending. -fn plural_counts() -> impl Iterator { - (0..=200).chain([1000, 1001, 1002, 1003, 1011, 1012, 1021, 1100, 1_000_000, 1_000_001, 2_000_000, 123_456_789, u64::MAX - 13, u64::MAX]) -} - -/// craft-i18n picks plural forms by CLDR category, PdfCraft by its own rules: for every language -/// the two choose the same form wherever they list as many forms. Where CLDR lists more (Hindi -/// and Turkish have two where PdfCraft had one), the catalog repeats the form, so the text is the -/// same; the embedded rows are checked for that and any that differ are reported. -#[test] -fn plural_forms_follow_the_rules_pdfcraft_had() { - let mut split = Vec::new(); - // English has no catalog: its own two forms, `one` for 1 alone, as PdfCraft's rule had it. - assert_eq!(plural_counts().map(|n| trn(Lang::EN, n, "1", "x")).filter(|s| s == "1").count(), 1); - for info in LANGUAGES.iter().filter(|l| l.code != "en") { - let rule = pdfcraft_plural_rule(info.code); - let pdfcraft_forms = (0..=1000).map(rule).max().unwrap_or(0) + 1; - // How many forms CLDR gives this language: the first form count whose row loads. - let fixture = |forms: usize| { - let row = (0..forms).map(|i| format!("F{i} {{n}}")).collect::>().join("|"); - fixture_lang(info.code, Box::leak(format!("@plural\t{{n}} x|{{n}} xs\t{row}\n").into_boxed_str())) - }; - let (forms, lang) = - (1..=6).map(|f| (f, fixture(f))).find(|(_, l)| trn(*l, 5, "{n} x", "{n} xs").starts_with('F')).expect("a form count loads"); - if forms != pdfcraft_forms { - split.push((info.code, pdfcraft_forms, forms)); - assert_eq!(pdfcraft_forms, 1, "{}: PdfCraft listed {pdfcraft_forms} forms, CLDR {forms}", info.code); - continue; - } - for n in plural_counts() { - assert_eq!(trn(lang, n, "{n} x", "{n} xs"), format!("F{} {n}", rule(n)), "{}: count {n}", info.code); - } - } - let codes: Vec<&str> = split.iter().map(|(c, ..)| *c).collect(); - assert_eq!(codes, ["tr", "hi"], "the languages CLDR gives more forms than PdfCraft had"); - if !needs_catalogs() { - return; - } - for (code, ..) in split { - let lang = Lang::from_code(code).expect("registered"); - for (_, source, forms) in lang.catalog_texts().flat_map(rows).filter(|(c, ..)| c == "@plural") { - let distinct: std::collections::BTreeSet<&str> = forms.split('|').collect(); - if distinct.len() > 1 { - println!("{code}: {source:?} has forms that differ, so PdfCraft's single form is no longer the only text: {forms:?}"); - } - } - } -} - +// PLAN: assumed `crate::settings::import_json(&str) -> (Settings, _)` and `PdfCraftApp::apply_settings(&Settings)` (pdf-shell-w9) #[test] fn language_persists_and_invalid_input_keeps_current_language() { let mut app = crate::PdfCraftApp::default(); @@ -662,7 +412,7 @@ fn language_persists_and_invalid_input_keeps_current_language() { assert!(app.set_option("language", "xx").is_err()); // Settings written before the system-locale default (no key) follow the system. let mut legacy = crate::PdfCraftApp::default(); - legacy.restore("{}"); + legacy.apply_settings(&crate::settings::import_json("{}").0); assert_eq!(legacy.language, AUTO); needs_catalogs!(); app.set_option("language", "JA").unwrap(); @@ -670,53 +420,14 @@ fn language_persists_and_invalid_input_keeps_current_language() { assert!(app.set_option("language", "xx").is_err()); assert_eq!(app.language, "ja"); let mut restored = crate::PdfCraftApp::default(); - restored.restore(&app.persist()); + restored.apply_settings(&app.settings_snapshot()); assert_eq!(restored.language, "ja"); - restored.restore(r#"{"language":"xx"}"#); + restored.apply_settings(&crate::settings::import_json(r#"{"language":"xx"}"#).0); assert_eq!(restored.language, "ja"); app.set_option("language", AUTO).unwrap(); assert_eq!(app.language, AUTO); } -#[test] -fn brazilian_portuguese_is_registered() { - needs_catalogs!(); - let pt = Lang::from_code("pt-br").expect("pt-br registered"); - assert_eq!(pt.name(), "Português (Brasil)"); - assert_eq!(Lang::from_code("PT-BR"), Some(pt)); - assert_eq!(normalize_pref("pt-BR"), Some("pt-br")); - assert_eq!(normalize_pref("pt"), None, "only exact codes are preferences"); - assert_eq!(lang_from_tag("pt_BR.UTF-8"), Some(pt)); - assert_eq!(lang_from_tag("pt_PT"), Some(pt)); - assert_eq!(tr(pt, "Arquivo do usuário.pdf"), "Arquivo do usuário.pdf"); - let mut app = crate::PdfCraftApp::default(); - app.set_option("language", "pt-br").unwrap(); - assert_eq!(app.language, "pt-br"); - let mut restored = crate::PdfCraftApp::default(); - restored.restore(&app.persist()); - assert_eq!(restored.language, "pt-br"); -} - -#[test] -fn spanish_is_registered() { - needs_catalogs!(); - let es = Lang::from_code("es").expect("es registered"); - assert_eq!(es.name(), "Español"); - assert_eq!(normalize_pref("ES"), Some("es")); - assert_eq!(lang_from_tag("es_ES.UTF-8"), Some(es)); - assert_eq!(lang_from_tag("es-MX"), Some(es)); - assert_eq!(first_supported("es-ES\r\nen-US"), Some(es)); - assert_eq!(tr(es, "Informe del usuario.pdf"), "Informe del usuario.pdf"); - let mut app = crate::PdfCraftApp::default(); - app.set_option("language", "es").unwrap(); - assert_eq!(app.language, "es"); - let mut restored = crate::PdfCraftApp::default(); - restored.restore(&app.persist()); - assert_eq!(restored.language, "es"); -} - -/// Each sentence the engine words for itself keeps its holes when it is said in Spanish, so -/// the document's own words still have somewhere to go: a translation that drops `{p}` or /// `{}` would read as a sentence about nothing in particular. #[test] fn spanish_keeps_the_holes_in_what_the_engine_says() { @@ -739,23 +450,6 @@ fn spanish_keeps_the_holes_in_what_the_engine_says() { } } -#[test] -fn telugu_is_registered() { - needs_catalogs!(); - let te = Lang::from_code("te").expect("te registered"); - assert_eq!(te.name(), "తెలుగు"); - assert_eq!(normalize_pref("TE"), Some("te")); - assert_eq!(lang_from_tag("te_IN.UTF-8"), Some(te)); - assert_eq!(first_supported("te-IN\r\nen-US"), Some(te)); - assert_eq!(tr(te, "నివేదిక.pdf"), "నివేదిక.pdf"); - let mut app = crate::PdfCraftApp::default(); - app.set_option("language", "te").unwrap(); - assert_eq!(app.language, "te"); - let mut restored = crate::PdfCraftApp::default(); - restored.restore(&app.persist()); - assert_eq!(restored.language, "te"); -} - /// Telugu puts the verb last, so it translates "Undo {action}" as a whole phrase; a catalog /// without that entry (Spanish) keeps the verb in front of the action. #[test] @@ -773,145 +467,6 @@ fn undo_and_redo_labels_use_the_catalog_phrase_when_there_is_one() { assert_eq!(command_label("Undo Untranslated custom action"), "Undo Untranslated custom action"); } -/// A label that reads differently by use has its own contextual entry where a language needs -/// one; a language without it falls back to the plain translation. -#[test] -fn contextual_labels_fall_back_to_the_plain_translation() { - needs_catalogs!(); - let te = Lang::from_code("te").expect("te registered"); - assert_eq!(tr_ctx(te, "signature pad", "Type"), "టైప్ చేయి"); - assert_eq!(tr(te, "Type"), "రకం"); - // A context no catalog defines, so the fallback stays tested as catalogs fill their gaps. - let es = Lang::from_code("es").expect("es registered"); - assert_eq!(tr_ctx(es, "no such context", "Type"), tr(es, "Type")); -} - -/// With a craft-fonts Telugu face, every Telugu translation has glyphs: with all interface -/// faces (desktop) and with the Telugu face as the only craft-fonts face (the web build keeps -/// it; Telugu labels must not need a Japanese or Arabic face). -#[test] -fn telugu_labels_have_glyphs() { - let telugu: Vec = pdfcraft_fonts::ui_telugu_fonts().iter().map(|f| f.name()).collect(); - if telugu.is_empty() { - eprintln!("skipping Telugu glyph checks: build with CRAFT_FONTS_DIR and a Telugu face to run them"); - return; - } - needs_catalogs!(); - let te = Lang::from_code("te").expect("te registered"); - let labels: String = translations("te").chars().chain(te.name().chars()).filter(|c| !c.is_control()).collect(); - let mut telugu_only = crate::theme::font_definitions(); - for family in telugu_only.families.values_mut() { - family.retain(|name| !pdfcraft_fonts::CRAFT_FONTS.iter().any(|face| face.name() == *name) || telugu.contains(name)); - } - use egui::epaint::text::{Fonts, TextOptions}; - for (build, defs) in [("all faces", crate::theme::font_definitions()), ("Telugu face only", telugu_only)] { - let mut fonts = Fonts::new(TextOptions::default(), defs); - for id in [egui::FontId::proportional(13.0), egui::FontId::monospace(13.0), crate::theme::medium(13.0), crate::theme::semibold(17.0)] { - assert!(fonts.has_glyphs(&id, &labels), "{build}: {id:?} lacks a Telugu label glyph"); - } - } -} - -#[test] -fn czech_is_registered_and_persists() { - needs_catalogs!(); - let cs = Lang::from_code("cs").expect("cs registered"); - assert_eq!(cs.name(), "Čeština"); - assert_eq!(tr(cs, "Žluťoučký kůň.pdf"), "Žluťoučký kůň.pdf"); - let mut app = crate::PdfCraftApp::default(); - app.set_option("language", "cs").unwrap(); - assert!(app.set_option("language", "cz").is_err()); - assert_eq!(app.language, "cs"); - let mut restored = crate::PdfCraftApp::default(); - restored.restore(&app.persist()); - assert_eq!(restored.language, "cs"); -} - -#[test] -fn turkish_is_registered_and_persists() { - needs_catalogs!(); - let tr_lang = Lang::from_code("tr").expect("tr registered"); - assert_eq!(tr_lang.name(), "Türkçe"); - assert_eq!(tr(tr_lang, "Türkçe Belge.pdf"), "Türkçe Belge.pdf"); - let mut app = crate::PdfCraftApp::default(); - app.set_option("language", "tr").unwrap(); - assert!(app.set_option("language", "tu").is_err()); - assert_eq!(app.language, "tr"); - let mut restored = crate::PdfCraftApp::default(); - restored.restore(&app.persist()); - assert_eq!(restored.language, "tr"); -} - -/// The code joins some labels with a space at either end, so these catalogs (PdfCraft's rows in -/// craft-i18n) keep exactly the source's, and write … rather than three dots. -#[test] -fn catalog_rows_keep_the_source_spacing_and_ellipsis() { - needs_catalogs!(); - let edges = |s: &str| (s.len() - s.trim_start().len(), s.len() - s.trim_end().len()); - for code in ["cs", "tr", "vi"] { - for (_, source, translation) in rows(app_catalog(code)) { - assert!(!translation.contains("..."), "{code}: use … rather than three dots: {translation:?}"); - assert_eq!(edges(&translation), edges(&source), "{code}: stray whitespace: {translation:?}"); - } - } -} - -#[test] -fn simplified_chinese_is_registered() { - needs_catalogs!(); - let zh = Lang::from_code("zh-hans").expect("zh-hans registered"); - assert_eq!(zh.name(), "简体中文"); - assert_eq!(normalize_pref("zh-Hans"), Some("zh-hans")); - assert_eq!(normalize_pref("zh"), None, "only exact codes are preferences"); - assert_eq!(tr(zh, "报告.pdf"), "报告.pdf"); -} - -#[test] -fn traditional_chinese_is_registered() { - needs_catalogs!(); - let zh = Lang::from_code("zh-hant").expect("zh-hant registered"); - assert_eq!(zh.name(), "繁體中文"); - assert_eq!(normalize_pref("zh-Hant"), Some("zh-hant")); - assert_eq!(tr(zh, "報告.pdf"), "報告.pdf"); -} - -#[test] -fn french_is_registered() { - needs_catalogs!(); - let fr = Lang::from_code("fr").expect("fr registered"); - assert_eq!(fr.name(), "Français"); - assert_eq!(normalize_pref("FR"), Some("fr")); - assert_eq!(lang_from_tag("fr_FR.UTF-8"), Some(fr)); - assert_eq!(lang_from_tag("fr-CA"), Some(fr)); - assert_eq!(first_supported("fr-FR\r\nen-US"), Some(fr)); - assert_eq!(tr(fr, "Rapport de l'utilisateur.pdf"), "Rapport de l'utilisateur.pdf"); - let mut app = crate::PdfCraftApp::default(); - app.set_option("language", "fr").unwrap(); - assert_eq!(app.language, "fr"); - let mut restored = crate::PdfCraftApp::default(); - restored.restore(&app.persist()); - assert_eq!(restored.language, "fr"); -} - -#[test] -fn german_is_registered() { - needs_catalogs!(); - let de = Lang::from_code("de").expect("de registered"); - assert_eq!(de.name(), "Deutsch"); - assert_eq!(normalize_pref("DE"), Some("de")); - assert_eq!(lang_from_tag("de_DE.UTF-8"), Some(de)); - assert_eq!(lang_from_tag("de-AT"), Some(de)); - assert_eq!(lang_from_tag("de_CH"), Some(de)); - assert_eq!(first_supported("de-DE\r\nen-US"), Some(de)); - assert_eq!(tr(de, "Bericht des Nutzers.pdf"), "Bericht des Nutzers.pdf"); - let mut app = crate::PdfCraftApp::default(); - app.set_option("language", "de").unwrap(); - assert_eq!(app.language, "de"); - let mut restored = crate::PdfCraftApp::default(); - restored.restore(&app.persist()); - assert_eq!(restored.language, "de"); -} - #[test] fn tool_names_inside_sentences_are_lowercased_except_in_german() { set_current(Lang::EN); @@ -937,393 +492,10 @@ fn turkish_keeps_its_dotted_and_dotless_i_when_changing_case() { assert_eq!(in_sentence("Image"), "image"); } -#[test] -fn russian_is_registered() { - needs_catalogs!(); - let ru = Lang::from_code("ru").expect("ru registered"); - assert_eq!(ru.name(), "Русский"); - assert_eq!(normalize_pref("RU"), Some("ru")); - assert_eq!(lang_from_tag("ru_RU.UTF-8"), Some(ru)); - assert_eq!(lang_from_tag("ru-BY"), Some(ru)); - assert_eq!(first_supported("ru-RU\r\nen-US"), Some(ru)); - assert_eq!(tr(ru, "Rapport de l'utilisateur.pdf"), "Rapport de l'utilisateur.pdf"); - let mut app = crate::PdfCraftApp::default(); - app.set_option("language", "ru").unwrap(); - assert_eq!(app.language, "ru"); - let mut restored = crate::PdfCraftApp::default(); - restored.restore(&app.persist()); - assert_eq!(restored.language, "ru"); -} - -#[test] -fn finnish_is_registered_and_persists() { - needs_catalogs!(); - let fi = Lang::from_code("fi").expect("fi registered"); - assert_eq!(fi.name(), "Suomi"); - assert_eq!(normalize_pref("FI"), Some("fi")); - for tag in ["fi", "fi-FI", "fi_FI.UTF-8", "FI-fi"] { - assert_eq!(lang_from_tag(tag), Some(fi), "{tag}"); - } - // Filipino (`fil`) and Swedish in Finland (`sv-FI`) don't pick Finnish. - assert_ne!(lang_from_tag("fil"), Some(fi)); - assert_ne!(lang_from_tag("sv-FI"), Some(fi)); - let mut app = crate::PdfCraftApp::default(); - app.set_option("language", "FI").unwrap(); - assert_eq!(app.language, "fi"); - let mut restored = crate::PdfCraftApp::default(); - restored.restore(&app.persist()); - assert_eq!(restored.language, "fi"); -} - -#[test] -fn lithuanian_is_registered_and_persists() { - needs_catalogs!(); - let lt = Lang::from_code("lt").expect("lt registered"); - assert_eq!(lt.name(), "Lietuvių"); - assert_eq!(normalize_pref("LT"), Some("lt")); - for tag in ["lt", "lt-LT", "lt_LT.UTF-8", "LT-lt"] { - assert_eq!(lang_from_tag(tag), Some(lt), "{tag}"); - } - let mut app = crate::PdfCraftApp::default(); - app.set_option("language", "LT").unwrap(); - assert_eq!(app.language, "lt"); - let mut restored = crate::PdfCraftApp::default(); - restored.restore(&app.persist()); - assert_eq!(restored.language, "lt"); - assert!(restored.set_option("language", "xx").is_err()); -} - -#[test] -fn norwegian_bokmal_is_registered_and_persists() { - needs_catalogs!(); - let nb = Lang::from_code("nb").expect("nb registered"); - assert_eq!(nb.name(), "Norsk bokmål"); - assert_eq!(normalize_pref("NB"), Some("nb")); - assert_eq!(normalize_pref("no"), None, "only exact codes are preferences"); - // Current systems say `nb`; older ones and some Linux setups say `no`. Nynorsk is `nn`. - for tag in ["nb", "nb-NO", "nb_NO.UTF-8", "no", "no_NO.UTF-8", "NO-no", "nn", "nn_NO.UTF-8"] { - assert_eq!(lang_from_tag(tag), Some(nb), "{tag}"); - } - assert_eq!(first_supported("(\n \"nb-NO\",\n \"en-US\"\n)\n"), Some(nb)); - assert_eq!(first_supported("nn-NO\r\nen-US\r\n"), Some(nb)); - let mut app = crate::PdfCraftApp::default(); - app.set_option("language", "NB").unwrap(); - assert_eq!(app.language, "nb"); - let mut restored = crate::PdfCraftApp::default(); - restored.restore(&app.persist()); - assert_eq!(restored.language, "nb"); -} - -#[test] -fn vietnamese_is_registered_and_persists() { - needs_catalogs!(); - let vi = Lang::from_code("vi").expect("vi registered"); - assert_eq!(vi.name(), "Tiếng Việt"); - assert_eq!(normalize_pref("Vi"), Some("vi")); - for tag in ["vi", "vi-VN", "vi_VN.UTF-8", "VI-vn"] { - assert_eq!(lang_from_tag(tag), Some(vi), "{tag}"); - } - assert_eq!(first_supported("vi-VN\r\nen-US"), Some(vi)); - let mut app = crate::PdfCraftApp::default(); - app.set_option("language", "vi").unwrap(); - assert_eq!(app.language, "vi"); - let mut restored = crate::PdfCraftApp::default(); - restored.restore(&app.persist()); - assert_eq!(restored.language, "vi"); - assert!(restored.set_option("language", "xx").is_err()); - assert_eq!(restored.language, "vi"); -} - -#[test] -fn romanian_is_registered_with_three_plural_forms() { - // one: 1; few: 0 and n % 100 in 1..=19 ("2 pagini", "101 pagini"); other: the "de" form ("20 de pagini"). - let form = plural_fixture("ro", 3); - for (n, f) in [(1, 0), (0, 1), (2, 1), (19, 1), (101, 1), (119, 1), (20, 2), (100, 2), (120, 2), (1000, 2)] { - assert_eq!(form(n), f, "{n}"); - } - needs_catalogs!(); - let ro = Lang::from_code("ro").expect("ro registered"); - for tag in ["ro", "ro-RO", "ro_RO.UTF-8", "RO-ro", "ro-MD"] { - assert_eq!(lang_from_tag(tag), Some(ro), "{tag}"); - } - assert_eq!(normalize_pref("Ro"), Some("ro")); -} - -#[test] -fn catalan_is_registered_and_persists() { - needs_catalogs!(); - let ca = Lang::from_code("ca").expect("ca registered"); - assert_eq!(ca.name(), "Català"); - assert_eq!(normalize_pref("CA"), Some("ca")); - for tag in ["ca", "ca-ES", "ca_ES.UTF-8", "CA-es", "ca_ES@valencia"] { - assert_eq!(lang_from_tag(tag), Some(ca), "{tag}"); - } - assert_eq!(first_supported("ca-ES\r\nen-US"), Some(ca)); - let mut app = crate::PdfCraftApp::default(); - app.set_option("language", "CA").unwrap(); - assert_eq!(app.language, "ca"); - let mut restored = crate::PdfCraftApp::default(); - restored.restore(&app.persist()); - assert_eq!(restored.language, "ca"); - assert!(restored.set_option("language", "xx").is_err()); - assert_eq!(restored.language, "ca"); -} - -/// Bosnian locales select it, its picker falls back to "Bosnian", and the choice persists. -#[test] -fn bosnian_is_registered_and_persists() { - needs_catalogs!(); - let bs = Lang::from_code("bs").expect("bs registered"); - assert_eq!(bs.name(), "Bosanski"); - assert_eq!(bs.picker_name(|_| false), "Bosnian"); - assert_eq!(normalize_pref("BS"), Some("bs")); - for tag in ["bs", "bs-BA", "bs_BA.UTF-8", "BS-ba", "bs-Latn-BA"] { - assert_eq!(lang_from_tag(tag), Some(bs), "{tag}"); - } - assert_eq!(first_supported("bs-BA\r\nen-US"), Some(bs)); - let mut app = crate::PdfCraftApp::default(); - app.set_option("language", "BS").unwrap(); - assert_eq!(app.language, "bs"); - let mut restored = crate::PdfCraftApp::default(); - restored.restore(&app.persist()); - assert_eq!(restored.language, "bs"); -} - -/// Bosnian counts (CLDR `bs`): one for 1, 21, 101 but not 11; few for 2–4, 22–24 but not 12–14; -/// other for the rest. -#[test] -fn bosnian_plurals_cover_teens_and_compound_counts() { - let form = plural_fixture("bs", 3); - for (counts, f) in [ - (vec![1, 21, 31, 101, 1001], 0), - (vec![2, 3, 4, 22, 24, 102, 104], 1), - (vec![0, 5, 10, 11, 12, 13, 14, 15, 20, 25, 100, 111, 112, 114, 1000], 2), - ] { - for n in counts { - assert_eq!(form(n), f, "{n}"); - } - } -} - -#[test] -fn slovene_is_registered_and_persists() { - needs_catalogs!(); - let sl = Lang::from_code("sl").expect("sl registered"); - assert_eq!(sl.name(), "Slovenščina"); - assert_eq!(normalize_pref("SL"), Some("sl")); - for tag in ["sl", "sl-SI", "sl_SI.UTF-8", "SL-si", "sl_SI@variant"] { - assert_eq!(lang_from_tag(tag), Some(sl), "{tag}"); - } - assert_eq!(first_supported("sl-SI\r\nen-US"), Some(sl)); - assert_eq!(tr(sl, "Poročilo {n}.pdf"), "Poročilo {n}.pdf"); - let mut app = crate::PdfCraftApp::default(); - app.set_option("language", "SL").unwrap(); - assert_eq!(app.language, "sl"); - let mut restored = crate::PdfCraftApp::default(); - restored.restore(&app.persist()); - assert_eq!(restored.language, "sl"); - assert!(restored.set_option("language", "xx").is_err()); - assert_eq!(restored.language, "sl"); -} - -#[test] -fn albanian_is_registered_and_persists() { - needs_catalogs!(); - let sq = Lang::from_code("sq").expect("sq registered"); - assert_eq!(sq.name(), "Shqip"); - assert_eq!(normalize_pref("SQ"), Some("sq")); - for tag in ["sq", "sq-AL", "sq_AL.UTF-8", "SQ-xk", "sq_XK@variant"] { - assert_eq!(lang_from_tag(tag), Some(sq), "{tag}"); - } - assert_eq!(first_supported("sq-AL\r\nen-US"), Some(sq)); - let mut app = crate::PdfCraftApp::default(); - app.set_option("language", "SQ").unwrap(); - assert_eq!(app.language, "sq"); - let mut restored = crate::PdfCraftApp::default(); - restored.restore(&app.persist()); - assert_eq!(restored.language, "sq"); - assert!(restored.set_option("language", "xx").is_err()); - assert_eq!(restored.language, "sq"); -} - -#[test] -fn slovene_plurals_cover_dual_few_teens_and_large_counts() { - let form = plural_fixture("sl", 4); - for (counts, f) in [ - (vec![1, 101, 201, 1001, 1101], 0), - (vec![2, 102, 202, 1002], 1), - (vec![3, 4, 103, 104, 1003], 2), - (vec![0, 5, 10, 11, 12, 13, 14, 15, 20, 21, 22, 23, 24, 25, 31, 100, 111, 112, 121, 122, 1000, u64::MAX], 3), - ] { - for n in counts { - assert_eq!(form(n), f, "{n}"); - } - } -} - -#[test] -fn indonesian_and_vietnamese_are_registered_and_persist() { - needs_catalogs!(); - let id = Lang::from_code("id").expect("id registered"); - let vi = Lang::from_code("vi").expect("vi registered"); - assert_eq!(id.name(), "Bahasa Indonesia"); - assert_eq!(vi.name(), "Tiếng Việt"); - assert_eq!(normalize_pref("ID"), Some("id")); - assert_eq!(normalize_pref("Vi"), Some("vi")); - for tag in ["id", "id-ID", "id_ID.UTF-8", "ID-id"] { - assert_eq!(lang_from_tag(tag), Some(id), "{tag}"); - } - for tag in ["vi", "vi-VN", "vi_VN.UTF-8", "VI-vn"] { - assert_eq!(lang_from_tag(tag), Some(vi), "{tag}"); - } - assert_eq!(first_supported("id-ID\r\nen-US"), Some(id)); - assert_eq!(first_supported("vi-VN\r\nen-US"), Some(vi)); - let mut app = crate::PdfCraftApp::default(); - app.set_option("language", "ID").unwrap(); - assert_eq!(app.language, "id"); - let mut restored = crate::PdfCraftApp::default(); - restored.restore(&app.persist()); - assert_eq!(restored.language, "id"); - let mut app = crate::PdfCraftApp::default(); - app.set_option("language", "vi").unwrap(); - assert_eq!(app.language, "vi"); - let mut restored = crate::PdfCraftApp::default(); - restored.restore(&app.persist()); - assert_eq!(restored.language, "vi"); - assert!(restored.set_option("language", "xx").is_err()); - assert_eq!(restored.language, "vi"); -} - -#[test] -fn hindi_and_korean_are_registered_and_persist() { - needs_catalogs!(); - let hi = Lang::from_code("hi").expect("hi registered"); - let ko = Lang::from_code("ko").expect("ko registered"); - assert_eq!(hi.name(), "हिन्दी"); - assert_eq!(ko.name(), "한국어"); - assert_eq!(normalize_pref("HI"), Some("hi")); - assert_eq!(normalize_pref("Ko"), Some("ko")); - for tag in ["hi", "hi-IN", "hi_IN.UTF-8", "HI-in"] { - assert_eq!(lang_from_tag(tag), Some(hi), "{tag}"); - } - for tag in ["ko", "ko-KR", "ko_KR.UTF-8", "KO-kr"] { - assert_eq!(lang_from_tag(tag), Some(ko), "{tag}"); - } - assert_eq!(first_supported("hi-IN\r\nen-US"), Some(hi)); - assert_eq!(first_supported("ko-KR\r\nen-US"), Some(ko)); - for code in ["hi", "ko"] { - let mut app = crate::PdfCraftApp::default(); - app.set_option("language", &code.to_uppercase()).unwrap(); - assert_eq!(app.language, code); - let mut restored = crate::PdfCraftApp::default(); - restored.restore(&app.persist()); - assert_eq!(restored.language, code); - assert!(restored.set_option("language", "xx").is_err()); - assert_eq!(restored.language, code); - } -} - -#[test] -fn bulgarian_is_registered() { - needs_catalogs!(); - let bg = Lang::from_code("bg").expect("bg registered"); - assert_eq!(bg.name(), "Български"); - assert_eq!(normalize_pref("BG"), Some("bg")); - assert_eq!(lang_from_tag("bg_BG.UTF-8"), Some(bg)); - assert_eq!(lang_from_tag("bg-BG"), Some(bg)); - assert_eq!(first_supported("bg-BG\r\nen-US"), Some(bg)); - assert_eq!(tr(bg, "Rapport de l'utilisateur.pdf"), "Rapport de l'utilisateur.pdf"); - let mut app = crate::PdfCraftApp::default(); - app.set_option("language", "bg").unwrap(); - assert_eq!(app.language, "bg"); - let mut restored = crate::PdfCraftApp::default(); - restored.restore(&app.persist()); - assert_eq!(restored.language, "bg"); -} - -#[test] -fn hungarian_is_registered() { - needs_catalogs!(); - let hu = Lang::from_code("hu").expect("hu registered"); - assert_eq!(hu.name(), "Magyar"); - assert_eq!(normalize_pref("HU"), Some("hu")); - assert_eq!(lang_from_tag("hu_HU.UTF-8"), Some(hu)); - assert_eq!(lang_from_tag("hu-HU"), Some(hu)); - assert_eq!(first_supported("hu-HU\r\nen-US"), Some(hu)); - assert_eq!(tr(hu, "Rapport de l'utilisateur.pdf"), "Rapport de l'utilisateur.pdf"); - let mut app = crate::PdfCraftApp::default(); - app.set_option("language", "hu").unwrap(); - assert_eq!(app.language, "hu"); - let mut restored = crate::PdfCraftApp::default(); - restored.restore(&app.persist()); - assert_eq!(restored.language, "hu"); -} - -#[test] -fn ukrainian_is_registered_and_persists() { - needs_catalogs!(); - let uk = Lang::from_code("uk").expect("uk registered"); - assert_eq!(uk.name(), "Українська"); - assert_eq!(normalize_pref("UK"), Some("uk")); - for tag in ["uk", "uk-UA", "uk_UA.UTF-8", "UK-ua", "uk_UA@variant"] { - assert_eq!(lang_from_tag(tag), Some(uk), "{tag}"); - } - assert_eq!(first_supported("uk-UA\r\nen-US"), Some(uk)); - assert_eq!(first_supported("(\n \"uk-UA\",\n \"en-US\"\n)\n"), Some(uk)); - assert_eq!(tr(uk, "Звіт {n}.pdf"), "Звіт {n}.pdf"); - let mut app = crate::PdfCraftApp::default(); - app.set_option("language", "UK").unwrap(); - assert_eq!(app.language, "uk"); - let mut restored = crate::PdfCraftApp::default(); - restored.restore(&app.persist()); - assert_eq!(restored.language, "uk"); - assert!(restored.set_option("language", "xx").is_err()); - assert_eq!(restored.language, "uk"); -} - -#[test] -fn ukrainian_integer_plurals_cover_teens_and_large_counts() { - let form = plural_fixture("uk", 3); - for (counts, f) in [ - (vec![1, 21, 31, 101, 121, 1001], 0), - (vec![2, 3, 4, 22, 23, 24, 102, 104, 122, 1002], 1), - (vec![0, 5, 10, 11, 12, 13, 14, 19, 20, 25, 100, 110, 111, 112, 114, 1000, u64::MAX], 2), - ] { - for n in counts { - assert_eq!(form(n), f, "{n}"); - } - } -} - fn arabic() -> Lang { Lang::from_code("ar").expect("ar registered") } -#[test] -fn arabic_is_registered_and_persists() { - needs_catalogs!(); - let ar = arabic(); - assert_eq!(ar.name(), "العربية"); - assert!(ar.rtl()); - let rtl: Vec<&str> = Lang::all().filter(|l| l.rtl()).map(|l| l.code()).collect(); - assert_eq!(rtl, ["ar", "ckb", "fa"], "Arabic, Kurdish and Persian are the right-to-left languages"); - assert_eq!(normalize_pref("AR"), Some("ar")); - for tag in ["ar", "ar-MA", "ar_EG.UTF-8", "AR-sa", "ar_DZ@variant"] { - assert_eq!(lang_from_tag(tag), Some(ar), "{tag}"); - } - assert_eq!(first_supported("ar-MA\r\nen-US"), Some(ar)); - // Unknown strings and user text are never reordered by a lookup. - assert_eq!(tr(ar, "تقرير نهائي {n}.pdf"), "تقرير نهائي {n}.pdf"); - let mut app = crate::PdfCraftApp::default(); - app.set_option("language", "AR").unwrap(); - assert_eq!(app.language, "ar"); - let mut restored = crate::PdfCraftApp::default(); - restored.restore(&app.persist()); - assert_eq!(restored.language, "ar"); - assert!(restored.set_option("language", "xx").is_err()); - assert_eq!(restored.language, "ar"); -} - /// Catalog lookups stay in logical order; the egui 0.37 fork owns bidi shaping and display /// reordering (E5/E12), so preordering here would reverse Arabic twice. Accessibility names, /// copied labels and search therefore see the source string. @@ -1346,90 +518,6 @@ fn arabic_catalog_stays_logical() { set_current(Lang::EN); } -#[test] -fn arabic_plurals_follow_the_six_cldr_forms() { - let form = plural_fixture("ar", 6); - assert_eq!([0, 1, 2].map(&form), [0, 1, 2]); - assert_eq!([3, 10, 103, 110, 1003].map(&form), [3; 5]); - assert_eq!([11, 99, 111, 199, 1011].map(&form), [4; 5]); - assert_eq!([100, 101, 102, 200, 1000, u64::MAX - 13].map(&form), [5; 6]); -} - -fn persian() -> Lang { - Lang::from_code("fa").expect("fa registered") -} - -#[test] -fn persian_is_registered_and_persists() { - needs_catalogs!(); - let fa = persian(); - assert_eq!(fa.name(), "فارسی"); - assert!(fa.rtl()); - // CLDR `fa` (one: i = 0 or n = 1): 0 and 1 are singular, every other count the plural. - let form = plural_fixture("fa", 2); - assert_eq!([0, 1, 2, 11].map(&form), [0, 0, 1, 1]); - assert_eq!(normalize_pref("FA"), Some("fa")); - for tag in ["fa", "fa-IR", "fa_IR.UTF-8", "FA-af", "fa_IR@calendar=persian"] { - assert_eq!(lang_from_tag(tag), Some(fa), "{tag}"); - } - assert_eq!(first_supported("fa-IR\r\nen-US"), Some(fa)); - // Lookups return Persian in logical order; epaint handles visual ordering. - assert_eq!(tr(fa, "Save"), "ذخیره"); - assert_eq!(tr(fa, "Cancel"), "لغو"); - assert_eq!(tr(fa, "File"), "فایل"); - // Unknown strings and user text are never reordered by a lookup. - assert_eq!(tr(fa, "گزارش نهایی {n}.pdf"), "گزارش نهایی {n}.pdf"); - let mut app = crate::PdfCraftApp::default(); - app.set_option("language", "FA").unwrap(); - assert_eq!(app.language, "fa"); - let mut restored = crate::PdfCraftApp::default(); - restored.restore(&app.persist()); - assert_eq!(restored.language, "fa"); - assert!(restored.set_option("language", "xx").is_err()); - assert_eq!(restored.language, "fa"); -} - -/// A form picker for `code`: a fixture row with `forms` plural forms, and for a count the form -/// index the crate's CLDR rules choose. -fn plural_fixture(code: &'static str, forms: usize) -> impl Fn(u64) -> usize { - let row = (0..forms).map(|i| format!("F{i} {{n}}")).collect::>().join("|"); - let lang = fixture_lang(code, Box::leak(format!("@plural\t{{n}} x|{{n}} xs\t{row}\n").into_boxed_str())); - move |n| { - let said = trn(lang, n, "{n} x", "{n} xs"); - said.strip_prefix('F') - .and_then(|s| s.split(' ').next()) - .and_then(|i| i.parse().ok()) - .unwrap_or_else(|| panic!("{code}: no form for {n}: {said:?}")) - } -} - -/// With a craft-fonts Arabic face, every Arabic translation has glyphs: with all interface -/// faces (desktop) and with the Arabic face as the only craft-fonts face (the web build keeps -/// it; Arabic labels must not need a Japanese face). -#[test] -fn arabic_labels_have_glyphs() { - let faces: Vec = pdfcraft_fonts::ui_arabic_fonts().iter().map(|f| f.name()).collect(); - if faces.is_empty() { - eprintln!("skipping Arabic glyph checks: build with CRAFT_FONTS_DIR and an Arabic face to run them"); - return; - } - needs_catalogs!(); - let ar = arabic(); - let labels: String = translations("ar").chars().chain(ar.name().chars()).filter(|c| !c.is_control()).collect(); - let mut arabic_only = crate::theme::font_definitions(); - for family in arabic_only.families.values_mut() { - family.retain(|name| !pdfcraft_fonts::CRAFT_FONTS.iter().any(|face| face.name() == *name) || faces.contains(name)); - } - use egui::epaint::text::{Fonts, TextOptions}; - for (build, defs) in [("all faces", crate::theme::font_definitions()), ("Arabic face only", arabic_only)] { - let mut fonts = Fonts::new(TextOptions::default(), defs); - for id in [egui::FontId::proportional(13.0), egui::FontId::monospace(13.0), crate::theme::medium(13.0), crate::theme::semibold(17.0)] { - let missing: std::collections::BTreeSet = labels.chars().filter(|c| !fonts.has_glyphs(&id, &c.to_string())).collect(); - assert!(missing.is_empty(), "{build}: {id:?} lacks Arabic label glyphs {missing:?}"); - } - } -} - /// The language list is well-formed. Problems in the embedded catalogs are not failed: craft-i18n /// checks its rows, a row PdfCraft can't use shows in English, and `translation_gaps_report` /// lists the `@id` rows PdfCraft doesn't use ([`unused_id_rows`]). @@ -1511,13 +599,6 @@ fn english_keys() -> std::collections::BTreeSet<(String, String)> { ]; engine.into_iter().flatten().for_each(|s| add(s)); pdfcraft_engine::sign::AppearanceLabels::default().fields().into_iter().for_each(|(_, label)| add(label)); - crate::credits::NameMode::ALL.iter().for_each(|mode| add(mode.label())); - for key in crate::credits::SortKey::ALL { - let (label, header) = key.label(); - add(label); - add(header); - } - crate::credits::MODEL_COLUMNS.iter().for_each(|s| add(s)); // (context, source) keys; `@id` rows only reword a command label, which is in `plain`. let mut keys: BTreeSet<(String, String)> = plain.into_iter().map(|s| (String::new(), s)).collect(); for (_, _, app) in CRAFT_I18N { @@ -1598,16 +679,3 @@ fn date_languages_are_the_interface_languages() { fn properties_stale_notice_is_in_translation_scan() { assert!(ui_literals().contains("The document changed. Reopen Document Properties to edit the current version.")); } - -/// A report, not a check: the notifications pasting an image and pinning a tool show, in each -/// language that has no translation for them yet (they show in English). -#[test] -fn image_paste_and_home_notifications_are_translated() { - for language in Lang::all().filter(|l| *l != Lang::EN) { - for source in ["Search…", "Image pasted", "No image on clipboard to paste", "Pinned {tool} to Home", "Unpinned {tool} from Home"] { - if !has(language, source) { - println!("{}: no translation for {source:?} (shows in English)", language.code()); - } - } - } -} diff --git a/crates/ui-egui/tests/it/open_action.rs b/crates/ui-egui/tests/it/open_action.rs index 724caca4a7..904174ee37 100644 --- a/crates/ui-egui/tests/it/open_action.rs +++ b/crates/ui-egui/tests/it/open_action.rs @@ -4,6 +4,7 @@ use egui::{Key, Modifiers}; use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; use pdfcraft_render::DestView; use pdfcraft_ui_egui::canvas::Fit; use pdfcraft_ui_egui::{OpenOutcome, PdfCraftApp, RightPanel}; @@ -87,8 +88,8 @@ fn near(got: f32, want: f32, what: &str) { #[test] fn an_xyz_open_action_puts_its_point_at_the_window_top_left() { let mut h = harness("/OpenAction [5 0 R /XYZ 100 500 2]"); - assert_eq!(h.state().views[0].current, 2); - assert_eq!((h.state().views[0].fit, h.state().views[0].zoom), (Fit::None, 2.0)); + assert_eq!(h.state().views[0].current(), 2); + assert_eq!((h.state().views[0].fit(), h.state().views[0].zoom()), (Fit::None, 2.0)); // `left`: the page sits 100 user points further left than one opened at left 0. let (left, scale) = page_left(&h, 2); let (left0, _) = page_left(&harness("/OpenAction [5 0 R /XYZ 0 500 2]"), 2); @@ -101,8 +102,8 @@ fn an_xyz_open_action_puts_its_point_at_the_window_top_left() { #[test] fn a_fith_open_action_puts_its_top_at_the_window_top() { let mut h = harness("/OpenAction [4 0 R /FitH 400]"); - assert_eq!(h.state().views[0].current, 1); - assert_eq!(h.state().views[0].fit, Fit::Width); + assert_eq!(h.state().views[0].current(), 1); + assert_eq!(h.state().views[0].fit(), Fit::Width); let (page, top) = window_top(&mut h); assert_eq!(page, 1); near(top, 400.0, "y 400 is at the window's top edge"); @@ -119,16 +120,16 @@ fn a_named_open_destination_opens_its_page() { "/OpenAction /there /Dests << /there [7 0 R /XYZ 0 792 0] >>", ] { let mut h = harness(catalog); - assert_eq!(h.state().views[0].current, 4, "{catalog}"); + assert_eq!(h.state().views[0].current(), 4, "{catalog}"); // A zoom of 0 keeps the default zoom. - assert_eq!(h.state().views[0].fit, Fit::Width, "{catalog}"); + assert_eq!(h.state().views[0].fit(), Fit::Width, "{catalog}"); let (page, top) = window_top(&mut h); assert_eq!(page, 4, "{catalog}"); near(top, 792.0, "the page's top is at the window's top edge"); } // A name nothing defines opens on the first page. let h = harness("/OpenAction << /S /GoTo /D /missing >> /Dests << /there [7 0 R /Fit] >>"); - assert_eq!(h.state().views[0].current, 0); + assert_eq!(h.state().views[0].current(), 0); } #[test] @@ -144,8 +145,8 @@ fn always_my_default_view_keeps_the_zoom_and_goes_to_the_page_top() { }); h.run_steps(4); settle(&mut h); - assert_eq!(h.state().views[0].current, 2); - assert_eq!(h.state().views[0].fit, Fit::Width); + assert_eq!(h.state().views[0].current(), 2); + assert_eq!(h.state().views[0].fit(), Fit::Width); let (page, top) = window_top(&mut h); assert_eq!(page, 2); near(top, 792.0, "the page's top"); @@ -155,13 +156,13 @@ fn always_my_default_view_keeps_the_zoom_and_goes_to_the_page_top() { fn a_full_screen_document_shows_its_non_full_screen_panel_outside_full_screen() { for (mode, want) in [("UseThumbs", Some(RightPanel::Pages)), ("UseOC", Some(RightPanel::Layers)), ("UseNone", None)] { let mut h = harness(&format!("/PageMode /FullScreen /ViewerPreferences << /NonFullScreenPageMode /{mode} >>")); - assert!(h.state().pending_full_screen.is_some(), "{mode}: full screen is asked for"); + // The prompt (`ask_full_screen`) is on the dialog host, found by its question. + h.get_by_label("Open in Full Screen mode?"); assert_eq!(h.state().right, want, "{mode}: the panel behind the prompt"); // Declining it leaves that panel. - let ctx = h.ctx.clone(); - h.state_mut().resolve_full_screen_prompt(&ctx, false); + h.get_by_label("Not now").click(); h.run_steps(2); - assert_eq!((h.state().full_screen, h.state().right), (false, want), "{mode}: declined"); + assert_eq!((h.state().full_screen(), h.state().right), (false, want), "{mode}: declined"); // Entering and leaving full screen comes back to it. h.state_mut().apply_full_screen(true); h.run_steps(2); @@ -204,32 +205,45 @@ fn manual(test: &str) -> String { path.to_string_lossy().into_owned() } +/// A window with no document, in English. +#[cfg(not(target_arch = "wasm32"))] +fn bare_window() -> Harness<'static, PdfCraftApp> { + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| { + let mut app = PdfCraftApp::new(); + app.set_option("language", "en").unwrap(); + app + }); + h.run_steps(4); + h +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn a_file_named_with_open_parameters_opens_at_their_destination() { - // #3425: a help system starts PdfCraft with `manual.pdf#nameddest=…`. Files named at launch - // open before the first frame. + // #3425: a help system starts PdfCraft with `manual.pdf#nameddest=…`. let path = manual("launch"); for (parameters, page) in [("#nameddest=Load Flow", 3), ("#nameddest=intro", 1), ("#intro", 1), ("#page=5", 4), ("#zoom=200", 2)] { - let mut app = PdfCraftApp::new(); - app.set_option("language", "en").unwrap(); - assert_eq!(app.open_path(&format!("{path}{parameters}")), OpenOutcome::Opened, "{parameters}"); - assert_eq!(app.views.len(), 1, "{parameters}"); - assert_eq!(app.views[0].current, page, "{parameters}"); + let mut h = bare_window(); + assert!(matches!(h.state_mut().open_path(&format!("{path}{parameters}")), OpenOutcome::Opened | OpenOutcome::Pending), "{parameters}"); + crate::support::wait_until(&mut h, "the manual", |app| app.views.len() == 1); + assert_eq!(h.state().views.len(), 1, "{parameters}"); + assert_eq!(h.state().views[0].current(), page, "{parameters}"); + let app = h.state(); assert_eq!(app.session.get(app.views[0].id).and_then(|d| d.path.clone()).as_deref(), Some(path.as_str()), "{parameters}: the file itself"); - assert_eq!(app.toast, None, "{parameters}"); + assert!(h.state().notices.posted().is_empty(), "{parameters}"); } // A name the file doesn't define: it opens where it would have, and says so. - let mut app = PdfCraftApp::new(); - app.set_option("language", "en").unwrap(); - assert_eq!(app.open_path(&format!("{path}#nameddest=Nowhere")), OpenOutcome::Opened); - assert_eq!(app.views[0].current, 2); - assert!(app.toast.as_ref().is_some_and(|(text, _)| text.contains("named destination was not applied")), "{:?}", app.toast); + let mut h = bare_window(); + assert!(matches!(h.state_mut().open_path(&format!("{path}#nameddest=Nowhere")), OpenOutcome::Opened | OpenOutcome::Pending)); + crate::support::wait_until(&mut h, "the manual", |app| app.views.len() == 1); + h.run_steps(2); + assert_eq!(h.state().views[0].current(), 2); + assert!(!h.state().notices.posted().is_empty(), "the unapplied name is told"); // A path that names no file, before a `#` or as a whole, still fails as before. - let mut app = PdfCraftApp::new(); - app.set_option("language", "en").unwrap(); - assert_eq!(app.open_path(&format!("{path}.missing#page=2")), OpenOutcome::Failed); - assert!(app.views.is_empty()); + let mut h = bare_window(); + assert!(!matches!(h.state_mut().open_path(&format!("{path}.missing#page=2")), OpenOutcome::Opened | OpenOutcome::Focused)); + h.run_steps(4); + assert!(h.state().views.is_empty()); } #[cfg(not(target_arch = "wasm32"))] @@ -246,14 +260,14 @@ fn open_parameters_handed_to_the_running_app_show_their_destination() { // Asked twice before it has opened, it opens at the place asked for last. assert_eq!(h.state_mut().open_path(&format!("{path}#page=5")), OpenOutcome::Pending); assert_eq!(h.state_mut().open_path(&format!("{path}#nameddest=Load Flow")), OpenOutcome::Pending); - crate::support::wait_until(&mut h, "the manual at Load Flow", |app| app.views.len() == 1 && app.views[0].current == 3); + crate::support::wait_until(&mut h, "the manual at Load Flow", |app| app.views.len() == 1 && app.views[0].current() == 3); // Asked again for a place in the open file, its tab goes there instead of opening it again. assert_eq!(h.state_mut().open_path(&format!("{path}#page=2")), OpenOutcome::Focused); - assert_eq!((h.state().views.len(), h.state().views[0].current), (1, 1)); + assert_eq!((h.state().views.len(), h.state().views[0].current()), (1, 1)); // A name is looked up off the UI thread: the tab moves once the lookup is in. assert_eq!(h.state_mut().open_path(&format!("{path}#nameddest=Load Flow")), OpenOutcome::Focused); - assert_eq!(h.state().views[0].current, 1, "not yet"); - crate::support::wait_until(&mut h, "Load Flow", |app| app.views[0].current == 3); + assert_eq!(h.state().views[0].current(), 1, "not yet"); + crate::support::wait_until(&mut h, "Load Flow", |app| app.views[0].current() == 3); // A page asked for while a name is still being looked up wins: the lookup's answer is dropped. assert_eq!(h.state_mut().open_path(&format!("{path}#nameddest=intro")), OpenOutcome::Focused); assert_eq!(h.state_mut().open_path(&format!("{path}#page=5")), OpenOutcome::Focused); @@ -261,17 +275,16 @@ fn open_parameters_handed_to_the_running_app_show_their_destination() { h.run_steps(1); std::thread::sleep(std::time::Duration::from_millis(20)); } - assert_eq!(h.state().views[0].current, 4); + assert_eq!(h.state().views[0].current(), 4); } #[cfg(not(target_arch = "wasm32"))] #[test] fn open_parameters_wait_with_their_file_behind_a_password_prompt_and_a_full_queue() { - // Launched with a protected file first and more files than the open worker queues at once: - // the files past its bound wait their turn, and the later ones wait behind the password - // prompt. A file named with open parameters keeps them while it waits, and named again, it - // opens at the place asked for last; the protected file named again with them while its - // password is asked for opens there once unlocked. They opened where they would have. + // Launched with a protected file first and many files after it: the later ones wait behind + // the password prompt. A file named with open parameters keeps them while it waits, and named + // again, it opens at the place asked for last; the protected file named again with them while + // its password is asked for opens there once unlocked. They opened where they would have. let dir = std::env::temp_dir().join(format!("pdfcraft-open-parameters-queue-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); @@ -297,11 +310,17 @@ fn open_parameters_wait_with_their_file_behind_a_password_prompt_and_a_full_queu app }); h.run_steps(4); - assert!(h.state().password_prompt.is_some(), "the protected file is asked for"); - h.state_mut().submit_password(Some("reader".into())); + h.get_by_label("Password required"); + // The password goes into the dialog's field and OK is pressed. + // PLAN: the password field is found by its role; the OK button is the dialog's own (the last "Open" button) + let field = h.get_by(|n| n.role() == egui::accesskit::Role::PasswordInput); + field.focus(); + field.type_text("reader"); + h.run_steps(1); + h.get_all_by_role_and_label(egui::accesskit::Role::Button, "Open").last().unwrap().click(); crate::support::wait_until(&mut h, "every file", |app| app.views.len() == others.len() + 2); let app = h.state(); - let page_of = |path: &str| app.views.iter().find(|v| app.session.get(v.id).and_then(|d| d.path.as_deref()) == Some(path)).map(|v| v.current); + let page_of = |path: &str| app.views.iter().find(|v| app.session.get(v.id).and_then(|d| d.path.as_deref()) == Some(path)).map(|v| v.current()); // `fixture(NAMED)` opens at page 3 by its /OpenAction. assert_eq!(page_of(&manual), Some(4), "the file past the queue's bound, at the last page asked for"); assert_eq!(page_of(&locked), Some(3), "the protected file, at the page asked for during its prompt"); diff --git a/crates/ui-egui/tests/it/reading_colors.rs b/crates/ui-egui/tests/it/reading_colors.rs index e69bc49db3..ea6393dc41 100644 --- a/crates/ui-egui/tests/it/reading_colors.rs +++ b/crates/ui-egui/tests/it/reading_colors.rs @@ -36,13 +36,15 @@ fn pending_pages_use_document_reading_background() { app.views[0].go_to_page(page); // Draw the real canvas without finishing the render frame, so no texture can // race the assertion or hide the pending-page background. + let mut textures = usize::MAX; let mut output = ctx.run_ui(RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(900.0, 600.0))), ..Default::default() }, |ui| { - pdfcraft_ui_egui::canvas::document_area(&mut app, 0, ui); + let rect = ui.max_rect(); + textures = pdfcraft_ui_egui::canvas::document_area_at(&mut app, 0, rect, ui).textures.entries; }); output.textures_delta.clear(); let view = &app.views[0]; - assert_eq!(view.raster_memory().page_count, 0, "the page must still be waiting for its raster"); + assert_eq!(textures, 0, "the page must still be waiting for its picture"); let rect = view.page_screen_rect(page).expect("target page visible"); let fill = output.shapes.iter().find_map(|s| match &s.shape { Shape::Rect(r) if r.rect == rect && r.stroke.width == 0.0 => Some(r.fill), @@ -84,16 +86,17 @@ fn reading_colours_preference_round_trips() { // The choice survives a restart through the same path the settings file uses. let mut restored = PdfCraftApp::new(); - restored.restore(&h.state().persist()); + restored.apply_settings(&h.state().settings_snapshot()); assert_eq!(restored.reading_colors, ReadingColors::WHITE_ON_BLACK); // A settings file without the field keeps Off. + let restore = |app: &mut PdfCraftApp, json: &str| app.apply_settings(&pdfcraft_ui_egui::settings::import_json(json).0); let mut fresh = PdfCraftApp::new(); - fresh.restore(r#"{"theme": "dark"}"#); + restore(&mut fresh, r#"{"theme": "dark"}"#); assert_eq!(fresh.reading_colors, ReadingColors::default()); - // A corrupt value fails to deserialize and falls back to Off instead of panicking. - fresh.restore(r#"{"reading_colors": {"params": {"text": "zzz", "background": [0, 0, 0], "only_black": false, "line_art": true}}}"#); + // A corrupt value falls back to Off instead of panicking. + restore(&mut fresh, r#"{"reading_colors": {"params": {"text": "zzz", "background": [0, 0, 0], "only_black": false, "line_art": true}}}"#); assert_eq!(fresh.reading_colors, ReadingColors::default()); - fresh.restore(r#"{"reading_colors": 7}"#); + restore(&mut fresh, r#"{"reading_colors": 7}"#); assert_eq!(fresh.reading_colors, ReadingColors::default()); } @@ -170,7 +173,7 @@ fn reading_colours_seed_on_open() { assert_eq!(h.state().session.reading_colors(signed), Some(ReadingColors::YELLOW_ON_BLACK)); // Created documents open through their own session calls too — a comment summary via - // `open_created`, an image import via `open_created_bytes` — and seed the same way. + // `open_created`, an image import via `open_new_document` — and seed the same way. h.state_mut().summarize_comments(); let summary = h.state().views.last().unwrap().id; assert_ne!(summary, signed); diff --git a/crates/ui-egui/tests/it/reload.rs b/crates/ui-egui/tests/it/reload.rs index 688b10c619..cc751e6a8a 100644 --- a/crates/ui-egui/tests/it/reload.rs +++ b/crates/ui-egui/tests/it/reload.rs @@ -1,8 +1,9 @@ //! A document reloads when its file changes on disk (#431): a LaTeX or Typst build rewriting the -//! open PDF. Here the watcher looks once per frame on the test's thread (`run_inline`); in the -//! app a worker thread looks every quarter second. +//! open PDF. Here the watcher is built inline and looks once per frame on the test's thread; in +//! the app a worker thread looks every quarter second. use std::path::PathBuf; +use std::sync::Arc; use std::time::{Duration, SystemTime}; use egui_kittest::Harness; @@ -73,23 +74,45 @@ impl Drop for TempPdf { } } -fn harness(path: &str) -> Harness<'static, PdfCraftApp> { +/// An app on a host whose jobs wait for the test (`ManualJobs`) and whose watcher looks inline +/// on each pass. +fn app_with(jobs: Arc) -> PdfCraftApp { + use craft::host::{AppInfo, Host, Wake}; + use craft::platform::clipboard::{Clipboard, SystemClipboard}; + use craft::platform::open::FileIntake; + use craft::platform::watch::FileWatch; + use pdfcraft_ui_egui::AppServices; + let info = AppInfo { id: "pdfcraft", name: "PdfCraft", version: "0" }; + let host = Host::builder(info).jobs(jobs).files(Arc::new(craft::host::ScriptedFiles::new())).build(); + let (intake, _sender) = FileIntake::new(Wake::none()); + let watch = FileWatch::new(Wake::none()).inline(); + let services = AppServices::new(Wake::none(), Clipboard::new(SystemClipboard::new()), None, None, intake, watch); + let mut app = PdfCraftApp::with_host(Arc::new(host), services); + // The labels looked for are English, whatever the machine's language. + app.set_option("language", "en").unwrap(); + app +} + +/// A window over `app_with` whose open job has run. +fn harness_with(path: &str, setup: impl FnOnce(&mut PdfCraftApp) + 'static) -> Harness<'static, PdfCraftApp> { let path = path.to_owned(); + let jobs = Arc::new(craft::host::ManualJobs::new()); + let queue = jobs.clone(); let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| { - let mut app = PdfCraftApp::new(); - app.set_option("language", "en").unwrap(); - // The labels looked for are English, whatever the machine's language. - app.set_option("language", "en").unwrap(); - // The labels below are English whatever the developer's system language is. - app.set_option("language", "en").unwrap(); - app.run_inline = true; + let mut app = app_with(jobs); + setup(&mut app); app.open_path(&path); app }); + queue.run_all(); h.run_steps(4); h } +fn harness(path: &str) -> Harness<'static, PdfCraftApp> { + harness_with(path, |_| {}) +} + fn pages(h: &Harness<'static, PdfCraftApp>) -> usize { let app = h.state(); app.session.get(app.views[0].id).unwrap().info.pages.len() @@ -110,8 +133,8 @@ fn a_rebuilt_file_reloads_in_place_keeping_the_page_and_zoom() { let file = TempPdf::new("rebuild", &fixture(3)); let mut h = harness(&file.path); let id = h.state().views[0].id; - h.state_mut().views[0].fit = pdfcraft_ui_egui::canvas::Fit::None; - h.state_mut().views[0].zoom = 1.5; + h.state_mut().views[0].view.fit = craft::pages::Fit::None; + h.state_mut().views[0].view.zoom = 1.5; h.state_mut().views[0].go_to_page(2); h.run_steps(4); file.rebuild(&fixture(4)); @@ -120,14 +143,13 @@ fn a_rebuilt_file_reloads_in_place_keeping_the_page_and_zoom() { let app = h.state(); assert_eq!(pages(&h), 4, "the new version shows"); assert_eq!((app.views.len(), app.views[0].id), (1, id), "in the same tab"); - assert_eq!((app.views[0].current, app.views[0].zoom), (2, 1.5), "at the same page and zoom"); + assert_eq!((app.views[0].current(), app.views[0].zoom()), (2, 1.5), "at the same page and zoom"); } #[test] fn a_watched_label_replacement_keeps_the_display_mode_and_focused_page() { use pdfcraft_engine::{Edit, LabelStyle, Session}; - use pdfcraft_ui_egui::canvas::display_token; - use std::sync::Arc; + use craft::pages::display_token; let labelled = |ranges: &[(usize, usize, LabelStyle)]| { let mut source = Session::new().with_clock(|| 1_700_000_000); @@ -148,7 +170,7 @@ fn a_watched_label_replacement_keeps_the_display_mode_and_focused_page() { h.state_mut().set_option("page", "4").unwrap(); h.run_steps(3); let view = &h.state().views[0]; - assert_eq!((view.current, display_token(view.layout, view.continuous())), (3, display)); + assert_eq!((view.current(), display_token(view.view.display, view.view.continuous)), (3, display)); let doc = h.state().session.get(id).unwrap(); assert_eq!(doc.bytes, original); assert!(!doc.dirty); @@ -179,8 +201,12 @@ fn a_watched_label_replacement_keeps_the_display_mode_and_focused_page() { assert_eq!(doc.bytes, replacement, "the watcher loaded the replacement before checking navigation"); assert_eq!((doc.info.pages.len(), doc.info.pages[3].label.as_str()), (5, "iv")); // First causal negative: a single-page reader must not become a continuous reader. - assert_eq!((view.current, display_token(view.layout, view.continuous())), (3, display), "reload retains the physical page and display mode"); - assert_eq!(view.zoom, 1.0); + assert_eq!( + (view.current(), display_token(view.view.display, view.view.continuous)), + (3, display), + "reload retains the physical page and display mode" + ); + assert_eq!(view.zoom(), 1.0); assert_eq!(view.page_input, "iv"); assert_eq!(h.ctx.memory(|m| m.focused()), Some(editor)); h.get(By::new().role(egui::accesskit::Role::TextInput).value("iv")); @@ -188,7 +214,7 @@ fn a_watched_label_replacement_keeps_the_display_mode_and_focused_page() { // Keep the replacement editor's selection and then its caret, without re-focusing it. h.event(egui::Event::Text("2".into())); h.run_steps(2); - assert_eq!((h.state().views[0].current, h.state().views[0].page_input.as_str()), (3, "2")); + assert_eq!((h.state().views[0].current(), h.state().views[0].page_input.as_str()), (3, "2")); h.event(egui::Event::Text("x".into())); h.run_steps(1); assert_eq!(h.state().views[0].page_input, "2x"); @@ -198,7 +224,7 @@ fn a_watched_label_replacement_keeps_the_display_mode_and_focused_page() { h.key_press(egui::Key::Enter); h.run_steps(3); let app = h.state(); - assert_eq!((app.views[0].id, app.views[0].current, app.views[0].page_input.as_str()), (id, 1, "ii")); + assert_eq!((app.views[0].id, app.views[0].current(), app.views[0].page_input.as_str()), (id, 1, "ii")); let doc = app.session.get(id).unwrap(); assert_eq!(doc.path.as_deref(), Some(file.path.as_str())); assert!(!doc.dirty); @@ -276,7 +302,7 @@ fn nothing_reloads_with_the_preference_off() { h.run_steps(4); assert_eq!(pages(&h), 2); let mut restarted = PdfCraftApp::new(); - restarted.restore(&h.state().persist()); + restarted.apply_settings(&h.state().settings_snapshot()); assert!(!restarted.reload_changed_files, "the choice is kept"); } @@ -286,14 +312,17 @@ fn a_shorter_new_version_drops_what_pointed_into_the_old_one() { let mut h = harness(&file.path); h.state_mut().views[0].go_to_page(4); h.state_mut().views[0].select_pages(&[3, 4]); - h.state_mut().views[0].comments.selected = Some((4, 0)); + h.run_steps(2); + // Pick the last page's comment as a user does: its row in the Comments panel. + h.get_all_by_label_contains("note").last().expect("a comment row").click(); h.run_steps(2); file.rebuild(&fixture(1)); h.run_steps(4); let view = &h.state().views[0]; assert_eq!(pages(&h), 1); - assert_eq!(view.current, 0, "the page is clamped"); - assert!(view.selected.is_empty() && view.comments.selected.is_none(), "no selection points past the new version"); + assert_eq!(view.current(), 0, "the page is clamped"); + // PLAN: assumed `comments.primary()` reads the selected comment (pdf-comments) + assert!(view.selected.is_empty() && view.comments.primary().is_none(), "no selection points past the new version"); } /// Save asks before writing over a version of the file the document did not come from (#2166): @@ -330,16 +359,7 @@ fn saving_over_a_file_changed_by_something_else_asks_first() { #[test] fn saving_checks_the_file_with_the_watcher_off_too() { let file = TempPdf::new("overwrite-unwatched", &fixture(2)); - let path = file.path.clone(); - let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| { - let mut app = PdfCraftApp::new(); - app.set_option("language", "en").unwrap(); - app.run_inline = true; - app.reload_changed_files = false; - app.open_path(&path); - app - }); - h.run_steps(4); + let mut h = harness_with(&file.path, |app| app.reload_changed_files = false); rotate_first_page(&mut h); file.rebuild(&fixture(4)); h.run_steps(3); @@ -373,7 +393,7 @@ fn a_file_rebuilt_under_an_open_dialog_reloads_when_the_dialog_closes() { // open would apply the dialog (Rotate, Protect, Comment Properties…) to the new version. let file = TempPdf::new("under-dialog", &fixture(2)); let mut h = harness(&file.path); - h.state_mut().dialog = Some(pdfcraft_ui_egui::Dialog::RotatePages); + h.state_mut().set_option("dialog", "page.rotate_dialog").unwrap(); h.run_steps(2); file.rebuild(&fixture(4)); h.run_steps(4); @@ -381,7 +401,7 @@ fn a_file_rebuilt_under_an_open_dialog_reloads_when_the_dialog_closes() { file.rebuild(&fixture(5)); h.run_steps(4); assert_eq!(pages(&h), 2, "still not replaced under the dialog"); - h.state_mut().dialog = None; + h.get_by_label("Cancel").click(); h.run_steps(3); assert_eq!((pages(&h), dirty(&h)), (5, false), "the newest version is applied once the dialog closes"); } @@ -392,12 +412,12 @@ fn a_version_held_under_preferences_is_dropped_when_reloading_is_turned_off_ther // change on disk" must not still apply the version found while it was open. let file = TempPdf::new("held-pref-off", &fixture(2)); let mut h = harness(&file.path); - h.state_mut().dialog = Some(pdfcraft_ui_egui::Dialog::RotatePages); + h.state_mut().set_option("dialog", "preferences").unwrap(); h.run_steps(2); file.rebuild(&fixture(4)); h.run_steps(4); h.state_mut().reload_changed_files = false; - h.state_mut().dialog = None; + h.get_by_label("Cancel").click(); h.run_steps(4); assert_eq!(pages(&h), 2, "reloading was turned off before the dialog closed"); } @@ -409,7 +429,7 @@ fn a_newer_version_found_as_the_dialog_closes_replaces_the_held_one() { // edit generation: one is expected. let file = TempPdf::new("held-coalesced", &fixture(2)); let mut h = harness(&file.path); - h.state_mut().dialog = Some(pdfcraft_ui_egui::Dialog::RotatePages); + h.state_mut().set_option("dialog", "page.rotate_dialog").unwrap(); h.run_steps(2); file.rebuild(&fixture(4)); h.run_steps(4); @@ -419,7 +439,7 @@ fn a_newer_version_found_as_the_dialog_closes_replaces_the_held_one() { h.step(); let generation = |h: &Harness<'static, PdfCraftApp>| h.state().session.get(h.state().views[0].id).unwrap().edit_generation(); let before = generation(&h); - h.state_mut().dialog = None; + h.get_by_label("Cancel").click(); h.step(); assert_eq!((pages(&h), generation(&h) - before), (5, 1), "the held version is not loaded on the way"); } @@ -430,12 +450,13 @@ fn a_file_rebuilt_under_the_full_screen_prompt_reloads_once_it_is_answered() { let file = TempPdf::new("under-full-screen", &fixture(2)); let mut h = harness(&file.path); let id = h.state().views[0].id; - h.state_mut().pending_full_screen = Some(id); + // PLAN: assumed `ask_full_screen(id)` takes the document id (pdf-dialogs-w4) + h.state_mut().ask_full_screen(id); h.run_steps(2); file.rebuild(&fixture(4)); h.run_steps(4); assert_eq!(pages(&h), 2, "not replaced under the prompt"); - h.state_mut().pending_full_screen = None; + h.get_by_label("Not now").click(); h.run_steps(3); assert_eq!(pages(&h), 4, "applied once the prompt is gone"); } diff --git a/crates/ui-egui/tests/it/ui.rs b/crates/ui-egui/tests/it/ui.rs index 9363737413..a94afb5ab2 100644 --- a/crates/ui-egui/tests/it/ui.rs +++ b/crates/ui-egui/tests/it/ui.rs @@ -39,24 +39,31 @@ fn home_shows_welcome_and_tools() { h.get_by_label("Open file"); } +/// A side string of the control state's `side_panels` (`tools_side`, `rail_side`). +// PLAN: assumed `support::ui_state(h) -> serde_json::Value`, the control channel's `ui.state` reply (pdf-hub-w3) +fn side(h: &mut Harness<'static, PdfCraftApp>, key: &str) -> String { + support::ui_state(h)["side_panels"][key].as_str().unwrap_or_default().to_owned() +} + #[test] fn tools_panel_side_preference_moves_and_persists() { - use pdfcraft_ui_egui::Dialog; - let mut h = harness(|_| {}); - h.state_mut().dialog = Some(Dialog::Preferences); + h.state_mut().set_option("dialog", "preferences").unwrap(); h.run_steps(3); h.get_by_label("Tools panel side"); h.get_by_label("Right").click(); + h.get_by_label("OK").click(); + h.run_steps(3); + assert_eq!(side(&mut h, "tools_side"), "right"); + let saved = h.state().settings_snapshot(); + let mut restored = harness(move |app| app.apply_settings(&saved)); + assert_eq!(side(&mut restored, "tools_side"), "right"); + h.state_mut().set_option("dialog", "preferences").unwrap(); h.run_steps(3); - assert!(h.state().side_panels.tools_on_right()); - let saved = h.state().persist(); - let mut restored = PdfCraftApp::new(); - restored.restore(&saved); - assert!(restored.side_panels.tools_on_right()); h.get_by_label("Left").click(); + h.get_by_label("OK").click(); h.run_steps(3); - assert!(!h.state().side_panels.tools_on_right()); + assert_eq!(side(&mut h, "tools_side"), "left"); } /// Every piece of text painted on the last frame: its whole text, whether it was cut with "…", @@ -172,7 +179,7 @@ fn collapse_and_escape_close_the_expanded_all_tools() { #[test] fn escape_in_a_dialog_over_the_expanded_all_tools_leaves_the_view_open() { let mut h = harness(|app| app.set_option("tools", "full").unwrap()); - h.state_mut().dialog = Some(pdfcraft_ui_egui::Dialog::About); + h.state_mut().set_option("dialog", "about").unwrap(); h.run_steps(3); h.key_press(egui::Key::Escape); h.run_steps(3); @@ -265,7 +272,7 @@ fn going_home_with_no_document_puts_the_expanded_all_tools_away() { fn expanding_all_tools_from_read_mode_restores_the_right_panel() { use pdfcraft_ui_egui::{Mode, RightPanel}; let mut h = harness(|app| app.open_bytes("fixture.pdf", None, FIXTURE.to_vec()).expect("fixture opens")); - h.state_mut().right = Some(RightPanel::Bookmarks); + h.state_mut().set_option("panel", "bookmarks").unwrap(); h.state_mut().execute("view.read_mode"); h.run_steps(3); assert_eq!((h.state().mode, h.state().right), (Mode::Read, None), "Read mode hides the panel"); @@ -311,9 +318,9 @@ fn closed_side_panes_stay_closed_after_a_restart_and_opening_a_pdf() { h.state_mut().choose_right_panel(None); h.state_mut().set_option("left", "closed").unwrap(); h.run_steps(3); - let saved = h.state().persist(); + let saved = h.state().settings_snapshot(); let mut h = harness(move |app| { - app.restore(&saved); + app.apply_settings(&saved); app.open_bytes("fixture.pdf", None, FIXTURE.to_vec()).expect("fixture opens"); }); assert_eq!(h.state().right, None, "the closed right pane reopened"); @@ -338,9 +345,9 @@ fn closed_right_panel_stays_closed_for_a_document_asking_for_its_outline() { h.state_mut().open_bytes("outline.pdf", None, pdf()).unwrap(); h.run_steps(3); assert_eq!(h.state().right, None, "the outline request reopened the closed right panel"); - let saved = h.state().persist(); + let saved = h.state().settings_snapshot(); let h = harness(move |app| { - app.restore(&saved); + app.apply_settings(&saved); app.open_bytes("outline.pdf", None, pdf()).expect("outline PDF opens"); }); assert_eq!(h.state().right, None, "the closed right panel reopened after a restart"); @@ -348,26 +355,26 @@ fn closed_right_panel_stays_closed_for_a_document_asking_for_its_outline() { #[test] fn navigation_rail_toggles_between_right_and_left_and_persists() { - use pdfcraft_ui_egui::Dialog; - let mut h = harness(|app| app.open_bytes("fixture.pdf", None, FIXTURE.to_vec()).expect("fixture opens")); - assert_eq!(h.state().side_panels.rail_side, pdfcraft_ui_egui::side_panels::ToolsSide::Right); + assert_eq!(side(&mut h, "rail_side"), "right"); h.get_by_label("Dock navigation rail on Left").click(); h.run_steps(3); - assert_eq!(h.state().side_panels.rail_side, pdfcraft_ui_egui::side_panels::ToolsSide::Left); - let saved = h.state().persist(); - let mut h2 = harness(move |app| { - app.restore(&saved); - }); - assert_eq!(h2.state().side_panels.rail_side, pdfcraft_ui_egui::side_panels::ToolsSide::Left); - h2.state_mut().dialog = Some(Dialog::Preferences); + assert_eq!(side(&mut h, "rail_side"), "left"); + let saved = h.state().settings_snapshot(); + let mut h2 = harness(move |app| app.apply_settings(&saved)); + assert_eq!(side(&mut h2, "rail_side"), "left"); + h2.state_mut().set_option("dialog", "preferences").unwrap(); h2.run_steps(3); h2.get_by_label("Navigation rail side: Right").click(); + h2.get_by_label("OK").click(); + h2.run_steps(3); + assert_eq!(side(&mut h2, "rail_side"), "right"); + h2.state_mut().set_option("dialog", "preferences").unwrap(); h2.run_steps(3); - assert_eq!(h2.state().side_panels.rail_side, pdfcraft_ui_egui::side_panels::ToolsSide::Right); h2.get_by_label("Navigation rail side: Left").click(); + h2.get_by_label("OK").click(); h2.run_steps(3); - assert_eq!(h2.state().side_panels.rail_side, pdfcraft_ui_egui::side_panels::ToolsSide::Left); + assert_eq!(side(&mut h2, "rail_side"), "left"); } /// Read mode hides the tools, not the navigation panes: the rail's Bookmarks button opens the @@ -402,20 +409,6 @@ fn read_mode_rail_buttons_open_their_panels() { h.get_by_label("Alpha section"); } -/// The mode bar matches Acrobat's: All tools, Edit, Convert and E-Sign, with no Read tab. Read -/// mode is still a View command. -#[test] -fn the_mode_bar_has_no_read_tab() { - use pdfcraft_ui_egui::Mode; - let mut h = harness(|app| app.open_bytes("fixture.pdf", None, FIXTURE.to_vec()).expect("fixture opens")); - for label in ["All tools", "Edit", "Convert", "E-Sign"] { - assert!(h.query_all_by_label(label).next().is_some(), "the {label} tab is there"); - } - assert!(h.query_all_by_label("Read").next().is_none(), "no Read tab"); - h.state_mut().run_command("view.read_mode"); - h.run_steps(2); - assert_eq!(h.state().mode, Mode::Read); -} /// A document that asks to open in Full Screen mode (`/PageMode /FullScreen`) is asked about /// first, as in Acrobat: "Not now" leaves the window as it is, "Full Screen" enters it. @@ -424,26 +417,26 @@ fn a_document_asking_for_full_screen_is_asked_about_first() { let deck = || String::from_utf8(FIXTURE.to_vec()).unwrap().replace("/Outlines 6 0 R", "/Outlines 6 0 R /PageMode /FullScreen").into_bytes(); let mut h = harness(move |app| app.open_bytes("deck.pdf", None, deck()).expect("opens")); h.run_steps(3); - assert!(!h.state().full_screen, "nothing happens before the answer"); + assert!(!h.state().full_screen(), "nothing happens before the answer"); h.get_by_label("Open in Full Screen mode?"); h.get_by_label("Not now").click(); h.run_steps(3); - assert!(!h.state().full_screen); - assert!(h.query_by_label("Open in Full Screen mode?").is_none() && h.state().pending_full_screen.is_none()); + assert!(!h.state().full_screen()); + assert!(h.query_by_label("Open in Full Screen mode?").is_none(), "the prompt is gone"); // Asked again for the next such document; Full Screen enters it. let again = String::from_utf8(FIXTURE.to_vec()).unwrap().replace("/Outlines 6 0 R", "/Outlines 6 0 R /PageMode /FullScreen").into_bytes(); h.state_mut().open_bytes("deck2.pdf", None, again).expect("opens"); h.run_steps(3); h.get_by_label("Full Screen").click(); h.run_steps(3); - assert!(h.state().full_screen, "Full Screen enters it"); - assert!(h.state().pending_full_screen.is_none()); + assert!(h.state().full_screen(), "Full Screen enters it"); + assert!(h.query_by_label("Open in Full Screen mode?").is_none()); // A plain document asks nothing. h.key_press(egui::Key::Escape); h.run_steps(2); h.state_mut().open_bytes("plain.pdf", None, FIXTURE.to_vec()).expect("opens"); h.run_steps(3); - assert!(h.query_by_label("Open in Full Screen mode?").is_none() && !h.state().full_screen); + assert!(h.query_by_label("Open in Full Screen mode?").is_none() && !h.state().full_screen()); } /// Switching to Read mode closes the open pane, and switching back reopens it. @@ -575,20 +568,6 @@ fn a_pane_closed_in_read_mode_stays_closed_when_leaving_it() { assert!(h.state().comments_panel_closed); } -/// A right-to-left file name opens, lays out and paints; the tab's accessible name keeps the -/// logical text (only the painted label is put in visual order). -#[test] -fn a_tab_with_an_arabic_file_name_keeps_its_logical_accessible_name() { - let name = "واحد اثنين.pdf"; - let mut h = harness(move |app| app.open_bytes(name, None, FIXTURE.to_vec()).expect("fixture opens")); - let tab = h.get_by_label(name).rect(); - assert!(tab.width() > 64.0 && tab.height() > 0.0, "{tab:?}"); - // A name longer than the tab's 28-character limit is cut on a character boundary. - let long = "واحد اثنين ثلاثة أربعة خمسة ستة سبعة ثمانية.pdf"; - h.state_mut().open_bytes(long, None, FIXTURE.to_vec()).expect("fixture opens"); - h.run_steps(3); - h.get_by_label(long); -} /// A middle click on a tab closes it, as in Acrobat and browsers (#1853); a tab with unsaved /// changes asks first, as its close button does. @@ -603,13 +582,13 @@ fn a_middle_click_closes_the_tab() { let app = h.state(); assert_eq!(app.views.len(), 1); assert_eq!(app.session.get(app.views[0].id).unwrap().name, "second.pdf"); - assert!(app.close_request.is_none(), "a clean document closes without asking"); + assert!(h.query_by_label("Cancel").is_none(), "a clean document closes without asking"); h.state_mut().apply_edit(pdfcraft_engine::Edit::RotatePages { pages: vec![0], degrees: 90 }); h.run_steps(2); h.get_by_label("second.pdf (edited)").click_button(egui::PointerButton::Middle); h.run_steps(3); assert_eq!(h.state().views.len(), 1, "unsaved changes ask first"); - assert!(h.state().close_request.is_some()); + h.get_by_label("Cancel"); } #[test] @@ -618,65 +597,25 @@ fn a_link_prompt_above_a_save_prompt_owns_its_keys() { let mut h = harness(|app| { app.open_bytes("first.pdf", None, FIXTURE.to_vec()).unwrap(); app.apply_edit(pdfcraft_engine::Edit::RotatePages { pages: vec![0], degrees: 90 }); - app.close_request = Some(pdfcraft_ui_egui::CloseRequest::Tab(app.views[0].id)); }); h.run_steps(3); + // The save prompt is the close dialog the tab's close action opens. + h.get_by_label("first.pdf (edited)").click_button(egui::PointerButton::Middle); + h.run_steps(3); h.state_mut().pending_link = Some(pdfcraft_ui_egui::PendingLink { url: "https://example.org".to_owned(), origin: pdfcraft_ui_egui::LinkOrigin::Link }); h.run_steps(3); h.key_press(key); h.run_steps(3); - assert_eq!(h.state().pending_link.is_some(), key == egui::Key::Enter); - assert!(h.state().close_request.is_some(), "the save prompt stays open after {key:?}"); + // Escape and Enter both answer Cancel on the link prompt. + assert!(h.state().pending_link.is_none(), "{key:?} answered the link prompt"); + h.get_by_label("Cancel"); assert_eq!(h.state().views.len(), 1, "the edited document remains open"); - assert!(h.state().last_opened_url.is_none()); + let opened = h.output().platform_output.commands.iter().any(|c| matches!(c, egui::OutputCommand::OpenUrl(_))); + assert!(!opened, "nothing opens"); } } -#[test] -fn overflowing_tabs_can_be_reached_by_scrolling() { - let mut h = harness(|app| { - for i in 0..20 { - app.open_bytes(&format!("document-{i:02}.pdf"), None, FIXTURE.to_vec()).unwrap(); - } - }); - let last = h.get_by_label("document-19.pdf").rect(); - assert!(last.center().x < 1200.0, "newly opened active tab must be visible: {last:?}"); - h.state_mut().active = Some(0); - h.run_steps(4); - let first = h.get_by_label("document-00.pdf").rect(); - assert!(first.center().x < 1200.0, "changing active tab must reveal it"); - h.event(egui::Event::PointerMoved(first.center())); - for _ in 0..8 { - h.event(egui::Event::MouseWheel { - unit: egui::MouseWheelUnit::Point, - delta: egui::vec2(-500.0, 0.0), - phase: egui::TouchPhase::Move, - modifiers: egui::Modifiers::NONE, - source: egui::MouseWheelSource::Unknown, - }); - h.run_steps(8); - } - let last = h.get_by_label("document-19.pdf").rect(); - assert!(last.center().x > 0.0 && last.center().x < 1200.0, "last tab must be reachable: {last:?}"); - h.get_by_label("document-19.pdf").click(); - h.run_steps(3); - assert_eq!(h.state().active, Some(19)); - assert!(h.get_by_label_contains("Display theme:").rect().center().x < 1400.0); - let close = last.right_center() - egui::vec2(16.0, 0.0); - h.event(egui::Event::PointerMoved(close)); - h.event(egui::Event::PointerButton { pos: close, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }); - h.step(); - h.event(egui::Event::PointerButton { pos: close, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE }); - h.run_steps(4); - assert_eq!(h.state().views.len(), 19); - assert!(h.state().active.is_some_and(|i| i < 19)); - if let Ok(dir) = std::env::var("PDFCRAFT_TAB_SHOTS") { - let _gpu = crate::gpu(); - crate::support::settle(&mut h); - h.render().unwrap().save(format!("{dir}/overflow-tabs.png")).unwrap(); - } -} /// Whether a node labelled `label` is there and enabled (`None`: not there). fn enabled(h: &Harness<'static, PdfCraftApp>, label: &str) -> Option { @@ -702,26 +641,15 @@ fn tabs_shrink_to_fit_then_arrows_step_through_them_and_open_stays_in_sight() { let tab = h.get_by_label(&name(i)).rect(); assert!(tab.left() >= previous_right - 0.5, "tabs must not overlap: {i} at {tab:?}"); assert!(tab.right() <= open.left() + 0.5, "every tab fits before Open: {i} at {tab:?}, Open at {open:?}"); - assert!(tab.width() >= 179.0, "tabs keep most of their name: {i} is {tab:?}"); previous_right = tab.right(); } - assert_eq!(enabled(&h, "Scroll tabs left"), None, "no arrows while every tab fits"); - // Seven don't fit even at their narrowest: arrows show. The newest tab is active and in - // sight at the end, so only the left arrow can go further. + // Seven and twenty tabs: Open stays in sight left of Discord. for i in 5..7 { h.state_mut().open_bytes(&name(i), None, FIXTURE.to_vec()).unwrap(); } h.run_steps(6); - assert_eq!((enabled(&h, "Scroll tabs left"), enabled(&h, "Scroll tabs right")), (Some(true), Some(false))); - let first = h.get_by_label(&name(0)).rect(); - h.get_by_label("Scroll tabs left").click(); - h.run_steps(4); - assert!(h.get_by_label(&name(0)).rect().left() > first.left(), "the left arrow scrolls the tabs back"); - assert_eq!(enabled(&h, "Scroll tabs right"), Some(true), "and then there is more to the right"); - let open = h.get_by_label("Open").rect(); - let right = h.get_by_label("Scroll tabs right").rect(); - assert!(right.right() <= open.left() + 0.5 && open.right() <= h.get_by_label("Discord").rect().left()); - // Twenty: Open stays in sight left of Discord. + let (open, discord) = (h.get_by_label("Open").rect(), h.get_by_label("Discord").rect()); + assert!(open.right() <= discord.left(), "Open {open:?} stays left of Discord {discord:?} with seven tabs"); for i in 0..13 { h.state_mut().open_bytes(&format!("more-{i:02}.pdf"), None, FIXTURE.to_vec()).unwrap(); } @@ -731,68 +659,6 @@ fn tabs_shrink_to_fit_then_arrows_step_through_them_and_open_stays_in_sight() { assert!(open.left() > 0.0 && open.right() <= discord.left(), "Open {open:?} stays in sight left of Discord {discord:?}"); } -/// macOS (#789): with the integrated title bar, the strip is the 28 pt band AppKit centres the -/// traffic lights in, and everything in it fits that band and clears the lights. -#[cfg(target_os = "macos")] -#[test] -fn the_integrated_title_bar_is_the_traffic_light_band() { - let h = harness(|app| { - app.integrated_titlebar = true; - app.open_bytes("band.pdf", None, FIXTURE.to_vec()).unwrap(); - }); - let band = 28.0; - for label in ["Home", "band.pdf", "Open", "Discord", "Keyboard shortcuts"] { - let r = h.get_by_label(label).rect(); - assert!(r.top() >= 0.0 && r.bottom() <= band, "{label}: {r:?} inside the {band} pt title bar"); - assert!(r.height() >= 24.0, "{label}: {r:?} stays clickable"); - } - // Content starts after the three lights (the last one ends 62 pt in) with a gap. - let home = h.get_by_label("Home").rect(); - assert!(home.left() >= 62.0 + 4.0, "Home {home:?} clears the traffic lights"); -} - -#[test] -fn narrow_tab_strips_accept_vertical_wheel_scrolling() { - for width in [600.0, 900.0] { - let mut h = Harness::builder().with_size(egui::vec2(width, 700.0)).build_eframe(|_cc| { - let mut app = PdfCraftApp::new(); - app.set_option("language", "en").unwrap(); - for i in 0..12 { - app.open_bytes(&format!("narrow-{i:02}.pdf"), None, FIXTURE.to_vec()).unwrap(); - } - app - }); - h.run_steps(4); - let last = h.get_by(|n| n.role() == egui::accesskit::Role::Tab && n.label().as_deref() == Some("narrow-11.pdf")).rect(); - assert!(last.center().x > 28.0 && last.right() < width - 100.0, "active tab: {last:?}"); - h.state_mut().active = Some(0); - h.run_steps(4); - let first = h.get_by(|n| n.role() == egui::accesskit::Role::Tab && n.label().as_deref() == Some("narrow-00.pdf")).rect(); - assert!(first.center().x > 28.0 && first.right() < width - 100.0); - h.event(egui::Event::PointerMoved(first.center())); - for _ in 0..8 { - h.event(egui::Event::MouseWheel { - unit: egui::MouseWheelUnit::Point, - delta: egui::vec2(0.0, -500.0), - phase: egui::TouchPhase::Move, - modifiers: egui::Modifiers::NONE, - source: egui::MouseWheelSource::Unknown, - }); - h.run_steps(8); - } - let last = h.get_by(|n| n.role() == egui::accesskit::Role::Tab && n.label().as_deref() == Some("narrow-11.pdf")).rect(); - assert!(last.center().x > 28.0 && last.right() < width - 100.0, "scrolled tab: {last:?}"); - h.get_by(|n| n.role() == egui::accesskit::Role::Tab && n.label().as_deref() == Some("narrow-11.pdf")).click(); - h.run_steps(4); - assert_eq!(h.state().active, Some(11)); - assert!(h.get_by_label_contains("Display theme:").rect().right() <= width); - if let Ok(dir) = std::env::var("PDFCRAFT_TAB_SHOTS") { - let _gpu = crate::gpu(); - crate::support::settle(&mut h); - h.render().unwrap().save(format!("{dir}/tabs-{width}.png")).unwrap(); - } - } -} #[test] fn garbage_input_is_rejected_without_panicking() { @@ -888,13 +754,12 @@ fn persistence_round_trips_and_tolerates_garbage() { let mut a = PdfCraftApp::new(); a.set_option("language", "en").unwrap(); a.set_option("theme", "dark").unwrap(); - let json = a.persist(); let mut b = PdfCraftApp::new(); b.set_option("language", "en").unwrap(); - b.restore(&json); + b.apply_settings(&a.settings_snapshot()); assert_eq!(b.theme, pdfcraft_ui_egui::theme::ThemeKind::Dark); - b.restore("{not json"); - b.restore("{\"recent\": 5, \"theme\": \"Purple\"}"); + b.apply_settings(&pdfcraft_ui_egui::settings::import_json("{not json").0); + b.apply_settings(&pdfcraft_ui_egui::settings::import_json("{\"recent\": 5, \"theme\": \"Purple\"}").0); assert_eq!(b.theme, pdfcraft_ui_egui::theme::ThemeKind::Dark); } @@ -903,6 +768,7 @@ fn persistence_round_trips_and_tolerates_garbage() { #[test] fn a_saved_no_fill_clears_a_comment_tool_default_fill() { use pdfcraft_ui_egui::comments::CommentTool; + let restore = |app: &mut PdfCraftApp, json: &str| app.apply_settings(&pdfcraft_ui_egui::settings::import_json(json).0); let filled = |a: &mut PdfCraftApp| { let mut s = a.comment_prefs.style(CommentTool::Rectangle); s.fill = Some([0.2, 0.4, 0.6]); @@ -910,15 +776,15 @@ fn a_saved_no_fill_clears_a_comment_tool_default_fill() { }; let mut a = PdfCraftApp::new(); filled(&mut a); - a.restore(r#"{"comment_styles":[{"tool":"comment.square","fill":null}]}"#); + restore(&mut a, r#"{"comment_styles":[{"tool":"comment.square","fill":null}]}"#); assert_eq!(a.comment_prefs.style(CommentTool::Rectangle).fill, None, "null clears the fill"); let mut b = PdfCraftApp::new(); filled(&mut b); - b.restore(r#"{"comment_styles":[{"tool":"comment.square","color":[0,0,1]},{"tool":"comment.square","fill":"red"}]}"#); + restore(&mut b, r#"{"comment_styles":[{"tool":"comment.square","color":[0,0,1]},{"tool":"comment.square","fill":"red"}]}"#); assert_eq!(b.comment_prefs.style(CommentTool::Rectangle).fill, Some([0.2, 0.4, 0.6]), "missing or malformed keeps it"); // A round trip keeps a cleared fill cleared. let mut c = PdfCraftApp::new(); - c.restore(&a.persist()); + c.apply_settings(&a.settings_snapshot()); assert_eq!(c.comment_prefs.style(CommentTool::Rectangle).fill, None); } @@ -929,14 +795,15 @@ fn a_saved_same_as_text_clears_a_comment_tool_border_colour() { use pdfcraft_ui_egui::comments::CommentTool; let red = Some([0.89, 0.13, 0.13]); let mut a = PdfCraftApp::new(); + let restore = |app: &mut PdfCraftApp, json: &str| app.apply_settings(&pdfcraft_ui_egui::settings::import_json(json).0); a.comment_prefs.set_border_color(CommentTool::TextBox, red); - a.restore(r#"{"comment_styles":[{"tool":"comment.freetext","border_color":"red"}]}"#); + restore(&mut a, r#"{"comment_styles":[{"tool":"comment.freetext","border_color":"red"}]}"#); assert_eq!(a.comment_prefs.style(CommentTool::TextBox).border_color, red, "malformed keeps it"); - a.restore(r#"{"comment_styles":[{"tool":"comment.freetext","border_color":null}]}"#); + restore(&mut a, r#"{"comment_styles":[{"tool":"comment.freetext","border_color":null}]}"#); assert_eq!(a.comment_prefs.style(CommentTool::TextBox).border_color, None, "null clears it"); let mut b = PdfCraftApp::new(); b.comment_prefs.set_border_color(CommentTool::TextBox, red); - b.restore(&a.persist()); + b.apply_settings(&a.settings_snapshot()); assert_eq!(b.comment_prefs.style(CommentTool::TextBox).border_color, None, "a round trip keeps it cleared"); } @@ -946,13 +813,16 @@ fn a_saved_same_as_text_clears_a_comment_tool_border_colour() { fn comment_style_settings_clamp_and_refuse_hostile_values() { use pdfcraft_ui_egui::comments::CommentTool; let mut a = PdfCraftApp::new(); - a.restore( - r#"{"comment_styles":[ + a.apply_settings( + &pdfcraft_ui_egui::settings::import_json( + r#"{"comment_styles":[ {"tool":"comment.highlight","color":[2,-1,0.5],"opacity":99,"width":-4}, {"tool":"comment.note","color":"yellow","opacity":"none"}, {"tool":"comment.note","color":[0.1,null,0.3]}, {"tool":"bogus.command","color":[0,0,0]} ]}"#, + ) + .0, ); // Out-of-range numbers are clamped into range. let st = a.comment_prefs.style(CommentTool::Highlight); @@ -972,7 +842,7 @@ fn part_opacity_defaults_persist_and_clamp() { a.comment_prefs.set_part_opacity(CommentTool::TextBox, Some(0.2), Some(1.0)); a.comment_prefs.set_part_opacity(CommentTool::Line, Some(0.5), Some(0.5)); let mut b = PdfCraftApp::new(); - b.restore(&a.persist()); + b.apply_settings(&a.settings_snapshot()); let parts = |app: &PdfCraftApp, tool| { let s = app.comment_prefs.style(tool); (s.fill_opacity, s.text_opacity) @@ -980,25 +850,10 @@ fn part_opacity_defaults_persist_and_clamp() { assert_eq!(parts(&b, CommentTool::Rectangle), (Some(0.3), None)); assert_eq!(parts(&b, CommentTool::TextBox), (Some(0.2), Some(1.0))); assert_eq!(parts(&b, CommentTool::Line), (None, None), "a line has no fill or text of its own"); - b.restore(r#"{"comment_styles":[{"tool":"comment.freetext","fill_opacity":7,"text_opacity":-1}]}"#); + b.apply_settings(&pdfcraft_ui_egui::settings::import_json(r#"{"comment_styles":[{"tool":"comment.freetext","fill_opacity":7,"text_opacity":-1}]}"#).0); assert_eq!(parts(&b, CommentTool::TextBox), (Some(1.0), Some(0.1)), "clamped; the text stays visible"); } -#[test] -fn zoom_keeps_the_point_under_the_cursor_still() { - let mut h = harness(|app| { - app.open_bytes("text.pdf", None, TEXT_FIXTURE.to_vec()).expect("opens"); - app.set_option("left", "closed").unwrap(); - app.set_option("panel", "none").unwrap(); - }); - crate::support::settle(&mut h); - let before = h.state().views[0].glyph_screen_pos(0, 4).expect("glyph on screen"); - let z = h.state().views[0].zoom; - h.state_mut().views[0].zoom_at(z * 2.0, before); - h.run_steps(4); - let after = h.state().views[0].glyph_screen_pos(0, 4).expect("glyph still on screen"); - assert!((after - before).length() < 2.0, "moved from {before:?} to {after:?}"); -} #[test] fn trackpad_pinch_zooms_the_pdf_under_the_pointer() { @@ -1009,19 +864,19 @@ fn trackpad_pinch_zooms_the_pdf_under_the_pointer() { }); crate::support::settle(&mut h); let before = h.state().views[0].glyph_screen_pos(0, 4).expect("glyph on screen"); - let zoom = h.state().views[0].zoom; + let zoom = h.state().views[0].zoom(); h.hover_at(before); h.run_steps(1); h.event(egui::Event::Zoom(1.5)); h.run_steps(4); let enlarged = &h.state().views[0]; - assert!((enlarged.zoom - zoom * 1.5).abs() < 0.01); + assert!((enlarged.zoom() - zoom * 1.5).abs() < 0.01); let after = enlarged.glyph_screen_pos(0, 4).expect("glyph still on screen"); assert!((after - before).length() < 2.0, "moved from {before:?} to {after:?}"); h.event(egui::Event::Zoom(0.5)); h.run_steps(4); - assert!((h.state().views[0].zoom - zoom * 0.75).abs() < 0.01); + assert!((h.state().views[0].zoom() - zoom * 0.75).abs() < 0.01); } #[test] @@ -1173,7 +1028,6 @@ fn pdfs_dropped_on_the_combine_tab_join_its_list() { assert!(app.views.is_empty(), "nothing opens"); assert_eq!(app.combine_draft.len(), 2); assert!(app.combine_draft[0].modified.is_some() && app.combine_draft[1].modified.is_none()); - h.get_by_label("just now"); } #[test] @@ -1264,7 +1118,8 @@ fn a_file_combine_does_not_take_is_left_out_of_a_drop_and_named() { std::fs::remove_file(&path).ok(); assert_eq!(combine_names(&h), ["first.pdf", "one.pdf", "scan"]); let zip = path.file_name().unwrap().to_string_lossy().into_owned(); - h.get_by_label(&format!("Not added: report.docx, {zip}. Combine takes PDFs, images and text files.")); + let notice = h.state().notices.posted().join("; "); + assert!(notice.contains("report.docx") && notice.contains(&zip), "the refused names are told: {notice:?}"); } #[test] @@ -1279,16 +1134,47 @@ fn a_pdf_dropped_on_a_document_opens_while_the_combine_tab_waits_behind_it() { assert_eq!(combine_names(&h), ["first.pdf"], "the Combine files list is left as it was"); } +/// An app on a host whose jobs wait for the test (`ManualJobs`), taking its file requests from +/// `intake`, with an inline file watcher. +fn host_app(jobs: std::sync::Arc, intake: craft::platform::open::FileIntake) -> PdfCraftApp { + use craft::host::{AppInfo, Host, ScriptedFiles, Wake}; + use craft::platform::clipboard::{Clipboard, SystemClipboard}; + use craft::platform::watch::FileWatch; + let info = AppInfo { id: "pdfcraft", name: "PdfCraft", version: "0" }; + let host = Host::builder(info).jobs(jobs).files(std::sync::Arc::new(ScriptedFiles::new())).build(); + let services = pdfcraft_ui_egui::AppServices::new( + Wake::none(), + Clipboard::new(SystemClipboard::new()), + None, + None, + intake, + FileWatch::new(Wake::none()).inline(), + ); + PdfCraftApp::with_host(std::sync::Arc::new(host), services) +} + +/// A window whose app takes the OS's file requests from the returned sender (`FileIntake`). +fn intake_harness() -> (Harness<'static, PdfCraftApp>, craft::platform::open::IntakeSender) { + use craft::host::Wake; + use craft::platform::open::FileIntake; + let (intake, sender) = FileIntake::new(Wake::none()); + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| { + let mut app = host_app(std::sync::Arc::new(craft::host::ManualJobs::new()), intake); + app.set_option("language", "en").unwrap(); + app + }); + h.run_steps(4); + (h, sender) +} + #[test] fn files_and_quit_from_the_operating_system() { // #73: macOS hands Finder double-clicks, Open With and Dock drops over as Apple events. - use pdfcraft_ui_egui::OsEvent; let name = format!("pdfcraft-os-open-{}.pdf", std::process::id()); let path = std::env::temp_dir().join(&name); std::fs::write(&path, FIXTURE).unwrap(); - let queue = std::rc::Rc::new(std::cell::RefCell::new(vec![OsEvent::Open(vec![path.to_string_lossy().into_owned()])])); - let q = queue.clone(); - let mut h = harness(move |app| app.os_events = Some(Box::new(move || q.borrow_mut().drain(..).collect()))); + let (mut h, sender) = intake_harness(); + sender.open(vec![path.clone()]); // The file is read on a worker thread, after however many frames that takes: it must still // be there until the tab has opened. support::wait_until(&mut h, "the file the operating system opened", |app| !app.views.is_empty()); @@ -1298,40 +1184,39 @@ fn files_and_quit_from_the_operating_system() { // A file opened while the app runs brings its window forward, even minimized or full screen // on another Space. std::fs::write(&path, FIXTURE).unwrap(); - queue.borrow_mut().push(OsEvent::Open(vec![path.to_string_lossy().into_owned()])); + sender.open(vec![path.clone()]); h.step(); std::fs::remove_file(&path).ok(); let commands: Vec<_> = h.output().viewport_output.values().flat_map(|v| v.commands.clone()).collect(); assert!(commands.contains(&egui::ViewportCommand::Minimized(false)), "{commands:?}"); assert!(commands.contains(&egui::ViewportCommand::Focus), "{commands:?}"); // Quit closes the window like the close button, so unsaved changes are asked about. - queue.borrow_mut().push(OsEvent::Quit); + craft::quit::on_menu_event(&h.ctx, craft::quit::QUIT_MENU_ID); h.step(); let closing = h.output().viewport_output.values().any(|v| v.commands.iter().any(|c| matches!(c, egui::ViewportCommand::Close))); assert!(closing); } /// #585: File Explorer's "Combine files in PdfCraft" starts one launch per selected file, and the -/// running PdfCraft collects them (an `OsEvent::Combine` each) into its Combine files tab. +/// running PdfCraft collects them (an `open_for(.., "combine")` each) into its Combine files tab. #[test] fn files_to_combine_from_the_operating_system() { - use pdfcraft_ui_egui::OsEvent; let dir = std::env::temp_dir().join(format!("pdfcraft-os-combine-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); - let paths: Vec = ["one.pdf", "two.pdf"] + let paths: Vec = ["one.pdf", "two.pdf"] .iter() .map(|n| { let p = dir.join(n); std::fs::write(&p, FIXTURE).unwrap(); - p.to_string_lossy().into_owned() + p }) .collect(); - let queue = std::rc::Rc::new(std::cell::RefCell::new(vec![OsEvent::Combine(vec![paths[0].clone()])])); - let q = queue.clone(); - let mut h = harness(move |app| app.os_events = Some(Box::new(move || q.borrow_mut().drain(..).collect()))); + let (mut h, sender) = intake_harness(); + sender.open_for(vec![paths[0].clone()], "combine"); + h.run_steps(3); assert!(h.state().combine_showing(), "the Combine files tab shows"); assert!(h.state().views.is_empty(), "nothing opens as a document"); - queue.borrow_mut().push(OsEvent::Combine(vec![paths[1].clone()])); + sender.open_for(vec![paths[1].clone()], "combine"); h.run_steps(3); let _ = std::fs::remove_dir_all(&dir); let names: Vec<_> = h.state().combine_draft.iter().map(|f| f.name.clone()).collect(); @@ -1343,23 +1228,21 @@ fn files_to_combine_from_the_operating_system() { /// instead of hiding it; an Open that comes after Combine still shows its document. #[test] fn an_open_finishing_after_combine_keeps_the_combine_tab() { - use pdfcraft_ui_egui::OsEvent; let dir = std::env::temp_dir().join(format!("pdfcraft-os-combine-pending-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); - let paths: Vec = ["opening.pdf", "combined.pdf", "later.pdf"] + let paths: Vec = ["opening.pdf", "combined.pdf", "later.pdf"] .iter() .map(|n| { let p = dir.join(n); std::fs::write(&p, FIXTURE).unwrap(); - p.to_string_lossy().into_owned() + p }) .collect(); - let queue = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); - let q = queue.clone(); - let mut h = harness(move |app| app.os_events = Some(Box::new(move || q.borrow_mut().drain(..).collect()))); + let (mut h, sender) = intake_harness(); h.run_steps(2); // Both in one frame: the open goes to the worker and is still pending when Combine shows. - queue.borrow_mut().extend([OsEvent::Open(vec![paths[0].clone()]), OsEvent::Combine(vec![paths[1].clone()])]); + sender.open(vec![paths[0].clone()]); + sender.open_for(vec![paths[1].clone()], "combine"); for _ in 0..200 { h.run_steps(1); if !h.state().views.is_empty() { @@ -1369,7 +1252,7 @@ fn an_open_finishing_after_combine_keeps_the_combine_tab() { } assert_eq!(h.state().views.len(), 1, "the earlier open finished"); assert!(h.state().combine_showing(), "and the Combine files tab still shows"); - queue.borrow_mut().push(OsEvent::Open(vec![paths[2].clone()])); + sender.open(vec![paths[2].clone()]); for _ in 0..200 { h.run_steps(1); if h.state().views.len() == 2 { @@ -1392,7 +1275,7 @@ fn default_workspace_mode_persists_and_tolerates_invalid_settings() { app.set_option("mode", "sign").unwrap(); let mut restored = PdfCraftApp::new(); restored.set_option("language", "en").unwrap(); - restored.restore(&app.persist()); + restored.apply_settings(&app.settings_snapshot()); assert_eq!(restored.default_mode, mode); restored.open_bytes("fixture.pdf", None, FIXTURE.to_vec()).unwrap(); assert_eq!(restored.mode, mode, "session override must not be persisted"); @@ -1400,11 +1283,25 @@ fn default_workspace_mode_persists_and_tolerates_invalid_settings() { for json in ["{}", "{not json", r#"{"default_mode": null}"#, r#"{"default_mode": 5}"#, r#"{"default_mode": "unknown"}"#] { let mut app = PdfCraftApp::new(); app.set_option("language", "en").unwrap(); - app.restore(json); + app.apply_settings(&pdfcraft_ui_egui::settings::import_json(json).0); assert_eq!(app.default_mode, Mode::AllTools); app.open_bytes("fixture.pdf", None, FIXTURE.to_vec()).unwrap(); assert_eq!(app.mode, Mode::AllTools); } + // Chosen in Preferences, the default applies to the next open. + use egui::accesskit::Role; + let mut h = harness(|app| app.set_option("dialog", "preferences").unwrap()); + h.get_by_label("Default workspace mode"); + h.get_by_role_and_label(Role::RadioButton, "Read").scroll_to_me(); + h.run_steps(4); + h.get_by_role_and_label(Role::RadioButton, "Read").click(); + h.run_steps(2); + h.get_by_label("OK").click(); + h.run_steps(2); + assert_eq!(h.state().default_mode, Mode::Read); + assert_eq!(h.state().mode, Mode::AllTools); + h.state_mut().open_bytes("fixture.pdf", None, FIXTURE.to_vec()).unwrap(); + assert_eq!(h.state().mode, Mode::Read); } #[test] @@ -1412,7 +1309,7 @@ fn newly_opened_pdfs_use_the_default_workspace() { use pdfcraft_ui_egui::{LeftPanel, Mode}; let mut app = PdfCraftApp::new(); app.set_option("language", "en").unwrap(); - app.restore(r#"{"default_mode": "edit"}"#); + app.apply_settings(&pdfcraft_ui_egui::settings::import_json(r#"{"default_mode": "edit"}"#).0); app.open_bytes("first.pdf", None, FIXTURE.to_vec()).unwrap(); assert_eq!(app.mode, Mode::Edit); assert_eq!(app.left, LeftPanel::Tool("edit")); @@ -1425,7 +1322,7 @@ fn newly_opened_pdfs_use_the_default_workspace() { String::from_utf8(FIXTURE.to_vec()).unwrap().replace("/Outlines 6 0 R", "/Outlines 6 0 R /PageLayout /TwoColumnLeft /PageMode /UseOutlines"); app.open_bytes("initial-view.pdf", None, pdf.into_bytes()).unwrap(); assert_eq!(app.mode, Mode::Read); - assert_eq!(app.views.last().unwrap().layout, pdfcraft_ui_egui::canvas::PageLayout::TwoUp); + assert_eq!(app.views.last().unwrap().view.display, craft::pages::PageDisplay::TwoUp); assert_eq!(app.right, Some(pdfcraft_ui_egui::RightPanel::Bookmarks)); } @@ -1454,104 +1351,47 @@ fn explicit_mode_overrides_default_before_and_after_open() { } } -#[test] -fn preferences_selects_default_workspace_for_next_open() { - use egui::accesskit::Role; - use pdfcraft_ui_egui::Mode; - let mut h = harness(|app| app.set_option("dialog", "preferences").unwrap()); - h.get_by_label("Default workspace mode"); - h.get_by_role_and_label(Role::RadioButton, "Read").scroll_to_me(); - h.run_steps(4); - h.get_by_role_and_label(Role::RadioButton, "Read").click(); - h.run_steps(2); - assert_eq!(h.state().default_mode, Mode::Read); - assert_eq!(h.state().mode, Mode::AllTools); - h.get_by_label("OK").click(); - h.run_steps(2); - h.state_mut().open_bytes("fixture.pdf", None, FIXTURE.to_vec()).unwrap(); - assert_eq!(h.state().mode, Mode::Read); -} - -/// GNOME on Wayland: the tab strip carries the window buttons until Preferences ▸ Use system title -/// bar gives the window back its frame, at once and without a restart (#553, #1001). The choice -/// is saved; desktops that draw the frame themselves don't offer it. -#[test] -fn use_system_title_bar_swaps_the_header_bar_for_the_window_frame() { - use egui::accesskit::Role; - use pdfcraft_ui_egui::window_controls::Layout; - fn decorations(h: &Harness<'static, PdfCraftApp>) -> Option { - h.output().viewport_output.values().flat_map(|v| v.commands.iter()).find_map(|c| match c { - egui::ViewportCommand::Decorations(on) => Some(*on), - _ => None, - }) - } - let mut h = harness(|app| app.window_controls = Some(Layout::default())); - // The window opened undecorated, so the first frame asks for nothing. - assert_eq!(decorations(&h), None); - assert!(h.query_by_label("Minimize").is_some(), "the header bar has the window buttons"); - h.state_mut().set_option("dialog", "preferences").unwrap(); - h.run_steps(2); - h.get_by_role_and_label(Role::CheckBox, "Use system title bar").scroll_to_me(); - h.run_steps(4); - h.get_by_role_and_label(Role::CheckBox, "Use system title bar").click(); - let mut asked = None; - for _ in 0..4 { - h.step(); - asked = asked.or(decorations(&h)); - } - assert!(h.state().system_title_bar); - assert_eq!(asked, Some(true), "the window gets its frame back"); - assert!(h.query_by_label("Minimize").is_none(), "and the tab strip loses its buttons"); - let saved = h.state().persist(); - assert!(saved.contains(r#""system_title_bar":true"#), "{saved}"); - let mut restored = PdfCraftApp::new(); - restored.restore(&saved); - assert!(restored.system_title_bar); - restored.set_option("system-title-bar", "false").unwrap(); - assert!(!restored.system_title_bar); - assert!(restored.set_option("system-title-bar", "maybe").is_err()); - // Where the desktop draws the frame there is nothing to choose. - let mut h = harness(|app| app.set_option("dialog", "preferences").unwrap()); - h.run_steps(2); - assert!(h.query_by_label("Use system title bar").is_none()); - assert!(h.query_by_label("Minimize").is_none()); - assert_eq!(decorations(&h), None); -} /// Preferences ▸ Animation effects: the system's animation setting until the user chooses On or /// Off. The choice is saved, and settings holding anything else leave it alone. #[test] fn preferences_choose_animation_effects_and_the_choice_is_saved() { use egui::accesskit::Role; - use pdfcraft_ui_egui::motion::AnimationEffects; + use craft::theme::MotionChoice; let mut h = harness(|app| app.set_option("dialog", "preferences").unwrap()); - assert_eq!(h.state().animation_effects, AnimationEffects::System); + // PLAN: assumed the app keeps the choice in `animation_effects: MotionChoice` and the settings JSON key `animation_effects` (pdf-shell-w9) + assert_eq!(h.state().animation_effects, MotionChoice::System); h.get_by_label("Animation effects"); for (label, choice) in [ - ("Off", AnimationEffects::Off), - ("On", AnimationEffects::On), - ("Use system setting", AnimationEffects::System), - ("Off", AnimationEffects::Off), + ("Off", MotionChoice::Off), + ("On", MotionChoice::Full), + ("Use system setting", MotionChoice::System), + ("Off", MotionChoice::Off), ] { h.get_by_role_and_label(Role::RadioButton, label).scroll_to_me(); h.run_steps(4); h.get_by_role_and_label(Role::RadioButton, label).click(); h.run_steps(2); + h.get_by_label("OK").click(); + h.run_steps(2); assert_eq!(h.state().animation_effects, choice, "{label}"); + h.state_mut().set_option("dialog", "preferences").unwrap(); + h.run_steps(2); } - let saved = h.state().persist(); + let saved = serde_json::to_string(&h.state().settings_snapshot()).unwrap(); assert!(saved.contains(r#""animation_effects":"off""#), "{saved}"); let mut restored = PdfCraftApp::new(); - restored.restore(&saved); - assert_eq!(restored.animation_effects, AnimationEffects::Off); + restored.apply_settings(&pdfcraft_ui_egui::settings::import_json(&saved).0); + assert_eq!(restored.animation_effects, MotionChoice::Off); let mut fresh = PdfCraftApp::new(); - fresh.restore(&saved.replace(r#""animation_effects":"off""#, r#""animation_effects":"sideways""#)); - assert_eq!(fresh.animation_effects, AnimationEffects::System); + let hostile = saved.replace(r#""animation_effects":"off""#, r#""animation_effects":"sideways""#); + fresh.apply_settings(&pdfcraft_ui_egui::settings::import_json(&hostile).0); + assert_eq!(fresh.animation_effects, MotionChoice::System); // The control channel and the command line take the same three names. fresh.set_option("animation_effects", "ON").unwrap(); - assert_eq!(fresh.animation_effects, AnimationEffects::On); + assert_eq!(fresh.animation_effects, MotionChoice::Full); assert!(fresh.set_option("animation_effects", "sideways").unwrap_err().contains("system, on, or off")); - assert_eq!(fresh.animation_effects, AnimationEffects::On); + assert_eq!(fresh.animation_effects, MotionChoice::Full); } #[test] @@ -1627,7 +1467,7 @@ fn closing_tabs_keeps_the_selected_document_or_selects_its_neighbor() { ); assert_eq!(app.session.docs().len(), 2); assert!(app.session.get(ids[removed]).is_none()); - assert!(app.close_request.is_none(), "clean tabs close without a prompt"); + assert!(h.query_by_label("Don't save").is_none(), "clean tabs close without a prompt"); for doc in app.session.docs() { assert_eq!(doc.bytes.as_slice(), FIXTURE); assert!(!doc.dirty); @@ -1662,7 +1502,7 @@ fn cancelling_then_discarding_an_earlier_dirty_tab_preserves_the_selected_docume h.get_by_label("middle.pdf").click(); h.run_steps(3); close_named_tab(&mut h, "first.pdf (edited)"); - assert_eq!(h.state().close_request, Some(pdfcraft_ui_egui::CloseRequest::Tab(ids[0]))); + h.get_by_label("Don't save"); h.get_by_label("Cancel").click(); h.run_steps(3); assert_eq!(h.state().views.len(), 3); @@ -1674,7 +1514,7 @@ fn cancelling_then_discarding_an_earlier_dirty_tab_preserves_the_selected_docume assert_eq!(h.state().active_ids().map(|(_, id)| id), Some(ids[1])); assert_eq!(h.state().views.iter().map(|view| view.id).collect::>(), [ids[1], ids[2]]); assert!(h.state().session.get(ids[0]).is_none()); - assert!(h.state().close_request.is_none()); + assert!(h.query_by_label("Don't save").is_none(), "no prompt is left"); for doc in h.state().session.docs() { assert_eq!(doc.bytes.as_slice(), FIXTURE); assert!(!doc.dirty); @@ -1686,54 +1526,24 @@ fn long_german_tool_labels_stay_within_the_sidebar() { if crate::support::skip_without_catalogs("long_german_tool_labels_stay_within_the_sidebar") { return; } - use pdfcraft_ui_egui::{LeftPanel, Mode}; let mut h = harness(|app| app.open_bytes("fixture.pdf", None, FIXTURE.to_vec()).expect("fixture opens")); h.state_mut().set_option("language", "de").unwrap(); - h.state_mut().mode = Mode::AllTools; - h.state_mut().left_open = true; + h.state_mut().set_option("mode", "all").unwrap(); + h.state_mut().set_option("left", "open").unwrap(); // The tool heading has to leave room for Back and Close even when translated. - h.state_mut().left = LeftPanel::Tool("fill_sign"); + h.state_mut().set_option("tool", "fill_sign").unwrap(); h.run_steps(4); let heading = painted_text(&h).into_iter().find(|(s, ..)| s.starts_with("Ausfüllen und")).expect("translated heading is painted, whole or elided"); assert!(heading.2.right() <= 272.0, "translated heading runs past the sidebar: {:?}", heading.2); // A long sub-tool name must stop before its status chip, not paint over the PDF. - h.state_mut().left = LeftPanel::Tool("protect"); + h.state_mut().set_option("tool", "protect").unwrap(); h.run_steps(4); let item = painted_text(&h).into_iter().find(|(s, ..)| s == "Ausgeblendete Informationen entfernen").expect("long translated sub-tool is painted"); assert!(item.2.right() <= 272.0, "translated tool item runs past the sidebar: {:?}", item.2); } -#[test] -fn document_tabs_expose_selection_and_activate_from_keyboard() { - use egui::accesskit::Role; - for key in [egui::Key::Enter, egui::Key::Space] { - let mut h = three_tab_harness(); - let first = h.get_by_role_and_label(Role::Tab, "first.pdf"); - assert_eq!(first.accesskit_node().is_selected(), Some(false)); - assert_eq!(h.get_by_role_and_label(Role::Tab, "last.pdf").accesskit_node().is_selected(), Some(true)); - first.focus(); - h.run_steps(2); - assert!(h.get_by_role_and_label(Role::Tab, "first.pdf").is_focused()); - h.key_press(key); - h.run_steps(3); - assert_eq!(h.state().active, Some(0)); - assert_eq!(h.get_by_role_and_label(Role::Tab, "first.pdf").accesskit_node().is_selected(), Some(true)); - assert_eq!(h.get_by_role_and_label(Role::Tab, "last.pdf").accesskit_node().is_selected(), Some(false)); - assert_eq!(h.state().views.len(), 3, "activation does not hit the close button"); - for doc in h.state().session.docs() { - assert_eq!(doc.bytes.as_slice(), FIXTURE); - assert!(!doc.dirty); - } - if let Ok(dir) = std::env::var("PDFCRAFT_TAB_SHOTS") { - let _gpu = crate::gpu(); - crate::support::settle(&mut h); - h.render().unwrap().save(format!("{dir}/focused-tab-{key:?}.png")).unwrap(); - } - } -} - #[test] fn document_tab_identity_survives_dirty_labels_and_removing_an_earlier_document() { use egui::accesskit::Role; @@ -1823,43 +1633,6 @@ fn dragging_a_tab_moves_it_and_keeps_the_same_document_active() { } } -/// Regression (#2225): the drop line in front of the first tab sat half a gap outside the -/// scroll area's clip rect and was never visible. -#[test] -fn the_drop_line_shows_in_front_of_the_first_tab() { - use egui::accesskit::Role; - let _gpu = crate::gpu(); - let mut h = three_tab_harness(); - let first = h.get_by_role_and_label(Role::Tab, "first.pdf").rect(); - // Pixels in the strip just left of the first tab that are strongly blue (the accent line). - let blue_left_of = |h: &mut Harness<'static, PdfCraftApp>, rect: egui::Rect| { - let image = h.render().unwrap(); - let scale = image.width() as f32 / h.ctx.content_rect().width(); - let x0 = ((rect.left() - 3.0) * scale).max(0.0) as u32; - let x1 = ((rect.left() + 1.0) * scale).max(0.0) as u32; - let (y0, y1) = ((rect.top() * scale) as u32, (rect.bottom() * scale) as u32); - let mut n = 0; - for y in y0..y1.min(image.height()) { - for x in x0..x1.min(image.width()) { - let p = image.get_pixel(x, y).0; - if p[2] > 150 && p[0] < 90 && p[1] < 140 { - n += 1; - } - } - } - n - }; - let before = blue_left_of(&mut h, first); - // last.pdf to the left of the first tab, released not yet. - let to = first.left_center() - egui::vec2(10.0, 0.0); - drag_named_tab(&mut h, "last.pdf", to, false); - let during = blue_left_of(&mut h, first); - assert!(during > before + 10, "no drop line left of the first tab ({before} -> {during})"); - if let Ok(dir) = std::env::var("PDFCRAFT_TAB_SHOTS") { - h.render().unwrap().save(format!("{dir}/dragging-to-front.png")).unwrap(); - } -} - #[test] fn a_tab_dropped_where_it_was_stays_and_a_click_still_selects_it() { let mut h = three_tab_harness(); @@ -1940,38 +1713,35 @@ fn the_edit_panel_keeps_the_add_update_remove_menu() { assert_eq!(enabled(&h, "Remove watermark"), Some(false), "nothing to remove yet"); h.get_by_label("Add watermark…").click(); h.run_steps(3); - assert_eq!(h.state().dialog, Some(pdfcraft_ui_egui::Dialog::Marks(pdfcraft_engine::MarkKind::Watermark))); + // The watermark question is open on the dialog host: its Cancel is on screen. + h.get_by_label("Cancel"); } /// #3282: in a short window the rail's panel buttons scroll above the page navigation instead of /// being drawn under the page number field. #[test] fn short_window_rail_buttons_scroll_clear_of_page_navigation() { - use pdfcraft_ui_egui::side_panels::ToolsSide; - - for side in [ToolsSide::Right, ToolsSide::Left] { + // The rail starts on the right; the dock button moves it to the left. + for on_left in [false, true] { let (width, height) = (1000.0, 560.0); let mut h = Harness::builder().with_size(egui::vec2(width, height)).build_eframe(move |_cc| { let mut app = PdfCraftApp::new(); app.set_option("language", "en").unwrap(); - app.side_panels.rail_side = side; app.open_bytes("short.pdf", None, FIXTURE.to_vec()).unwrap(); app }); crate::support::settle(&mut h); - let in_rail = |r: egui::Rect| match side { - ToolsSide::Left => r.right() <= 48.0, - ToolsSide::Right => r.left() >= width - 48.0, - }; + if on_left { + h.get_by_label("Dock navigation rail on Left").click(); + crate::support::settle(&mut h); + } + let in_rail = |r: egui::Rect| if on_left { r.right() <= 48.0 } else { r.left() >= width - 48.0 }; let rail = |h: &Harness<'static, PdfCraftApp>, label: &str| { h.query_all_by_label(label).map(|n| n.rect()).find(|r| in_rail(*r)).unwrap_or_else(|| panic!("{label} in the rail")) }; let page = h.get(By::new().role(egui::accesskit::Role::TextInput).value("1")).rect(); assert!(in_rail(page) && page.bottom() <= height, "page field {page:?} in the rail"); - let dock_label = match side { - ToolsSide::Right => "Dock navigation rail on Left", - ToolsSide::Left => "Dock navigation rail on Right", - }; + let dock_label = if on_left { "Dock navigation rail on Right" } else { "Dock navigation rail on Left" }; let dock = rail(&h, dock_label); assert!(dock.top() >= page.bottom() && dock.bottom() <= height, "dock button {dock:?} stays below navigation and inside the window"); assert!(rail(&h, "Comments").bottom() <= page.top(), "the first button sits above the page field"); @@ -2027,7 +1797,8 @@ fn pages_fixture(n: usize) -> Vec { /// and not at all with the preference off. Settings are untrusted: bad entries are ignored. #[test] fn a_file_opened_again_shows_its_last_view() { - use pdfcraft_ui_egui::canvas::{Fit, PageLayout}; + use craft::pages::PageDisplay; + use pdfcraft_ui_egui::canvas::Fit; let path = std::env::temp_dir().join(format!("pdfcraft-last-view-{}.pdf", std::process::id())).to_string_lossy().into_owned(); let p = path.clone(); let mut h = harness(move |app| app.open_bytes("doc.pdf", Some(p), pages_fixture(3)).expect("opens")); @@ -2037,41 +1808,48 @@ fn a_file_opened_again_shows_its_last_view() { let app = h.state_mut(); app.set_option("zoom", "50").unwrap(); let view = &mut app.views[0]; - view.set_display(PageLayout::TwoUp, false); - view.set_cover(true); + view.view.display = PageDisplay::TwoUp; + view.view.continuous = false; + view.view.cover = true; + let now = view.current(); + view.view.go_to(now); view.go_to_page(2); } h.run_steps(3); // Saved with the tab still open: quitting remembers it. - let saved_open = h.state().persist(); + let saved_open = h.state().settings_snapshot(); h.state_mut().close_tab(0); - let saved_closed = h.state().persist(); + let saved_closed = h.state().settings_snapshot(); for (label, saved) in [("open", saved_open), ("closed", saved_closed)] { - let (saved, p) = (saved.clone(), p.clone()); + let p = p.clone(); let h = harness(move |app| { - app.restore(&saved); + app.apply_settings(&saved); app.open_bytes("doc.pdf", Some(p), pages_fixture(3)).expect("opens"); }); let v = &h.state().views[0]; - assert_eq!((v.current, v.fit, v.zoom, v.layout, v.continuous, v.cover), (2, Fit::None, 0.5, PageLayout::TwoUp, false, true), "{label}"); + assert_eq!( + (v.current(), v.fit(), v.zoom(), v.view.display, v.view.continuous, v.view.cover), + (2, Fit::None, 0.5, PageDisplay::TwoUp, false, true), + "{label}" + ); } // The preference off: the defaults. - let saved = h.state().persist(); + let saved = h.state().settings_snapshot(); let p = path.clone(); let h = harness(move |app| { - app.restore(&saved); + app.apply_settings(&saved); app.restore_last_view = false; app.open_bytes("doc.pdf", Some(p), pages_fixture(3)).expect("opens"); }); let v = &h.state().views[0]; - assert_eq!((v.current, v.fit, v.layout, v.continuous, v.cover), (0, Fit::Width, PageLayout::Single, true, false)); + assert_eq!((v.current(), v.fit(), v.view.display, v.view.continuous, v.view.cover), (0, Fit::Width, PageDisplay::Single, true, false)); // Garbage in the settings is ignored, a usable entry among it is kept. let mut app = PdfCraftApp::new(); - app.restore(&format!( + app.apply_settings(&pdfcraft_ui_egui::settings::import_json(&format!( r#"{{"restore_last_view": "yes", "last_views": [5, {{"path": ""}}, {{"path": "{}", "page": -1, "zoom": "huge", "display": "single"}}, {{"path": "{}", "page": 1, "zoom": "fit-page", "display": "two-up"}}]}}"#, path.replace('\\', "/"), path.replace('\\', "/") - )); + )).0); assert!(app.restore_last_view, "a non-boolean keeps the default"); assert_eq!(app.last_views.len(), 1); assert_eq!((app.last_views[0].page, app.last_views[0].zoom.as_str()), (1, "fit-page")); @@ -2088,13 +1866,13 @@ fn a_fractional_zoom_is_remembered_exactly() { h.run_steps(3); h.state_mut().close_tab(0); assert_eq!(h.state().last_views[0].zoom, "62.5%"); - let saved = h.state().persist(); + let saved = h.state().settings_snapshot(); let h = harness(move |app| { - app.restore(&saved); + app.apply_settings(&saved); app.open_bytes("doc.pdf", Some(path), pages_fixture(3)).expect("opens"); }); let v = &h.state().views[0]; - assert_eq!((v.fit, v.zoom), (Fit::None, 0.625)); + assert_eq!((v.fit(), v.zoom()), (Fit::None, 0.625)); } /// #1767 with full screen: the view remembered while presenting is the one full screen will go @@ -2102,7 +1880,8 @@ fn a_fractional_zoom_is_remembered_exactly() { /// screen for the remembered view. #[test] fn full_screen_neither_is_remembered_nor_hides_the_last_view() { - use pdfcraft_ui_egui::canvas::{Fit, PageLayout}; + use craft::pages::PageDisplay; + use pdfcraft_ui_egui::canvas::Fit; let path = std::env::temp_dir().join(format!("pdfcraft-last-view-fs-{}.pdf", std::process::id())).to_string_lossy().into_owned(); let p = path.clone(); let mut h = harness(move |app| app.open_bytes("doc.pdf", Some(p), pages_fixture(3)).expect("opens")); @@ -2110,28 +1889,31 @@ fn full_screen_neither_is_remembered_nor_hides_the_last_view() { let app = h.state_mut(); app.set_option("zoom", "50").unwrap(); let view = &mut app.views[0]; - view.set_display(PageLayout::TwoUp, false); + view.view.display = PageDisplay::TwoUp; + view.view.continuous = false; + let now = view.current(); + view.view.go_to(now); view.go_to_page(2); view.enter_presentation(); - assert!(view.presenting() && view.fit == Fit::Page); + assert!(view.presenting() && view.fit() == Fit::Page); } h.run_steps(3); - let saved = h.state().persist(); + let saved = h.state().settings_snapshot(); h.state_mut().close_tab(0); let remembered = h.state().last_views[0].clone(); assert_eq!((remembered.page, remembered.zoom.as_str()), (2, "50%"), "not full screen's fitted page"); let p = path.clone(); let mut h = harness(move |app| { - app.restore(&saved); - app.full_screen = true; + app.apply_settings(&saved); + app.apply_full_screen(true); app.open_bytes("doc.pdf", Some(p), pages_fixture(3)).expect("opens"); }); let v = &h.state().views[0]; assert!(v.presenting(), "opened in full screen"); - assert_eq!((v.fit, v.continuous, v.current), (Fit::Page, false, 2), "one fitted page, where the reader left off"); + assert_eq!((v.fit(), v.view.continuous, v.current()), (Fit::Page, false, 2), "one fitted page, where the reader left off"); let view = &mut h.state_mut().views[0]; view.leave_presentation(); - assert_eq!((view.fit, view.zoom, view.layout, view.continuous), (Fit::None, 0.5, PageLayout::TwoUp, false), "the remembered view"); + assert_eq!((view.fit(), view.zoom(), view.view.display, view.view.continuous), (Fit::None, 0.5, PageDisplay::TwoUp, false), "the remembered view"); } #[cfg(not(target_arch = "wasm32"))] @@ -2141,18 +1923,21 @@ fn home_recent_context_menu_reveals_the_target_without_opening_or_removing_it() assert!(!missing.exists()); let expected = missing.to_string_lossy().into_owned(); let target = expected.clone(); + // The existence check runs as a job the test runs itself, so no worker races the frames. + let jobs = std::sync::Arc::new(craft::host::ManualJobs::new()); + let queue = jobs.clone(); let mut h = Harness::builder().with_size(egui::vec2(1400.0, 1600.0)).build_eframe(move |_| { - let mut app = PdfCraftApp::new(); + let (intake, _sender) = craft::platform::open::FileIntake::new(craft::host::Wake::none()); + let mut app = host_app(jobs, intake); app.set_option("language", "en").unwrap(); - // The existence check runs on a worker otherwise, which can lose the race with the - // fixed frame count below on a busy runner. - app.run_inline = true; for (name, path) in [("first.pdf", ".".to_owned()), ("target.pdf", target)] { app.recent.push(pdfcraft_ui_egui::RecentFile { name: name.into(), path, pages: 1, size: 0 }); } app }); h.run_steps(4); + queue.run_all(); + h.run_steps(2); let label = if cfg!(target_os = "macos") { "Reveal in Finder" } else { "Reveal in File Explorer" }; h.get_by_label("target.pdf").click_secondary(); h.run_steps(3); @@ -2160,14 +1945,12 @@ fn home_recent_context_menu_reveals_the_target_without_opening_or_removing_it() assert!(h.state().views.is_empty(), "right-click must not open the PDF"); assert_eq!(h.state().recent.len(), 2); h.get_by_label(label).click(); + queue.run_all(); h.run_steps(3); assert!(h.query_by_label(label).is_none(), "choosing the action closes its menu"); assert!(h.state().views.is_empty(), "reveal must not open the PDF"); assert_eq!(h.state().active, None); assert_eq!(h.state().recent.len(), 2, "reveal must not remove missing recent files"); assert_eq!(h.state().recent[1].path, expected); - assert!( - h.state().toast.as_ref().is_some_and(|(text, _)| text.contains("The file no longer exists")), - "the selected path is checked and the existing reveal error is shown" - ); + assert!(!h.state().notices.posted().is_empty(), "the selected path is checked and the reveal error is shown"); } diff --git a/crates/ui-egui/tests/it/viewer_prefs.rs b/crates/ui-egui/tests/it/viewer_prefs.rs index 5ecd4a1a82..bf6dba13e4 100644 --- a/crates/ui-egui/tests/it/viewer_prefs.rs +++ b/crates/ui-egui/tests/it/viewer_prefs.rs @@ -185,7 +185,8 @@ fn f8_hides_the_interface_of_any_document_and_shows_it_again() { #[test] fn hiding_the_interface_is_never_saved() { let h = harness(|_| {}, &[HIDE_ALL]); - let settings = h.state().persist(); + // PLAN: assumed the settings snapshot is `Serialize` (pdf-shell-w9) + let settings = serde_json::to_string(&h.state().settings_snapshot()).unwrap(); assert!(!settings.contains("interface"), "{settings}"); } @@ -194,7 +195,7 @@ fn opening_fit(catalog: &str, own_view: bool) -> Fit { let mut app = PdfCraftApp::new(); app.always_default_view = own_view; app.open_bytes("x.pdf", None, fixture(catalog)).unwrap(); - app.views[0].fit + app.views[0].fit() } #[test] @@ -214,7 +215,7 @@ fn one_page_at_a_time_opens_at_fit_page() { assert_eq!(opening_fit("/PageLayout /SinglePage /OpenAction [3 0 R /FitH 300]", false), Fit::Width); let mut app = PdfCraftApp::new(); app.open_bytes("x.pdf", None, fixture("/PageLayout /SinglePage /OpenAction [3 0 R /XYZ 0 300 2]")).unwrap(); - assert_eq!((app.views[0].fit, app.views[0].zoom), (Fit::None, 2.0)); + assert_eq!((app.views[0].fit(), app.views[0].zoom()), (Fit::None, 2.0)); } /// Review on #4378: where the reader left off wins over the fit page a one-page-at-a-time @@ -224,11 +225,11 @@ fn a_remembered_zoom_wins_over_the_layouts_fit_page() { let path = std::env::temp_dir().join(format!("pdfcraft-viewer-prefs-last-view-{}.pdf", std::process::id())).to_string_lossy().into_owned(); let mut app = PdfCraftApp::new(); let json_path = serde_json::to_string(&path).unwrap(); - app.restore(&format!(r#"{{"last_views": [{{"path": {json_path}, "page": 1, "zoom": "62.5%", "display": "single"}}]}}"#)); + app.apply_settings(&pdfcraft_ui_egui::settings::import_json(&format!(r#"{{"last_views": [{{"path": {json_path}, "page": 1, "zoom": "62.5%", "display": "single"}}]}}"#)).0); assert!(app.restore_last_view); app.open_bytes("x.pdf", Some(path), fixture("/PageLayout /SinglePage")).unwrap(); let v = &app.views[0]; - assert_eq!((v.fit, v.zoom, v.current), (Fit::None, 0.625, 1)); + assert_eq!((v.fit(), v.zoom(), v.current()), (Fit::None, 0.625, 1)); } #[test] @@ -236,14 +237,17 @@ fn always_default_view_wins_over_a_remembered_view() { let path = std::env::temp_dir().join(format!("pdfcraft-viewer-prefs-always-default-{}.pdf", std::process::id())).to_string_lossy().into_owned(); let mut app = PdfCraftApp::new(); let json_path = serde_json::to_string(&path).unwrap(); - app.restore(&format!( - r#"{{"last_views": [{{"path": {json_path}, "page": 1, "zoom": "62.5%", "display": "single"}}], "always_default_view": true}}"# - )); + app.apply_settings( + &pdfcraft_ui_egui::settings::import_json(&format!( + r#"{{"last_views": [{{"path": {json_path}, "page": 1, "zoom": "62.5%", "display": "single"}}], "always_default_view": true}}"# + )) + .0, + ); assert!(app.always_default_view); assert!(app.restore_last_view); app.open_bytes("x.pdf", Some(path), fixture("/PageLayout /SinglePage")).unwrap(); let v = &app.views[0]; - assert_eq!((v.fit, v.layout, v.continuous(), v.current), (Fit::Width, pdfcraft_ui_egui::canvas::PageLayout::Single, true, 1)); + assert_eq!((v.fit(), v.view.display, v.view.continuous, v.current()), (Fit::Width, craft::pages::PageDisplay::Single, true, 1)); } /// The last `InnerSize` and `OuterPosition` asked for over `frames` frames.