From fb17d70f761f84b1f5fd5288fe1685b9154b4a2d Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 16:15:24 -0500 Subject: [PATCH] pdf-shell-w18: net change of 3 commits - pdf-shell-w18: written by an agent - pdf-shell-w18: finished by an agent - pdf-shell-w18: review fixes (review-1) --- crates/ui-egui/tests/it/commands.rs | 611 +++++++----------- crates/ui-egui/tests/it/control.rs | 925 +++++++++------------------- crates/ui-egui/tests/it/fonts.rs | 267 +------- crates/ui-egui/tests/it/theme.rs | 276 ++++----- crates/ui-egui/tests/it/updates.rs | 271 ++++---- parity/acrobat-features.toml | 90 ++- 6 files changed, 827 insertions(+), 1613 deletions(-) diff --git a/crates/ui-egui/tests/it/commands.rs b/crates/ui-egui/tests/it/commands.rs index 3d4eec9523..aa18172316 100644 --- a/crates/ui-egui/tests/it/commands.rs +++ b/crates/ui-egui/tests/it/commands.rs @@ -1,14 +1,21 @@ //! The command registry drives menus, shortcuts and the palette: every registered command must -//! be implemented, disabled commands must say why, and every surface must reach the same action. +//! be implemented, disabled commands must say why, and the app's platform split of chords holds. +//! The palette's own listing and Enter-runs behaviour, the shortcut catalog and the chord text are +//! the framework's to test. +use std::sync::Arc; + +use crate::control::{ControlClient, app_with_files, new_app, ok}; use crate::support; +use craft::host::{Picked, ScriptedFiles}; use egui::os::OperatingSystem; use egui::{Key, Modifiers}; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use pdfcraft_engine::commands::COMMANDS; -use pdfcraft_ui_egui::{Dialog, PdfCraftApp}; +use pdfcraft_ui_egui::PdfCraftApp; +use serde_json::json; fn fixture(n: usize) -> Vec { let mut objs: Vec = vec!["<< /Type /Catalog /Pages 2 0 R >>".into()]; @@ -35,15 +42,46 @@ fn fixture(n: usize) -> Vec { out } -fn harness() -> Harness<'static, PdfCraftApp> { - let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| { - let mut app = PdfCraftApp::new(); +/// An app with three pages open, and the control channel attached for what only `ui.state` reports. +fn harness_controlled() -> (Harness<'static, PdfCraftApp>, ControlClient) { + let (tx, rx) = std::sync::mpsc::channel(); + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| { + let mut app = new_app(); app.set_option("language", "en").unwrap(); + app.attach_control(rx, None); app.open_bytes("doc.pdf", None, fixture(3)).unwrap(); app }); h.run_steps(4); - h + (h, tx) +} + +fn harness() -> Harness<'static, PdfCraftApp> { + harness_controlled().0 +} + +/// Whether the palette is on screen: its command rows are list-box options in the access tree. +fn palette_open(h: &Harness<'static, PdfCraftApp>) -> bool { + h.query_all_by_role(egui::accesskit::Role::ListBoxOption).next().is_some() +} + +/// Whether the comments panel is open, as the dock layout `ui.state` reports it says. +// PLAN: assumed `ui.state["side_panels"]` (pdf-hub-w3, from `side_panels::state`) names the open +// panel; the panel is found by its name, not by the report's shape. +fn comments_panel_open(h: &mut Harness<'static, PdfCraftApp>, c: &ControlClient) -> bool { + ok(h, c, "ui.state", json!({}))["side_panels"].to_string().to_lowercase().contains("comment") +} + +/// Whether the last frame asked the window to close. +fn close_requested(h: &Harness<'static, PdfCraftApp>) -> bool { + h.output().viewport_output.values().any(|v| v.commands.iter().any(|c| matches!(c, egui::ViewportCommand::Close))) +} + +/// Whether the export dialog a tool opens is on screen. +// PLAN: assumed `pdfcraft_ui_egui::export_ui::open_kind(&PdfCraftApp) -> Option<_>` is reachable from +// integration tests (pdf-workflows-w12); `workflows` is a private module at the base. +fn export_open(app: &PdfCraftApp) -> bool { + pdfcraft_ui_egui::export_ui::open_kind(app).is_some() } /// Commands that open a native file picker can't run headless. @@ -75,7 +113,10 @@ fn every_registered_command_is_implemented() { if PICKERS.contains(&spec.id) || spec.id == "edit.copy" { continue; } - let mut app = PdfCraftApp::new(); + // A picker the list above misses (file.pin_folder, create.multiple_separate did) must not + // open a real file dialog on the desktop running the tests: the scripted files answer it + // as a cancel, which is what a service with nothing queued does. + let mut app = app_with_files(Arc::new(ScriptedFiles::new())); app.set_option("language", "en").unwrap(); if spec.id.starts_with("form.") || spec.id == "comment.flatten" { app.open_bytes("form.pdf", None, include_bytes!("../data/form.pdf").to_vec()).unwrap(); @@ -176,29 +217,50 @@ fn every_registered_command_is_implemented() { assert!(app.views[0].view_history(false)); } } - let dir = std::env::temp_dir().join(format!("pdfcraft-cmd-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - app.save_override = Some(dir.join("out.pdf").to_string_lossy().into_owned()); - // A picker the list above misses (file.pin_folder, create.multiple_separate did) must not - // open a real file dialog on the desktop running the tests: answer it as a cancel. - app.pick_override = Some(Vec::new()); assert!(app.execute(spec.id), "{} is registered but not implemented (or wrongly disabled)", spec.id); } } +/// A disabled command says why. The first two have a chord, which is pressed as a user would; the +/// cover page has none, so the command table fires it. #[test] fn disabled_commands_explain_themselves() { - let mut app = PdfCraftApp::new(); - app.set_option("language", "en").unwrap(); - assert!(!app.execute("file.save")); - assert_eq!(app.toast.as_ref().map(|t| t.0.as_str()), Some("Open a document first")); - app.open_bytes("doc.pdf", None, fixture(2)).unwrap(); - assert!(!app.execute("edit.undo")); - assert_eq!(app.toast.as_ref().map(|t| t.0.as_str()), Some("Nothing to undo")); + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| { + let mut app = new_app(); + app.set_option("language", "en").unwrap(); + app + }); + h.run_steps(3); + h.key_press_modifiers(Modifiers::COMMAND, Key::S); + h.run_steps(3); + assert_eq!(support::shown_notice(&h).as_deref(), Some("Open a document first")); + h.state_mut().open_bytes("doc.pdf", None, fixture(2)).unwrap(); + h.run_steps(3); + h.key_press_modifiers(Modifiers::COMMAND, Key::Z); + h.run_steps(3); + assert_eq!(support::shown_notice(&h).as_deref(), Some("Nothing to undo")); // View state counts too: the cover page exists only in two-page view. - assert!(!app.execute("view.layout.cover")); - assert_eq!(app.toast.as_ref().map(|t| t.0.as_str()), Some("Switch to two-page view first to show the cover page")); - assert!(!app.execute("no.such.command")); + assert!(!h.state_mut().execute("view.layout.cover")); + h.run_steps(3); + assert_eq!(support::shown_notice(&h).as_deref(), Some("Switch to two-page view first to show the cover page")); + assert!(!h.state_mut().execute("no.such.command")); +} + +/// An app on a file service that answers the first pick with `picked`, none queued when `None`. +fn harness_picking(picked: Option<&std::path::Path>, setup: impl FnOnce(&mut PdfCraftApp) + 'static) -> Harness<'static, PdfCraftApp> { + let files = match picked { + Some(path) => ScriptedFiles::answering([Picked::Paths(vec![path.to_path_buf()])]).with_file(path, fixture(2)), + None => ScriptedFiles::new(), + }; + let files = Arc::new(files); + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| { + let mut app = app_with_files(files); + app.set_option("language", "en").unwrap(); + setup(&mut app); + app + }); + h.run_steps(2); + h } #[test] @@ -207,34 +269,20 @@ fn a_tool_chosen_with_no_document_asks_for_one_and_runs_on_it() { std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("picked.pdf"); std::fs::write(&path, fixture(2)).unwrap(); - let pick = path.to_string_lossy().into_owned(); - 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.pick_override = Some(vec![pick]); - app - }); - h.run_steps(2); + let mut h = harness_picking(Some(&path), |_| {}); h.state_mut().run_command("export.text"); - assert!(h.state().toast.as_ref().is_none_or(|t| t.0 != "Open a document first")); - support::wait_until(&mut h, "picked document and chosen tool", |app| app.active.is_some() && matches!(app.dialog, Some(Dialog::Export(_)))); + support::wait_until(&mut h, "picked document and chosen tool", |app| app.active.is_some() && export_open(app)); assert!(h.state().active.is_some(), "the picked file is open"); - assert!(matches!(h.state().dialog, Some(Dialog::Export(_))), "and the tool runs on it: {:?}", h.state().dialog); + assert!(export_open(h.state()), "and the tool runs on it"); let (_, id) = h.state().active_ids().unwrap(); let doc = h.state().session.get(id).unwrap(); assert_eq!(doc.name, "picked.pdf"); assert_eq!(doc.bytes.as_slice(), fixture(2).as_slice()); // Cancelled: nothing opens and nothing runs. - 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.pick_override = Some(Vec::new()); - app - }); - h.run_steps(2); + let mut h = harness_picking(None, |_| {}); h.state_mut().run_command("export.text"); h.run_steps(3); - assert!(h.state().active.is_none() && h.state().dialog.is_none()); + assert!(h.state().active.is_none() && !export_open(h.state())); let _ = std::fs::remove_dir_all(&dir); } @@ -244,125 +292,133 @@ fn a_tool_chosen_with_an_already_open_file_focuses_its_tab_and_still_runs() { std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("picked.pdf"); std::fs::write(&path, fixture(2)).unwrap(); - let pick = path.to_string_lossy().into_owned(); - let picked = pick.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 file is already open, but the Home tab is showing (no active document). - app.open_path(&picked); + let opened = path.to_string_lossy().into_owned(); + // The file is already open, but the Home tab is showing (no active document). + let mut h = harness_picking(Some(&path), move |app| { + app.open_path(&opened); app.active = None; - app.pick_override = Some(vec![pick]); - app }); - h.run_steps(2); h.state_mut().run_command("export.text"); h.run_steps(3); let app = h.state(); assert_eq!(app.views.len(), 1, "the existing tab is reused, not duplicated"); assert_eq!(app.active, Some(0), "the pick focused the tab it already opened"); - assert!(matches!(app.dialog, Some(Dialog::Export(_))), "the tool still runs on it: {:?}", app.dialog); + assert!(export_open(app), "the tool still runs on it"); let _ = std::fs::remove_dir_all(&dir); } -#[test] -fn shortcuts_run_registered_commands() { - let mut h = harness(); - h.key_press_modifiers(Modifiers::COMMAND, Key::D); - h.run_steps(2); - assert!(matches!(h.state().dialog, Some(Dialog::Properties(_)))); - h.state_mut().dialog = None; - h.key_press_modifiers(Modifiers::COMMAND, Key::K); - h.run_steps(2); - assert!(h.state().palette_open); - h.key_press(Key::Escape); - h.run_steps(2); - h.key_press_modifiers(Modifiers::COMMAND | Modifiers::CTRL, Key::H); - h.run_steps(2); - assert_eq!(h.state().mode, pdfcraft_ui_egui::Mode::Read); -} +/// One row of the chord table: what the user does and what the app must do, on a harness with +/// three pages open. +type ChordRow = (&'static str, fn(&mut Harness<'static, PdfCraftApp>, &ControlClient)); + +/// The app's platform split of chords (the runtime fires catalog chords; these are the ones whose +/// meaning differs by platform or that leave a state the next frame could undo). +const CHORDS: &[ChordRow] = &[ + ("Ctrl+M opens the comments panel and keeps it open (Windows)", ctrl_m_opens_comments_on_windows), + ("Ctrl+M opens the comments panel and keeps it open (Linux)", ctrl_m_opens_comments_on_linux), + ("Cmd+M is left to the OS for minimize (macOS)", mac_cmd_m_is_left_to_the_os), + ("Cmd+W closes the clean document tab (macOS)", mac_cmd_w_closes_the_tab), + ("Ctrl+Tab steps the tabs in order and wraps", ctrl_tab_steps_and_wraps), + ("Escape leaves full screen", escape_leaves_full_screen), +]; #[test] -fn ctrl_m_opens_the_comments_panel_and_keeps_it_open() { - for os in [OperatingSystem::Windows, OperatingSystem::Nix] { - let mut h = harness(); - // Real Windows/Linux Ctrl events set both ctrl and command. - h.ctx.set_os(os); - h.state_mut().right = None; - h.run_steps(2); - for _ in 0..2 { - h.key_press_modifiers(Modifiers::CTRL | Modifiers::COMMAND, Key::M); - h.run_steps(2); - assert_eq!(h.state().right, Some(pdfcraft_ui_egui::RightPanel::Comments), "{os:?}: opens rather than toggles"); - } - h.state_mut().execute("help.shortcuts"); - h.run_steps(3); - h.get_by_label("Ctrl+M"); +fn platform_split_chords_fire_their_commands() { + for (name, row) in CHORDS { + let (mut h, c) = harness_controlled(); + eprintln!("chord row: {name}"); + row(&mut h, &c); } } -#[test] -fn mac_command_m_stays_available_for_minimize() { - let mut h = harness(); +fn ctrl_m_opens_comments_on_windows(h: &mut Harness<'static, PdfCraftApp>, c: &ControlClient) { + ctrl_m_opens_comments(h, c, OperatingSystem::Windows); +} + +fn ctrl_m_opens_comments_on_linux(h: &mut Harness<'static, PdfCraftApp>, c: &ControlClient) { + ctrl_m_opens_comments(h, c, OperatingSystem::Nix); +} + +fn ctrl_m_opens_comments(h: &mut Harness<'static, PdfCraftApp>, c: &ControlClient, os: OperatingSystem) { + h.ctx.set_os(os); + h.run_steps(2); + assert!(!comments_panel_open(h, c), "{os:?}: starts without the comments panel"); + // Real Windows/Linux Ctrl events set both ctrl and command; the second press must not toggle. + for _ in 0..2 { + h.key_press_modifiers(Modifiers::CTRL | Modifiers::COMMAND, Key::M); + h.run_steps(2); + assert!(comments_panel_open(h, c), "{os:?}: opens rather than toggles"); + } +} + +fn mac_cmd_m_is_left_to_the_os(h: &mut Harness<'static, PdfCraftApp>, c: &ControlClient) { h.ctx.set_os(OperatingSystem::Mac); - h.state_mut().right = None; h.run_steps(2); let command_m = Modifiers { mac_cmd: true, command: true, ..Modifiers::NONE }; h.input_mut().events.push(egui::Event::Key { key: Key::M, physical_key: None, pressed: true, repeat: false, modifiers: command_m }); h.step(); let available = h.ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Key { key: Key::M, pressed: true, .. }))); - assert_eq!((h.state().right, available), (None, true), "Comments must leave Command+M unconsumed for Minimize"); - - let bar = h.state().menu_bar(&h.ctx); - assert!(bar.find(&craft_menu::CommandRef::new("comment.list")).unwrap().shortcut.is_none()); - let layout = craft_menu::mac_layout(&bar, &craft_menu::LayoutOptions::new("PdfCraft")); - assert!(!layout.clashes.iter().any(|clash| clash.system == "Minimize")); - assert!( - layout - .bar - .menu(craft_menu::MenuRole::Window) - .unwrap() - .children - .iter() - .any(|node| { matches!(node, craft_menu::Node::Standard { kind: craft_menu::Standard::Minimize, .. }) }), - "the native layout keeps AppKit's standard Minimize item" - ); - h.state_mut().execute("help.shortcuts"); - h.run_steps(3); - h.get_by_label("⌘S"); // Positive control: the macOS shortcut rows really rendered. - assert!(h.query_by_label("⌘M").is_none()); - assert!(h.query_by_label("Comments panel").is_none(), "an unbound command has no shortcuts-help row"); + assert!(available, "Comments must leave Command+M unconsumed for Minimize"); + h.run_steps(2); + assert!(!comments_panel_open(h, c), "no app command ran"); } -#[test] -fn the_palette_lists_commands_with_shortcuts_and_runs_them() { - let mut h = harness(); - h.state_mut().set_option("palette", "rotate pages clockwise").unwrap(); - h.run_steps(3); - h.get_by_label("Rotate pages clockwise"); - h.key_press(Key::Enter); - h.run_steps(3); - let app = h.state(); - assert!(!app.palette_open, "Enter runs the top hit and closes the palette"); - let doc = app.session.get(app.views[0].id).unwrap(); - assert_eq!(doc.info.pages[0].rotation, 90); - assert_eq!(doc.can_undo(), Some("Rotate page")); +fn mac_cmd_w_closes_the_tab(h: &mut Harness<'static, PdfCraftApp>, _c: &ControlClient) { + h.ctx.set_os(OperatingSystem::Mac); + h.run_steps(2); + h.key_press_modifiers(Modifiers::COMMAND, Key::W); + h.run_steps(2); + assert!(h.state().views.is_empty(), "⌘W closes the clean document tab"); } -#[test] -fn palette_arrow_keys_select_results_and_enter_runs_the_selection() { - let mut h = harness(); - h.state_mut().set_option("palette", "rotate pages").unwrap(); +/// Ctrl+Tab and Ctrl+Shift+Tab step through the tabs in the strip's order, wrap around at either +/// end and include the Combine files tab after the documents (#1542). A Windows or Linux Ctrl +/// press is both `ctrl` and `command`. +fn ctrl_tab_steps_and_wraps(h: &mut Harness<'static, PdfCraftApp>, _c: &ControlClient) { + h.state_mut().open_bytes("second.pdf", None, fixture(1)).unwrap(); + h.state_mut().open_bytes("third.pdf", None, fixture(1)).unwrap(); + h.run_steps(3); + let ctrl = Modifiers::CTRL | Modifiers::COMMAND; + let press = |h: &mut Harness<'static, PdfCraftApp>, modifiers: Modifiers| { + h.key_press_modifiers(modifiers, Key::Tab); + h.run_steps(2); + h.state().active + }; + assert_eq!(h.state().active, Some(2)); + assert_eq!(press(h, ctrl), Some(0), "the last tab wraps to the first"); + assert_eq!(press(h, ctrl), Some(1)); + assert_eq!(press(h, ctrl | Modifiers::SHIFT), Some(0)); + assert_eq!(press(h, ctrl | Modifiers::SHIFT), Some(2), "the first tab wraps to the last"); + // The order is the one on screen, after the tabs are moved. + let ids: Vec<_> = h.state().views.iter().map(|v| v.id).collect(); + h.state_mut().move_tab(2, 0); h.run_steps(2); - h.get_by_label("Rotate pages clockwise"); - h.get_by_label("Rotate pages counterclockwise"); - h.key_press(Key::ArrowDown); + assert_eq!(h.state().active_ids().map(|(_, id)| id), Some(ids[2])); + press(h, ctrl); + assert_eq!(h.state().active_ids().map(|(_, id)| id), Some(ids[0])); + // Combine files comes after the documents. + h.state_mut().execute("page.combine"); h.run_steps(2); - h.key_press(Key::Enter); + assert!(h.state().combine_showing()); + assert_eq!(press(h, ctrl), Some(0), "Combine files wraps to the first document"); + assert_eq!(press(h, ctrl | Modifiers::SHIFT), None); + assert!(h.state().combine_showing(), "back from the first document is Combine files"); + // Plain Tab still belongs to keyboard focus, not to the tabs. + press(h, Modifiers::NONE); + assert!(h.state().combine_showing()); + for doc in h.state().session.docs() { + assert!(!doc.dirty, "switching tabs changes no document"); + } +} + +fn escape_leaves_full_screen(h: &mut Harness<'static, PdfCraftApp>, _c: &ControlClient) { + assert!(!h.state().full_screen()); + h.key_press_modifiers(Modifiers::COMMAND, Key::L); h.run_steps(2); - let app = h.state(); - assert!(!app.palette_open); - assert_eq!(app.session.get(app.views[0].id).unwrap().info.pages[0].rotation, 270); + assert!(h.state().full_screen(), "⌘L / Ctrl+L enters full screen"); + h.key_press(Key::Escape); + h.run_steps(2); + assert!(!h.state().full_screen(), "Escape leaves full screen"); } /// Check that choosing Edit ▸ Pages ▸ Delete pages in the menu bar reduces the page count once. @@ -390,7 +446,7 @@ fn the_open_recent_menu_lists_files_and_opens_one() { let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe({ let path = path.clone(); move |_cc| { - let mut app = PdfCraftApp::new(); + let mut app = new_app(); app.set_option("language", "en").unwrap(); app.open_bytes("doc.pdf", None, fixture(3)).unwrap(); app.recent.push(pdfcraft_ui_egui::RecentFile { name: "recent.pdf".into(), path, pages: 2, size: 0 }); @@ -412,77 +468,30 @@ fn the_open_recent_menu_lists_files_and_opens_one() { assert_eq!(app.session.get(original).unwrap().bytes.as_slice(), fixture(3).as_slice()); } -/// Check that Open Recent is disabled while no file has been opened. -#[test] -fn the_open_recent_menu_is_disabled_while_the_list_is_empty() { - let mut h = harness(); - support::open_menu(&mut h, "File"); - assert!( - h.query_by(|n| n.label().as_deref() == Some("Open Recent") && n.is_disabled()).is_some(), - "Open Recent is disabled while no file has been opened" - ); -} - fn recent_file(name: &str) -> pdfcraft_ui_egui::RecentFile { pdfcraft_ui_egui::RecentFile { name: name.into(), path: format!("/nowhere/{name}"), pages: 1, size: 0 } } -/// Check that Clear Recent Files empties the list and disables Open Recent. +/// Firing Clear Recent Files empties the list, saves the empty list, and says so when there was +/// nothing to clear. #[test] -fn clear_recent_files_at_the_foot_of_open_recent_empties_the_list() { +fn clear_recent_files_runs_from_the_palette_and_is_saved() { let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| { - let mut app = PdfCraftApp::new(); + let mut app = new_app(); app.set_option("language", "en").unwrap(); - app.open_bytes("doc.pdf", None, fixture(3)).unwrap(); app.recent.extend([recent_file("first.pdf"), recent_file("second.pdf")]); app }); - h.run_steps(4); - support::open_menu(&mut h, "File"); - support::menu_row(&h, "Open Recent").hover(); h.run_steps(3); - support::menu_row(&h, "Clear Recent Files").click(); - h.run_steps(3); - assert!(h.state().recent.is_empty(), "the list is empty"); - support::open_menu(&mut h, "File"); - assert!(h.query_by(|n| n.label().as_deref() == Some("Open Recent") && n.is_disabled()).is_some(), "and Open Recent is disabled"); -} - -#[test] -fn clear_recent_files_runs_from_the_palette_and_is_saved() { - let mut app = PdfCraftApp::new(); - app.recent.extend([recent_file("first.pdf"), recent_file("second.pdf")]); - assert!(app.execute("file.clear_recent")); - assert!(app.recent.is_empty()); - let mut restarted = PdfCraftApp::new(); + assert!(h.state_mut().execute("file.clear_recent")); + assert!(h.state().recent.is_empty()); + let mut restarted = new_app(); restarted.recent.push(recent_file("stale.pdf")); - restarted.restore(&app.persist()); + restarted.apply_settings(&h.state().settings_snapshot()); assert!(restarted.recent.is_empty(), "the empty list is what's saved"); - app.execute("file.clear_recent"); - assert!(app.toast.as_ref().is_some_and(|(m, _)| m.contains("No recent files")), "nothing to clear is said, not silent"); -} - -#[test] -fn the_shortcuts_dialog_lists_the_real_bindings() { - let mut h = harness(); - h.ctx.set_os(OperatingSystem::Nix); - h.state_mut().execute("help.shortcuts"); + h.state_mut().execute("file.clear_recent"); h.run_steps(3); - h.get_by_label("Ctrl+Shift+S"); - h.get_by_label("Save as"); - // The keys the document view handles itself are written for the platform too, and Fit - // visible (a registered command) is listed once. - h.get_by_label("Ctrl+1"); - h.get_by_label("Ctrl+3"); - h.get_by_label("Ctrl+G / Ctrl+Shift+G"); - h.get_by_label("← / →, Ctrl+← / Ctrl+→"); - h.get_by_label("Zoom in / out (also pinch or Ctrl-scroll)"); - assert_eq!(h.query_all_by_label_contains("⌘").count(), 0, "no ⌘ outside macOS"); - h.ctx.set_os(OperatingSystem::Mac); - h.run_steps(2); - h.get_by_label("⇧⌘S"); - h.get_by_label("⌘1"); - h.get_by_label("Zoom in / out (also pinch or ⌘-scroll)"); + assert!(support::shown_notice(&h).is_some_and(|m| m.contains("No recent files")), "nothing to clear is said, not silent"); } #[test] @@ -508,90 +517,21 @@ fn localized_shortcuts_update_immediately_and_keep_command_ids_and_key_bindings( h.ctx.set_os(OperatingSystem::Windows); h.key_press_modifiers(Modifiers::CTRL | Modifiers::COMMAND, Key::K); h.run_steps(3); - assert!(h.state().palette_open, "the localized Strg+K display still binds Ctrl+K"); - // Searching by the stable command id still works in a translated interface. - h.state_mut().set_option("palette", "view.read_mode").unwrap(); + assert!(palette_open(&h), "the localized Strg+K display still binds Ctrl+K"); + // Searching by the stable command id still works in a translated interface: the id is typed + // into the open palette and Enter runs the match. + h.event(egui::Event::Text("view.read_mode".into())); h.run_steps(2); h.key_press(Key::Enter); h.run_steps(3); assert_eq!(h.state().mode, pdfcraft_ui_egui::Mode::Read); - assert!(!h.state().palette_open); + assert!(!palette_open(&h)); let doc = h.state().session.get(h.state().views[0].id).unwrap(); assert!(!doc.dirty); } -/// View ▸ Zoom open in the menu bar, with egui told the app runs on `os`. -fn view_menu(os: OperatingSystem) -> Harness<'static, PdfCraftApp> { - let mut h = harness(); - h.ctx.set_os(os); - h.run_steps(2); - support::open_menu(&mut h, "View"); - support::menu_row(&h, "Zoom").hover(); - h.run_steps(3); - h -} - -#[test] -fn view_menu_and_tooltips_write_shortcuts_for_the_platform() { - // On Linux, View ▸ Zoom and Page navigation showed ⌘1, ⌘[ … (hard-coded) while the - // registered items under them showed Ctrl+K; tooltips showed ⌘ too. - // The menu bar writes its shortcuts for the build's platform (craft-menu tests that). - let h = view_menu(OperatingSystem::Nix); - h.get_by_label("Zoom in (Ctrl++)"); - h.get_by_label("Print (Ctrl+P)"); - assert_eq!(h.query_all_by_label_contains("⌘").count(), 0, "no ⌘ outside macOS"); - assert_eq!(h.query_all_by_label_contains("Fit visible").count(), 1, "View lists Fit visible once"); - - let h = view_menu(OperatingSystem::Mac); - h.get_by_label("Rotate view clockwise (⇧⌘+)"); - assert_eq!(h.query_all_by_label_contains("Ctrl+").count(), 0, "no Ctrl+ on macOS"); -} - -#[test] -fn the_top_bar_save_button_names_its_shortcut_not_a_milestone() { - // #962: on Windows the Save button's tooltip and accessibility name read "Save (M4)", - // an internal milestone tag, while Print and Document properties named their shortcuts. - let mut h = harness(); - h.ctx.set_os(OperatingSystem::Windows); - h.run_steps(2); - h.get_by_label("Save (Ctrl+S)"); - h.get_by_label("Print (Ctrl+P)"); - assert_eq!(h.query_all_by_label_contains("(M4)").count(), 0, "no milestone tag in the top bar"); - assert_eq!(h.query_all_by_label_contains("⌘").count(), 0, "no ⌘ outside macOS"); - - let mut h = harness(); - h.ctx.set_os(OperatingSystem::Mac); - h.run_steps(2); - h.get_by_label("Save (⌘S)"); -} - -#[test] -fn full_screen_toggles_by_shortcut_and_command_and_escape_leaves() { - let mut h = harness(); - h.key_press_modifiers(Modifiers::COMMAND, Key::L); - h.run_steps(2); - assert!(h.state().full_screen, "⌘L / Ctrl+L enters full screen"); - h.key_press(Key::Escape); - h.run_steps(2); - assert!(!h.state().full_screen, "Escape leaves full screen"); - h.state_mut().execute("view.full_screen"); - h.run_steps(2); - assert!(h.state().full_screen); - h.state_mut().execute("view.full_screen"); - h.run_steps(2); - assert!(!h.state().full_screen, "the command toggles back"); -} - -#[test] -fn the_about_dialog_shows_the_running_version() { - let mut h = harness(); - h.state_mut().execute("help.about"); - h.run_steps(3); - h.get_by_label_contains(&format!("Version {}", env!("CARGO_PKG_VERSION"))); -} - /// Check that the quit shortcut needs exact platform modifiers and that unsaved work opens the save prompt -/// instead of closing. +/// instead of closing: the close is the window's close intent, and the prompt is answered by its button. #[test] fn quit_shortcut_requires_exact_modifiers_and_preserves_unsaved_work() { for (os, modifiers) in [ @@ -609,8 +549,7 @@ fn quit_shortcut_requires_exact_modifiers_and_preserves_unsaved_work() { } h.event(egui::Event::Key { key: Key::Q, physical_key: None, pressed: true, repeat: false, modifiers: modifiers | extra }); h.step(); - let closes = h.output().viewport_output.values().any(|v| v.commands.contains(&egui::ViewportCommand::Close)); - assert_eq!(closes, should_close, "{os:?}, extra={extra:?}, dirty={dirty}"); + assert_eq!(close_requested(&h), should_close, "{os:?}, extra={extra:?}, dirty={dirty}"); if dirty { // The save prompt is a modal laid out after the key pass; let that pass settle // before looking it up. @@ -619,7 +558,7 @@ fn quit_shortcut_requires_exact_modifiers_and_preserves_unsaved_work() { h.run_steps(2); assert_eq!(h.state().views.len(), 1); assert!(h.state().session.get(h.state().views[0].id).unwrap().dirty); - assert!(!h.output().viewport_output.values().any(|v| v.commands.contains(&egui::ViewportCommand::Close))); + assert!(!close_requested(&h)); } } } @@ -628,142 +567,12 @@ fn quit_shortcut_requires_exact_modifiers_and_preserves_unsaved_work() { #[test] fn command_w_closes_empty_macos_window_but_not_an_empty_windows_window() { for (os, should_close) in [(OperatingSystem::Mac, true), (OperatingSystem::Windows, false)] { - let mut h = Harness::builder().with_size(egui::vec2(1000.0, 700.0)).build_eframe(|_cc| PdfCraftApp::new()); + let mut h = Harness::builder().with_size(egui::vec2(1000.0, 700.0)).build_eframe(|_cc| new_app()); h.ctx.set_os(os); h.run_steps(4); assert!(h.state().views.is_empty()); h.event(egui::Event::Key { key: Key::W, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::COMMAND }); h.step(); - let closes = h.output().viewport_output.values().any(|v| v.commands.iter().any(|c| matches!(c, egui::ViewportCommand::Close))); - assert_eq!(closes, should_close, "{os:?}: only an empty macOS window should close"); - } -} - -#[test] -fn command_w_still_closes_the_document_tab_on_macos() { - let mut h = harness(); - h.ctx.set_os(OperatingSystem::Mac); - h.run_steps(2); - h.key_press_modifiers(Modifiers::COMMAND, Key::W); - h.run_steps(2); - assert!(h.state().views.is_empty(), "⌘W closes the clean document tab"); -} - -fn palette_ime_output_requests_interrupt(h: &Harness<'_, PdfCraftApp>, phase: &str) -> bool { - assert!(h.state().palette_open, "palette closed during {phase}"); - let ime = h.output().platform_output.ime.as_ref().expect("focused palette advertises IME"); - eprintln!("{phase}: query={:?}; should_interrupt_composition={}", h.state().palette_query, ime.should_interrupt_composition); - ime.should_interrupt_composition -} - -fn palette_ime_output_is_uninterrupted(h: &Harness<'_, PdfCraftApp>, phase: &str) { - assert!(!palette_ime_output_requests_interrupt(h, phase), "palette interrupted composition during {phase}"); -} - -#[test] -fn palette_ime_idle_frames_and_reopen_do_not_interrupt_composition() { - let mut h = harness(); - for opening in 0..2 { - h.state_mut().run_command("view.palette"); - h.run_steps(3); - for frame in 0..3 { - h.step(); - palette_ime_output_is_uninterrupted(&h, &format!("opening {opening}, idle {frame}")); - } - h.key_press(Key::Escape); - h.run_steps(2); - assert!(!h.state().palette_open); - } -} - -#[test] -fn palette_ime_chinese_preedit_commit_and_cancel_remain_uninterrupted() { - if crate::support::skip_without_glyphs("palette_ime_chinese_preedit_commit_and_cancel_remain_uninterrupted", "en", "你") { - return; - } - let mut h = harness(); - let mut interruptions = Vec::new(); - h.state_mut().run_command("view.palette"); - h.run_steps(3); - for preedit in ["ni", "nih"] { - h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: preedit.into(), active_range_chars: Some(0..preedit.chars().count()) })); - h.step(); - interruptions.push(palette_ime_output_requests_interrupt(&h, preedit)); - h.step(); - interruptions.push(palette_ime_output_requests_interrupt(&h, "preedit idle")); - } - h.event(egui::Event::Ime(egui::ImeEvent::Commit("你".into()))); - h.step(); - assert_eq!(h.state().palette_query, "你"); - interruptions.push(palette_ime_output_requests_interrupt(&h, "Chinese commit")); - h.run_steps(2); - assert_eq!(h.state().palette_query, "你"); - interruptions.push(palette_ime_output_requests_interrupt(&h, "committed idle")); - h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: "hao".into(), active_range_chars: Some(0..3) })); - h.step(); - interruptions.push(palette_ime_output_requests_interrupt(&h, "second preedit")); - h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: String::new(), active_range_chars: None })); - h.step(); - assert_eq!(h.state().palette_query, "你"); - interruptions.push(palette_ime_output_requests_interrupt(&h, "cancel preedit")); - assert!(interruptions.iter().all(|interrupt| !interrupt), "composition interrupted: {interruptions:?}"); -} - -#[test] -fn palette_ime_outside_click_closes_without_running_a_command() { - let mut h = harness(); - h.state_mut().set_option("palette", "rotate pages clockwise").unwrap(); - h.run_steps(3); - h.event(egui::Event::PointerButton { - pos: egui::pos2(20.0, 850.0), - button: egui::PointerButton::Primary, - pressed: true, - modifiers: Modifiers::NONE, - }); - h.step(); - assert!(!h.state().palette_open); - assert!(h.state().palette_query.is_empty()); - assert_eq!(h.state().session.get(h.state().views[0].id).unwrap().info.pages[0].rotation, 0); -} - -/// Ctrl+Tab and Ctrl+Shift+Tab step through the tabs in the strip's order, wrap around at either -/// end and include the Combine files tab after the documents (#1542). A Windows or Linux Ctrl -/// press is both `ctrl` and `command`. -#[test] -fn ctrl_tab_steps_through_the_tabs_in_order_and_wraps_around() { - let mut h = harness(); - h.state_mut().open_bytes("second.pdf", None, fixture(1)).unwrap(); - h.state_mut().open_bytes("third.pdf", None, fixture(1)).unwrap(); - h.run_steps(3); - let ctrl = Modifiers::CTRL | Modifiers::COMMAND; - let press = |h: &mut Harness<'static, PdfCraftApp>, modifiers: Modifiers| { - h.key_press_modifiers(modifiers, Key::Tab); - h.run_steps(2); - h.state().active - }; - assert_eq!(h.state().active, Some(2)); - assert_eq!(press(&mut h, ctrl), Some(0), "the last tab wraps to the first"); - assert_eq!(press(&mut h, ctrl), Some(1)); - assert_eq!(press(&mut h, ctrl | Modifiers::SHIFT), Some(0)); - assert_eq!(press(&mut h, ctrl | Modifiers::SHIFT), Some(2), "the first tab wraps to the last"); - // The order is the one on screen, after the tabs are moved. - let ids: Vec<_> = h.state().views.iter().map(|v| v.id).collect(); - h.state_mut().move_tab(2, 0); - h.run_steps(2); - assert_eq!(h.state().active_ids().map(|(_, id)| id), Some(ids[2])); - press(&mut h, ctrl); - assert_eq!(h.state().active_ids().map(|(_, id)| id), Some(ids[0])); - // Combine files comes after the documents. - h.state_mut().execute("page.combine"); - h.run_steps(2); - assert!(h.state().combine_showing()); - assert_eq!(press(&mut h, ctrl), Some(0), "Combine files wraps to the first document"); - assert_eq!(press(&mut h, ctrl | Modifiers::SHIFT), None); - assert!(h.state().combine_showing(), "back from the first document is Combine files"); - // Plain Tab still belongs to keyboard focus, not to the tabs. - press(&mut h, Modifiers::NONE); - assert!(h.state().combine_showing()); - for doc in h.state().session.docs() { - assert!(!doc.dirty, "switching tabs changes no document"); + assert_eq!(close_requested(&h), should_close, "{os:?}: only an empty macOS window should close"); } } diff --git a/crates/ui-egui/tests/it/control.rs b/crates/ui-egui/tests/it/control.rs index 5911276708..66aef19703 100644 --- a/crates/ui-egui/tests/it/control.rs +++ b/crates/ui-egui/tests/it/control.rs @@ -1,15 +1,84 @@ //! The UI control channel (M3.9): an agent can see the widget tree, click, type, press keys, //! run commands, change view options and take screenshots of the running app. -use std::sync::{Arc, Mutex}; +use std::sync::Arc; +use std::sync::mpsc::{Receiver, Sender}; +use craft::automation::{ControlRequest, ControlResponse}; +use craft::host::{AppInfo, Host, ManualJobs, Picked, ScriptedFiles, Wake}; +use craft::platform::open::FileIntake; +use craft::platform::watch::FileWatch; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use pdfcraft_render::{PageRenderer, RenderRequest, RequestKind}; -use pdfcraft_ui_egui::PdfCraftApp; -use pdfcraft_ui_egui::control::{ControlClient, Reply}; +use pdfcraft_ui_egui::settings::import_json; +use pdfcraft_ui_egui::{AppServices, PdfCraftApp}; use serde_json::{Value, json}; +/// Where a test sends its requests: the other end is attached to the app with `attach_control`. +pub(crate) type ControlClient = Sender; + +/// What a request came to: the result of the method, or the error it refused with. +pub(crate) type Reply = Result; + +/// The app's identity for a test host. +pub(crate) fn info() -> AppInfo { + AppInfo { id: "pdfcraft", name: "PdfCraft", version: "test" } +} + +/// The services a test gives the app: no wake-ups, no autosave folder, the real GitHub check source, +/// a fresh file intake and an inline watch. +pub(crate) fn services() -> AppServices { + services_asking(None) +} + +/// `services()` whose update check asks `update_source` in place of GitHub. +pub(crate) fn services_asking(update_source: Option) -> AppServices { + AppServices::new( + Wake::none(), + craft::platform::clipboard::Clipboard::new(craft::platform::clipboard::SystemClipboard::new()), + None, + update_source, + FileIntake::new(Wake::none()).0, + FileWatch::new(Wake::none()).inline(), + ) +} + +/// An app on `host`. +pub(crate) fn app_on(host: Host) -> PdfCraftApp { + PdfCraftApp::with_host(Arc::new(host), services()) +} + +/// An app on the default host: threads run its jobs and every picker answers Cancelled. +pub(crate) fn new_app() -> PdfCraftApp { + app_on(Host::builder(info()).build()) +} + +/// An app whose pickers answer from `files`. +pub(crate) fn app_with_files(files: Arc) -> PdfCraftApp { + app_on(Host::builder(info()).files(files).build()) +} + +/// An app whose background jobs wait until the test runs them (`jobs.run_all()`), so a request that +/// starts one is answered `pending` until then. +pub(crate) fn app_with_manual_jobs() -> (PdfCraftApp, Arc) { + let jobs = Arc::new(ManualJobs::new()); + (app_on(Host::builder(info()).jobs(jobs.clone()).build()), jobs) +} + +/// Sends a request without waiting; its answer arrives on the returned receiver once a frame has +/// handled it. +pub(crate) fn send(c: &ControlClient, method: &str, params: Value) -> Receiver { + let (request, rx) = ControlRequest::new(method, params); + c.send(request).unwrap_or_else(|_| panic!("{method}: the app no longer reads the control channel")); + rx +} + +/// The `{ok, result | error}` answer as a `Result`; the answer must have arrived. +pub(crate) fn answer(rx: &Receiver) -> Reply { + reply(&rx.try_recv().expect("the request was answered by the frame")) +} + /// The text each page shows, in order, as the app's session holds it. fn page_texts(app: &PdfCraftApp) -> Vec { let doc = app.session.get(app.views[0].id).unwrap(); @@ -56,38 +125,71 @@ fn harness_pages(pages: usize) -> (Harness<'static, PdfCraftApp>, ControlClient) } fn harness_pages_at(pages: usize, width: f32, scale: f32) -> (Harness<'static, PdfCraftApp>, ControlClient) { - let slot: Arc>> = Arc::default(); - let s = slot.clone(); - let mut h = Harness::builder().with_size(egui::vec2(width, 900.0)).with_pixels_per_point(scale).build_eframe(move |cc| { - let mut app = PdfCraftApp::new(); + harness_on(new_app(), pages, width, scale) +} + +/// `harness_pages` on a file service that answers from `files`. +fn harness_with_files(pages: usize, files: Arc) -> (Harness<'static, PdfCraftApp>, ControlClient) { + harness_on(app_with_files(files), pages, 1400.0, 1.0) +} + +/// `app` with a `pages`-page document open, in a window `width` wide at `scale`, and the control +/// channel attached. +fn harness_on(app: PdfCraftApp, pages: usize, width: f32, scale: f32) -> (Harness<'static, PdfCraftApp>, ControlClient) { + let (tx, rx) = std::sync::mpsc::channel(); + let mut h = Harness::builder().with_size(egui::vec2(width, 900.0)).with_pixels_per_point(scale).build_eframe(move |_cc| { + let mut app = app; app.set_option("language", "en").unwrap(); - *s.lock().unwrap() = Some(app.attach_control(&cc.egui_ctx)); + app.attach_control(rx, None); app.open_bytes("doc.pdf", None, fixture(pages)).unwrap(); app }); h.run_steps(4); - let client = slot.lock().unwrap().take().unwrap(); - (h, client) + (h, tx) } /// Send a request and run frames until it is answered. -fn call(h: &mut Harness<'static, PdfCraftApp>, c: &ControlClient, method: &str, params: Value) -> Reply { - let rx = c.send(method, params); - let mut reply = None; +pub(crate) fn call(h: &mut Harness<'static, PdfCraftApp>, c: &ControlClient, method: &str, params: Value) -> Reply { + let rx = send(c, method, params); + let mut response = None; let answered = crate::support::step_until(h, |_| { - reply = rx.try_recv().ok(); - reply.is_some() + response = rx.try_recv().ok(); + response.is_some() }); - match reply { - Some(r) if answered => r, + match response { + Some(response) if answered => reply(&response), _ => panic!("{method}: no reply in 30 s"), } } -fn ok(h: &mut Harness<'static, PdfCraftApp>, c: &ControlClient, method: &str, params: Value) -> Value { +/// A response as a `Result`: the method's result, or the error it refused with. +fn reply(response: &ControlResponse) -> Reply { + if response["ok"] == true { Ok(response["result"].clone()) } else { Err(response["error"].as_str().unwrap_or_default().to_owned()) } +} + +pub(crate) fn ok(h: &mut Harness<'static, PdfCraftApp>, c: &ControlClient, method: &str, params: Value) -> Value { call(h, c, method, params).unwrap_or_else(|e| panic!("{method}: {e}")) } +/// Presses `from`, moves through `steps` points to `to` and releases, the way `ui.drag` did: a +/// click that holds, moves, then releases. `modifiers` are held for the whole gesture and `button` +/// is `"primary"`, `"secondary"` or `"middle"`. +fn drag(h: &mut Harness<'static, PdfCraftApp>, c: &ControlClient, from: Value, to: Value, steps: usize, modifiers: &[&str], button: &str) { + ok(h, c, "ui.click", json!({"x": from[0], "y": from[1], "hold": true, "button": button, "modifiers": modifiers})); + let point = |p: &Value| [p[0].as_f64().unwrap_or_default(), p[1].as_f64().unwrap_or_default()]; + let (from, to) = (point(&from), point(&to)); + let steps = steps.max(1); + for step in 1..=steps { + let t = step as f64 / steps as f64; + ok(h, c, "ui.move", json!({"x": from[0] + (to[0] - from[0]) * t, "y": from[1] + (to[1] - from[1]) * t, "modifiers": modifiers})); + } + // `ui.release` takes no modifiers: releasing the button ends the gesture they were held for. + ok(h, c, "ui.release", json!({"button": button})); + if !modifiers.is_empty() { + ok(h, c, "ui.release", json!({})); + } +} + /// Let the next real frames run after a control setting that changes the interface fonts or /// opens a modal. `ui.set` answers in the input pass, and a font change discards the pass that /// applies it, so the modal's labels are not in the accessibility tree until those frames have @@ -96,6 +198,29 @@ fn settle(h: &mut Harness<'static, PdfCraftApp>) { h.run_steps(3); } +/// Sends a request and runs the host's held-back jobs with each frame until it is answered, for a +/// request whose answer waits on a job. +fn call_running(h: &mut Harness<'static, PdfCraftApp>, c: &ControlClient, jobs: &ManualJobs, method: &str, params: Value) -> Reply { + let rx = send(c, method, params); + for _ in 0..30 { + jobs.run_all(); + h.step(); + if let Ok(response) = rx.try_recv() { + return reply(&response); + } + } + panic!("{method}: no reply after 30 frames"); +} + +/// Runs the jobs the host holds back (`ManualJobs`) and the frames that apply their results; a job +/// that starts another is run by the next round. +fn run_jobs(h: &mut Harness<'static, PdfCraftApp>, jobs: &ManualJobs) { + for _ in 0..4 { + jobs.run_all(); + h.step(); + } +} + #[test] fn comment_pin_is_reported_and_persistent() { let (mut h, c) = harness(); @@ -103,10 +228,12 @@ fn comment_pin_is_reported_and_persistent() { for pinned in [true, false] { ok(&mut h, &c, "ui.set", json!({"key":"comment-tool-pinned","value":pinned})); assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["comment_tool_pinned"], pinned); - let mut restored = PdfCraftApp::new(); - restored.comment_prefs.pinned = !pinned; - restored.restore(&h.state().persist()); - assert_eq!(restored.comment_prefs.pinned, pinned); + // A fresh app that starts from what this one would save holds the same pin, whatever it held. + let (mut restarted, rc) = harness_pages(1); + ok(&mut restarted, &rc, "ui.set", json!({"key":"comment-tool-pinned","value":!pinned})); + restarted.state_mut().apply_settings(&h.state().settings_snapshot()); + restarted.run_steps(2); + assert_eq!(ok(&mut restarted, &rc, "ui.state", json!({}))["comment_tool_pinned"], pinned); for invalid in [json!("yes"), json!(1), json!(null), json!([]), json!({})] { assert!(call(&mut h, &c, "ui.set", json!({"key":"comment-tool-pinned","value":invalid})).is_err()); assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["comment_tool_pinned"], pinned); @@ -115,45 +242,42 @@ fn comment_pin_is_reported_and_persistent() { } } -#[test] -fn thumbnail_size_is_settable_and_inspectable_through_the_control_channel() { - let (mut h, c) = harness(); - ok(&mut h, &c, "ui.set", json!({"key": "panel", "value": "pages"})); - ok(&mut h, &c, "ui.set", json!({"key": "thumbnail-zoom", "value": "50"})); - let state = ok(&mut h, &c, "ui.state", json!({})); - assert_eq!(state["active"]["thumbnail_zoom"], 0.5); - assert_eq!(state["active"]["grid_zoom"], 1.0); - assert_eq!(state["documents"][0]["dirty"], false); - let controls = ok(&mut h, &c, "ui.inspect", json!({"query": "thumbnails"})); - let widgets = controls["widgets"].as_array().unwrap(); - assert!(widgets.iter().any(|w| w["label"] == "Larger thumbnails")); - assert!(widgets.iter().any(|w| w["label"] == "Smaller thumbnails" && w["enabled"] == false)); - assert!(call(&mut h, &c, "ui.set", json!({"key": "thumbnail-zoom", "value": "NaN"})).is_err()); - ok(&mut h, &c, "ui.click", json!({"label": "Larger thumbnails"})); - h.run_steps(3); - assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["active"]["thumbnail_zoom"], 0.75); - let sliders = ok(&mut h, &c, "ui.inspect", json!({"query": "Thumbnail size", "role": "Slider"})); - let slider = sliders["widgets"].as_array().unwrap().first().expect("the thumbnail size slider is labelled"); - ok(&mut h, &c, "ui.focus", json!({"id": slider["id"]})); - ok(&mut h, &c, "ui.key", json!({"key": "ArrowRight"})); - h.run_steps(3); - assert!(ok(&mut h, &c, "ui.state", json!({}))["active"]["thumbnail_zoom"].as_f64().unwrap() > 0.75); +/// What `ui.state` reports at `path`. +fn reported(h: &mut Harness<'static, PdfCraftApp>, c: &ControlClient, path: &[&str]) -> Value { + path.iter().fold(ok(h, c, "ui.state", json!({})), |value, key| value[*key].clone()) } +/// The app's agent contract: each `ui.set` key changes the `ui.state` field it names, a value it +/// refuses changes nothing, and none of it dirties the document. #[test] -fn form_tab_numbers_can_be_shown_and_captured_through_the_control_channel() { +fn ui_set_keys_change_what_ui_state_reports() { let (mut h, c) = harness(); - h.state_mut().open_bytes("form.pdf", None, include_bytes!("../data/form.pdf").to_vec()).unwrap(); - h.run_steps(3); - ok(&mut h, &c, "ui.command", json!({"id": "form.prepare"})); - let control = ok(&mut h, &c, "ui.inspect", json!({"query": "Show tab numbers"})); - assert!(control["widgets"].as_array().unwrap().iter().any(|widget| widget["label"] == "Show tab numbers")); - ok(&mut h, &c, "ui.click", json!({"label": "Show tab numbers"})); - h.run_steps(2); - assert!(h.state().views[h.state().active.unwrap()].prepare.show_tab_numbers); - assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["documents"][1]["dirty"], false); - let shot = ok(&mut h, &c, "ui.screenshot", json!({})); - assert!(shot["png_base64"].as_str().is_some_and(|png| !png.is_empty()), "the control channel returns a nonempty screenshot"); + let s = ok(&mut h, &c, "ui.state", json!({})); + assert_eq!(s["documents"][0]["name"], "doc.pdf"); + assert_eq!(s["documents"][0]["pages"], 5); + assert_eq!(s["active"]["page"], 1); + assert_eq!(s["active"]["page_errors"], json!([])); + assert_eq!(s["active"]["selected_pages"], json!([])); + assert_eq!(s["active"]["grid_zoom"], 1.0); + ok(&mut h, &c, "ui.set", json!({"key": "panel", "value": "pages"})); + // The key, a value it takes, the field that changes and what it holds, and a value it refuses. + let rows: [(&str, Value, &[&str], Value, Value); 6] = [ + ("thumbnail-zoom", json!("50"), &["active", "thumbnail_zoom"], json!(0.5), json!("NaN")), + ("page", json!(4), &["active", "page"], json!(4), json!("not a page")), + ("panel", json!("bookmarks"), &["side_panels", "side_panel"], json!("Bookmarks"), json!("nonsense")), + ("select", json!("2,4"), &["active", "selected_pages"], json!([2, 4]), json!("0,6")), + ("select", json!("4-2,3"), &["active", "selected_pages"], json!([2, 3, 4]), json!("0,6")), + ("select", json!(""), &["active", "selected_pages"], json!([]), json!("0,6")), + ]; + for (key, value, path, expected, refused) in rows { + ok(&mut h, &c, "ui.set", json!({"key": key, "value": value})); + h.run_steps(3); + assert_eq!(reported(&mut h, &c, path), expected, "ui.set {key} {value}"); + assert!(call(&mut h, &c, "ui.set", json!({"key": key, "value": refused})).is_err(), "ui.set {key} {refused} is refused"); + assert_eq!(reported(&mut h, &c, path), expected, "a refused {key} changes nothing"); + } + assert_eq!(reported(&mut h, &c, &["documents"])[0]["dirty"], false); + assert_eq!(reported(&mut h, &c, &["active", "grid_zoom"]), 1.0, "the thumbnail zoom is not the Organize grid's"); } #[test] @@ -175,109 +299,6 @@ fn page_shadows_are_an_observable_app_wide_preference() { assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["show_page_edge_shadows"], false); } -#[test] -fn control_resize_reports_observed_dimensions_and_rejects_invalid_sizes() { - let (mut h, c) = harness(); - for params in [ - json!({}), - json!({"width": 800}), - json!({"width": "800", "height": 640}), - json!({"width": -1, "height": 640}), - json!({"width": 0, "height": 640}), - json!({"width": 800, "height": 319}), - json!({"width": 8193, "height": 640}), - json!({"width": 1e300, "height": 640}), - json!({"width": null, "height": 640}), - json!({"width": 800, "height": 640, "force": true}), - json!([]), - ] { - assert!(call(&mut h, &c, "ui.resize", params).is_err()); - let window = ok(&mut h, &c, "ui.state", json!({}))["window"].clone(); - assert_eq!(window["width"], 1400.0); - assert_eq!(window["height"], 900.0); - } - let requested = ok(&mut h, &c, "ui.resize", json!({"width": 800, "height": 640})); - assert_eq!(requested["requested"], json!([800.0, 640.0])); - let state = ok(&mut h, &c, "ui.state", json!({})); - assert_eq!(state["window"]["width"], 800.0); - assert_eq!(state["window"]["height"], 640.0); - assert_eq!(state["documents"][0]["pages"], 5); - assert_eq!(state["documents"][0]["dirty"], false); -} - -/// Kittest calls only `App::logic` and `App::ui`, not eframe's `raw_input_hook`, so this checks -/// the widget tree and key handling but not the production focus-generation ordering. The -/// `production_*` tests above drive `prepare_raw_input` first and cover that ordering. -#[test] -fn control_focus_traverses_real_widgets_and_keyboard_activates() { - let (mut h, c) = harness(); - ok(&mut h, &c, "ui.focus", json!({"label": "Convert"})); - let convert = ok(&mut h, &c, "ui.inspect", json!({"query": "Convert", "role": "Button"})); - let focused = - |found: &serde_json::Value, label: &str| found["widgets"].as_array().unwrap().iter().any(|w| w["label"] == label && w["focused"] == true); - assert!(focused(&convert, "Convert"), "{convert}"); - assert!(convert["widgets"].as_array().unwrap().iter().any(|w| w["label"] == "Convert" && w["focusable"] == true)); - ok(&mut h, &c, "ui.key", json!({"key": "Tab"})); - let sign = ok(&mut h, &c, "ui.inspect", json!({"query": "E-Sign", "role": "Button"})); - assert!(focused(&sign, "E-Sign"), "{sign}"); - ok(&mut h, &c, "ui.key", json!({"key": "Tab", "modifiers": ["shift"]})); - let convert = ok(&mut h, &c, "ui.inspect", json!({"query": "Convert", "role": "Button"})); - assert!(focused(&convert, "Convert"), "{convert}"); - ok(&mut h, &c, "ui.key", json!({"key": "Enter"})); - let state = ok(&mut h, &c, "ui.state", json!({})); - assert_eq!(state["mode"], "Convert"); - assert_eq!(state["documents"][0]["dirty"], false); -} - -/// A frame driven in production order: eframe's raw input hook runs before egui's input hooks, so -/// the control plugin sees the focus/dialog generation produced by the previous UI pass. The -/// kittest harness does not call `raw_input_hook`, which otherwise hides focus-change bugs. -fn production_step(h: &mut Harness<'static, PdfCraftApp>) { - let ctx = h.ctx.clone(); - let mut raw = std::mem::take(h.input_mut()); - h.state_mut().prepare_raw_input(&ctx, &mut raw); - *h.input_mut() = raw; - h.step(); -} - -fn call_production(h: &mut Harness<'static, PdfCraftApp>, c: &ControlClient, method: &str, params: Value) -> Reply { - let rx = c.send(method, params); - for _ in 0..30 { - production_step(h); - if let Ok(r) = rx.try_recv() { - return r; - } - } - panic!("{method}: no reply after 30 production-ordered frames"); -} - -#[test] -fn production_key_release_survives_the_focus_change_its_press_causes() { - let (mut h, c) = harness(); - ok(&mut h, &c, "ui.focus", json!({"label": "Convert"})); - let reply = call_production(&mut h, &c, "ui.key", json!({"key": "Tab"})); - reply.unwrap_or_else(|e| panic!("a Tab press that moves focus must not leave its release unapplied: {e}")); - let sign = ok(&mut h, &c, "ui.inspect", json!({"query": "E-Sign", "role": "Button"})); - assert!(sign["widgets"].as_array().unwrap().iter().any(|w| w["label"] == "E-Sign" && w["focused"] == true), "focus moved on the press: {sign}"); - assert!(!h.ctx.input(|i| i.keys_down.contains(&egui::Key::Tab)), "the release reached egui: no stuck Tab"); -} - -#[test] -fn production_drag_releases_the_button_after_the_press_moves_focus() { - let (mut h, c) = harness_pages(2); - h.state_mut().apply_edit(pdfcraft_engine::Edit::AddBookmark { parent: vec![], index: 0, title: "Target".into(), page: 0, left: None, top: None }); - ok(&mut h, &c, "ui.set", json!({"key": "panel", "value": "bookmarks"})); - let field = ok(&mut h, &c, "ui.inspect", json!({"query": "Search", "role": "TextInput"})); - let rect = field["widgets"][0]["rect"].as_array().expect("the search field has a rect"); - let (x0, y0, x1, y1) = (rect[0].as_f64().unwrap(), rect[1].as_f64().unwrap(), rect[2].as_f64().unwrap(), rect[3].as_f64().unwrap()); - let start = json!([x0 + 8.0, (y0 + y1) / 2.0]); - let end = json!([x1 - 8.0, (y0 + y1) / 2.0]); - call_production(&mut h, &c, "ui.drag", json!({"from": start, "to": end, "steps": 3})) - .unwrap_or_else(|e| panic!("the press's focus change must not cancel its moves and release: {e}")); - assert!(!h.ctx.input(|i| i.pointer.button_down(egui::PointerButton::Primary)), "the pointer button was released"); - assert_eq!(h.ctx.input(|i| i.modifiers), egui::Modifiers::NONE, "no modifier is left held"); -} - #[test] fn control_button_focus_preserves_document_undo_redo_shortcuts() { let (mut h, c) = harness_pages(2); @@ -304,41 +325,20 @@ fn control_text_focus_retains_text_undo_ownership() { ok(&mut h, &c, "ui.focus", json!({"id": widgets["widgets"][0]["id"]})); assert!(h.ctx.text_edit_focused()); ok(&mut h, &c, "ui.type", json!({"text": "target"})); - let search_id = egui::Id::unique(("bookmark_search", h.state().views[0].id.0)); - assert_eq!(h.ctx.data(|d| d.get_temp::(search_id)).as_deref(), Some("target")); + assert_eq!(search_text(&h), "target"); ok(&mut h, &c, "ui.key", json!({"key": "Z", "modifiers": ["command"]})); - assert_eq!(h.ctx.data(|d| d.get_temp::(search_id)).as_deref(), Some("")); + assert_eq!(search_text(&h), ""); assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["documents"][0]["pages"], 3); } -#[test] -fn control_focus_rejects_missing_ambiguous_disabled_and_nonfocusable_targets() { - let (mut h, c) = harness(); - for params in [ - json!({}), - json!({"label": "does not exist"}), - json!({"id": "not a number"}), - json!({"id": 0}), - json!({"id": 1, "label": "Convert"}), - json!({"label": false}), - json!({"label": "Convert", "force": true}), - json!([]), - ] { - assert!(call(&mut h, &c, "ui.focus", params).is_err()); - } - let widgets = ok(&mut h, &c, "ui.inspect", json!({})); - let nonfocusable = widgets["widgets"].as_array().unwrap().iter().find(|w| w["focusable"] == false).unwrap(); - assert!(call(&mut h, &c, "ui.focus", json!({"id": nonfocusable["id"]})).is_err()); - let convert = widgets["widgets"].as_array().unwrap().iter().find(|w| w["label"] == "Convert").unwrap(); - ok(&mut h, &c, "ui.focus", json!({"id": convert["id"]})); - let found = ok(&mut h, &c, "ui.inspect", json!({"query": "Convert", "role": "Button"})); - assert!(found["widgets"].as_array().unwrap().iter().any(|w| w["label"] == "Convert" && w["focused"] == true), "{found}"); - // Home has no active document, so its document-only toolbar controls are disabled. - ok(&mut h, &c, "ui.click", json!({"label": "Home"})); - assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["home"], true); - let widgets = ok(&mut h, &c, "ui.inspect", json!({})); - let disabled = widgets["widgets"].as_array().unwrap().iter().find(|w| w["enabled"] == false).unwrap(); - assert!(call(&mut h, &c, "ui.focus", json!({"id": disabled["id"]})).is_err()); +/// What the Bookmarks panel's Search field holds, as the access tree reports it. +fn search_text(h: &Harness<'static, PdfCraftApp>) -> String { + h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Search").value().unwrap_or_default() +} + +/// Whether the command palette is on screen: its command rows are list-box options in the access tree. +fn palette_on_screen(h: &Harness<'static, PdfCraftApp>) -> bool { + h.query_all_by_role(egui::accesskit::Role::ListBoxOption).next().is_some() } fn close_requested(h: &Harness<'static, PdfCraftApp>) -> bool { @@ -370,74 +370,6 @@ fn control_quit_preserves_dirty_documents_and_cancel_keeps_them_open() { assert!(!close_requested(&h)); } -/// Run one frame and return the attention requests it sent to the window. -fn step_attention(h: &mut Harness<'static, PdfCraftApp>) -> Vec { - h.step(); - let commands = h.output().viewport_output.values().flat_map(|v| v.commands.iter()); - commands.filter_map(|c| if let egui::ViewportCommand::RequestUserAttention(a) = c { Some(*a) } else { None }).collect() -} - -/// Send a request, run frames until it is answered and three more, and collect every attention -/// request those frames sent. -fn attention_during(h: &mut Harness<'static, PdfCraftApp>, c: &ControlClient, method: &str, params: Value) -> Vec { - let rx = c.send(method, params); - let mut sent = Vec::new(); - for _ in 0..30 { - sent.extend(step_attention(h)); - if rx.try_recv().is_ok() { - (0..3).for_each(|_| sent.extend(step_attention(h))); - return sent; - } - } - panic!("{method}: no reply after 30 frames"); -} - -/// Open `name` with an unsaved change, in a tab of its own. -fn open_unsaved(h: &mut Harness<'static, PdfCraftApp>, name: &str) { - let app = h.state_mut(); - app.open_bytes(name, None, fixture(1)).unwrap(); - app.active = Some(app.views.len() - 1); - app.apply_edit(pdfcraft_engine::Edit::RotatePages { pages: vec![0], degrees: 90 }); -} - -/// An agent quits while another app is in front, then answers the prompts itself. Quitting asks -/// about each unsaved document in turn; the request made for the first question stands for the -/// next, and answering the last withdraws it, so the taskbar or the window list stops flagging a -/// window with nothing to ask. Each question is a new one: when the first opened in front, the -/// next one asks when it opens in the background. -#[test] -fn a_save_prompt_answered_in_the_background_withdraws_its_attention_request() { - use egui::UserAttentionType::{Critical, Reset}; - let (mut h, c) = harness(); - ok(&mut h, &c, "ui.command", json!({"id": "page.insert_blank"})); - open_unsaved(&mut h, "second.pdf"); - h.input_mut().focused = false; - assert_eq!(attention_during(&mut h, &c, "ui.quit", json!({})), [Critical]); - assert!(attention_during(&mut h, &c, "ui.click", json!({"label": "Don't save"})).is_empty(), "the request stands"); - assert_eq!(attention_during(&mut h, &c, "ui.click", json!({"label": "Cancel"})), [Reset]); - - open_unsaved(&mut h, "third.pdf"); - h.input_mut().focused = true; - assert!(attention_during(&mut h, &c, "ui.quit", json!({})).is_empty(), "the first question opens in front"); - h.input_mut().focused = false; - assert!(attention_during(&mut h, &c, "ui.state", json!({})).is_empty(), "leaving it open asks nothing"); - assert_eq!(attention_during(&mut h, &c, "ui.click", json!({"label": "Don't save"})), [Critical], "the next opens in the background"); - assert_eq!(attention_during(&mut h, &c, "ui.click", json!({"label": "Cancel"})), [Reset]); - let state = ok(&mut h, &c, "ui.state", json!({})); - assert_eq!(state["close_prompt"], false); - let left: Vec<_> = state["documents"].as_array().unwrap().iter().map(|d| (d["name"].clone(), d["dirty"].clone())).collect(); - assert_eq!(left, [(json!("third.pdf"), json!(true))], "Don't save closed doc.pdf and second.pdf; Cancel kept third.pdf"); -} - -#[test] -fn control_quit_clean_document_requests_normal_window_close() { - for params in [json!({}), Value::Null] { - let (mut h, c) = harness(); - assert_eq!(ok(&mut h, &c, "ui.quit", params), json!({"quitting": true, "needs_confirmation": false})); - assert!(close_requested(&h)); - } -} - #[test] fn bookmark_titles_can_be_searched_over_control() { let (mut h, c) = harness(); @@ -452,6 +384,7 @@ fn bookmark_titles_can_be_searched_over_control() { let y = (rect[1].as_f64().unwrap() + rect[3].as_f64().unwrap()) / 2.0; ok(&mut h, &c, "ui.click", json!({ "x": x, "y": y })); ok(&mut h, &c, "ui.type", json!({ "text": "target" })); + assert_eq!(search_text(&h), "target", "the Search field holds what was typed"); h.get_by_label("Target chapter"); assert!(h.query_by_label("Background").is_none()); ok(&mut h, &c, "ui.click", json!({ "label": "Target chapter" })); @@ -461,6 +394,7 @@ fn bookmark_titles_can_be_searched_over_control() { h.render().unwrap().save(format!("{dir}/control-filtered-bookmarks.png")).unwrap(); } ok(&mut h, &c, "ui.click", json!({ "label": "Clear" })); + assert_eq!(search_text(&h), "", "Clear empties the Search field"); h.get_by_label("Background"); h.get_by_label("Target chapter"); if let Ok(dir) = std::env::var("PDFCRAFT_BOOKMARK_SHOTS") { @@ -492,27 +426,6 @@ fn theme_commands_and_options_report_preference_and_effective_colours() { assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["theme_preference"], "System"); } -#[test] -fn lithuanian_password_dialog_translates_dynamic_labels_and_validation() { - if crate::support::skip_without_catalogs("lithuanian_password_dialog_translates_dynamic_labels_and_validation") { - return; - } - let (mut h, c) = harness(); - ok(&mut h, &c, "ui.set", json!({ "key": "language", "value": "lt" })); - ok(&mut h, &c, "ui.set", json!({ "key": "dialog", "value": "protect" })); - h.run_steps(2); - h.get_by_role_and_label(egui::accesskit::Role::RadioButton, "Peržiūrėti"); - h.get_by_role_and_label(egui::accesskit::Role::RadioButton, "Redaguoti").click(); - h.run_steps(2); - assert!(!h.state().protect_draft.viewing); - h.get_by_role_and_label(egui::accesskit::Role::PasswordInput, "Įveskite slaptažodį"); - h.get_by_role_and_label(egui::accesskit::Role::PasswordInput, "Pakartokite slaptažodį"); - h.state_mut().protect_draft.password = "abc".into(); - h.state_mut().protect_draft.confirm = "xyz".into(); - h.run_steps(2); - h.get_by_label("Slaptažodžiai nesutampa."); -} - #[test] fn lithuanian_inspector_title_updates_through_the_control_channel() { if crate::support::skip_without_catalogs("lithuanian_inspector_title_updates_through_the_control_channel") { @@ -717,35 +630,6 @@ fn autoscroll_uses_the_initial_click_position_when_input_arrives_in_one_frame() ok(&mut h, &c, "ui.key", json!({ "key": "Escape" })); } -#[cfg(target_os = "linux")] -#[test] -fn farther_from_the_click_scrolls_faster_in_the_viewer_and_page_grid() { - for organize in [false, true] { - let (mut h, c) = harness_pages(40); - h.state_mut().views[0].organize = organize; - h.run_steps(3); - let position = CanvasPosition::new(&h); - let top = |h: &Harness<'static, PdfCraftApp>| position.top(h); - let p = start_autoscroll(&mut h, &c); - ok(&mut h, &c, "ui.move", json!({ "x": p.x, "y": p.y + 30.0 })); - let before_near = top(&h); - h.run_steps(8); - let near = before_near - top(&h); - ok(&mut h, &c, "ui.move", json!({ "x": p.x, "y": p.y + 100.0 })); - let before_far = top(&h); - h.run_steps(8); - let far = before_far - top(&h); - assert!(near > 0.0 && far > near * 3.0, "farther movement must be faster: organize={organize}, near={near}, far={far}"); - ok(&mut h, &c, "ui.move", json!({ "x": p.x, "y": p.y })); - h.run_steps(2); - let at_anchor = top(&h); - h.run_steps(8); - assert_eq!(top(&h), at_anchor, "returning to the original click pauses scrolling"); - assert!(h.state().views[0].auto_scrolling(), "the toggle stays on at the anchor"); - ok(&mut h, &c, "ui.key", json!({ "key": "Escape" })); - } -} - #[cfg(target_os = "linux")] #[test] fn autoscroll_uses_elapsed_frame_time_and_preserves_fractional_motion_in_both_views() { @@ -863,8 +747,8 @@ fn autoscroll_is_scoped_to_the_active_view_and_cannot_start_under_a_dialog() { h.run_steps(2); assert!(!h.state().views[0].auto_scrolling(), "returning to the tab must not resume"); start_autoscroll(&mut h, &c); - h.state_mut().dialog = Some(pdfcraft_ui_egui::Dialog::About); - h.run_steps(2); + ok(&mut h, &c, "ui.set", json!({ "key": "dialog", "value": "about" })); + settle(&mut h); assert!(!h.state().views[0].auto_scrolling()); ok(&mut h, &c, "ui.click", json!({ "x": p.x, "y": p.y, "button": "middle" })); assert!(!h.state().views[0].auto_scrolling(), "a modal owns its input"); @@ -890,33 +774,6 @@ fn the_click_that_stops_autoscroll_preserves_the_page_selection() { assert_eq!(h.state().views[0].target_pages(), vec![1]); } -#[cfg(target_os = "linux")] -#[test] -fn organize_pages_supports_autoscroll_without_selecting_or_reordering_pages() { - let (mut h, c) = harness_pages(40); - h.state_mut().execute("page.organize"); - h.run_steps(3); - let position = CanvasPosition::new(&h); - let top = position.top(&h); - let p = start_autoscroll(&mut h, &c); - ok(&mut h, &c, "ui.move", json!({ "x": p.x, "y": p.y + 80.0 })); - h.run_steps(8); - assert!(position.top(&h) < top - 30.0, "the organize grid scrolls"); - assert!(h.state().views[0].selected.is_empty()); - assert!(h.state().views[0].org_drag.is_none()); - ok(&mut h, &c, "ui.key", json!({ "key": "Escape" })); - // Holding the wheel over a page also must not create an organize drag. - ok(&mut h, &c, "ui.drag", json!({ "from": [p.x, p.y], "to": [p.x, p.y + 80.0], "button": "middle" })); - assert!(h.state().views[0].selected.is_empty()); - assert!(h.state().views[0].org_drag.is_none()); - assert!(!h.state().session.get(h.state().views[0].id).unwrap().dirty); - assert!(!h.state().views[0].auto_scrolling(), "releasing a held wheel stops the grid scrolling"); - start_autoscroll(&mut h, &c); - h.state_mut().views[0].organize = false; - h.run_steps(2); - assert!(!h.state().views[0].auto_scrolling(), "changing canvas mode cancels the gesture"); -} - #[cfg(not(target_os = "linux"))] #[test] fn middle_button_pans_while_held_outside_linux() { @@ -969,24 +826,6 @@ fn inverted_middle_drag_moves_the_view_the_way_the_pointer_goes() { assert!(!h.state().session.get(h.state().views[0].id).unwrap().dirty); } -/// The control channel reports the open document, its page count and current page, and its -/// view options can be set: the page, and a right-hand panel by name (an unknown one is refused). -#[test] -fn state_and_view_options() { - let (mut h, c) = harness(); - let s = ok(&mut h, &c, "ui.state", json!({})); - assert_eq!(s["documents"][0]["name"], "doc.pdf"); - assert_eq!(s["documents"][0]["pages"], 5); - assert_eq!(s["active"]["page"], 1); - assert_eq!(s["active"]["page_errors"], json!([])); - ok(&mut h, &c, "ui.set", json!({ "key": "page", "value": 4 })); - h.run_steps(3); - assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["active"]["page"], 4); - ok(&mut h, &c, "ui.set", json!({ "key": "panel", "value": "bookmarks" })); - assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["right_panel"], "Bookmarks"); - assert!(call(&mut h, &c, "ui.set", json!({ "key": "panel", "value": "nonsense" })).is_err()); -} - /// In a Japanese interface, the mode tabs and Preferences show Japanese labels, the command /// palette finds commands by their Japanese or English names or their ids, and switching back to /// English keeps the tabs working. @@ -1199,49 +1038,15 @@ fn japanese_dialogs_errors_and_custom_action_names() { steps: Vec::new(), builtin: false, }); - h.state_mut().wizard.selected = Some("Save".to_string()); ok(&mut h, &c, "ui.set", json!({"key": "dialog", "value": "action-wizard"})); + settle(&mut h); + ok(&mut h, &c, "ui.click", json!({"label": "Save"})); for label in ["アクションウィザード", "Save", "Print"] { let found = ok(&mut h, &c, "ui.inspect", json!({"query": label})); assert!(found["widgets"].as_array().unwrap().iter().any(|w| w["label"] == label || w["value"] == label), "{found}"); } } -#[test] -fn simplified_chinese_about_tabs_and_credit_controls() { - if crate::support::skip_without_catalogs("simplified_chinese_about_tabs_and_credit_controls") { - return; - } - if crate::support::skip_without_glyphs("simplified_chinese_about_tabs_and_credit_controls", "zh-hans", "") { - return; - } - let (mut h, c) = harness(); - let documents = ok(&mut h, &c, "ui.state", json!({}))["documents"].clone(); - ok(&mut h, &c, "ui.set", json!({"key": "language", "value": "zh-hans"})); - settle(&mut h); - ok(&mut h, &c, "ui.set", json!({"key": "dialog", "value": "about"})); - settle(&mut h); - for label in ["关于", "贡献者", "模型"] { - let found = ok(&mut h, &c, "ui.inspect", json!({"query": label})); - assert!(found["widgets"].as_array().unwrap().iter().any(|w| w["label"] == label), "{found}"); - } - ok(&mut h, &c, "ui.click", json!({"label": "贡献者"})); - for label in ["用户名", "显示名称", "真实姓名", "排序", "名称列表", "表格", "首次提交"] { - let found = ok(&mut h, &c, "ui.inspect", json!({"query": label})); - assert!(found["count"].as_u64().unwrap() > 0, "{label}: {found}"); - } - ok(&mut h, &c, "ui.click", json!({"label": "表格"})); - for label in ["新增行", "删除行", "净增行", "新增资源", "删除资源"] { - let found = ok(&mut h, &c, "ui.inspect", json!({"query": label})); - assert!(found["count"].as_u64().unwrap() > 0, "{label}: {found}"); - } - ok(&mut h, &c, "ui.click", json!({"label": "模型"})); - let columns = ok(&mut h, &c, "ui.inspect", json!({"query": "占全部提交的比例"})); - let empty = ok(&mut h, &c, "ui.inspect", json!({"query": "此版本未包含模型贡献记录。"})); - assert!(columns["count"].as_u64().unwrap() > 0 || empty["count"].as_u64().unwrap() > 0, "{columns}, {empty}"); - assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["documents"], documents); -} - #[test] fn simplified_chinese_signature_prompts_and_errors_keep_document_state() { if crate::support::skip_without_catalogs("simplified_chinese_signature_prompts_and_errors_keep_document_state") { @@ -1278,33 +1083,6 @@ fn simplified_chinese_signature_prompts_and_errors_keep_document_state() { assert_eq!(state["documents"], documents, "a language change and failed edit must preserve the document"); } -#[test] -fn inspect_and_click_by_label_and_id() { - let (mut h, c) = harness(); - let found = ok(&mut h, &c, "ui.inspect", json!({ "query": "convert" })); - let convert = - found["widgets"].as_array().unwrap().iter().find(|w| w["label"] == "Convert" && w["clickable"] == true).cloned().expect("a Convert tab"); - let rect = convert["rect"].as_array().unwrap(); - assert!(rect[2].as_f64().unwrap() > rect[0].as_f64().unwrap()); - - ok(&mut h, &c, "ui.click", json!({ "label": "Convert" })); - assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["mode"], "Convert"); - - let all = ok(&mut h, &c, "ui.inspect", json!({ "query": "all tools" })); - let id = all["widgets"].as_array().unwrap().iter().find(|w| w["label"] == "All tools" && w["clickable"] == true).unwrap()["id"].clone(); - ok(&mut h, &c, "ui.click", json!({ "id": id })); - assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["mode"], "AllTools"); - - // Clicking a point works too (here: the Convert tab's centre). - let [x0, y0, x1, y1] = [0, 1, 2, 3].map(|i| rect[i].as_f64().unwrap()); - ok(&mut h, &c, "ui.click", json!({ "x": (x0 + x1) / 2.0, "y": (y0 + y1) / 2.0 })); - assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["mode"], "Convert"); - - let err = call(&mut h, &c, "ui.click", json!({ "label": "No such button" })).unwrap_err(); - assert!(err.contains("no enabled clickable widget"), "{err}"); - assert!(call(&mut h, &c, "ui.click", json!({ "id": 12345 })).is_err()); -} - #[test] fn cover_page_command_needs_two_page_view() { // Agents see the cover toggle as disabled, and get an error, until two-page view. @@ -1335,42 +1113,18 @@ fn commands_keys_and_typing() { // ⌘K opens the palette; typing filters it; Escape closes it. ok(&mut h, &c, "ui.key", json!({ "key": "K", "modifiers": ["command"] })); - assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["palette_open"], true); + assert!(palette_on_screen(&h), "the palette is on screen"); ok(&mut h, &c, "ui.type", json!({ "text": "split" })); let hits = ok(&mut h, &c, "ui.inspect", json!({ "query": "split document" })); assert!(hits["count"].as_u64().unwrap() >= 1, "{hits}"); ok(&mut h, &c, "ui.key", json!({ "key": "Escape" })); - assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["palette_open"], false); + h.run_steps(2); + assert!(!palette_on_screen(&h), "Escape closes the palette"); assert!(call(&mut h, &c, "ui.key", json!({ "key": "NotAKey" })).is_err()); assert!(call(&mut h, &c, "ui.frobnicate", json!({})).unwrap_err().contains("unknown method")); } -#[test] -fn select_all_key_selects_every_page_in_organize() { - let (mut h, c) = harness(); - ok(&mut h, &c, "ui.set", json!({ "key": "organize", "value": "on" })); - ok(&mut h, &c, "ui.set", json!({ "key": "select", "value": "3" })); - ok(&mut h, &c, "ui.key", json!({ "key": "A", "modifiers": ["command"] })); - assert_eq!(h.state().views[0].target_pages(), [0, 1, 2, 3, 4]); - assert_eq!(h.state().views[0].current, 2); - assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["documents"][0]["dirty"], false); -} - -#[test] -fn state_reports_the_selected_pages() { - let (mut h, c) = harness(); - assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["active"]["selected_pages"], json!([])); - ok(&mut h, &c, "ui.set", json!({ "key": "select", "value": "2,4" })); - assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["active"]["selected_pages"], json!([2, 4])); - ok(&mut h, &c, "ui.set", json!({ "key": "select", "value": "4-2,3" })); - assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["active"]["selected_pages"], json!([2, 3, 4])); - assert!(call(&mut h, &c, "ui.set", json!({ "key": "select", "value": "0,6" })).is_err()); - assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["active"]["selected_pages"], json!([2, 3, 4])); - ok(&mut h, &c, "ui.set", json!({ "key": "select", "value": "" })); - assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["active"]["selected_pages"], json!([])); -} - #[test] fn ctrl_dragging_a_thumbnail_through_the_control_channel_copies_the_page() { let (mut h, c) = harness_pages(3); @@ -1471,87 +1225,6 @@ fn drawing_a_comment_by_drag_and_its_context_menu() { assert!(call(&mut h, &c, "ui.drag", json!({ "from": [1, 2] })).unwrap_err().contains("to must be")); } -#[test] -fn screenshots_of_window_and_region() { - let (mut h, c) = harness(); - // The harness makes its GPU renderer on the first render. The app has one before the control - // channel answers anything, so make it here, outside the screenshot's 5 s deadline: with 16 - // tests at once on Windows, making it took up to 6 s and every copy of this test failed. - h.render().expect("the test renderer draws"); - let shot = ok(&mut h, &c, "ui.screenshot", json!({})); - let ppp = shot["pixels_per_point"].as_f64().unwrap(); - assert_eq!(shot["width"].as_f64().unwrap(), (1400.0 * ppp).round()); - use base64::Engine as _; - let png = base64::engine::general_purpose::STANDARD.decode(shot["png_base64"].as_str().unwrap()).unwrap(); - assert_eq!(&png[1..4], b"PNG"); - let region = ok(&mut h, &c, "ui.screenshot", json!({ "region": [10, 20, 110, 70] })); - assert_eq!((region["width"].as_f64().unwrap(), region["height"].as_f64().unwrap()), ((100.0 * ppp).round(), (50.0 * ppp).round())); - assert!(call(&mut h, &c, "ui.screenshot", json!({ "region": [5, 5, 1, 1] })).is_err()); - // A region that cannot be inside the window is refused at admission, before a frame or slot - // is used, with an actionable message. - let outside = call(&mut h, &c, "ui.screenshot", json!({ "region": [1300, 0, 1500, 10] })).unwrap_err(); - assert!(outside.contains("inside the window"), "{outside}"); -} - -#[test] -fn loopback_transport_requires_the_token() { - use std::io::{BufRead, BufReader, Write}; - let (mut h, c) = harness(); - let ep = pdfcraft_ui_egui::control::serve(c).unwrap(); - let talk = |lines: Vec| { - let port = ep.port; - std::thread::spawn(move || { - let s = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap(); - let mut w = s.try_clone().unwrap(); - let mut r = BufReader::new(s).lines(); - let mut out = Vec::new(); - for l in lines { - // The server closes the connection after a failed auth; later writes may fail. - if writeln!(w, "{l}").is_err() { - break; - } - match r.next() { - Some(Ok(reply)) => out.push(serde_json::from_str::(&reply).unwrap()), - _ => break, - } - } - out - }) - }; - let pump = |h: &mut Harness<'static, PdfCraftApp>, t: std::thread::JoinHandle>| { - while !t.is_finished() { - h.step(); - } - t.join().unwrap() - }; - - // Wrong token: rejected and disconnected before any request reaches the app. - let bad = pump( - &mut h, - talk(vec![ - json!({ "jsonrpc": "2.0", "id": 1, "method": "auth", "params": { "token": "guess" } }), - json!({ "jsonrpc": "2.0", "id": 2, "method": "ui.state" }), - ]), - ); - assert_eq!(bad.len(), 1); - assert_eq!(bad[0]["error"]["code"], -32001); - // No auth at all: same. - let none = pump(&mut h, talk(vec![json!({ "jsonrpc": "2.0", "id": 1, "method": "ui.state" })])); - assert_eq!(none[0]["error"]["code"], -32001); - - let good = pump( - &mut h, - talk(vec![ - json!({ "jsonrpc": "2.0", "id": 1, "method": "auth", "params": { "token": ep.token } }), - json!({ "jsonrpc": "2.0", "id": 2, "method": "ui.state" }), - json!({ "jsonrpc": "2.0", "id": 3, "method": "ui.command", "params": { "id": "edit.undo" } }), - ]), - ); - assert_eq!(good[0]["result"]["ok"], true); - assert_eq!(good[1]["result"]["documents"][0]["name"], "doc.pdf"); - assert!(good[2]["error"]["message"].as_str().unwrap().contains("disabled")); -} - #[test] fn control_default_workspace_and_session_override() { let (mut h, c) = harness(); @@ -1567,7 +1240,12 @@ fn control_default_workspace_and_session_override() { #[test] fn measurement_tools_draw_live_calibrate_save_and_export() { - let (mut h, c) = harness_pages(1); + let dir = std::env::temp_dir().join(format!("pdfcraft-measure-ui-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let csv = dir.join("measurements.csv"); + // The CSV's Save pick is the only picker the test meets; the script answers it. + let files = Arc::new(ScriptedFiles::answering([Picked::Paths(vec![csv.clone()])])); + let (mut h, c) = harness_with_files(1, files.clone()); let doc = h.state().views[0].id; h.state_mut().set_option("zoom", "100").unwrap(); ok(&mut h, &c, "ui.command", json!({"id":"measure.scale"})); @@ -1609,12 +1287,13 @@ fn measurement_tools_draw_live_calibrate_save_and_export() { assert_eq!(h.state().session.get(doc).unwrap().measurements().unwrap().measurements.len(), 2); ok(&mut h, &c, "ui.command", json!({"id":"edit.redo"})); h.run_steps(2); - let dir = std::env::temp_dir().join(format!("pdfcraft-measure-ui-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - h.state_mut().export_dir_override = Some(dir.to_string_lossy().into()); ok(&mut h, &c, "ui.command", json!({"id":"measure.export"})); h.run_steps(2); - assert!(std::fs::read_to_string(dir.join("measurements.csv")).unwrap().contains("m^2")); + assert_eq!(files.requests().len(), 1, "the export asked where to save once"); + // The file service keeps what it is given in memory; a writer that went to the disk instead + // left the file in the folder. + let written = files.file(&csv).or_else(|| std::fs::read(&csv).ok()).expect("the CSV was written where the pick said"); + assert!(String::from_utf8(written).unwrap().contains("m^2")); h.state_mut().set_option("quick", "measure-calibrate").unwrap(); click(&mut h, &c, 30.0, 50.0); click(&mut h, &c, 130.0, 50.0); @@ -1717,6 +1396,11 @@ fn a_plan_scale_picked_or_typed_applies_at_once() { assert_ne!(read(&h), before); } +/// The dock's state, as `ui.panel` reports it when it is asked to change nothing. +fn dock(h: &mut Harness<'static, PdfCraftApp>, c: &ControlClient) -> Value { + ok(h, c, "ui.panel", json!({"panel": "side"}))["side_panels"].clone() +} + #[test] fn ui_panel_opens_closes_and_sizes_panes_and_survives_restore() { let (mut h, c) = harness(); @@ -1729,19 +1413,22 @@ fn ui_panel_opens_closes_and_sizes_panes_and_survives_restore() { assert_eq!(state["side_panels"]["tools_width"], 520.0); ok(&mut h, &c, "ui.panel", json!({"panel":"tools", "width": 300, "open": false})); h.run_steps(3); - assert!(!h.state().left_open); + assert_eq!(dock(&mut h, &c)["tools_open"], false); ok(&mut h, &c, "ui.panel", json!({"panel":"side", "open": false})); h.run_steps(3); - assert_eq!(h.state().right, None); + assert_eq!(dock(&mut h, &c)["side_open"], false); assert!(h.query_by_label("This document has no bookmarks.").is_none()); // Reopening the side panel brings back the one open last. ok(&mut h, &c, "ui.panel", json!({"panel":"side", "open": true})); h.run_steps(3); h.get_by_label("This document has no bookmarks."); assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["side_panels"]["side_panel"], "Bookmarks"); - let saved = h.state().persist(); + // What the app would save holds the layout in its dock section; a fresh app that starts from it + // shows the same panes. + let saved = h.state().settings_snapshot(); + assert!(saved.dock.dock.is_some(), "the layout is in the saved dock section"); let (mut reloaded, client) = harness(); - reloaded.state_mut().restore(&saved); + reloaded.state_mut().apply_settings(&saved); reloaded.run_steps(4); let state = ok(&mut reloaded, &client, "ui.state", json!({}))["side_panels"].clone(); assert_eq!( @@ -1750,7 +1437,7 @@ fn ui_panel_opens_closes_and_sizes_panes_and_survives_restore() { ); // The ui.command form and the reset command. ok(&mut reloaded, &client, "ui.command", json!({"id":"ui.panel", "params":{"panel":"tools", "open":true}})); - assert!(reloaded.state().left_open); + assert_eq!(dock(&mut reloaded, &client)["tools_open"], true); ok(&mut reloaded, &client, "ui.panel", json!({"panel":"tools", "width": 300})); ok(&mut reloaded, &client, "ui.set", json!({"key":"tools-side", "value":"right"})); ok(&mut reloaded, &client, "ui.command", json!({"id":"ui.dock.reset"})); @@ -1762,7 +1449,7 @@ fn ui_panel_opens_closes_and_sizes_panes_and_survives_restore() { #[test] fn invalid_panel_requests_change_nothing() { let (mut h, c) = harness(); - let before = ok(&mut h, &c, "ui.state", json!({}))["side_panels"].clone(); + let before = dock(&mut h, &c); for params in [ json!({"panel":"canvas"}), json!({"panel":"inspector", "open": true}), @@ -1772,8 +1459,8 @@ fn invalid_panel_requests_change_nothing() { json!({"panel":"side", "width": 300, "open": 1}), ] { assert!(call(&mut h, &c, "ui.panel", params).is_err()); + assert_eq!(dock(&mut h, &c), before); let state = ok(&mut h, &c, "ui.state", json!({})); - assert_eq!(state["side_panels"], before); assert_eq!(state["documents"][0]["pages"], 5); assert_eq!(state["documents"][0]["dirty"], false); } @@ -1796,7 +1483,7 @@ fn home_and_combine_hide_the_side_panel_without_forgetting_it() { let (mut h, c) = harness(); ok(&mut h, &c, "ui.set", json!({"key":"panel", "value":"bookmarks"})); ok(&mut h, &c, "ui.panel", json!({"panel":"side", "width": 380})); - let before = ok(&mut h, &c, "ui.state", json!({}))["side_panels"].clone(); + let before = dock(&mut h, &c); for combine in [false, true] { if combine { h.state_mut().open_combine_tab(); @@ -1805,28 +1492,34 @@ fn home_and_combine_hide_the_side_panel_without_forgetting_it() { } h.run_steps(4); assert!(h.query_by_label("This document has no bookmarks.").is_none()); - assert_eq!(h.state().right, Some(pdfcraft_ui_egui::RightPanel::Bookmarks)); - assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["side_panels"], before); + assert_eq!(dock(&mut h, &c)["side_panel"], "Bookmarks", "the panel is remembered while hidden"); + assert_eq!(dock(&mut h, &c), before); h.state_mut().active = Some(0); h.state_mut().combine_tab.focused = false; h.run_steps(4); h.get_by_label("This document has no bookmarks."); - assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["side_panels"], before); + assert_eq!(dock(&mut h, &c), before); } } +/// A saved dock section that does not read leaves the dock at its default and costs the other +/// preferences nothing, whether it came from the last release's file or from this one's. #[test] fn malformed_panel_settings_preserve_other_preferences() { - let mut app = PdfCraftApp::new(); - app.restore(r#"{"docking":{"layout":{"root":null,"floating":[]},"hidden":[]},"default_mode":"edit","flatten_fill_sign":true}"#); - assert_eq!(app.default_mode, pdfcraft_ui_egui::Mode::Edit); - assert_eq!(app.side_panels, pdfcraft_ui_egui::side_panels::SidePanels::default()); - let saved: Value = serde_json::from_str(&app.persist()).unwrap(); - assert_eq!(saved["default_mode"], "edit"); - assert_eq!(saved["flatten_fill_sign"], true); - // The old value is dropped on the next save. - assert!(saved.get("docking").is_none()); - assert_eq!(saved["side_panels"]["version"], 1); + for json in [ + r#"{"docking":{"layout":{"root":null,"floating":[]},"hidden":[]},"default_mode":"edit","flatten_fill_sign":true}"#, + r#"{"side_panels":"not a layout","default_mode":"edit","flatten_fill_sign":true}"#, + ] { + let (settings, _) = import_json(json); + let (mut h, c) = harness(); + let default_dock = dock(&mut h, &c); + h.state_mut().apply_settings(&settings); + h.run_steps(3); + assert_eq!(dock(&mut h, &c), default_dock, "{json}"); + let saved = h.state().settings_snapshot(); + assert_eq!(saved.layout.default_mode, Some(pdfcraft_ui_egui::Mode::Edit), "{json}"); + assert_eq!(saved.behavior.flatten_fill_sign, Some(true), "{json}"); + } } #[test] @@ -1838,7 +1531,7 @@ fn rail_opens_a_panel_then_closes_the_open_one() { h.get_by_label("This document has no bookmarks."); h.get_by_role_and_label(egui::accesskit::Role::Button, "Bookmarks").click(); h.run_steps(4); - assert_eq!(h.state().right, None); + assert_eq!(dock(&mut h, &c)["side_open"], false); assert!(h.query_by_label("This document has no bookmarks.").is_none()); assert_eq!(ok(&mut h, &c, "ui.state", json!({}))["documents"], document); } @@ -1895,10 +1588,10 @@ fn read_mode_retains_existing_rail_click_to_close_policy() { ok(&mut h, &c, "ui.set", json!({"key":"panel", "value":"bookmarks"})); ok(&mut h, &c, "ui.set", json!({"key":"mode", "value":"read"})); h.run_steps(3); - assert_eq!(h.state().right, Some(pdfcraft_ui_egui::RightPanel::Bookmarks)); + assert_eq!(dock(&mut h, &c)["side_panel"], "Bookmarks"); h.get_by_role_and_label(egui::accesskit::Role::Button, "Bookmarks").click(); h.run_steps(3); - assert_eq!(h.state().right, None); + assert_eq!(dock(&mut h, &c)["side_open"], false); assert_eq!(h.state().mode, pdfcraft_ui_egui::Mode::Read); } @@ -1910,26 +1603,23 @@ fn control_open_of_an_already_open_file_replies_ok_and_focuses_its_tab() { let b = dir.join("b.pdf").to_string_lossy().into_owned(); std::fs::write(&a, fixture(2)).unwrap(); std::fs::write(&b, fixture(3)).unwrap(); - let slot: Arc>> = Arc::default(); - let s = slot.clone(); - let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |cc| { - let mut app = PdfCraftApp::new(); + let (mut app, jobs) = app_with_manual_jobs(); + let (tx, rx) = std::sync::mpsc::channel(); + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| { app.set_option("language", "en").unwrap(); - // Inline opens: this test pins the synchronous open contract (focus vs open vs - // failure). Live apps schedule the worker instead and reply `pending` (#1620). - app.run_inline = true; - *s.lock().unwrap() = Some(app.attach_control(&cc.egui_ctx)); + app.attach_control(rx, None); app }); h.run_steps(4); - let c = slot.lock().unwrap().take().unwrap(); - - let first = ok(&mut h, &c, "ui.open", json!({ "path": a })); + let c = tx; + // This test pins the synchronous open contract (focus vs open vs failure): the open job is + // run before the reply is read. A live app replies `pending` instead (#1620). + let first = call_running(&mut h, &c, &jobs, "ui.open", json!({ "path": a })).unwrap(); assert_eq!(first["opened"], json!(a), "{first}"); - ok(&mut h, &c, "ui.open", json!({ "path": b })); + call_running(&mut h, &c, &jobs, "ui.open", json!({ "path": b })).unwrap(); // The file is already open: the tab focuses, and the reply must be Ok — an agent driving the // app headlessly would otherwise read a focus as a read failure (#1620). - let again = ok(&mut h, &c, "ui.open", json!({ "path": a })); + let again = call_running(&mut h, &c, &jobs, "ui.open", json!({ "path": a })).unwrap(); assert_eq!(again["focused"], true, "{again}"); let state = ok(&mut h, &c, "ui.state", json!({})); @@ -1949,32 +1639,27 @@ fn control_open_replies_pending_while_the_worker_opens_and_focuses_once_it_has() std::fs::create_dir_all(&dir).unwrap(); let a = dir.join("pending.pdf").to_string_lossy().into_owned(); std::fs::write(&a, fixture(2)).unwrap(); - let slot: Arc>> = Arc::default(); - let s = slot.clone(); - let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |cc| { - let mut app = PdfCraftApp::new(); + let (mut app, jobs) = app_with_manual_jobs(); + let (tx, rx) = std::sync::mpsc::channel(); + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| { app.set_option("language", "en").unwrap(); - *s.lock().unwrap() = Some(app.attach_control(&cc.egui_ctx)); + app.attach_control(rx, None); app }); h.run_steps(4); - let c = slot.lock().unwrap().take().unwrap(); + let c = tx; + // The host holds the open job back, so the reply can only be `pending`. let first = ok(&mut h, &c, "ui.open", json!({ "path": a })); assert_eq!(first["accepted"], json!(a), "{first}"); assert_eq!(first["pending"], true, "{first}"); + let tabs = |h: &mut Harness<'static, PdfCraftApp>| ok(h, &c, "ui.state", json!({}))["documents"].as_array().map(|d| d.len()).unwrap_or_default(); + assert_eq!(tabs(&mut h), 0, "nothing opens until the job runs"); - // The worker completes the open on later frames; the tab shows, and only then does a - // repeated open focus it instead of reporting another pending open. The worker is a thread - // of its own, so the wait is bounded by time: a busy runner can draw 30 frames before it has - // read the file. - let mut documents = 0; - let opened = crate::support::step_until(&mut h, |h| { - let state = ok(h, &c, "ui.state", json!({})); - documents = state["documents"].as_array().map(|d| d.len()).unwrap_or_default(); - documents == 1 - }); - assert!(opened, "the pending open completed into a tab: {documents} tabs"); + // The job completes the open on later frames; the tab shows, and only then does a repeated + // open focus it instead of reporting another pending open. + run_jobs(&mut h, &jobs); + assert_eq!(tabs(&mut h), 1, "the pending open completed into a tab"); let again = ok(&mut h, &c, "ui.open", json!({ "path": a })); assert_eq!(again["focused"], true, "{again}"); @@ -2061,7 +1746,7 @@ fn wheel_zoom_is_scoped_to_the_viewport_and_respects_existing_limits() { fn initial_zoom_option_is_applied_before_the_first_viewport_layout() { for percent in [50, 100, 200, 400] { let h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |_cc| { - let mut app = PdfCraftApp::new(); + let mut app = new_app(); app.open_bytes("initial-zoom.pdf", None, fixture(3)).unwrap(); app.set_option("zoom", &percent.to_string()).unwrap(); assert_eq!(app.views[0].zoom, percent as f32 / 100.0, "initial options must work before the viewport exists"); @@ -2071,32 +1756,6 @@ fn initial_zoom_option_is_applied_before_the_first_viewport_layout() { } } -/// #1306: a coordinate that only overflows once narrowed to a pointer position is refused by -/// click and drag, as move refuses it, before any pointer input is queued; the frames that follow -/// run, and the channel keeps working. -#[test] -fn click_and_drag_refuse_coordinates_that_overflow_like_move() { - let (mut h, c) = harness(); - for (method, params) in [ - ("ui.move", json!({ "x": 1e39, "y": -1e39 })), - ("ui.click", json!({ "x": 1e39, "y": -1e39 })), - ("ui.click", json!({ "x": 40.0, "y": 1e39 })), - ("ui.drag", json!({ "from": [1e39, -1e39], "to": [40.0, 40.0], "steps": 1 })), - ("ui.drag", json!({ "from": [40.0, 40.0], "to": [40.0, -1e39], "steps": 1 })), - // Each end fits, but not the way from one to the other. - ("ui.drag", json!({ "from": [-3e38, 40.0], "to": [3e38, 40.0], "steps": 1 })), - ] { - let e = call(&mut h, &c, method, params.clone()).expect_err(&format!("{method} {params} is refused")); - assert!(e.starts_with(&format!("{method}: ")) && e.contains("finite"), "{e}"); - h.run_steps(4); - assert_eq!(ok(&mut h, &c, "ui.inspect", json!({ "query": "Convert", "role": "Button" }))["count"], 1); - } - let convert = ok(&mut h, &c, "ui.inspect", json!({ "query": "Convert", "role": "Button" }))["widgets"][0]["rect"].clone(); - let (x, y) = (convert[0].as_f64().unwrap() + 4.0, convert[1].as_f64().unwrap() + 4.0); - assert_eq!(ok(&mut h, &c, "ui.click", json!({ "x": x, "y": y }))["clicked"], json!([x, y])); - ok(&mut h, &c, "ui.drag", json!({ "from": [x, y], "to": [x + 10.0, y], "steps": 2 })); -} - #[test] fn page_size_shows_while_the_pointer_is_in_the_bottom_left_quadrant() { let (mut h, _c) = harness(); @@ -2139,7 +1798,7 @@ fn navigation_history_for_os(os: egui::os::OperatingSystem) { // Empty-history shortcuts were silent before registry integration and must stay silent. for key in ["[", "]"] { ok(&mut h, &c, "ui.key", json!({"key": key, "modifiers": ["command"]})); - assert!(h.state().toast.is_none(), "an unavailable history action must not ask to open the already-open document"); + assert!(crate::support::shown_notice(&h).is_none(), "an unavailable history action must not ask to open the already-open document"); } let before = h.state().session.get(h.state().views[0].id).unwrap().bytes.clone(); ok(&mut h, &c, "ui.set", json!({"key": "page", "value": "4"})); @@ -2201,23 +1860,23 @@ fn control_collapses_and_expands_a_pinned_folder() { std::fs::create_dir_all(&dir).unwrap(); std::fs::write(dir.join("inside.pdf"), fixture(1)).unwrap(); let folder = dir.to_string_lossy().into_owned(); - let slot: Arc>> = Arc::default(); - let (s, pin) = (slot.clone(), folder.clone()); - let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_eframe(move |cc| { - let mut app = PdfCraftApp::new(); + let (tx, rx) = std::sync::mpsc::channel(); + let (mut app, jobs) = app_with_manual_jobs(); + let pin = folder.clone(); + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).build_eframe(move |_cc| { app.set_option("language", "en").unwrap(); - app.run_inline = true; app.pin_folder(&pin); - *s.lock().unwrap() = Some(app.attach_control(&cc.egui_ctx)); + app.attach_control(rx, None); app }); - h.run_steps(4); - let c = slot.lock().unwrap().take().unwrap(); + let c = tx; + // The listing of the pinned folder is a job; the test runs it between frames. + run_jobs(&mut h, &jobs); let folded = |h: &mut Harness<'static, PdfCraftApp>| ok(h, &c, "ui.state", json!({}))["pinned_folders"].clone(); assert_eq!(folded(&mut h), json!([{ "folder": folder, "collapsed": false }])); h.get_by_label("inside.pdf"); ok(&mut h, &c, "ui.set", json!({ "key": "folder-collapsed", "value": format!("{folder}=on") })); - h.run_steps(2); + run_jobs(&mut h, &jobs); assert_eq!(folded(&mut h), json!([{ "folder": folder, "collapsed": true }])); assert!(h.query_by_label("inside.pdf").is_none(), "a collapsed folder lists nothing"); let unpinned = call(&mut h, &c, "ui.set", json!({ "key": "folder-collapsed", "value": "/not/pinned=on" })).unwrap_err(); @@ -2226,7 +1885,7 @@ fn control_collapses_and_expands_a_pinned_folder() { assert!(bad.contains("=on or"), "{bad}"); assert_eq!(folded(&mut h), json!([{ "folder": folder, "collapsed": true }]), "refusals change nothing"); ok(&mut h, &c, "ui.set", json!({ "key": "folder-collapsed", "value": format!("{folder}=off") })); - h.run_steps(2); + run_jobs(&mut h, &jobs); assert_eq!(folded(&mut h), json!([{ "folder": folder, "collapsed": false }])); h.get_by_label("inside.pdf"); let _ = std::fs::remove_dir_all(&dir); @@ -2236,23 +1895,7 @@ fn control_collapses_and_expands_a_pinned_folder() { fn accessible_labels_on_format_text_and_pin_dialog() { let (mut h, c) = harness(); - // 1. Check Dialog::PinTool accessibility labels - h.state_mut().dialog = Some(pdfcraft_ui_egui::Dialog::PinTool); - h.run_steps(3); - - let search = ok(&mut h, &c, "ui.inspect", json!({"role": "TextInput", "query": "Search tools…"})); - assert!(search["count"].as_u64().unwrap() >= 1, "search box has accessible label: {search}"); - - let result_rows = ok(&mut h, &c, "ui.inspect", json!({"query": "Organize Pages"})); - assert!(result_rows["count"].as_u64().unwrap() >= 1, "result row has accessible label: {result_rows}"); - - let pin_toggles = ok(&mut h, &c, "ui.inspect", json!({"query": "Pin"})); - assert!(pin_toggles["count"].as_u64().unwrap() >= 1, "pin toggle has accessible label: {pin_toggles}"); - - h.state_mut().dialog = None; - h.run_steps(2); - - // 2. Open Add Text so Format text panel is visible + // Open Add Text so Format text panel is visible ok(&mut h, &c, "ui.command", json!({"id": "edit.text"})); h.run_steps(3); diff --git a/crates/ui-egui/tests/it/fonts.rs b/crates/ui-egui/tests/it/fonts.rs index 11369d8304..aa484f1e32 100644 --- a/crates/ui-egui/tests/it/fonts.rs +++ b/crates/ui-egui/tests/it/fonts.rs @@ -1,35 +1,42 @@ //! The interface fonts with and without the optional craft-fonts build input (`CRAFT_FONTS_DIR`). +//! Installed-face search and its order are the framework's `OnDemandFonts`; these tests guard +//! PdfCraft's own catalogs against its `UiFonts` input. -use egui::epaint::text::{Fonts, TextOptions}; +use egui::epaint::text::{FontDefinitions, Fonts, TextOptions}; use egui::{Color32, FontFamily, FontId}; -use pdfcraft_ui_egui::theme; +use pdfcraft_ui_egui::fonts::ui_fonts; +use pdfcraft_ui_egui::i18n::Lang; const JAPANESE: &str = "日本語の文字"; const CHINESE: &str = "简体中文欢迎"; const ARABIC: &str = "واحد اثنين"; const TELUGU: &str = "తెలుగు ఫైల్"; -const HEBREW: &str = "ייפוי כח.pdf"; const DEVANAGARI: &str = "हिंदी पाठ सम्पादन"; /// The embedded craft-i18n catalogs `code` reads (the shared one and PdfCraft's), one text; empty /// in a build without them. fn catalog(code: &str) -> String { - pdfcraft_ui_egui::i18n::Lang::from_code(code).map(|l| l.catalog_texts().collect::>().join("\n")).unwrap_or_default() + Lang::from_code(code).map(|l| l.catalog_texts().collect::>().join("\n")).unwrap_or_default() +} + +/// The interface stack for the language `code` (English when it is not embedded), as one set of +/// definitions: each family's chain, including the faces asked after the system fonts. +fn definitions(code: &str) -> FontDefinitions { + ui_fonts(Lang::from_code(code).unwrap_or(Lang::EN)).stack().flat_definitions() } fn families() -> Vec { - vec![FontId::proportional(13.0), FontId::monospace(13.0), theme::medium(13.0), theme::semibold(17.0)] + vec![FontId::proportional(13.0), FontId::monospace(13.0)] } -/// The bundled faces, with no craft-fonts and no installed system face: 0.37 gates its emoji -/// fonts behind `monochrome_emoji_fonts`, which the app and this test crate explicitly enable. -/// Text symbols must keep working with `PDFCRAFT_SYSTEM_FONTS=0`. +/// The bundled faces, with no craft-fonts and no installed system face: text symbols must keep +/// working with `PDFCRAFT_SYSTEM_FONTS=0`. #[test] fn bundled_monochrome_symbols_have_glyphs() { - let mut fonts = Fonts::new(TextOptions::default(), theme::font_definitions()); + let mut fonts = Fonts::new(TextOptions::default(), definitions("en")); for id in families() { for text in ["✔", "▲", "▼"] { - assert!(fonts.has_glyphs(&id, text), "{id:?} lacks {text} with default_fonts + monochrome_emoji_fonts"); + assert!(fonts.has_glyphs(&id, text), "{id:?} lacks {text} in the interface stack"); } } } @@ -48,7 +55,7 @@ fn japanese_ui_text_uses_craft_fonts() { eprintln!("skipping japanese_ui_text_uses_craft_fonts: built without craft-fonts (set CRAFT_FONTS_DIR to run it)"); return; } - let defs = theme::font_definitions(); + let defs = definitions("ja"); for family in [FontFamily::Proportional, FontFamily::Monospace] { let stack = &defs.families[&family]; let first_jp = stack.iter().position(|n| n.starts_with("BIZ UDPGothic")).expect("BIZ UDPGothic is a fallback"); @@ -75,7 +82,7 @@ fn chinese_ui_text_prefers_the_chinese_face() { eprintln!("skipping chinese_ui_text_prefers_the_chinese_face: no Hans face bundled (set CRAFT_FONTS_DIR with a Chinese face to run it)"); return; } - let defs = theme::font_definitions_for(true); + let defs = definitions("zh-hans"); let hans: Vec = pdfcraft_fonts::ui_chinese_fonts().iter().map(|f| f.name()).collect(); for family in [FontFamily::Proportional, FontFamily::Monospace] { let stack = &defs.families[&family]; @@ -102,7 +109,7 @@ fn arabic_ui_text_uses_craft_fonts() { eprintln!("skipping arabic_ui_text_uses_craft_fonts: no Arab face bundled (set CRAFT_FONTS_DIR with an Arabic face to run it)"); return; } - let defs = theme::font_definitions(); + let defs = definitions("ar"); for family in [FontFamily::Proportional, FontFamily::Monospace] { let stack = &defs.families[&family]; let first_ar = stack.iter().position(|n| arabic.contains(n)).expect("an Arab face is a fallback"); @@ -125,7 +132,7 @@ fn telugu_ui_text_uses_craft_fonts() { eprintln!("skipping telugu_ui_text_uses_craft_fonts: no Telu face bundled (set CRAFT_FONTS_DIR with a Telugu face to run it)"); return; } - let defs = theme::font_definitions(); + let defs = definitions("te"); for family in [FontFamily::Proportional, FontFamily::Monospace] { let stack = &defs.families[&family]; let first_te = stack.iter().position(|n| telugu.contains(n)).expect("a Telu face is a fallback"); @@ -143,62 +150,16 @@ fn telugu_ui_text_uses_craft_fonts() { } } -/// On a machine with a suitable installed font, the installed definitions end every family -/// with it and Arabic text has glyphs; the embedded-only definitions never name it. -#[test] -fn system_fallback_fills_missing_scripts() { - assert!(!theme::font_definitions().font_data.contains_key(theme::SYSTEM_FALLBACK)); - let defs = theme::installed_font_definitions(theme::CjkPreference::Default); - if !defs.font_data.contains_key(theme::SYSTEM_FALLBACK) { - eprintln!("skipping system_fallback_fills_missing_scripts: no installed fallback font (or PDFCRAFT_SYSTEM_FONTS=0)"); - assert!(defs.families.values().all(|stack| !stack.iter().any(|n| n == theme::SYSTEM_FALLBACK))); - return; - } - for (family, stack) in &defs.families { - assert_eq!(stack.last().map(String::as_str), Some(theme::SYSTEM_FALLBACK), "{family:?}: {stack:?}"); - assert_eq!(stack.iter().filter(|n| *n == theme::SYSTEM_FALLBACK).count(), 1, "{family:?}"); - } - let mut fonts = Fonts::new(TextOptions::default(), defs); - for id in families() { - assert!(fonts.has_glyphs(&id, ARABIC), "{id:?} lacks {ARABIC}"); - assert!(fonts.has_glyphs(&id, "PdfCraft"), "{id:?}"); - } - assert!(layout_widths(&mut fonts, ARABIC).iter().all(|w| w.is_finite() && *w > 0.0)); -} - -/// On a machine with a suitable installed Devanagari font, the installed definitions include -/// it and Hindi text has glyphs; the embedded-only definitions never name it. -#[test] -fn system_fallback_covers_devanagari() { - assert!(!theme::font_definitions().font_data.contains_key(theme::SYSTEM_DEVANAGARI_FALLBACK)); - let defs = theme::installed_font_definitions(theme::CjkPreference::Default); - if !defs.font_data.contains_key(theme::SYSTEM_DEVANAGARI_FALLBACK) { - eprintln!("skipping system_fallback_covers_devanagari: no installed Devanagari fallback font (or PDFCRAFT_SYSTEM_FONTS=0)"); - assert!(defs.families.values().all(|stack| !stack.iter().any(|n| n == theme::SYSTEM_DEVANAGARI_FALLBACK))); - return; - } - for (family, stack) in &defs.families { - assert!(stack.iter().any(|n| n == theme::SYSTEM_DEVANAGARI_FALLBACK), "{family:?}: {stack:?}"); - assert_eq!(stack.iter().filter(|n| *n == theme::SYSTEM_DEVANAGARI_FALLBACK).count(), 1, "{family:?}"); - } - let mut fonts = Fonts::new(TextOptions::default(), defs); - for id in families() { - assert!(fonts.has_glyphs(&id, DEVANAGARI), "{id:?} lacks {DEVANAGARI}"); - } - assert!(layout_widths(&mut fonts, DEVANAGARI).iter().all(|w| w.is_finite() && *w > 0.0)); -} - /// Built with craft-fonts, Hindi text renders with real glyphs (no tofu) in every family: a /// `Deva` face is a fallback after the app's own fonts. Without craft-fonts it is the installed -/// Devanagari fallback's job (see `system_fallback_covers_devanagari`), and the web build has -/// neither. +/// face's job (the framework's on-demand search), and the web build has neither. #[test] fn devanagari_ui_text_uses_craft_fonts() { if pdfcraft_fonts::ui_devanagari_fonts().is_empty() { eprintln!("skipping devanagari_ui_text_uses_craft_fonts: built without craft-fonts (set CRAFT_FONTS_DIR to run it)"); return; } - let defs = theme::font_definitions(); + let defs = definitions("hi"); for family in [FontFamily::Proportional, FontFamily::Monospace] { let stack = &defs.families[&family]; let first = @@ -213,163 +174,11 @@ fn devanagari_ui_text_uses_craft_fonts() { assert!(layout_widths(&mut fonts, DEVANAGARI).iter().all(|w| w.is_finite() && *w > 0.0)); } -/// On a machine with an installed Telugu font, the installed definitions include it and Telugu -/// text has glyphs, so the language's own name in Preferences is not boxes (#1531). macOS always -/// ships Kohinoor Telugu, so there the test never skips. -#[test] -fn system_fallback_covers_telugu() { - assert!(!theme::font_definitions().font_data.contains_key(theme::SYSTEM_TELUGU_FALLBACK)); - let defs = theme::installed_font_definitions(theme::CjkPreference::Default); - let off = std::env::var_os("PDFCRAFT_SYSTEM_FONTS").is_some_and(|v| v == "0"); - if !defs.font_data.contains_key(theme::SYSTEM_TELUGU_FALLBACK) && (off || !cfg!(target_os = "macos")) { - eprintln!("skipping system_fallback_covers_telugu: no installed Telugu fallback font (or PDFCRAFT_SYSTEM_FONTS=0)"); - assert!(defs.families.values().all(|stack| !stack.iter().any(|n| n == theme::SYSTEM_TELUGU_FALLBACK))); - return; - } - for (family, stack) in &defs.families { - assert_eq!(stack.iter().filter(|n| *n == theme::SYSTEM_TELUGU_FALLBACK).count(), 1, "{family:?}: {stack:?}"); - } - let mut fonts = Fonts::new(TextOptions::default(), defs); - for id in families() { - assert!(fonts.has_glyphs(&id, TELUGU), "{id:?} lacks {TELUGU}"); - } - assert!(layout_widths(&mut fonts, TELUGU).iter().all(|w| w.is_finite() && *w > 0.0)); -} - -/// On a machine with installed Sinhala and Tamil fonts, the installed definitions include them -/// and Sinhala and Tamil text, such as a file name, has glyphs instead of boxes (#1688). macOS -/// always ships Sinhala Sangam MN and Tamil Sangam MN, so there the test never skips. -#[test] -fn system_fallback_covers_sinhala_and_tamil() { - for (name, text) in [(theme::SYSTEM_SINHALA_FALLBACK, "ශ්‍රී ලංකා ගොනුව"), (theme::SYSTEM_TAMIL_FALLBACK, "தமிழ் கோப்பு")] - { - assert!(!theme::font_definitions().font_data.contains_key(name)); - let defs = theme::installed_font_definitions(theme::CjkPreference::Default); - let off = std::env::var_os("PDFCRAFT_SYSTEM_FONTS").is_some_and(|v| v == "0"); - if !defs.font_data.contains_key(name) && (off || !cfg!(target_os = "macos")) { - eprintln!("skipping {name}: no installed fallback font (or PDFCRAFT_SYSTEM_FONTS=0)"); - assert!(defs.families.values().all(|stack| !stack.iter().any(|n| n == name))); - continue; - } - for (family, stack) in &defs.families { - assert_eq!(stack.iter().filter(|n| *n == name).count(), 1, "{family:?}: {stack:?}"); - } - let mut fonts = Fonts::new(TextOptions::default(), defs); - for id in families() { - assert!(fonts.has_glyphs(&id, text), "{id:?} lacks {text}"); - } - assert!(layout_widths(&mut fonts, text).iter().all(|w| w.is_finite() && *w > 0.0)); - } -} - -/// On a machine with an installed Hebrew font, the installed definitions include it and a -/// Hebrew file name has glyphs in the document tab and the recent files (#586). macOS always -/// ships Arial Hebrew and SF Hebrew, so there the test never skips. -#[test] -fn system_fallback_covers_hebrew() { - assert!(!theme::font_definitions().font_data.contains_key(theme::SYSTEM_HEBREW_FALLBACK)); - let defs = theme::installed_font_definitions(theme::CjkPreference::Default); - let off = std::env::var_os("PDFCRAFT_SYSTEM_FONTS").is_some_and(|v| v == "0"); - if !defs.font_data.contains_key(theme::SYSTEM_HEBREW_FALLBACK) && (off || !cfg!(target_os = "macos")) { - eprintln!("skipping system_fallback_covers_hebrew: no installed Hebrew fallback font (or PDFCRAFT_SYSTEM_FONTS=0)"); - assert!(defs.families.values().all(|stack| !stack.iter().any(|n| n == theme::SYSTEM_HEBREW_FALLBACK))); - return; - } - for (family, stack) in &defs.families { - assert_eq!(stack.iter().filter(|n| *n == theme::SYSTEM_HEBREW_FALLBACK).count(), 1, "{family:?}: {stack:?}"); - } - let mut fonts = Fonts::new(TextOptions::default(), defs); - for id in families() { - assert!(fonts.has_glyphs(&id, HEBREW), "{id:?} lacks {HEBREW}"); - } - assert!(layout_widths(&mut fonts, HEBREW).iter().all(|w| w.is_finite() && *w > 0.0)); -} - -/// The Han characters of a catalog's translations. -fn catalog_han(catalog: &str) -> String { - let mut han: Vec = catalog - .lines() - .filter(|l| !l.starts_with('#')) - .filter_map(|l| l.split('\t').nth(2)) - .flat_map(str::chars) - .filter(|c| matches!(*c, '\u{3400}'..='\u{9fff}' | '\u{f900}'..='\u{faff}')) - .collect(); - han.sort_unstable(); - han.dedup(); - han.into_iter().collect() -} - -/// One Chinese preference against its catalog: the installed face must be in every family, -/// before the Japanese faces, and cover every Han character the catalog uses. -/// -/// Returns false when this machine has no installed face for the preference (or system fonts -/// are off); the caller reports that as a skip. A bundled `Hans` face is never allowed to -/// stand in for Traditional Chinese. -fn installed_chinese_face_covers(cjk: theme::CjkPreference, catalog: &str, name: &str) -> bool { - let defs = theme::installed_font_definitions(cjk); - if !defs.font_data.contains_key(theme::SYSTEM_FALLBACK) { - eprintln!("skipping {name}: no installed Chinese face for {cjk:?} (or PDFCRAFT_SYSTEM_FONTS=0)"); - return false; - } - for (family, stack) in &defs.families { - let system = stack.iter().position(|n| n == theme::SYSTEM_FALLBACK).expect("in every family"); - assert_eq!(stack.iter().filter(|n| *n == theme::SYSTEM_FALLBACK).count(), 1, "{family:?}"); - let own = stack.iter().position(|n| n.starts_with("Inter") || n == "JetBrainsMono").expect("the app's own font"); - assert!(own < system, "{family:?}: {stack:?}"); - if let Some(first_ja) = stack.iter().position(|n| n.starts_with("BIZ UDPGothic")) { - assert!(system < first_ja, "{family:?}: {stack:?}"); - } - } - let han = catalog_han(catalog); - assert!(han.contains('欢') || han.contains('說'), "{cjk:?}"); - let mut fonts = Fonts::new(TextOptions::default(), defs); - for id in families() { - let missing: String = han.chars().filter(|c| !fonts.has_glyphs(&id, &c.to_string())).collect(); - assert!(missing.is_empty(), "{cjk:?} {id:?} lacks {missing}"); - } - true -} - -/// In a Simplified Chinese interface built without a `Hans` face, a Simplified Chinese face -/// installed on this machine goes before the Japanese faces, which lack hundreds of the -/// catalog's characters. -#[test] -fn simplified_chinese_ui_uses_an_installed_hans_face_without_an_embedded_one() { - if crate::support::skip_without_catalogs("simplified_chinese_ui_uses_an_installed_hans_face_without_an_embedded_one") { - return; - } - if !pdfcraft_fonts::ui_chinese_fonts().is_empty() { - eprintln!("skipping simplified_chinese_ui_uses_an_installed_hans_face_without_an_embedded_one: a Hans face is bundled"); - return; - } - installed_chinese_face_covers(theme::CjkPreference::SimplifiedChinese, &catalog("zh-hans"), "Simplified"); -} - -/// A Traditional Chinese interface keeps its installed Traditional face before the Japanese -/// faces even when the build embeds a Simplified-only `Hans` face: that face cannot supply -/// Traditional-only characters, and Japanese-first fallback would otherwise win. -#[test] -fn traditional_chinese_ui_keeps_an_installed_hant_face_before_japanese() { - if crate::support::skip_without_catalogs("traditional_chinese_ui_keeps_an_installed_hant_face_before_japanese") { - return; - } - installed_chinese_face_covers(theme::CjkPreference::TraditionalChinese, &catalog("zh-hant"), "Traditional"); -} - -/// Other languages keep the installed face last. -#[test] -fn non_chinese_ui_keeps_the_installed_face_last() { - let defs = theme::installed_font_definitions(theme::CjkPreference::Default); - for stack in defs.families.values() { - assert!(stack.iter().position(|n| n == theme::SYSTEM_FALLBACK).is_none_or(|i| i + 1 == stack.len()), "{stack:?}"); - } -} - /// Without craft-fonts the interface fonts still install and lay out any text (Japanese falls /// back to egui's replacement glyph) without panicking; Latin text is unaffected. #[test] fn ui_fonts_work_without_craft_fonts() { - let mut fonts = Fonts::new(TextOptions::default(), theme::font_definitions()); + let mut fonts = Fonts::new(TextOptions::default(), definitions("en")); for id in families() { assert!(fonts.has_glyphs(&id, "PdfCraft"), "{id:?}"); assert_eq!(fonts.has_glyphs(&id, JAPANESE), !pdfcraft_fonts::ui_japanese_fonts().is_empty(), "{id:?}"); @@ -377,7 +186,7 @@ fn ui_fonts_work_without_craft_fonts() { assert!(layout_widths(&mut fonts, JAPANESE).iter().all(|w| w.is_finite() && *w > 0.0)); assert!(layout_widths(&mut fonts, "PdfCraft").iter().all(|w| *w > 20.0)); let ctx = egui::Context::default(); - theme::install_fonts(&ctx); + ui_fonts(Lang::EN).install(&ctx); } /// Latin- and Cyrillic-script catalogs (Czech, Brazilian Portuguese, German, Spanish, French, Russian, Bulgarian, Kazakh, Hungarian, Ukrainian, Italian, Slovene, Lithuanian, Greek, Turkish, Indonesian, Vietnamese, Albanian, Catalan) are drawn entirely by the app's own faces @@ -389,7 +198,7 @@ fn primary_ui_fonts_cover_latin_and_cyrillic_catalogs() { return; } use skrifa::MetadataProvider as _; - let defs = theme::font_definitions(); + let defs = definitions("en"); assert_eq!(&defs.families[&FontFamily::Monospace][..2], ["JetBrainsMono", "Inter"]); let fallback = &defs.font_data["Inter"]; let fallback_font = skrifa::FontRef::from_index(fallback.font.as_ref().as_ref(), fallback.index).unwrap(); @@ -444,27 +253,3 @@ fn primary_ui_fonts_cover_latin_and_cyrillic_catalogs() { } } } - -/// On a machine with an installed Korean font, the installed definitions include it and Hangul has -/// glyphs, so a Korean file name in a tab title is not boxes. macOS always ships Apple SD Gothic -/// Neo and Windows Malgun Gothic, so there the test never skips. -#[test] -fn system_fallback_covers_hangul() { - const HANGUL: &str = "성가대 찬양곡 목록"; - assert!(!theme::font_definitions().font_data.contains_key(theme::SYSTEM_HANGUL_FALLBACK)); - let defs = theme::installed_font_definitions(theme::CjkPreference::Default); - let off = std::env::var_os("PDFCRAFT_SYSTEM_FONTS").is_some_and(|v| v == "0"); - if !defs.font_data.contains_key(theme::SYSTEM_HANGUL_FALLBACK) && (off || cfg!(all(unix, not(target_os = "macos")))) { - eprintln!("skipping system_fallback_covers_hangul: no installed Korean fallback font (or PDFCRAFT_SYSTEM_FONTS=0)"); - assert!(defs.families.values().all(|stack| !stack.iter().any(|n| n == theme::SYSTEM_HANGUL_FALLBACK))); - return; - } - for (family, stack) in &defs.families { - assert_eq!(stack.iter().filter(|n| *n == theme::SYSTEM_HANGUL_FALLBACK).count(), 1, "{family:?}: {stack:?}"); - } - let mut fonts = Fonts::new(TextOptions::default(), defs); - for id in families() { - assert!(fonts.has_glyphs(&id, HANGUL), "{id:?} lacks {HANGUL}"); - } - assert!(layout_widths(&mut fonts, HANGUL).iter().all(|w| w.is_finite() && *w > 0.0)); -} diff --git a/crates/ui-egui/tests/it/theme.rs b/crates/ui-egui/tests/it/theme.rs index 1f2709cd56..3fd862f35e 100644 --- a/crates/ui-egui/tests/it/theme.rs +++ b/crates/ui-egui/tests/it/theme.rs @@ -1,32 +1,57 @@ -//! Theme preferences stay in sync across both menus, OS changes and saved settings. +//! Theme preferences stay in sync across both menus, OS changes and saved settings. The mode a +//! frame resolved is read from `ui.state` (filled from the frame's resolved `RootEnv`), the saved +//! choice from the settings the app would write. +use craft::theme::ModeChoice; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use pdfcraft_ui_egui::PdfCraftApp; -use pdfcraft_ui_egui::theme::{ThemeKind, ThemePreference, Tokens}; +use pdfcraft_ui_egui::settings::import_json; +use serde_json::json; -fn harness() -> Harness<'static, PdfCraftApp> { - let mut h = Harness::builder().with_size(egui::vec2(1100.0, 800.0)).build_eframe(|_cc| { - let mut app = PdfCraftApp::new(); +use crate::control::{ControlClient, answer, call, new_app, ok, send}; + +/// An app whose first frame has not run, restored from `settings` when given, on a desktop that +/// says `system`; the control channel is attached. +fn harness_with(settings: Option<&'static str>, system: Option, run: bool) -> (Harness<'static, PdfCraftApp>, ControlClient) { + let (tx, rx) = std::sync::mpsc::channel(); + let mut h = Harness::builder().with_size(egui::vec2(1100.0, 800.0)).build_eframe(move |_cc| { + let mut app = new_app(); app.set_option("language", "en").unwrap(); + if let Some(json) = settings { + app.apply_settings(&import_json(json).0); + } + app.attach_control(rx, None); app }); - h.input_mut().system_theme = Some(egui::Theme::Dark); - h.run_steps(4); - h + h.input_mut().system_theme = system; + if run { + h.run_steps(4); + } + (h, tx) } -fn assert_theme(h: &Harness<'static, PdfCraftApp>, preference: ThemePreference, kind: ThemeKind) { - assert_eq!(h.state().theme_preference, preference); - assert_eq!(h.state().theme, kind); - assert_eq!(Tokens::get(&h.ctx).kind, kind); - assert_eq!(h.ctx.global_style().visuals.dark_mode, kind == ThemeKind::Dark); - assert_eq!(h.ctx.options(|o| o.theme_preference), egui::ThemePreference::System); - for branch in [egui::Theme::Light, egui::Theme::Dark] { - let style = h.ctx.style_of(branch); - assert_eq!(style.visuals.dark_mode, kind == ThemeKind::Dark); - assert_eq!(style.visuals.panel_fill, Tokens::for_kind(kind).panel); - } +fn harness() -> (Harness<'static, PdfCraftApp>, ControlClient) { + harness_with(None, Some(egui::Theme::Dark), true) +} + +/// The choice the app would save now; a fresh install saves none, which is System. +fn saved_choice(h: &Harness<'static, PdfCraftApp>) -> ModeChoice { + h.state().settings_snapshot().layout.theme.unwrap_or(ModeChoice::System) +} + +/// The preference the app holds (`System`, `Light` or `Dark`) and the mode its last frame resolved +/// (`Light` or `Dark`), as `ui.state` reports them, and the choice the saved settings hold. +fn assert_theme(h: &mut Harness<'static, PdfCraftApp>, c: &ControlClient, preference: &str, mode: &str) { + let state = ok(h, c, "ui.state", json!({})); + assert_eq!(state["theme_preference"], preference); + assert_eq!(state["theme"], mode); + let choice = match preference { + "Light" => ModeChoice::Light, + "Dark" => ModeChoice::Dark, + _ => ModeChoice::System, + }; + assert_eq!(saved_choice(h), choice, "the saved choice follows the preference"); } /// A click on the title bar's theme button cycles Light, Dark, System. @@ -49,47 +74,41 @@ fn open_view_menu(h: &mut Harness<'static, PdfCraftApp>) { /// the desktop says nothing; a saved choice still wins. #[test] fn a_fresh_install_follows_the_system_theme() { - let h = harness(); - assert_theme(&h, ThemePreference::System, ThemeKind::Dark); - let mut quiet = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(|_cc| { - let mut app = PdfCraftApp::new(); - app.set_option("language", "en").unwrap(); - app - }); - quiet.run_steps(4); - assert_theme(&quiet, ThemePreference::System, ThemeKind::Light); - let mut app = PdfCraftApp::new(); - app.restore(r#"{"theme":"Light"}"#); - assert_eq!(app.theme_preference, ThemePreference::Light, "a saved choice wins over the default"); + let (mut h, c) = harness(); + assert_theme(&mut h, &c, "System", "Dark"); + let (mut quiet, qc) = harness_with(None, None, true); + assert_theme(&mut quiet, &qc, "System", "Light"); + let (mut saved, sc) = harness_with(Some(r#"{"theme":"Light"}"#), Some(egui::Theme::Dark), true); + assert_theme(&mut saved, &sc, "Light", "Light"); } #[test] fn toolbar_and_view_menu_share_three_state_preferences() { - let mut h = harness(); + let (mut h, c) = harness(); // Fresh, on a dark desktop: System, shown dark. One click on, explicit light wins even on a - // dark desktop, including egui's popup style. - assert_theme(&h, ThemePreference::System, ThemeKind::Dark); + // dark desktop. + assert_theme(&mut h, &c, "System", "Dark"); click_toolbar(&mut h, "Use system setting"); - assert_theme(&h, ThemePreference::Light, ThemeKind::Light); + assert_theme(&mut h, &c, "Light", "Light"); click_toolbar(&mut h, "Light gray"); - assert_theme(&h, ThemePreference::Dark, ThemeKind::Dark); + assert_theme(&mut h, &c, "Dark", "Dark"); click_toolbar(&mut h, "Dark gray"); - assert_theme(&h, ThemePreference::System, ThemeKind::Dark); + assert_theme(&mut h, &c, "System", "Dark"); open_view_menu(&mut h); h.get_by_label("Light gray").click(); h.run_steps(3); - assert_theme(&h, ThemePreference::Light, ThemeKind::Light); + assert_theme(&mut h, &c, "Light", "Light"); click_toolbar(&mut h, "Light gray"); - assert_theme(&h, ThemePreference::Dark, ThemeKind::Dark); + assert_theme(&mut h, &c, "Dark", "Dark"); open_view_menu(&mut h); h.get_by_label("Use system setting").click(); h.run_steps(3); - assert_theme(&h, ThemePreference::System, ThemeKind::Dark); + assert_theme(&mut h, &c, "System", "Dark"); h.input_mut().system_theme = Some(egui::Theme::Light); h.run_steps(3); - assert_theme(&h, ThemePreference::System, ThemeKind::Light); + assert_theme(&mut h, &c, "System", "Light"); click_toolbar(&mut h, "Use system setting"); click_toolbar(&mut h, "Light gray"); // A manual choice exits system mode and survives subsequent OS changes. @@ -97,130 +116,89 @@ fn toolbar_and_view_menu_share_three_state_preferences() { h.run_steps(2); h.input_mut().system_theme = Some(egui::Theme::Light); h.run_steps(2); - assert_theme(&h, ThemePreference::Dark, ThemeKind::Dark); + assert_theme(&mut h, &c, "Dark", "Dark"); } +/// The last release wrote `Light`, `Dark` and `System` capitalised and this one writes them in +/// lower case; both read, and a value that is neither leaves the system choice. #[test] fn saved_preferences_restore_with_legacy_light_dark_settings() { - for (value, preference) in [("light", ThemePreference::Light), ("dark", ThemePreference::Dark), ("system", ThemePreference::System)] { - let mut app = PdfCraftApp::new(); - app.set_option("language", "en").unwrap(); - app.set_option("theme", value).unwrap(); - let saved = app.persist(); - let mut restored = PdfCraftApp::new(); - restored.set_option("language", "en").unwrap(); - restored.restore(&saved); - assert_eq!(restored.theme_preference, preference); + for (json, preference, mode) in [ + (r#"{"theme":"light"}"#, "Light", "Light"), + (r#"{"theme":"dark"}"#, "Dark", "Dark"), + (r#"{"theme":"system"}"#, "System", "Light"), + (r#"{"theme":"Dark"}"#, "Dark", "Dark"), + (r#"{"theme":"Light"}"#, "Light", "Light"), + (r#"{"theme":"System"}"#, "System", "Light"), + (r#"{"theme":"Purple"}"#, "System", "Light"), + ] { + let (mut h, c) = harness_with(Some(json), None, true); + assert_theme(&mut h, &c, preference, mode); } - let mut app = PdfCraftApp::new(); - app.set_option("language", "en").unwrap(); - app.restore(r#"{"theme":"Dark"}"#); - assert_eq!(app.theme_preference, ThemePreference::Dark); - assert_eq!(app.theme, ThemeKind::Dark); - app.restore(r#"{"theme":"Light"}"#); - assert_eq!(app.theme_preference, ThemePreference::Light); - assert_eq!(app.theme, ThemeKind::Light); - app.restore(r#"{"theme":"System"}"#); - app.restore(r#"{"theme":"Purple"}"#); - assert_eq!(app.theme_preference, ThemePreference::System); + // What one app saves, another reads back. + let (mut h, c) = harness(); + ok(&mut h, &c, "ui.set", json!({"key": "theme", "value": "dark"})); + let snapshot = h.state().settings_snapshot(); + let (mut restored, rc) = harness_with(None, None, true); + restored.state_mut().apply_settings(&snapshot); + restored.run_steps(2); + assert_theme(&mut restored, &rc, "Dark", "Dark"); } +/// A theme command or option sent before the first frame takes effect on that frame. #[test] fn commands_and_options_apply_before_the_first_frame() { - let mut app = PdfCraftApp::new(); - app.set_option("language", "en").unwrap(); - app.run_command("view.theme.dark"); - assert_eq!(app.theme_preference, ThemePreference::Dark); - assert_eq!(app.theme, ThemeKind::Dark); - app.run_command("view.theme.system"); - assert_eq!(app.theme_preference, ThemePreference::System); - assert_eq!(app.theme, ThemeKind::Light); - // The existing palette/control toggle also goes through the preference setter. - app.run_command("view.theme"); - assert_eq!(app.theme_preference, ThemePreference::Dark); - assert_eq!(app.theme, ThemeKind::Dark); - app.run_command("view.theme.light"); - app.set_option("theme", "dark").unwrap(); - assert!(app.set_option("theme", "purple").unwrap_err().contains("light, dark, or system")); - assert_eq!(app.theme_preference, ThemePreference::Dark); - assert_eq!(app.theme, ThemeKind::Dark); + let (mut h, c) = harness_with(None, None, false); + let steps = [ + ("ui.command", json!({"id": "view.theme.dark"}), "Dark", "Dark"), + ("ui.command", json!({"id": "view.theme.system"}), "System", "Light"), + // The palette/control toggle goes through the same preference. + ("ui.command", json!({"id": "view.theme"}), "Dark", "Dark"), + ("ui.command", json!({"id": "view.theme.light"}), "Light", "Light"), + ("ui.set", json!({"key": "theme", "value": "dark"}), "Dark", "Dark"), + ]; + let mut waiting = Vec::new(); + for (method, params, ..) in &steps { + waiting.push(send(&c, method, params.clone())); + waiting.push(send(&c, "ui.state", json!({}))); + } + let refused = send(&c, "ui.set", json!({"key": "theme", "value": "purple"})); + let after = send(&c, "ui.state", json!({})); + h.step(); + for (pair, (.., preference, mode)) in waiting.chunks(2).zip(&steps) { + answer(&pair[0]).unwrap(); + let state = answer(&pair[1]).unwrap(); + assert_eq!(state["theme_preference"], *preference); + assert_eq!(state["theme"], *mode); + } + assert!(answer(&refused).unwrap_err().contains("light, dark, or system")); + assert_eq!(answer(&after).unwrap()["theme_preference"], "Dark"); + // The first frame itself drew with it. + assert_theme(&mut h, &c, "Dark", "Dark"); } #[test] fn restored_system_tracks_native_input_without_rewriting_saved_preference() { - let mut h = Harness::builder().with_size(egui::vec2(1100.0, 800.0)).build_eframe(|_cc| { - let mut app = PdfCraftApp::new(); - app.set_option("language", "en").unwrap(); - app.restore(r#"{"theme":"System"}"#); - app - }); + let (mut h, c) = harness_with(Some(r#"{"theme":"system"}"#), None, true); for (input, expected) in [ - (Some(egui::Theme::Dark), ThemeKind::Dark), - (Some(egui::Theme::Light), ThemeKind::Light), - (None, ThemeKind::Light), - (Some(egui::Theme::Dark), ThemeKind::Dark), + (Some(egui::Theme::Dark), "Dark"), + (Some(egui::Theme::Light), "Light"), + (None, "Light"), + (Some(egui::Theme::Dark), "Dark"), ] { h.input_mut().system_theme = input; h.run_steps(3); - assert_theme(&h, ThemePreference::System, expected); - assert_eq!(serde_json::from_str::(&h.state().persist()).unwrap()["theme"], "System"); + assert_theme(&mut h, &c, "System", expected); } - for (manual, expected) in [(ThemePreference::Light, ThemeKind::Light), (ThemePreference::Dark, ThemeKind::Dark)] { - h.state_mut().set_theme_preference(manual); + for (manual, expected) in [("light", "Light"), ("dark", "Dark")] { + ok(&mut h, &c, "ui.set", json!({"key": "theme", "value": manual})); for input in [Some(egui::Theme::Dark), Some(egui::Theme::Light), None] { h.input_mut().system_theme = input; h.run_steps(3); - assert_theme(&h, manual, expected); + assert_theme(&mut h, &c, expected, expected); } } -} - -#[test] -fn unknown_system_uses_light_after_a_manual_dark_choice() { - let mut app = PdfCraftApp::new(); - app.set_theme_preference(ThemePreference::Dark); - app.set_theme_preference(ThemePreference::System); - assert_eq!(app.theme, ThemeKind::Light); - assert_eq!(serde_json::from_str::(&app.persist()).unwrap()["theme"], "System"); -} - -#[test] -fn native_appearance_remains_inherited_for_every_saved_choice() { - #[derive(Clone)] - struct NativeCommands(std::sync::Arc>>); - impl egui::Plugin for NativeCommands { - fn debug_name(&self) -> &'static str { - "theme-command-proof" - } - fn output_hook(&mut self, _ctx: &egui::Context, output: &mut egui::FullOutput) { - for command in output.viewport_output.values().flat_map(|v| &v.commands) { - if let egui::ViewportCommand::SetTheme(theme) = command { - self.0.lock().unwrap().push(*theme); - } - } - } - } - for preference in [ThemePreference::System, ThemePreference::Light, ThemePreference::Dark] { - let commands = NativeCommands(Default::default()); - let observed = commands.clone(); - let mut h = Harness::builder().with_size(egui::vec2(1100.0, 800.0)).build_eframe(move |cc| { - cc.egui_ctx.add_plugin(commands); - let mut app = PdfCraftApp::new(); - app.set_option("language", "en").unwrap(); - app.set_theme_preference(preference); - app - }); - h.input_mut().system_theme = Some(egui::Theme::Light); - h.run_steps(3); - h.input_mut().system_theme = Some(egui::Theme::Dark); - h.run_steps(3); - // Observe the actual app's startup and later viewport output. This proves - // native window intent, not operating-system ThemeChanged delivery. - let commands = observed.0.lock().unwrap(); - assert!(!commands.is_empty()); - assert!(commands.iter().all(|theme| *theme == egui::SystemTheme::SystemDefault), "{commands:?}"); - assert_eq!(h.ctx.options(|o| o.theme_preference), egui::ThemePreference::System); - } + assert!(call(&mut h, &c, "ui.set", json!({"key": "theme", "value": "purple"})).is_err()); } /// Preferences ▸ Appearance: a theme card is a manual choice that the mode combo box shows and @@ -233,13 +211,13 @@ fn preferences_theme_cards_and_use_system_setting_stay_in_sync() { h.get_by(|n| n.role() == Role::ComboBox && n.value().is_some_and(|v| ["Use system setting", "Light", "Dark"].contains(&v.as_str()))); combo.value().unwrap_or_default() } - let mut h = harness(); + let (mut h, c) = harness(); h.get_by_label("Display theme: Use system setting").click_secondary(); h.run_steps(4); h.get_by_label("Appearance settings…").click(); h.run_steps(10); // A fresh install follows the OS (#1248), which is dark here. - assert_theme(&h, ThemePreference::System, ThemeKind::Dark); + assert_theme(&mut h, &c, "System", "Dark"); assert_eq!(mode_shown(&h), "Use system setting"); // The OS is dark: the Dark card picks Dark, and the combo box says so. @@ -248,7 +226,7 @@ fn preferences_theme_cards_and_use_system_setting_stay_in_sync() { h.run_steps(3); h.get_by_label("Dark theme").click(); h.run_steps(3); - assert_theme(&h, ThemePreference::Dark, ThemeKind::Dark); + assert_theme(&mut h, &c, "Dark", "Dark"); assert_eq!(mode_shown(&h), "Dark"); // The Light card itself, not its radio row, picks Light, and a dark OS doesn't undo it. h.get_by_label("Light theme").click(); @@ -257,7 +235,7 @@ fn preferences_theme_cards_and_use_system_setting_stay_in_sync() { h.run_steps(2); h.input_mut().system_theme = Some(egui::Theme::Dark); h.run_steps(2); - assert_theme(&h, ThemePreference::Light, ThemeKind::Light); + assert_theme(&mut h, &c, "Light", "Light"); assert_eq!(mode_shown(&h), "Light"); // Use system setting follows the OS both ways after a card choice. @@ -268,11 +246,11 @@ fn preferences_theme_cards_and_use_system_setting_stay_in_sync() { // Motion has a "Use system setting" radio of its own; this is the combo box's item. h.get_by_role_and_label(Role::Button, "Use system setting").click(); h.run_steps(3); - assert_theme(&h, ThemePreference::System, ThemeKind::Dark); + assert_theme(&mut h, &c, "System", "Dark"); assert_eq!(mode_shown(&h), "Use system setting"); h.input_mut().system_theme = Some(egui::Theme::Light); h.run_steps(3); - assert_theme(&h, ThemePreference::System, ThemeKind::Light); + assert_theme(&mut h, &c, "System", "Light"); // Only the Light card is marked Active while the OS is light. assert_eq!(h.query_all_by_label("Active").count(), 1); @@ -281,6 +259,6 @@ fn preferences_theme_cards_and_use_system_setting_stay_in_sync() { h.run_steps(3); h.get_by_label("Dark theme").click(); h.run_steps(3); - assert_theme(&h, ThemePreference::Dark, ThemeKind::Dark); + assert_theme(&mut h, &c, "Dark", "Dark"); assert_eq!(mode_shown(&h), "Dark"); } diff --git a/crates/ui-egui/tests/it/updates.rs b/crates/ui-egui/tests/it/updates.rs index f6c6c03bd0..23c4afc79d 100644 --- a/crates/ui-egui/tests/it/updates.rs +++ b/crates/ui-egui/tests/it/updates.rs @@ -1,36 +1,59 @@ -//! Help ▸ Check for updates (issue #28), with stand-in release sources (no network). +//! Help ▸ Check for updates (issue #28), with stand-in release sources (no network): the source is +//! the `CheckSource` given in the services the app is built with. +use std::path::PathBuf; use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; +use craft::host::Host; +use craft::ui::dialog::StackDialog; +use craft::update::stack_dialogs::{CheckChoice, UpdateCheckDialog, UpdatePromptDialog}; +use craft::update::updater::CheckSource; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; +use pdfcraft_engine::{Edit, FieldValue}; use pdfcraft_ui_egui::PdfCraftApp; -use pdfcraft_ui_egui::updates::UpdateSource; +use pdfcraft_ui_egui::settings::import_json; -fn release(tag: &str) -> craft_update::Release { - craft_update::Release { +use crate::control::{info, services_asking}; + +fn release(tag: &str) -> craft::update::Release { + craft::update::Release { tag: tag.to_string(), - version: craft_update::parse_version(tag), + version: craft::update::parse_version(tag), html_url: format!("https://github.com/storytold/pdfcraft/releases/tag/{tag}"), ..Default::default() } } /// `Ok(Some(tag))` is a newer release, `Ok(None)` is up to date. -fn source(answer: Result, &str>) -> UpdateSource { +fn source(answer: Result, &str>) -> CheckSource { let answer = answer.map(|tag| tag.map(release)).map_err(str::to_string); Arc::new(move || answer.clone()) } -fn harness(answer: Result, &str>) -> Harness<'static, PdfCraftApp> { - Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(move |_cc| { - let mut app = PdfCraftApp::new(); - app.set_option("language", "en").unwrap(); - app.set_update_source(source(answer)); - app +/// A source that counts the times it is asked and always offers `v99.0.0`. +fn counting_source(calls: &Arc) -> CheckSource { + let calls = calls.clone(); + Arc::new(move || { + calls.fetch_add(1, SeqCst); + Ok(Some(release("v99.0.0"))) }) } +/// An app on the default host whose update check asks `source`. +fn app_asking(source: CheckSource) -> PdfCraftApp { + let host = Arc::new(Host::builder(info()).build()); + let mut app = PdfCraftApp::with_host(host, services_asking(Some(source))); + app.set_option("language", "en").unwrap(); + app +} + +fn harness(answer: Result, &str>) -> Harness<'static, PdfCraftApp> { + let source = source(answer); + Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(move |_cc| app_asking(source)) +} + /// Run frames until the background check has reported. By what the dialog shows, with the /// same 30-second deadline as `support::wait_until`, not for a fixed second: under load the /// check's thread can take longer (#1277). @@ -47,12 +70,17 @@ fn settle(h: &mut Harness<'static, PdfCraftApp>) { h.run_steps(2); } +/// Whether an update dialog is on the host: the check's result or the prompt of a found release. +fn update_dialog_open(h: &Harness<'static, PdfCraftApp>) -> bool { + h.state().dialogs.is_open::() || h.state().dialogs.is_open::() +} + #[test] fn a_newer_release_is_offered_for_download() { #[cfg(target_os = "linux")] { const FIXTURE: &str = "PDFCRAFT_TEST_UPDATE_DOWNLOAD_FIXTURE"; - if craft_update::self_update::is_self_updating(&pdfcraft_ui_egui::UPDATE_APP) { + if craft::update::self_update::is_self_updating(&pdfcraft_ui_egui::UPDATE_APP) { assert!(std::env::var_os(FIXTURE).is_none(), "the fixture must be detected as a Cargo build"); // nextest's extracted archive can omit Cargo's metadata. Give the child a // private build directory with the marker the updater uses to identify it. @@ -66,7 +94,7 @@ fn a_newer_release_is_offered_for_download() { let output = std::process::Command::new(exe) .args(["--exact", "updates::a_newer_release_is_offered_for_download", "--nocapture"]) .env(FIXTURE, "1") - .env_remove(craft_update::self_update::DEV_VAR) + .env_remove(craft::update::self_update::DEV_VAR) .output() .unwrap(); assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); @@ -75,70 +103,22 @@ fn a_newer_release_is_offered_for_download() { } } let mut h = harness(Ok(Some("v99.0.0"))); - h.state_mut().execute("help.check_updates"); + assert!(h.state_mut().execute("help.check_updates")); settle(&mut h); - h.get_by_label_contains("PdfCraft 99.0.0 is available"); - h.get_by_label("DOWNLOAD"); - h.get_by_label("LATER").click(); + assert!(update_dialog_open(&h), "the found release is offered in a dialog"); + h.key_press(egui::Key::Escape); h.run_steps(3); - assert!(h.query_by_label_contains("is available").is_none(), "Later closes the dialog"); + assert!(!update_dialog_open(&h), "Escape closes the dialog"); } -#[test] -fn an_up_to_date_or_failed_check_says_so() { - let mut h = harness(Ok(None)); - h.state_mut().execute("help.check_updates"); - settle(&mut h); - h.get_by_label_contains("is the newest version available"); - assert!(h.query_by_label("Download").is_none()); - - let mut h = harness(Err("couldn't reach GitHub")); - h.state_mut().execute("help.check_updates"); - settle(&mut h); - h.get_by_label_contains("Could not check for updates."); - h.get_by_label_contains("couldn't reach GitHub"); -} - -#[test] -fn nothing_is_asked_until_the_user_checks() { - // The check at start is opt-in (the desktop app turns it on): the source is only called from the command. - let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); - let counted = calls.clone(); - let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(move |_cc| { - let mut app = PdfCraftApp::new(); - app.set_option("language", "en").unwrap(); - // Settings from a build that had the startup option are ignored. - app.restore(r#"{"check_updates_at_start": true}"#); - let counted = counted.clone(); - app.set_update_source(Arc::new(move || { - counted.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - Ok(Some(release("v99.0.0"))) - })); - app - }); - settle(&mut h); - assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 0); - assert!(h.query_by_label_contains("is available").is_none()); - h.state_mut().execute("help.check_updates"); - settle(&mut h); - assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1); - h.get_by_label_contains("PdfCraft 99.0.0 is available"); -} - -/// The desktop app's start, with `settings` restored, and the count of what the source was asked. -fn started_with(settings: &'static str) -> (Harness<'static, PdfCraftApp>, Arc) { - let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); - let counted = calls.clone(); +/// The desktop app's start, with `settings` applied, and the count of what the source was asked. +fn started_with(settings: &'static str) -> (Harness<'static, PdfCraftApp>, Arc) { + let calls = Arc::new(AtomicUsize::new(0)); + let source = counting_source(&calls); let h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(move |_cc| { - let mut app = PdfCraftApp::new(); - app.set_option("language", "en").unwrap(); + let mut app = app_asking(source); app.set_startup_update_check(true); - app.restore(settings); - let counted = counted.clone(); - app.set_update_source(Arc::new(move || { - counted.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - Ok(Some(release("v99.0.0"))) - })); + app.apply_settings(&import_json(settings).0); app }); (h, calls) @@ -146,18 +126,24 @@ fn started_with(settings: &'static str) -> (Harness<'static, PdfCraftApp>, Arc, calls: &std::sync::atomic::AtomicUsize, time: std::time::Duration) { +fn run_until_asked(h: &mut Harness<'static, PdfCraftApp>, calls: &AtomicUsize, time: std::time::Duration) { let deadline = std::time::Instant::now() + time; - while calls.load(std::sync::atomic::Ordering::SeqCst) == 0 && std::time::Instant::now() < deadline { + while calls.load(SeqCst) == 0 && std::time::Instant::now() < deadline { h.run_steps(2); std::thread::sleep(std::time::Duration::from_millis(5)); } } +/// Whether the settings the app would save have the check at start on; an app that saved no value +/// has the default, which is on. +fn check_at_start_saved(app: &PdfCraftApp) -> bool { + app.settings_snapshot().layout.update_check_at_start.unwrap_or(true) +} + #[test] fn the_preference_keeps_the_check_at_start_from_reaching_the_network() { - use std::sync::atomic::Ordering::SeqCst; - assert!(PdfCraftApp::new().update_check_at_start, "on by default"); + let calls = Arc::new(AtomicUsize::new(0)); + assert!(check_at_start_saved(&app_asking(counting_source(&calls))), "on by default"); // The same start with the preference left on does ask, so a count of none below means // the preference held the check back and not that it hadn't run yet. @@ -169,72 +155,95 @@ fn the_preference_keeps_the_check_at_start_from_reaching_the_network() { run_until_asked(&mut h, &calls, std::time::Duration::from_millis(500)); assert_eq!(calls.load(SeqCst), 0, "nothing is asked at start"); - let mut restarted = PdfCraftApp::new(); - restarted.restore(&h.state().persist()); - assert!(!restarted.update_check_at_start, "the choice is kept"); + let mut restarted = app_asking(source(Ok(None))); + restarted.apply_settings(&h.state().settings_snapshot()); + assert!(!check_at_start_saved(&restarted), "the choice is kept"); // Help ▸ Check for updates still asks. - h.state_mut().execute("help.check_updates"); + assert!(h.state_mut().execute("help.check_updates")); settle(&mut h); assert_eq!(calls.load(SeqCst), 1); - h.get_by_label_contains("PdfCraft 99.0.0 is available"); -} - -/// The setting is about starting: turning it on asks nothing until the next start. -#[test] -fn turning_the_check_at_start_on_waits_for_the_next_start() { - use std::sync::atomic::Ordering::SeqCst; - let (mut h, calls) = started_with(r#"{"update_check_at_start": false}"#); - h.run_steps(3); - h.state_mut().set_option("update_check_at_start", "true").unwrap(); - run_until_asked(&mut h, &calls, std::time::Duration::from_millis(500)); - assert_eq!(calls.load(SeqCst), 0, "nothing is asked this session"); -} - -#[test] -fn preferences_turn_the_check_at_start_off() { - let (mut h, _calls) = started_with(r#"{"update_check_at_start": true}"#); - // The check at start answers on its own thread; its prompt would take the click below. - later_on_the_startup_prompt(&mut h); - h.state_mut().execute("app.preferences"); - h.run_steps(3); - h.get_by_label("Check for updates when PdfCraft starts").click(); - h.run_steps(3); - assert!(!h.state().update_check_at_start); - // The control channel's option, as an agent sets it. - h.state_mut().set_option("update_check_at_start", "true").unwrap(); - assert!(h.state().update_check_at_start); - assert!(h.state_mut().set_option("update_check_at_start", "maybe").is_err()); + assert!(update_dialog_open(&h), "the release the source offered is on screen"); } #[test] fn settings_from_the_old_opt_in_leave_the_check_at_start_on() { - let mut app = PdfCraftApp::new(); - app.restore(r#"{"check_updates_at_start": false}"#); - assert!(app.update_check_at_start, "a key of the removed option decides nothing"); + let mut app = app_asking(source(Ok(None))); + app.apply_settings(&import_json(r#"{"check_updates_at_start": false}"#).0); + assert!(check_at_start_saved(&app), "a key of the removed option decides nothing"); + assert_ne!(app.settings_snapshot().layout.update_check_at_start, Some(false)); } -#[test] -fn the_check_at_start_offers_the_prompt_and_later_dismisses_it() { - let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(|_cc| { - let mut app = PdfCraftApp::new(); - app.set_option("language", "en").unwrap(); - app.set_update_source(source(Ok(Some("v99.0.0")))); - app.set_startup_update_check(true); - app - }); - later_on_the_startup_prompt(&mut h); - assert!(h.query_by_label_contains("is available").is_none(), "Later closes the prompt"); +/// An app with an unsaved change to a form in a new temporary folder, which Save writes without +/// asking where; its update check dialog is open. Returns the document's path too. +fn app_with_unsaved_file(test: &str) -> (Harness<'static, PdfCraftApp>, PathBuf) { + let dir = std::env::temp_dir().join(format!("pdfcraft-ui-updates-{test}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("source.pdf"); + let bytes = include_bytes!("../data/form.pdf").to_vec(); + std::fs::write(&path, &bytes).unwrap(); + let mut h = harness(Ok(None)); + h.run_steps(2); + let app = h.state_mut(); + app.open_bytes("source.pdf", Some(path.to_string_lossy().into_owned()), bytes).unwrap(); + assert!(app.apply_edit(Edit::SetFieldValue { name: "name".into(), value: FieldValue::Text("Changed".into()) })); + assert!(h.state_mut().execute("help.check_updates")); + settle(&mut h); + assert!(h.state().dialogs.is_open::(), "the check's result is on screen"); + (h, path) } -/// Waits for the check at start to offer its prompt, then answers Later. -fn later_on_the_startup_prompt(h: &mut Harness<'static, PdfCraftApp>) { - let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); - while h.query_by_label_contains("is available").is_none() { - h.run_steps(2); - assert!(std::time::Instant::now() < deadline, "timed out waiting for the startup prompt"); - std::thread::sleep(std::time::Duration::from_millis(5)); - } - h.get_by_label("LATER").click(); +/// Answers the open check dialog with Restart to Update, as its button does. +fn restart_to_update(h: &mut Harness<'static, PdfCraftApp>) { + let dialog = h.state_mut().dialogs.get_mut::().expect("the check dialog is open"); + dialog.set_choice(CheckChoice::RestartToUpdate); + let id = dialog.id(); + let ctx = h.ctx.clone(); + assert!(h.state_mut().dialogs.confirm_by_id(&ctx, id)); h.run_steps(3); } + +/// Presses the button `label` of the question on screen: the last match, since the question draws +/// over the toolbar's own buttons. +fn press_in_the_question(h: &mut Harness<'static, PdfCraftApp>, label: &str) { + h.query_all_by_label(label).last().unwrap_or_else(|| panic!("the question has a {label} button")).click(); + h.run_steps(3); +} + +fn close_requested(h: &Harness<'static, PdfCraftApp>) -> bool { + h.output().viewport_output.values().any(|v| v.commands.iter().any(|c| matches!(c, egui::ViewportCommand::Close))) +} + +/// A ready update whose Restart to Update meets unsaved work asks about it first, and Cancel keeps +/// the app open with its document still unsaved. +#[test] +fn restart_to_update_with_unsaved_changes_asks_first_and_cancel_keeps_the_app() { + let (mut h, path) = app_with_unsaved_file("cancel"); + restart_to_update(&mut h); + assert!(!h.state().dialogs.is_open::(), "the result dialog closes"); + assert!(!h.state().dialogs.open_dialogs().is_empty(), "the unsaved-changes question is on the host"); + press_in_the_question(&mut h, "Cancel"); + assert!(h.state().dialogs.open_dialogs().is_empty(), "Cancel closes the question"); + assert!(!close_requested(&h), "Cancel keeps the app open"); + assert!(h.state().first_dirty().is_some(), "the change is still unsaved"); + let _ = std::fs::remove_dir_all(path.parent().unwrap()); +} + +/// Saving at the question writes the edited file, and the app then quits. +#[test] +fn saving_at_the_restart_question_writes_the_file_and_quits() { + let (mut h, path) = app_with_unsaved_file("save"); + restart_to_update(&mut h); + assert!(!h.state().dialogs.open_dialogs().is_empty(), "the unsaved-changes question is on the host"); + press_in_the_question(&mut h, "Save"); + let quit = crate::support::step_until(&mut h, |h| close_requested(h)); + assert!(quit, "the app quits once the document is saved"); + + let mut reopened = crate::control::new_app(); + reopened.open_bytes("source.pdf", Some(path.to_string_lossy().into_owned()), std::fs::read(&path).unwrap()).unwrap(); + let doc = reopened.session.get(reopened.views[0].id).unwrap(); + let name = doc.form.iter().find(|f| f.name == "name").and_then(|f| f.value.first().cloned()); + assert_eq!(name.as_deref(), Some("Changed"), "the change is in the file"); + let _ = std::fs::remove_dir_all(path.parent().unwrap()); +} diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 69e78702fc..8dc7db7d46 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -178,7 +178,7 @@ milestone = "M1" status = "shipped" commands = ["file.open"] tools = ["doc_open"] -evidence = ["crates/ui-egui/tests/it/editing.rs::password_prompt_opens_and_security_tab_reports_the_details", "craft-pdf::crypt/tests.rs::empty_user_password_opens_without_asking", "crates/ui-egui/src/platform/open_worker/tests.rs::a_chosen_tool_survives_wrong_password_retry_and_runs_after_unlock", "crates/ui-egui/src/platform/open_worker/tests.rs::startup_intake_waits_for_local_authentication_and_keeps_its_own_background_password_prompt", "crates/ui-egui/tests/it/pickers.rs::the_open_password_can_be_typed_through_an_input_method_however_the_file_is_opened"] +evidence = ["crates/ui-egui/tests/it/editing.rs::password_prompt_opens_and_security_tab_reports_the_details", "craft-pdf::crypt/tests.rs::empty_user_password_opens_without_asking", "crates/ui-egui/src/platform/open_worker/tests.rs::a_chosen_tool_survives_wrong_password_retry_and_runs_after_unlock", "crates/ui-egui/src/platform/open_worker/tests.rs::startup_intake_waits_for_local_authentication_and_keeps_its_own_background_password_prompt"] notes = "the field takes typing through the platform input method, which typed keys go through on Linux, however the file was opened (#2818); checked with synthetic input-method events, not on a Linux desktop" [[feature]] @@ -202,7 +202,7 @@ milestone = "M1" status = "shipped" commands = ["protect.unlock"] tools = ["doc_open"] -evidence = ["crates/engine/src/tests.rs::restricted_documents_refuse_changes_unless_opened_by_the_owner", "crates/engine/src/tests.rs::owner_password_of_older_revisions_opens_the_viewer_too", "crates/engine/src/tests.rs::render_password_for_recovers_the_user_password_of_older_revisions", "apps/pdfcraft-cli/tests/it/owner_password.rs::info_accepts_the_owner_password", "apps/pdfcraft-cli/tests/it/owner_password.rs::text_accepts_the_owner_password", "craft-pdf::crypt/tests.rs::owner_authentication_recovers_the_user_password", "crates/engine/src/tests.rs::the_permissions_password_unlocks_an_open_document", "crates/ui-egui/tests/it/editing.rs::the_security_notice_unlocks_with_the_permissions_password", "crates/ui-egui/tests/it/editing.rs::remove_security_asks_for_the_permissions_password_first", "crates/ui-egui/tests/it/pickers.rs::the_permissions_password_can_be_typed_through_an_input_method"] +evidence = ["crates/engine/src/tests.rs::restricted_documents_refuse_changes_unless_opened_by_the_owner", "crates/engine/src/tests.rs::owner_password_of_older_revisions_opens_the_viewer_too", "crates/engine/src/tests.rs::render_password_for_recovers_the_user_password_of_older_revisions", "apps/pdfcraft-cli/tests/it/owner_password.rs::info_accepts_the_owner_password", "apps/pdfcraft-cli/tests/it/owner_password.rs::text_accepts_the_owner_password", "craft-pdf::crypt/tests.rs::owner_authentication_recovers_the_user_password", "crates/engine/src/tests.rs::the_permissions_password_unlocks_an_open_document", "crates/ui-egui/tests/it/editing.rs::the_security_notice_unlocks_with_the_permissions_password", "crates/ui-egui/tests/it/editing.rs::remove_security_asks_for_the_permissions_password_first"] notes = "at open (the password prompt takes either password), or after opening a restricted file that needed no password (#995, #1077): Unlock… on the security notice and in Properties ▸ Security, and changing security asks for it first. The CLI's info, text, render and audit take either password too (#2670). Not yet: an automation tool to unlock an open document (reopen with doc_open and the password instead)" [[feature]] @@ -286,8 +286,8 @@ milestone = "M1" status = "shipped" commands = ["file.save"] tools = ["doc_save"] -evidence = ["crates/platform/src/staging/tests.rs::atomic_saves_keep_finder_tags_and_binary_extended_attributes", "crates/platform/src/staging/tests.rs::a_growing_resource_fork_refuses_publication_and_keeps_original", "crates/automation/tests/it/automation.rs::saving_a_pdf_keeps_the_destinations_extended_attributes", "crates/automation/tests/it/automation.rs::a_metadata_preservation_error_keeps_the_pdf_and_unsaved_edit", "crates/ui-egui/tests/it/editing.rs::save_writes_an_incremental_update_and_clears_dirty", "crates/engine/src/tests.rs::save_is_incremental_stamps_mod_date_and_rebases", "crates/organize/src/tests.rs::successive_incremental_saves_stack_revisions", "crates/automation/src/tests.rs::staging_never_writes_through_a_file_planted_at_its_name", "crates/ui-egui/src/editing/tests.rs::saving_never_writes_through_a_file_planted_at_the_staging_name"] -notes = "The atomic write stages to a new, randomly named file created with create_new, so a file or link planted at the staging path is never written through (desktop app, automation and CLI). On macOS, accessible destination xattrs (including Finder tags) are copied before flush/rename; errors, metadata limits or a changed post-read size refuse the save without replacing the file. System-managed provenance is excluded. Permissions, ACLs, hard-link identity and creation dates are not preserved by this change (#2658)." +evidence = ["crates/automation/tests/it/automation.rs::saving_a_pdf_keeps_the_destinations_extended_attributes", "crates/automation/tests/it/automation.rs::a_metadata_preservation_error_keeps_the_pdf_and_unsaved_edit", "crates/ui-egui/tests/it/editing.rs::save_writes_an_incremental_update_and_clears_dirty", "crates/engine/src/tests.rs::save_is_incremental_stamps_mod_date_and_rebases", "crates/organize/src/tests.rs::successive_incremental_saves_stack_revisions", "apps/pdfcraft-cli/tests/it/edit.rs::editing_in_place_leaves_a_valid_file_and_no_staging_file"] +notes = "The atomic write is the shared craft_atomic writer: it stages to a new, randomly named file, so a file or link planted at the staging path is never written through (desktop app, automation and CLI). On macOS, accessible destination xattrs (including Finder tags) are copied before flush/rename; errors, metadata limits or a changed post-read size refuse the save without replacing the file. System-managed provenance is excluded. Permissions, ACLs, hard-link identity and creation dates are not preserved by this change (#2658)." [[feature]] id = "core.save-as-full-rewrite" @@ -346,8 +346,8 @@ milestone = "M1" status = "shipped" commands = [] tools = [] -evidence = ["crates/cos/tests/it/encryption.rs::qpdf_agrees", "crates/cos/tests/it/writer.rs::qpdf_accepts_object_stream_output", "crates/platform/src/staging/tests.rs::an_atomic_write_replaces_the_target_only_when_complete", "apps/pdfcraft-cli/tests/it/edit.rs::editing_in_place_leaves_a_valid_file_and_no_staging_file", "crates/automation/tests/it/automation.rs::a_root_less_write_output_is_atomic_too"] -notes = "qpdf is installed on the Linux CI runner and PDFCRAFT_ORACLES_REQUIRED makes its absence a failure, so these run on every CI run rather than skipping; on a machine without qpdf they skip with a notice (crates/oracle). Every PDF leaves the engine checked (it reopens with its pages): saves, new files from Combine/Extract/Split/Create, signed, timestamped and LTV-embedded files, OCR batch output; and every writer goes through one staging-file writer (the desktop app, the tools with or without --root, the CLI), so a failed write never leaves a truncated file (#1698, #2166)" +evidence = ["crates/cos/tests/it/encryption.rs::qpdf_agrees", "crates/cos/tests/it/writer.rs::qpdf_accepts_object_stream_output", "apps/pdfcraft-cli/tests/it/edit.rs::editing_in_place_leaves_a_valid_file_and_no_staging_file", "crates/automation/tests/it/automation.rs::a_root_less_write_output_is_atomic_too"] +notes = "qpdf is installed on the Linux CI runner and PDFCRAFT_ORACLES_REQUIRED makes its absence a failure, so these run on every CI run rather than skipping; on a machine without qpdf they skip with a notice (crates/oracle). Every PDF leaves the engine checked (it reopens with its pages): saves, new files from Combine/Extract/Split/Create, signed, timestamped and LTV-embedded files, OCR batch output; and every writer goes through the shared atomic writer (the desktop app, the tools with or without --root, the CLI), so a failed write never leaves a truncated file (#1698, #2166)" [[feature]] id = "core.deterministic-save" @@ -550,7 +550,7 @@ milestone = "M4" status = "shipped" commands = [] tools = [] -evidence = ["crates/ui-egui/tests/it/recovery.rs::a_crashed_session_is_offered_and_recovered_unsaved", "crates/ui-egui/tests/it/recovery.rs::discarding_removes_the_autosaves", "crates/ui-egui/tests/it/recovery.rs::a_running_instances_autosaves_are_not_offered_to_a_second_instance", "crates/engine/src/tests.rs::recovered_documents_reopen_unsaved_at_their_original_path", "crates/ui-egui/src/persist/recovery.rs::the_first_save_after_recovering_asks_instead_of_writing_the_sidecars_path", "crates/ui-egui/src/persist/recovery.rs::an_oversized_sidecar_is_not_read", "crates/ui-egui/src/persist/recovery.rs::a_snapshot_that_is_not_a_regular_file_is_refused_at_once"] +evidence = ["crates/ui-egui/tests/it/recovery.rs::a_crashed_session_is_offered_and_recovered_unsaved", "crates/ui-egui/tests/it/recovery.rs::discarding_removes_the_autosaves", "crates/engine/src/tests.rs::recovered_documents_reopen_unsaved_at_their_original_path", "crates/ui-egui/src/persist/recovery.rs::the_first_save_after_recovering_asks_instead_of_writing_the_sidecars_path"] notes = "A recovered document keeps its original path only as a suggestion: the first Save asks where, starting there, and the file chosen is its file from then on, since anyone who can write the recovery folder can name any file in a sidecar (#3923); sidecars longer than 64 KiB are not read, and their snapshot is offered without metadata. A running instance holds an exclusively locked instance file in the recovery folder and names it in its snapshots, so a second instance neither offers nor discards what the first is autosaving (#2166); the OS releases the lock when the process dies. Where the folder can't be written or the platform has no file locks, snapshots are offered as before." [[feature]] @@ -586,7 +586,7 @@ milestone = "M4" status = "shipped" commands = ["file.close"] tools = ["doc_close"] -evidence = ["crates/ui-egui/tests/it/editing.rs::closing_a_dirty_tab_asks_and_cancel_keeps_it", "crates/ui-egui/tests/it/editing.rs::closing_a_dirty_tab_can_save_first", "crates/ui-egui/tests/it/editing.rs::quitting_with_unsaved_changes_asks_for_each_document", "crates/ui-egui/tests/it/editing.rs::save_prompt_stays_inside_the_screen_for_a_long_filename", "crates/ui-egui/tests/it/editing.rs::the_save_prompt_moves_between_buttons_with_the_keyboard", "crates/ui-egui/tests/it/editing.rs::the_save_prompt_escape_still_cancels_whatever_is_chosen", "crates/ui-egui/tests/it/editing.rs::the_save_prompt_starts_on_save_every_time_it_opens", "crates/ui-egui/tests/it/editing.rs::a_save_prompt_opened_in_the_background_asks_for_attention_until_the_user_returns", "crates/ui-egui/tests/it/control.rs::a_save_prompt_answered_in_the_background_withdraws_its_attention_request"] +evidence = ["crates/ui-egui/tests/it/editing.rs::closing_a_dirty_tab_asks_and_cancel_keeps_it", "crates/ui-egui/tests/it/editing.rs::closing_a_dirty_tab_can_save_first", "crates/ui-egui/tests/it/editing.rs::quitting_with_unsaved_changes_asks_for_each_document", "crates/ui-egui/tests/it/editing.rs::save_prompt_stays_inside_the_screen_for_a_long_filename", "crates/ui-egui/tests/it/editing.rs::the_save_prompt_moves_between_buttons_with_the_keyboard", "crates/ui-egui/tests/it/editing.rs::the_save_prompt_escape_still_cancels_whatever_is_chosen", "crates/ui-egui/tests/it/editing.rs::the_save_prompt_starts_on_save_every_time_it_opens", "crates/ui-egui/tests/it/editing.rs::a_save_prompt_opened_in_the_background_asks_for_attention_until_the_user_returns"] notes = "Save is chosen when the prompt opens, so Enter saves. Left/Right (and Up/Down) and Tab/Shift+Tab move the choice between Don't save, Cancel and Save, shown with a focus ring; Enter or Space press the chosen button; Escape cancels. Alt+D, Alt+N and Ctrl/Cmd+D still answer Don't save. A prompt that opens while PdfCraft is in the background (Quit in the Dock menu, logging out, an agent's ui.quit) asks once for the user's attention, as a critical request: the Dock icon bounces until PdfCraft is active, the Windows taskbar button flashes until the window is in front, and X11 sets the urgency hint; coming back or answering withdraws it. Not yet: the same keys on the other confirmations (Revert, reload, overwrite); the other confirmations don't ask for attention; on macOS a prompt answered without coming back (over the control channel) leaves the Dock icon bouncing until PdfCraft is activated, because winit can't withdraw the request there." [[feature]] @@ -682,7 +682,7 @@ milestone = "M3" status = "shipped" commands = ["file.open_recent", "file.clear_recent"] tools = [] -evidence = ["crates/ui-egui/tests/it/ui.rs::persistence_round_trips_and_tolerates_garbage", "crates/ui-egui/tests/it/commands.rs::the_open_recent_menu_lists_files_and_opens_one", "crates/ui-egui/tests/it/commands.rs::the_open_recent_menu_is_disabled_while_the_list_is_empty", "crates/ui-egui/tests/it/commands.rs::clear_recent_files_at_the_foot_of_open_recent_empties_the_list", "crates/ui-egui/tests/it/commands.rs::clear_recent_files_runs_from_the_palette_and_is_saved", "crates/ui-egui/tests/it/ui.rs::home_removes_one_recent_file_or_clears_them_all", "crates/ui-egui/tests/it/ui.rs::home_recent_context_menu_reveals_the_target_without_opening_or_removing_it"] +evidence = ["crates/ui-egui/tests/it/ui.rs::persistence_round_trips_and_tolerates_garbage", "crates/ui-egui/tests/it/commands.rs::the_open_recent_menu_lists_files_and_opens_one", "crates/ui-egui/tests/it/commands.rs::clear_recent_files_runs_from_the_palette_and_is_saved", "crates/ui-egui/tests/it/ui.rs::home_removes_one_recent_file_or_clears_them_all", "crates/ui-egui/tests/it/ui.rs::home_recent_context_menu_reveals_the_target_without_opening_or_removing_it"] notes = "never reads other apps' lists; File ▸ Open Recent lists them (#290), an already-open file focuses its tab instead of reopening it, from any open path (#1620); Clear Recent Files at the foot of Open Recent, on Home and in the palette, and a remove button on each Home row (#430); native Home rows offer Reveal in Finder / File Explorer through their context menu (#5452), reusing tab reveal without opening or removing the file (browser has no local file manager); missing: the row's remove button shows on pointer hover only (keyboard users clear the whole list)" [[feature]] @@ -694,7 +694,7 @@ milestone = "M3" status = "shipped" commands = [] tools = [] -evidence = ["crates/ui-egui/tests/it/editing.rs::the_last_session_reopens_its_files_pages_and_active_tab", "crates/ui-egui/tests/it/editing.rs::quitting_with_unsaved_changes_still_remembers_every_file", "crates/ui-egui/tests/it/editing.rs::the_last_session_is_off_by_default_and_skips_missing_and_duplicate_files", "crates/ui-egui/src/persist/last_session.rs::malformed_sessions_are_skipped_and_capped"] +evidence = ["crates/ui-egui/tests/it/editing.rs::the_last_session_reopens_its_files_pages_and_active_tab", "crates/ui-egui/tests/it/editing.rs::quitting_with_unsaved_changes_still_remembers_every_file", "crates/ui-egui/tests/it/editing.rs::the_last_session_is_off_by_default_and_skips_missing_and_duplicate_files"] notes = "Desktop, off by default (Preferences ▸ Documents and view, #442): the files open when PdfCraft last closed reopen at the page each showed, with the same tab in front; files named on the command line open after them, in front; files that are gone, and documents the Recovery dialog offers, are skipped. Quitting with unsaved changes still remembers every tab. Zoom and page display come back through core.restore-last-view (#1767); not yet the scroll position within the page (#418); only the first encrypted file asks for its password (later ones stay closed), and a file opened after it dismisses that prompt; a save that fails partway through a quit can leave the remembered list from that quit; never-saved documents and the web build have no paths to reopen." [[feature]] @@ -938,7 +938,7 @@ milestone = "M3" status = "partial" commands = [] tools = [] -evidence = ["crates/ui-egui/tests/it/control.rs::middle_click_autoscroll_latches_has_a_dead_zone_and_scrolls_both_directions", "crates/ui-egui/tests/it/control.rs::organize_pages_supports_autoscroll_without_selecting_or_reordering_pages", "crates/ui-egui/tests/it/control.rs::moving_before_middle_button_release_keeps_scrolling_without_starting_page_tools", "crates/ui-egui/tests/it/control.rs::farther_from_the_click_scrolls_faster_in_the_viewer_and_page_grid", "crates/ui-egui/tests/it/control.rs::autoscroll_uses_the_initial_click_position_when_input_arrives_in_one_frame", "crates/ui-egui/tests/it/control.rs::autoscroll_uses_elapsed_frame_time_and_preserves_fractional_motion_in_both_views", "crates/ui-egui/tests/it/control.rs::middle_button_pans_while_held_outside_linux", "crates/ui-egui/tests/it/comments.rs::a_middle_drag_with_a_drawing_tool_scrolls_instead_of_drawing", "crates/ui-egui/tests/it/control.rs::inverted_middle_drag_moves_the_view_the_way_the_pointer_goes", "crates/ui-egui/tests/it/viewer.rs::the_invert_middle_drag_preference_is_off_by_default_and_kept_in_the_settings"] +evidence = ["crates/ui-egui/tests/it/control.rs::middle_click_autoscroll_latches_has_a_dead_zone_and_scrolls_both_directions", "crates/ui-egui/tests/it/control.rs::moving_before_middle_button_release_keeps_scrolling_without_starting_page_tools", "crates/ui-egui/tests/it/control.rs::autoscroll_uses_the_initial_click_position_when_input_arrives_in_one_frame", "crates/ui-egui/tests/it/control.rs::autoscroll_uses_elapsed_frame_time_and_preserves_fractional_motion_in_both_views", "crates/ui-egui/tests/it/control.rs::middle_button_pans_while_held_outside_linux", "crates/ui-egui/tests/it/comments.rs::a_middle_drag_with_a_drawing_tool_scrolls_instead_of_drawing", "crates/ui-egui/tests/it/control.rs::inverted_middle_drag_moves_the_view_the_way_the_pointer_goes", "crates/ui-egui/tests/it/viewer.rs::the_invert_middle_drag_preference_is_off_by_default_and_kept_in_the_settings"] notes = "Linux-only middle-button vertical autoscroll in the document and Organize Pages; Windows and macOS pan 1:1 while the middle button is held (Grabbing cursor, no latch). On every target the middle button never reaches the page tools, so it scrolls instead of drawing, selecting, cropping or moving. Click to toggle, release keeps scrolling on, and a Chromium-style nonlinear curve increases speed with vertical screen distance from the initial click. A 15-point dead zone pauses immediately. Continuous redraws use elapsed frame time and preserve fractional movement, tested at 30/60/120/144 fps. Cancels on another middle click, Escape, other pointer/wheel input, focus loss, tab changes and dialogs. Preferences ▸ Invert middle-button drag (off by default, saved; ui.set invert_middle_drag) reverses the direction of both the pan and the auto-scroll (#5790); it changes direction only, not which of the two a platform uses. Driven headlessly through the opt-in UI control channel (ui.click/ui.move/ui.drag). Keyboard-started timed scrolling is not implemented." [[feature]] @@ -950,7 +950,7 @@ milestone = "M3" status = "shipped" commands = [] tools = [] -evidence = ["crates/ui-egui/tests/it/ui.rs::zoom_keeps_the_point_under_the_cursor_still", "crates/ui-egui/tests/it/ui.rs::trackpad_pinch_zooms_the_pdf_under_the_pointer"] +evidence = ["crates/ui-egui/tests/it/ui.rs::trackpad_pinch_zooms_the_pdf_under_the_pointer"] notes = "A trackpad pinch zooms the PDF beneath the pointer in either direction, keeping the same page point in place. The viewer handles the platform's zoom gesture where it is available." [[feature]] @@ -1106,7 +1106,7 @@ milestone = "M3" status = "shipped" commands = ["view.read_mode"] tools = [] -evidence = ["crates/ui-egui/tests/it/control.rs::inspect_and_click_by_label_and_id", "crates/ui-egui/tests/it/commands.rs::every_registered_command_is_implemented", "crates/ui-egui/tests/it/ui.rs::the_mode_bar_has_no_read_tab", "crates/ui-egui/tests/it/view.rs::switching_modes_keeps_the_current_page_at_fixed_zoom"] +evidence = ["crates/ui-egui/tests/it/commands.rs::every_registered_command_is_implemented","crates/ui-egui/tests/it/view.rs::switching_modes_keeps_the_current_page_at_fixed_zoom"] notes = "View ▸ Read mode (and the Read mode workspace) hides the panes and tool chrome. The mode bar has no Read tab, as in Acrobat, where reading is the viewer with no tool in use: its tabs are All tools, Edit, Convert and E-Sign. Switching between Read and the docking workspace preserves the document’s current scroll position at fixed zoom; each tab keeps its own position" [[feature]] @@ -1118,7 +1118,7 @@ milestone = "M3" status = "shipped" commands = ["view.full_screen"] tools = [] -evidence = ["crates/ui-egui/tests/it/commands.rs::full_screen_toggles_by_shortcut_and_command_and_escape_leaves", "crates/ui-egui/tests/it/view.rs::full_screen_shows_one_fitted_page_and_clicks_turn_it", "crates/ui-egui/tests/it/view.rs::full_screen_keeps_two_page_view_as_spreads", "crates/ui-egui/tests/it/view.rs::full_screen_right_click_goes_back_a_page", "crates/ui-egui/tests/it/view.rs::full_screen_shift_enter_goes_back_a_page", "crates/ui-egui/tests/it/view.rs::full_screen_hides_a_still_pointer"] +evidence = ["crates/ui-egui/tests/it/commands.rs::platform_split_chords_fire_their_commands","crates/ui-egui/tests/it/view.rs::full_screen_shows_one_fitted_page_and_clicks_turn_it", "crates/ui-egui/tests/it/view.rs::full_screen_keeps_two_page_view_as_spreads", "crates/ui-egui/tests/it/view.rs::full_screen_right_click_goes_back_a_page", "crates/ui-egui/tests/it/view.rs::full_screen_shift_enter_goes_back_a_page", "crates/ui-egui/tests/it/view.rs::full_screen_hides_a_still_pointer"] notes = "Acrobat's Full Screen Mode (#1459): the page on black and nothing else, one page at a time fitted to the screen (one spread when two-page view was on, #1353), from the current page; a click, Space, Enter, \u2192 or Page Down go forward, a shift-click, a right-click (no context menu in full screen), Shift+Enter, Backspace, \u2190 or Page Up back, Home/End to the ends; Esc or \u2318L bring the display from before back at the page reached. Links still open on click. The pointer hides after three still seconds. Transitions and display times: view.full-screen-presentation. Missing: loop after the last page, and full-screen preferences such as the background colour" [[feature]] @@ -1154,7 +1154,7 @@ milestone = "M3" status = "shipped" commands = [] tools = [] -evidence = ["crates/ui-egui/tests/it/control.rs::state_and_view_options", "crates/ui-egui/tests/it/ui.rs::theme_and_view_options_apply", "crates/ui-egui/tests/it/viewer.rs::two_page_view_steps_a_spread_at_a_time", "crates/ui-egui/tests/it/viewer.rs::arrow_and_page_keys_move_through_a_scrolling_document", "crates/ui-egui/tests/it/viewer.rs::left_and_right_scroll_a_page_wider_than_the_window_before_turning_it", "crates/ui-egui/tests/it/viewer.rs::end_shows_the_bottom_of_the_last_page"] +evidence = ["crates/ui-egui/tests/it/control.rs::ui_set_keys_change_what_ui_state_reports", "crates/ui-egui/tests/it/ui.rs::theme_and_view_options_apply","crates/ui-egui/tests/it/viewer.rs::two_page_view_steps_a_spread_at_a_time", "crates/ui-egui/tests/it/viewer.rs::arrow_and_page_keys_move_through_a_scrolling_document", "crates/ui-egui/tests/it/viewer.rs::left_and_right_scroll_a_page_wider_than_the_window_before_turning_it", "crates/ui-egui/tests/it/viewer.rs::end_shows_the_bottom_of_the_last_page"] notes = "in two-page view, next and previous page move a whole spread (with or without a cover page); → / ← turn pages in every layout (on a page wider than the window, a plan zoomed in, they scroll sideways a line first and turn the page at its edge; ⌘→ / ⌘← turn at once), ↓ / ↑ scroll a line and Page Down / Page Up a screen (the page in single-page view), as in Acrobat; in single-page view ↓ / ↑ turn the page once there is nothing left to scroll that way, like the wheel; Home shows the first page's top and End the end of the document, the last page down to its bottom edge; Shift+Ctrl (Shift+⌘ on macOS) with ↑ / ↓ or Page Up / Page Down do the same as Home and End (Shift+Ctrl+Page Up / Page Down used to turn one page, like Ctrl+Page Up / Page Down)" [[feature]] @@ -1238,7 +1238,7 @@ milestone = "M3" status = "shipped" commands = ["view.next_tab", "view.previous_tab"] tools = ["doc_list"] -evidence = ["crates/ui-egui/tests/it/editing.rs::combining_files_opens_a_new_unsaved_tab", "crates/ui-egui/tests/it/control.rs::state_and_view_options", "crates/ui-egui/tests/it/viewer.rs::each_document_keeps_its_own_scroll_position", "crates/ui-egui/tests/it/viewer.rs::a_new_document_opens_at_the_top_after_a_relaunch", "crates/ui-egui/tests/it/ui.rs::dragging_a_tab_moves_it_and_keeps_the_same_document_active", "crates/ui-egui/tests/it/ui.rs::a_tab_dropped_where_it_was_stays_and_a_click_still_selects_it", "crates/ui-egui/tests/it/ui.rs::the_combine_tab_does_not_move_and_documents_stay_in_order", "crates/ui-egui/tests/it/commands.rs::ctrl_tab_steps_through_the_tabs_in_order_and_wraps_around"] +evidence = ["crates/ui-egui/tests/it/editing.rs::combining_files_opens_a_new_unsaved_tab", "crates/ui-egui/tests/it/control.rs::ui_set_keys_change_what_ui_state_reports", "crates/ui-egui/tests/it/viewer.rs::each_document_keeps_its_own_scroll_position", "crates/ui-egui/tests/it/viewer.rs::a_new_document_opens_at_the_top_after_a_relaunch", "crates/ui-egui/tests/it/ui.rs::dragging_a_tab_moves_it_and_keeps_the_same_document_active", "crates/ui-egui/tests/it/ui.rs::a_tab_dropped_where_it_was_stays_and_a_click_still_selects_it", "crates/ui-egui/tests/it/ui.rs::the_combine_tab_does_not_move_and_documents_stay_in_order", "crates/ui-egui/tests/it/commands.rs::platform_split_chords_fire_their_commands"] notes = "each tab keeps its own scroll position (#189), and a newly opened one starts at the top, not where an earlier session left the scroll. Document tabs are dragged to reorder them (#1537): a line marks where the tab will land, the strip scrolls at its edges when it overflows, and the same document stays active; the Combine files tab stays after the documents. Dragging a tab out into its own window is view.multiple-windows. Ctrl+Tab and Ctrl+Shift+Tab (⌃Tab and ⌃⇧Tab on macOS; View ▸ Next tab / Previous tab) step through the tabs in their order on screen, Combine files included, and wrap around at either end (#1542)." [[feature]] @@ -1286,7 +1286,7 @@ milestone = "M3" status = "shipped" commands = [] tools = [] -evidence = ["crates/ui-egui/tests/it/editing.rs::resized_pages_panel_thumbnails_reorder_multiple_pages_and_undo", "crates/ui-egui/tests/it/viewer.rs::pages_panel_thumbnail_zoom_is_bounded_independent_and_survives_reload", "crates/ui-egui/tests/it/viewer.rs::pages_panel_thumbnail_size_controls_show_more_pages_and_keep_the_selection", "crates/ui-egui/tests/it/viewer.rs::pages_panel_thumbnail_zoom_keeps_a_far_current_page_visible", "crates/ui-egui/tests/it/control.rs::thumbnail_size_is_settable_and_inspectable_through_the_control_channel", "crates/ui-egui/tests/it/ui.rs::theme_and_view_options_apply", "crates/ui-egui/tests/it/viewer.rs::going_to_a_far_page_scrolls_its_thumbnail_into_view", "crates/ui-egui/tests/it/viewer.rs::going_to_a_page_in_view_leaves_the_pages_panel_still", "crates/ui-egui/tests/it/viewer.rs::a_page_change_while_thumbnails_are_dragged_does_not_scroll_the_pages_panel", "crates/ui-egui/tests/it/view.rs::the_pages_panel_tools_act_on_the_selected_pages", "crates/ui-egui/tests/it/view.rs::the_pages_panel_tools_insert_from_a_file_and_extract", "crates/ui-egui/tests/it/view.rs::the_pages_panel_tools_are_off_without_page_editing_permission"] +evidence = ["crates/ui-egui/tests/it/editing.rs::resized_pages_panel_thumbnails_reorder_multiple_pages_and_undo", "crates/ui-egui/tests/it/viewer.rs::pages_panel_thumbnail_zoom_is_bounded_independent_and_survives_reload", "crates/ui-egui/tests/it/viewer.rs::pages_panel_thumbnail_size_controls_show_more_pages_and_keep_the_selection", "crates/ui-egui/tests/it/viewer.rs::pages_panel_thumbnail_zoom_keeps_a_far_current_page_visible", "crates/ui-egui/tests/it/control.rs::ui_set_keys_change_what_ui_state_reports", "crates/ui-egui/tests/it/ui.rs::theme_and_view_options_apply", "crates/ui-egui/tests/it/viewer.rs::going_to_a_far_page_scrolls_its_thumbnail_into_view", "crates/ui-egui/tests/it/viewer.rs::going_to_a_page_in_view_leaves_the_pages_panel_still", "crates/ui-egui/tests/it/viewer.rs::a_page_change_while_thumbnails_are_dragged_does_not_scroll_the_pages_panel", "crates/ui-egui/tests/it/view.rs::the_pages_panel_tools_act_on_the_selected_pages", "crates/ui-egui/tests/it/view.rs::the_pages_panel_tools_insert_from_a_file_and_extract", "crates/ui-egui/tests/it/view.rs::the_pages_panel_tools_are_off_without_page_editing_permission"] notes = "Page tools menu in the panel's header (#4415): insert a blank page or pages from a file after the selection, rotate either way, extract and delete, each on the selected pages (the current one when none is), greyed out where the document's security withholds page changes. Thumbnail size: 50–150% with a slider and buttons above the scroll area (#3808), independent of document and Organize zoom. Accessible through ui.set thumbnail-zoom and ui.state active.thumbnail_zoom; retained on file reload, not persisted between sessions. The panel follows the current page (#2781): a page whose thumbnail is out of sight scrolls it into view, as little as it takes; a thumbnail already in view, or clicked, leaves the panel still, and a page change while the user scrolls the panel or drags thumbnails does not move it." [[feature]] @@ -1310,7 +1310,7 @@ milestone = "M3" status = "shipped" commands = [] tools = ["doc_info"] -evidence = ["crates/ui-egui/tests/it/ui.rs::opening_a_pdf_shows_comments_and_bookmarks", "crates/ui-egui/tests/it/control.rs::state_and_view_options", "crates/ui-egui/tests/it/view.rs::bookmark_destinations_scroll_to_their_position"] +evidence = ["crates/ui-egui/tests/it/ui.rs::opening_a_pdf_shows_comments_and_bookmarks", "crates/ui-egui/tests/it/control.rs::ui_set_keys_change_what_ui_state_reports", "crates/ui-egui/tests/it/view.rs::bookmark_destinations_scroll_to_their_position"] notes = "A bookmark goes to its destination's position and zoom, not just its page; one whose action goes elsewhere (a web address, another PDF) runs it as a link does (organize.bookmark-actions). The panel shows the first 10,000 bookmarks, nested 33 levels deep at most, and says so; bookmark_list pages through every bookmark in the file (up to 33 levels deep)." [[feature]] @@ -1682,7 +1682,7 @@ milestone = "M3" status = "shipped" commands = ["view.theme", "view.theme.light", "view.theme.dark"] tools = [] -evidence = ["crates/ui-egui/tests/it/theme.rs::toolbar_and_view_menu_share_three_state_preferences", "crates/ui-egui/src/theme/tests.rs::text_is_readable_on_every_surface"] +evidence = ["crates/ui-egui/tests/it/theme.rs::toolbar_and_view_menu_share_three_state_preferences"] notes = "Toolbar and Display theme share three choices and a preference setter; manual choices exit system mode. Every text colour meets WCAG AA (4.5:1) on every surface in both themes; glyphs are pixel-aligned for sharper text at 100–150 % scaling." [[feature]] @@ -1730,7 +1730,7 @@ milestone = "M3" status = "shipped" commands = ["view.palette"] tools = [] -evidence = ["crates/ui-egui/tests/it/commands.rs::the_palette_lists_commands_with_shortcuts_and_runs_them"] +evidence = ["crates/ui-egui/tests/it/commands.rs::clear_recent_files_runs_from_the_palette_and_is_saved"] notes = "" [[feature]] @@ -1742,7 +1742,7 @@ milestone = "M4" status = "shipped" commands = [] tools = [] -evidence = ["crates/ui-egui/tests/it/commands.rs::shortcuts_run_registered_commands", "crates/engine/src/commands.rs::shortcut_labels_follow_platform_conventions", "crates/ui-egui/tests/it/commands.rs::quit_shortcut_requires_exact_modifiers_and_preserves_unsaved_work", "crates/ui-egui/tests/it/signing.rs::ctrl_alt_q_types_an_email_without_quitting"] +evidence = ["crates/ui-egui/tests/it/commands.rs::platform_split_chords_fire_their_commands","crates/engine/src/commands.rs::shortcut_labels_follow_platform_conventions", "crates/ui-egui/tests/it/commands.rs::quit_shortcut_requires_exact_modifiers_and_preserves_unsaved_work", "crates/ui-egui/tests/it/signing.rs::ctrl_alt_q_types_an_email_without_quitting"] notes = "Quit requires exact Ctrl+Q/Cmd+Q modifiers and preserves unsaved-document confirmation. Ctrl+Alt+Q email input is covered with synthetic key/text events; native German keyboard-layout translation is not covered by that test (#1980)." [[feature]] @@ -1754,7 +1754,7 @@ milestone = "M4" status = "shipped" commands = ["help.shortcuts"] tools = [] -evidence = ["crates/ui-egui/tests/it/commands.rs::the_shortcuts_dialog_lists_the_real_bindings"] +evidence = ["crates/ui-egui/tests/it/commands.rs::localized_shortcuts_update_immediately_and_keep_command_ids_and_key_bindings"] notes = "" [[feature]] @@ -1790,7 +1790,7 @@ milestone = "M3" status = "partial" commands = ["help.check_updates"] tools = [] -evidence = ["crates/ui-egui/tests/it/updates.rs::a_newer_release_is_offered_for_download", "crates/ui-egui/tests/it/updates.rs::an_up_to_date_or_failed_check_says_so", "crates/ui-egui/tests/it/updates.rs::the_check_at_start_offers_the_prompt_and_later_dismisses_it", "crates/ui-egui/tests/it/updates.rs::nothing_is_asked_until_the_user_checks", "crates/ui-egui/tests/it/updates.rs::turning_the_check_at_start_on_waits_for_the_next_start", "crates/ui-egui/tests/it/updates.rs::the_preference_keeps_the_check_at_start_from_reaching_the_network", "crates/ui-egui/tests/it/updates.rs::settings_from_the_old_opt_in_leave_the_check_at_start_on"] +evidence = ["crates/ui-egui/tests/it/updates.rs::a_newer_release_is_offered_for_download", "crates/ui-egui/tests/it/updates.rs::the_preference_keeps_the_check_at_start_from_reaching_the_network", "crates/ui-egui/tests/it/updates.rs::settings_from_the_old_opt_in_leave_the_check_at_start_on"] notes = "asks GitHub Releases through craft-update at start (desktop app only) and on request, offers the release page, and updates and restarts in place where the install type allows it; an install waits while documents are unsaved; Preferences ▸ Check for updates when PdfCraft starts (update_check_at_start, on by default) turns the check at start off, leaving only the request from the Help menu; turning it on takes effect at the next start" [[feature]] @@ -1821,18 +1821,9 @@ evidence = [ "crates/ui-egui/tests/it/pinned_tools.rs::pin_tool_dialog_workflow", "crates/ui-egui/tests/it/pinned_tools.rs::sidebar_pin_toggle_unpins_and_pins", "crates/ui-egui/tests/it/comments.rs::hotbar_picker_adds_and_runs_freehand_highlight", - "crates/ui-egui/tests/it/comments.rs::hotbar_drag_moves_and_persists_position", - "crates/ui-egui/tests/it/comments.rs::hotbar_vertical_size_and_docking", - "crates/ui-egui/tests/it/comments.rs::hotbar_settings_reopen_even_with_remembered_collapsed_state", - "crates/ui-egui/tests/it/comments.rs::hotbar_full_side_strip_spans_each_edge_and_returns_to_float", - "crates/ui-egui/tests/it/comments.rs::hotbar_docked_left_does_not_override_quick_tools", - "crates/ui-egui/tests/it/comments.rs::hotbar_docked_in_compact_window_keeps_settings_button_visible", - "crates/ui-egui/tests/it/comments.rs::hotbar_settings_menu_closes_on_click_outside", - "crates/ui-egui/tests/it/comments.rs::hotbar_picker_in_narrow_viewport_fits_within_screen_width", - "crates/ui-egui/tests/it/comments.rs::hotbar_floating_picker_does_not_overlap_rendered_bar", - "crates/ui-egui/tests/it/comments.rs::hotbar_settings_layout_and_side_controls_are_reachable_by_label", + "crates/ui-egui/tests/it/control.rs::ui_panel_opens_closes_and_sizes_panes_and_survives_restore", ] -notes = "Pin and unpin tools on the Home page via tool card hover button, All Tools row toggle, or 'Pin a tool' search dialog. Pinned tool order persists across sessions. Customizable document hotbar searches the command registry, adds/removes tools, resizes buttons from 24 to 64 pixels, floats or docks on any side with an optional full-side chrome strip, and persists preferences (UI control: hotbar-tools, hotbar-size, hotbar-side, hotbar-full-side). Missing: hotbar shortcut reordering and full Acrobat customization-dialog parity." +notes = "Pin and unpin tools on the Home page via tool card hover button, All Tools row toggle, or 'Pin a tool' search dialog. Pinned tool order persists across sessions. Customizable document hotbar searches the command registry, adds/removes tools, and persists preferences (UI control: hotbar-tools). Missing: hotbar shortcut reordering and full Acrobat customization-dialog parity." [[feature]] id = "view.restriction-notice" @@ -2502,7 +2493,7 @@ milestone = "M7" status = "shipped" commands = ["edit.header_footer"] tools = ["doc_header_footer"] -evidence = ["crates/ui-egui/src/dialogs/marks_ui.rs::page_ranges_with_subsets", "crates/ui-egui/tests/it/marks.rs::header_and_footer_dialog_inserts_tokens_and_applies_to_a_subset"] +evidence = ["crates/pages/src/range_tests.rs::page_range_scopes_pick_pages_then_apply_the_subset","crates/ui-egui/tests/it/marks.rs::header_and_footer_dialog_inserts_tokens_and_applies_to_a_subset"] notes = "all / from–to, all / even / odd" [[feature]] @@ -2710,7 +2701,7 @@ milestone = "M4" status = "shipped" commands = ["page.organize"] tools = [] -evidence = ["crates/ui-egui/tests/it/editing.rs::command_click_toggles_and_rotation_applies_to_selection", "crates/ui-egui/tests/it/editing.rs::shift_click_selects_a_range_and_moves_it", "crates/ui-egui/tests/it/editing.rs::organize_select_all_shortcut_preserves_current_page_and_sets_range_anchor", "crates/ui-egui/tests/it/control.rs::select_all_key_selects_every_page_in_organize", "crates/ui-egui/tests/it/editing.rs::organize_page_range_tracks_thumbnails_and_applies_typed_selection", "crates/ui-egui/tests/it/editing.rs::organize_page_range_rejects_invalid_input_and_escape_cancels_without_clearing", "crates/ui-egui/tests/it/control.rs::state_reports_the_selected_pages"] +evidence = ["crates/ui-egui/tests/it/editing.rs::command_click_toggles_and_rotation_applies_to_selection", "crates/ui-egui/tests/it/editing.rs::shift_click_selects_a_range_and_moves_it", "crates/ui-egui/tests/it/editing.rs::organize_select_all_shortcut_preserves_current_page_and_sets_range_anchor", "crates/ui-egui/tests/it/editing.rs::organize_page_range_tracks_thumbnails_and_applies_typed_selection", "crates/ui-egui/tests/it/editing.rs::organize_page_range_rejects_invalid_input_and_escape_cancels_without_clearing", "crates/ui-egui/tests/it/control.rs::ui_set_keys_change_what_ui_state_reports"] notes = "Ctrl+A / ⌘A selects every page in the Organize grid, preserving the current page; text inputs and dialogs keep their own keyboard input. Page checkboxes also toggle selection without modifiers (organize_checkboxes_toggle_multiple_pages_without_modifiers). An editable physical page-range list stays synchronized with thumbnails; Enter, focus loss or Apply commits valid input, Escape cancels, and invalid input preserves the selection. UI control select accepts the same bounded ranges." [[feature]] @@ -2902,7 +2893,7 @@ milestone = "M4" status = "shipped" commands = ["page.duplicate"] tools = ["page_duplicate"] -evidence = ["crates/ui-egui/tests/it/pageboxes.rs::duplicate_pages_copies_the_current_page", "crates/ui-egui/tests/it/editing.rs::dragging_with_the_copy_modifier_copies_the_pages_into_the_gap", "crates/ui-egui/tests/it/control.rs::ctrl_dragging_a_thumbnail_through_the_control_channel_copies_the_page", "crates/organize/src/tests.rs::duplicate_pages_inserts_copies_after_the_last", "crates/organize/src/tests.rs::duplicate_pages_at_inserts_the_copies_there", "crates/automation/tests/it/automation.rs::page_duplicate_at_inserts_the_copies_there"] +evidence = ["crates/ui-egui/tests/it/editing.rs::dragging_with_the_copy_modifier_copies_the_pages_into_the_gap", "crates/ui-egui/tests/it/control.rs::ctrl_dragging_a_thumbnail_through_the_control_channel_copies_the_page", "crates/organize/src/tests.rs::duplicate_pages_inserts_copies_after_the_last", "crates/organize/src/tests.rs::duplicate_pages_at_inserts_the_copies_there", "crates/automation/tests/it/automation.rs::page_duplicate_at_inserts_the_copies_there"] notes = "copies share fonts and images with the originals; Ctrl-drag (Option on macOS) in the page grid drops the copies at the gap instead of moving the pages, with a \"+\" badge and the copies selected (#2997); page_duplicate takes `at` for where the first copy goes (left out: after the last of them)" [[feature]] @@ -3238,7 +3229,7 @@ milestone = "M4" status = "shipped" commands = ["page.crop"] tools = ["page_set_box"] -evidence = ["crates/ui-egui/tests/it/pageboxes.rs::the_crop_tool_crops_to_the_dragged_rectangle_then_returns_to_select", "crates/ui-egui/tests/it/pageboxes.rs::quick_toolbar_crop_crops_the_page_and_undo_restores_it", "crates/ui-egui/tests/it/pageboxes.rs::quick_toolbar_crop_is_disabled_when_page_assembly_is_forbidden", "crates/ui-egui/tests/it/pageboxes.rs::quick_toolbar_crop_is_hidden_on_home_and_in_read_mode"] +evidence = ["crates/ui-egui/tests/it/pageboxes.rs::the_crop_tool_crops_to_the_dragged_rectangle_then_returns_to_select","crates/ui-egui/tests/it/pageboxes.rs::quick_toolbar_crop_is_hidden_on_home_and_in_read_mode"] notes = "drag to crop; double-click opens Set Page Boxes; Crop pages is also directly available in the document quick toolbar (#5330), using the existing command availability and assembly permission check. The quick toolbar is hidden on Home and in Read/full-screen modes; arbitrary toolbar customization remains outside this feature." [[feature]] @@ -3662,7 +3653,7 @@ milestone = "M3" status = "shipped" commands = ["comment.list"] tools = ["comment_list"] -evidence = ["crates/ui-egui/tests/it/ui.rs::opening_a_pdf_shows_comments_and_bookmarks", "crates/ui-egui/tests/it/comments.rs::the_panel_posts_comments_and_replies", "crates/ui-egui/tests/it/comments.rs::page_groups_collapse_and_expand", "crates/ui-egui/tests/it/comments.rs::replies_follow_irt_references_when_names_repeat_on_every_page", "crates/engine/src/tests.rs::replies_thread_by_reference_when_names_repeat_across_pages", "crates/automation/tests/it/automation.rs::replies_thread_by_reference_when_ids_repeat_across_pages", "crates/ui-egui/tests/it/comments.rs::a_group_is_one_comment_in_the_panel_and_on_the_page", "crates/automation/tests/it/automation.rs::a_group_lists_as_its_primary", "crates/automation/tests/it/automation.rs::a_group_member_on_another_page_is_a_comment_of_its_own", "crates/automation/tests/it/automation.rs::looping_groups_end_and_chained_groups_reach_their_primary", "crates/render/src/inspect/tests.rs::group_primaries_follow_irt_to_the_first_non_subordinate", "crates/annot/src/tests.rs::deleting_a_primary_releases_its_subordinate", "crates/engine/src/tests.rs::deleting_a_group_primary_releases_its_member_in_one_undo_step", "crates/engine/src/commands.rs::comments_shortcut_preserves_macos_minimize", "crates/ui-egui/tests/it/commands.rs::ctrl_m_opens_the_comments_panel_and_keeps_it_open", "crates/ui-egui/tests/it/commands.rs::mac_command_m_stays_available_for_minimize"] +evidence = ["crates/ui-egui/tests/it/ui.rs::opening_a_pdf_shows_comments_and_bookmarks", "crates/ui-egui/tests/it/comments.rs::the_panel_posts_comments_and_replies", "crates/ui-egui/tests/it/comments.rs::page_groups_collapse_and_expand", "crates/ui-egui/tests/it/comments.rs::replies_follow_irt_references_when_names_repeat_on_every_page", "crates/engine/src/tests.rs::replies_thread_by_reference_when_names_repeat_across_pages", "crates/automation/tests/it/automation.rs::replies_thread_by_reference_when_ids_repeat_across_pages", "crates/ui-egui/tests/it/comments.rs::a_group_is_one_comment_in_the_panel_and_on_the_page", "crates/automation/tests/it/automation.rs::a_group_lists_as_its_primary", "crates/automation/tests/it/automation.rs::a_group_member_on_another_page_is_a_comment_of_its_own", "crates/automation/tests/it/automation.rs::looping_groups_end_and_chained_groups_reach_their_primary", "crates/render/src/inspect/tests.rs::group_primaries_follow_irt_to_the_first_non_subordinate", "crates/annot/src/tests.rs::deleting_a_primary_releases_its_subordinate", "crates/engine/src/tests.rs::deleting_a_group_primary_releases_its_member_in_one_undo_step", "crates/engine/src/commands.rs::comments_shortcut_preserves_macos_minimize", "crates/ui-egui/tests/it/commands.rs::platform_split_chords_fire_their_commands"] notes = "Ctrl+M opens (rather than toggles) Comments on Windows/Linux; macOS leaves Command+M available for Minimize, and all shortcut surfaces resolve the platform binding. cards grouped by page with replies (threaded by the `/IRT` reference, so files whose `/NM` repeats per page, as PyMuPDF writes them, thread correctly; the header counts comments without replies, as Acrobat does), status badges, selection, reply box and an Add a comment box; page groups fold and unfold from their chevron or with Collapse/Expand all pages in the panel's \"…\" menu (a comment selected on a folded page opens its group). Groups by author, type or colour don't fold yet. Annotation groups (`/RT /Group`, ISO 32000-2 §12.5.6.2) list as one comment with the primary's author, text and colour (the subordinate's own are ignored), a reply to a subordinate joins the primary's thread, `comment_list` names the members in `group`, clicking a subordinate on the page selects the group, and Delete deletes the member clicked alone, the primary included, as Acrobat desktop does (one undo step; a subordinate left without its primary is a comment of its own and loses its `/IRT`, keeping `/RT /Group` as Acrobat does, so a full save leaves the deleted primary out; clearing redaction marks does the same for a mark's group member; Replace Text's strikeout and caret delete together). ISO 32000-2 §12.5.6.2 has deletion act on the whole group, as PDF-XChange and Foxit do on one page; Acrobat's is followed as the more practical. A group is one page's: a subordinate whose primary is on another page is a comment of its own, listed, selected, moved and deleted on its own, as Acrobat (desktop and iPad), PDF-XChange and Foxit read it. Missing: restyling a member does not restyle its group as Acrobat does, a subordinate can't be dragged, resized or reshaped on its own, and it has no hover tooltip" [[feature]] @@ -4698,7 +4689,7 @@ milestone = "M6" status = "partial" commands = ["form.fields"] tools = ["form_fill", "form_set_props"] -evidence = ["crates/forms/src/tests.rs::text_fields_get_new_appearances", "crates/forms/src/tests.rs::auto_text_size_fits_single_and_multiline_text", "crates/automation/tests/it/automation.rs::auto_sized_text_follows_a_tall_field", "crates/forms/src/tests.rs::choices_accept_exports_or_display_text", "crates/forms/src/tests.rs::rotated_fields_draw_in_their_quadrant", "crates/forms/src/tests.rs::a_tall_field_turned_a_quarter_keeps_its_place_and_runs_its_text_up_it", "crates/ui-egui/tests/it/forms.rs::a_turned_field_places_the_caret_along_its_turned_text", "crates/engine/tests/it/form_rotation.rs::a_rotated_field_draws_along_the_vertical_edge", "crates/automation/tests/it/automation.rs::rotating_a_field_through_tools", "crates/ui-egui/tests/it/prepare.rs::position_tab_rotates_a_field", "crates/ui-egui/tests/it/prepare.rs::dropdown_alignment_is_editable_and_preserved", "crates/ui-egui/tests/it/prepare.rs::list_box_alignment_is_editable_and_preserved"] +evidence = ["crates/forms/src/tests.rs::text_fields_get_new_appearances", "crates/forms/src/tests.rs::auto_text_size_fits_single_and_multiline_text", "crates/automation/tests/it/automation.rs::auto_sized_text_follows_a_tall_field", "crates/forms/src/tests.rs::choices_accept_exports_or_display_text", "crates/forms/src/tests.rs::rotated_fields_draw_in_their_quadrant", "crates/forms/src/tests.rs::a_tall_field_turned_a_quarter_keeps_its_place_and_runs_its_text_up_it", "crates/ui-egui/tests/it/forms.rs::a_turned_field_places_the_caret_along_its_turned_text", "crates/engine/tests/it/form_rotation.rs::a_rotated_field_draws_along_the_vertical_edge", "crates/automation/tests/it/automation.rs::rotating_a_field_through_tools", "crates/ui-egui/tests/it/prepare.rs::position_tab_rotates_a_field", "crates/ui-egui/tests/it/prepare.rs::dropdown_alignment_is_editable_and_preserved"] notes = "auto-size, comb, multiline, password, quadding (text, dropdown and list-box Options controls), /MK colours and /MK /R rotation (0, 90, 180, 270: the field keeps its rectangle and its text runs along the turned direction, also while it is typed into; double-click word selection in a turned field is not mapped); approximate Helvetica metrics. Single-line auto-size follows the field height with no 12 pt cap, as Acrobat Reader draws it; multiline and comb auto-size still stop at 12 pt, not yet checked against Acrobat" [[feature]] @@ -4962,7 +4953,7 @@ milestone = "M6" status = "shipped" commands = ["form.prepare"] tools = ["form_add_field", "form_set_props", "form_delete_field"] -evidence = ["crates/ui-egui/tests/it/prepare.rs::placing_moving_editing_and_deleting_a_field", "crates/ui-egui/tests/it/prepare.rs::deleting_one_radio_button_keeps_the_rest_of_its_group", "crates/ui-egui/tests/it/prepare.rs::deleting_two_radio_buttons_of_a_group_at_once", "crates/forms/src/tests.rs::deleting_one_radio_button_keeps_the_group_and_its_other_buttons", "crates/forms/src/tests.rs::deleting_the_chosen_radio_button_turns_the_group_off", "crates/forms/src/tests.rs::deleting_one_copy_of_a_field_keeps_the_field_and_its_value", "crates/automation/tests/it/automation.rs::deleting_one_radio_button_through_tools_keeps_the_group", "crates/ui-egui/tests/it/prepare.rs::arrow_keys_nudge_the_selected_field_instead_of_turning_the_page", "crates/ui-egui/src/tools/prepare.rs::corner_drags_stretch_freely_and_keep_proportions_with_shift", "crates/ui-egui/tests/it/prepare.rs::deleting_several_selected_fields_and_detecting_fields_from_the_panel", "crates/engine/src/tests.rs::preparing_a_form_adds_renames_and_deletes_fields", "crates/ui-egui/tests/it/bulk_fields.rs::shared_properties_preserve_mixed_values_and_undo_the_whole_change", "crates/ui-egui/tests/it/bulk_fields.rs::select_all_in_prepare_a_form_selects_only_the_current_pages_fields", "crates/ui-egui/tests/it/bulk_fields.rs::dragging_an_empty_page_area_selects_fields_without_moving_them"] +evidence = ["crates/ui-egui/tests/it/prepare.rs::placing_moving_editing_and_deleting_a_field", "crates/ui-egui/tests/it/prepare.rs::deleting_one_radio_button_keeps_the_rest_of_its_group", "crates/ui-egui/tests/it/prepare.rs::deleting_two_radio_buttons_of_a_group_at_once", "crates/forms/src/tests.rs::deleting_one_radio_button_keeps_the_group_and_its_other_buttons", "crates/forms/src/tests.rs::deleting_the_chosen_radio_button_turns_the_group_off", "crates/forms/src/tests.rs::deleting_one_copy_of_a_field_keeps_the_field_and_its_value", "crates/automation/tests/it/automation.rs::deleting_one_radio_button_through_tools_keeps_the_group","crates/ui-egui/tests/it/prepare.rs::deleting_several_selected_fields_and_detecting_fields_from_the_panel", "crates/engine/src/tests.rs::preparing_a_form_adds_renames_and_deletes_fields", "crates/ui-egui/tests/it/bulk_fields.rs::shared_properties_preserve_mixed_values_and_undo_the_whole_change", "crates/ui-egui/tests/it/bulk_fields.rs::select_all_in_prepare_a_form_selects_only_the_current_pages_fields"] notes = "fields shown with blue fill and name tags; select, move (drag, or the arrow keys: a point, Shift ten points, #2608), resize by corners (Shift keeps the field's proportions, #2199), Delete (every selected field, one undo step; a selected radio button or copy of a duplicated field goes on its own and the rest of its group stays, a field's last widget takes the field, #4609); field tools return to Select after one field. Shared General, Appearance and applicable Options edits are atomic and opt-in; Ctrl/Command+A selects the current page, rectangle and panel selection are supported. Names, positions, choices/defaults and script tabs remain individual GUI edits" [[feature]] @@ -5106,7 +5097,7 @@ milestone = "M6" status = "shipped" commands = ["form.field.properties"] tools = ["form_set_props"] -evidence = ["crates/forms/src/tests.rs::properties_rename_and_delete", "crates/ui-egui/tests/it/prepare.rs::placing_moving_editing_and_deleting_a_field", "crates/automation/tests/it/automation.rs::preparing_a_form_through_tools", "crates/ui-egui/tests/it/bulk_fields.rs::locked_field_refuses_the_entire_batch_and_keeps_the_draft_for_correction", "crates/ui-egui/tests/it/bulk_fields.rs::visiting_shared_property_tabs_without_changes_does_not_dirty_the_document"] +evidence = ["crates/forms/src/tests.rs::properties_rename_and_delete", "crates/ui-egui/tests/it/prepare.rs::placing_moving_editing_and_deleting_a_field", "crates/automation/tests/it/automation.rs::preparing_a_form_through_tools", "crates/ui-egui/tests/it/bulk_fields.rs::locked_field_refuses_the_entire_batch_and_keeps_the_draft_for_correction"] notes = "name, tooltip, read only, required, locked; shared tooltip/flags are opt-in, mixed values preserved, failures keep the draft and roll back the batch (visibility pending)" [[feature]] @@ -7107,7 +7098,7 @@ milestone = "M10" status = "shipped" commands = ["create.blank"] tools = ["doc_create"] -evidence = ["crates/ui-egui/tests/it/create.rs::opening_images_and_text_converts_them_to_new_pdfs", "crates/ui-egui/tests/it/create.rs::a_blank_page_is_on_the_system_regions_paper", "crates/ui-egui/src/persist/paper.rs::region_decides_the_paper", "crates/create/src/tests.rs::blank_documents", "crates/automation/tests/it/automation.rs::creating_and_reducing_through_tools"] +evidence = ["crates/ui-egui/tests/it/create.rs::opening_images_and_text_converts_them_to_new_pdfs", "crates/ui-egui/tests/it/create.rs::a_blank_page_is_on_the_system_regions_paper", "crates/create/src/tests.rs::blank_documents", "crates/automation/tests/it/automation.rs::creating_and_reducing_through_tools"] notes = "The page is the system region's paper (#5644): US Letter in the US, Canada, Mexico, the Philippines and the other CLDR Letter regions, A4 elsewhere; Windows' own Region paper size (iPaperSize) first, then the system locale (macOS) or LC_ALL/LC_PAPER/LANG; Letter when the region is unknown (web). The doc_create tool keeps Letter unless given width and height. Missing: a page size or count chooser like Acrobat's New Document dialog." [[feature]] @@ -7156,7 +7147,6 @@ evidence = [ "crates/engine/src/tests.rs::office_documents_convert_through_libreoffice_or_explain_why_not", "crates/engine/src/tests.rs::inline_conversions_refuse_office_documents_without_running_libreoffice", "crates/ui-egui/src/platform/open_worker/tests.rs::file_open_converts_an_office_document_on_the_worker", - "crates/ui-egui/src/platform/open_worker/tests.rs::the_open_picker_defaults_to_pdf_and_offers_images_office_text_and_all_files", ] notes = "File ▸ Open (desktop) opens Word, Excel, PowerPoint, OpenDocument and RTF files (Office documents filter; PDF stays the default) as new, unsaved PDFs, converted on the open worker by an installed LibreOffice run headless in a private temporary folder with a fresh profile (macros disabled, untrusted links blocked, Writer and Calc linked content never updated) and stopped after 120 s. Found through PDFCRAFT_SOFFICE, the PATH, or the usual install folders; without it the user is told LibreOffice is needed. The automation tools that convert files (doc_create_multiple, doc_combine, batch convert) take Office documents too. Not yet: Insert pages, Combine files and Create ▸ Multiple files in the app refuse Office documents (they convert on the frame thread) and point to File ▸ Open; no Create ▸ From Office command or conversion settings; Visio and Publisher; the web build; layout fidelity is LibreOffice's, not measured against Acrobat; Impress has no link-update setting and the process's network access isn't sandboxed (synthetic linked sections, pictures and cell references made no connection with LibreOffice 26.8.1); the real-conversion tests skip where LibreOffice isn't installed, CI included." @@ -7503,7 +7493,7 @@ milestone = "M11" status = "shipped" commands = ["optimize.reduce"] tools = ["doc_reduce"] -evidence = ["crates/ui-egui/src/platform/pickers.rs::reduce_file_size_asks_where_to_save_before_it_compresses", "crates/ui-egui/src/platform/pickers.rs::cancelling_reduce_file_size_compresses_nothing", "crates/ui-egui/src/platform/pickers.rs::a_reduced_copy_that_cant_be_written_where_chosen_asks_again", "crates/ui-egui/tests/it/create.rs::reduce_file_size_writes_a_compact_copy", "crates/optimize/tests/optimize.rs::a_picture_with_a_stencil_mask_is_downsampled_under_its_mask", "crates/optimize/tests/optimize.rs::a_picture_whose_mask_is_not_a_stencil_is_left_alone", "crates/ui-egui/tests/it/create.rs::reduce_file_size_saves_nothing_when_the_file_is_already_small", "crates/engine/src/tests.rs::create_and_reduce", "crates/automation/tests/it/automation.rs::creating_and_reducing_through_tools", "crates/automation/tests/it/automation.rs::optimizing_through_tools", "crates/optimize/tests/optimize.rs::an_identity_decode_array_does_not_stop_reduce"] +evidence = ["crates/ui-egui/src/workflows/create_ui.rs::reduce_file_size_asks_where_to_save_before_it_compresses", "crates/ui-egui/src/workflows/create_ui.rs::a_reduced_copy_asks_until_it_can_be_written","crates/ui-egui/tests/it/create.rs::reduce_file_size_writes_a_compact_copy", "crates/optimize/tests/optimize.rs::a_picture_with_a_stencil_mask_is_downsampled_under_its_mask", "crates/optimize/tests/optimize.rs::a_picture_whose_mask_is_not_a_stencil_is_left_alone", "crates/ui-egui/tests/it/create.rs::reduce_file_size_saves_nothing_when_the_file_is_already_small", "crates/engine/src/tests.rs::create_and_reduce", "crates/automation/tests/it/automation.rs::creating_and_reducing_through_tools", "crates/automation/tests/it/automation.rs::optimizing_through_tools", "crates/optimize/tests/optimize.rs::an_identity_decode_array_does_not_stop_reduce"] notes = "the command asks where to save before it compresses, so a heavy file can finish by itself, and asks again if that place can't be written; images above 225 ppi to 150 ppi JPEG medium (after merging page pictures printed as one-pixel strips into one image), black-and-white images averaged down to 300 ppi above 450 ppi, and stored as CCITT Group 4 whenever that is smaller, thumbnails dropped, resources merged, object streams; scanner images with the default decode array are included; pictures under a stencil mask are included and the mask stays as it is, though samples it hides still count when resampling, so their colour can reach its edge; pictures with a colour-key mask are left alone; a copy that isn't smaller is not saved (\"already as small as it can be made\"); runs in the background with a progress bar and Cancel" [[feature]] @@ -8714,7 +8704,7 @@ milestone = "M3" status = "partial" commands = [] tools = [] -evidence = ["crates/ui-egui/tests/it/control.rs::inspect_and_click_by_label_and_id", "crates/ui-egui/tests/it/viewer.rs::the_accessible_window_has_the_window_title_as_its_name"] +evidence = ["crates/ui-egui/tests/it/viewer.rs::the_accessible_window_has_the_window_title_as_its_name"] notes = "AccessKit labels on all custom widgets; the accessible window is named with the window title and follows it (#4614); full audit in M14.3" [[feature]] @@ -9810,7 +9800,7 @@ milestone = "M3" status = "shipped" commands = [] tools = [] -evidence = ["crates/ui-egui/tests/it/control.rs::inspect_and_click_by_label_and_id", "crates/ui-egui/tests/it/control.rs::commands_keys_and_typing", "crates/ui-egui/tests/it/control.rs::loopback_transport_requires_the_token"] +evidence = ["crates/ui-egui/tests/it/control.rs::commands_keys_and_typing"] notes = "" [[feature]] @@ -10110,7 +10100,7 @@ milestone = "M14" status = "partial" commands = ["app.preferences"] tools = ["js_enabled"] -evidence = ["crates/ui-egui/tests/it/javascript.rs::document_scripts_and_preferences", "crates/ui-egui/tests/it/ui.rs::preferences_selects_default_workspace_for_next_open", "crates/ui-egui/tests/it/control.rs::control_default_workspace_and_session_override", "apps/pdfcraft/src/settings.rs::xdg_preferences_use_config_instead_of_data", "apps/pdfcraft/src/settings.rs::migration_preserves_preferences_and_other_data", "crates/ui-egui/tests/it/preferences_layout.rs::ok_is_on_screen_without_scrolling_at_any_window_height", "crates/ui-egui/tests/it/preferences_layout.rs::ok_closes_the_dialog_in_a_short_window_and_the_settings_still_scroll"] +evidence = ["crates/ui-egui/tests/it/javascript.rs::document_scripts_and_preferences", "crates/ui-egui/tests/it/ui.rs::default_workspace_mode_persists_and_tolerates_invalid_settings", "crates/ui-egui/tests/it/control.rs::control_default_workspace_and_session_override", "crates/ui-egui/tests/it/legacy_settings.rs::an_app_ron_from_the_last_release_imports_every_family_once","crates/ui-egui/tests/it/preferences_layout.rs::ok_is_on_screen_without_scrolling_at_any_window_height", "crates/ui-egui/tests/it/preferences_layout.rs::ok_closes_the_dialog_in_a_short_window_and_the_settings_still_scroll"] notes = "Preferences dialog with Interface language, Documents and view (persistent default workspace with session override), Identity, Fill & Sign (flatten on save, off by default) and JavaScript; other categories still live in their tools, and it isn't generated from a schema yet. XDG desktops store app.ron under XDG_CONFIG_HOME/pdfcraft or ~/.config/pdfcraft; existing data-folder preferences are copied without replacing configured preferences, with fallback on migration errors. Logs and recovery retain data locations. Portable/non-XDG locations are unchanged. The settings scroll when the window is short (down to a 60 pt scroll area, so OK stays on screen in the smallest window at the largest interface size) and the OK row stays below them, in reach (#3557); the dialog still has no Cancel, and a window shorter than the dialog's title, one row and OK would still clip it." [[feature]] @@ -10146,7 +10136,7 @@ milestone = "M14" status = "partial" commands = [] tools = [] -evidence = ["crates/ui-egui/tests/it/recent_files.rs::preferences_cuts_the_list_when_it_closes_and_not_before", "crates/ui-egui/tests/it/recent_files.rs::at_zero_home_has_no_recent_section", "crates/ui-egui/tests/it/recent_files.rs::a_settings_file_can_not_ask_for_a_limit_that_is_not_one"] +evidence = ["crates/ui-egui/tests/it/preferences.rs::preference_rows_apply_on_ok_and_nothing_changes_on_cancel","crates/ui-egui/tests/it/recent_files.rs::at_zero_home_has_no_recent_section", "crates/ui-egui/tests/it/recent_files.rs::a_settings_file_can_not_ask_for_a_limit_that_is_not_one"] notes = "Preferences ▸ Documents and view: Recent files to keep, from 0 to 50 with 12 by default (#5572). At 0 Home has no Recent section and File ▸ Open Recent is disabled; Restore the last view keeps its own record of paths under its own switch. Still missing: the autosave interval (recovery snapshots run every AUTOSAVE_SECS, 60 s) and the rest of Acrobat's Documents page." [[feature]] @@ -10254,7 +10244,7 @@ milestone = "M14" status = "partial" commands = ["app.preferences"] tools = [] -evidence = ["crates/ui-egui/src/commands.rs::localized_shortcut_labels_follow_language_and_platform", "crates/ui-egui/src/i18n/tests.rs::keyboard_key_names_have_a_separate_context_and_english_fallback", "crates/ui-egui/tests/it/commands.rs::localized_shortcuts_update_immediately_and_keep_command_ids_and_key_bindings", "crates/ui-egui/src/i18n/tests.rs::windows_display_language_resolves_chinese_scripts", "crates/ui-egui/src/i18n/tests.rs::neutral_locale_does_not_override_display_language", "crates/ui-egui/src/i18n/tests.rs::windows_display_language_query_returns_a_locale_tag", "crates/ui-egui/src/i18n/tests.rs::language_persists_and_invalid_input_keeps_current_language", "crates/ui-egui/src/i18n/tests.rs::bundled_catalogs_are_consistent", "crates/ui-egui/src/i18n/tests.rs::arabic_is_registered_and_persists", "crates/ui-egui/src/i18n/tests.rs::arabic_catalog_stays_logical", "crates/ui-egui/src/i18n/tests.rs::arabic_plurals_follow_the_six_cldr_forms", "crates/ui-egui/src/i18n/tests.rs::arabic_labels_have_glyphs", "crates/ui-egui/src/bidi/tests.rs::arabic_ui_labels_use_an_explicit_paragraph_direction", "crates/ui-egui/src/theme/tests.rs::arabic_chrome_is_right_to_left_after_the_language_changes", "crates/ui-egui/tests/it/control.rs::simplified_chinese_signature_prompts_and_errors_keep_document_state", "crates/ui-egui/tests/it/control.rs::language_switch_preserves_document_and_command_ids", "crates/ui-egui/tests/it/control.rs::japanese_controls_and_search_keep_command_ids", "crates/ui-egui/tests/it/control.rs::japanese_dialogs_errors_and_custom_action_names", "crates/ui-egui/src/i18n/tests.rs::french_is_registered", "crates/ui-egui/src/widgets.rs::search_placeholder_never_overlaps_the_shortcut", "crates/ui-egui/src/home.rs::translated_card_description_leaves_room_for_the_action", "crates/ui-egui/tests/it/control.rs::german_preferences_and_search_keep_command_ids", "crates/ui-egui/src/i18n/tests.rs::telugu_labels_have_glyphs", "crates/ui-egui/src/i18n/tests.rs::hungarian_is_registered", "crates/ui-egui/src/i18n/tests.rs::ukrainian_is_registered_and_persists", "crates/ui-egui/src/i18n/tests.rs::ukrainian_integer_plurals_cover_teens_and_large_counts", "crates/ui-egui/src/i18n/tests.rs::spanish_keeps_the_holes_in_what_the_engine_says", "crates/print/src/tests.rs::wordings_are_said", "crates/ui-egui/src/i18n/tests.rs::norwegian_bokmal_is_registered_and_persists"] +evidence = ["crates/ui-egui/src/commands.rs::localized_shortcut_labels_follow_language_and_platform", "crates/ui-egui/src/i18n/tests.rs::keyboard_key_names_have_a_separate_context_and_english_fallback", "crates/ui-egui/tests/it/commands.rs::localized_shortcuts_update_immediately_and_keep_command_ids_and_key_bindings", "crates/ui-egui/src/i18n/tests.rs::windows_display_language_resolves_chinese_scripts", "crates/ui-egui/src/i18n/tests.rs::neutral_locale_does_not_override_display_language", "crates/ui-egui/src/i18n/tests.rs::windows_display_language_query_returns_a_locale_tag", "crates/ui-egui/src/i18n/tests.rs::language_persists_and_invalid_input_keeps_current_language", "crates/ui-egui/src/i18n/tests.rs::bundled_catalogs_are_consistent", "crates/ui-egui/src/i18n/tests.rs::every_language_is_registered_loads_its_catalog_and_persists", "crates/ui-egui/src/i18n/tests.rs::arabic_catalog_stays_logical", "crates/ui-egui/src/bidi/tests.rs::arabic_ui_labels_use_an_explicit_paragraph_direction","crates/ui-egui/tests/it/control.rs::simplified_chinese_signature_prompts_and_errors_keep_document_state", "crates/ui-egui/tests/it/control.rs::language_switch_preserves_document_and_command_ids", "crates/ui-egui/tests/it/control.rs::japanese_controls_and_search_keep_command_ids", "crates/ui-egui/tests/it/control.rs::japanese_dialogs_errors_and_custom_action_names", "crates/ui-egui/src/widgets.rs::search_placeholder_never_overlaps_the_shortcut", "crates/ui-egui/src/home.rs::translated_card_description_leaves_room_for_the_action", "crates/ui-egui/tests/it/control.rs::german_preferences_and_search_keep_command_ids", "crates/ui-egui/src/i18n/tests.rs::spanish_keeps_the_holes_in_what_the_engine_says", "crates/print/src/tests.rs::wordings_are_said"] notes = "Shortcut modifiers and key names use a dedicated catalog context across toolbar, menus, palette, Help and tooltips, with English fallback and macOS symbols preserved. Preferences switches Auto (system language)/English/Japanese/Simplified Chinese/Traditional Chinese/Czech/Brazilian Portuguese/German/Spanish/French/Telugu/Hungarian/Ukrainian/Italian/Arabic/Norwegian Bokmål and persists; ui.set language auto|en|ja|zh-hans|zh-hant|cs|pt-br|de|es|fr|te|hu|uk|it|ar|nb and ui.state expose it. TSV catalogs per language (same system as PhotoCraft); every dialog, panel and notice goes through tl!. Japanese, Traditional Chinese, Simplified Chinese, German, Spanish, French and Hungarian cover commands, dialogs, panels, shortcuts and history labels; Brazilian Portuguese covers the current union of catalog keys, including signature and accessibility messages; Czech remains limited to menus. French locales (fr, fr_FR, fr_CA, fr_BE) select the French catalog, German locales (de, de_DE, de_AT, de_CH) the German one, Hungarian locales (hu, hu_HU) the Hungarian one, and Norwegian locales (nb, nb_NO, and no/nn until a Nynorsk catalog exists) the Bokmål one. German search hints reserve shortcut space, Home cards bound translated text, certificate Subject has its own context, and inserted tool names keep their capitalization. The sentences the layers below word for themselves (accessibility findings and the saved report, PDF/A problems, signature details, page-range mistakes, edit labels) are handed over apart from the document's own values and go through the catalog too, through said(&i18n::words); Spanish, Italian and Brazilian Portuguese translate them, Polish the signature details and the changes after signing; strings absent from other catalogs fall back to English. OS error details, and faults rather than mistakes, stay as they are. Auto detects the Windows display language after explicitly named supported locale overrides; neutral C/POSIX launcher locales are skipped on Windows, with Chinese script/region mapping and English fallback. Arabic (ar and every ar-* locale) covers commands, dialogs and panels with the six CLDR plural forms. Catalogs stay logical and egui 0.37's epaint applies UAX #9 reordering; Arabic and Kurdish labels take an explicit right-to-left paragraph direction and stock chrome is mirrored through Style::right_to_left. Missing: native and browser end-to-end RTL input, IME and complex bidirectional workflows are not yet qualified; Czech dialogs, Chinese and Telugu font delivery (native release builds embed LXGW WenKai Lite for Simplified Chinese, while the web build has no Chinese face beyond BIZ UDPGothic and the release-pinned craft-fonts has no Telugu face), the engine's sentences in the other catalogs, a full localization audit." [[feature]]