From b507f6a103fb8dd5cc0c5f1bfe8bd8c6ecc90b0a Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 09:58:22 -0500 Subject: [PATCH] App red round 6 g3: fixes from the g3 fixer --- crates/ui-egui/src/app.rs | 1 - crates/ui-egui/src/app/settings.rs | 20 ++++- crates/ui-egui/src/editing.rs | 11 +-- crates/ui-egui/src/editing/tests.rs | 4 +- crates/ui-egui/src/lib.rs | 2 - crates/ui-egui/tests/it/control.rs | 29 +++---- crates/ui-egui/tests/it/forms.rs | 101 ++++++++++++----------- crates/ui-egui/tests/it/pinned_tools.rs | 10 +-- crates/ui-egui/tests/it/support/input.rs | 16 ++++ crates/ui-egui/tests/it/ui.rs | 29 +++---- 10 files changed, 127 insertions(+), 96 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 71a8bb1280..3758f3c11c 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -430,7 +430,6 @@ impl PdfCraftApp { control: None, control_server: None, control_epoch: 0, - bookmark_rename: None, bookmark_clipboard: None, word_count_options: Default::default(), printer_marks_draft: Default::default(), diff --git a/crates/ui-egui/src/app/settings.rs b/crates/ui-egui/src/app/settings.rs index d6abbfb036..e1b57ef612 100644 --- a/crates/ui-egui/src/app/settings.rs +++ b/crates/ui-egui/src/app/settings.rs @@ -363,6 +363,17 @@ pub fn motion_from_name(name: &str) -> Option { } } +/// The theme choice a saved name stands for: the last release's `Light`, `Dark` and `System`, and +/// the names the framework writes. +pub fn theme_from_name(name: &str) -> Option { + match name { + "Light" | "light" => Some(ModeChoice::Light), + "Dark" | "dark" => Some(ModeChoice::Dark), + "System" | "system" => Some(ModeChoice::System), + _ => None, + } +} + /// A restored colour: an `[r, g, b]` array of finite numbers, each clamped to 0–1 (a hostile file /// must not hand the painter NaN or a huge value). pub(crate) fn rgb_triple(v: &Value) -> Option<[f64; 3]> { @@ -495,6 +506,13 @@ pub fn import_json(text: &str) -> (PdfCraftSettings, Vec) { } motion }); + let theme = r.string("theme").and_then(|name| { + let theme = theme_from_name(&name); + if theme.is_none() { + r.fail("theme", "unknown theme name"); + } + theme + }); let combine_columns = r.value("combine_columns").and_then(crate::combine_ui::columns_from_legacy); Layout { reopen_last_session: r.bool("reopen_last_session"), @@ -508,7 +526,7 @@ pub fn import_json(text: &str) -> (PdfCraftSettings, Vec) { pinned_folders: r.text("pinned_folders"), pinned_folders_collapsed: r.text("pinned_folders_collapsed"), pinned_tools: r.list("pinned_tools"), - theme: r.typed("theme"), + theme, scroll_speed: r.typed("scroll_speed"), invert_middle_drag: r.bool("invert_middle_drag"), animation_effects, diff --git a/crates/ui-egui/src/editing.rs b/crates/ui-egui/src/editing.rs index 640287e25a..7ee1fe1d4e 100644 --- a/crates/ui-egui/src/editing.rs +++ b/crates/ui-egui/src/editing.rs @@ -1262,13 +1262,12 @@ impl PdfCraftApp { let (left, top) = (left.map(f64::from), top.map(f64::from)); self.apply_edit(ctx, Edit::AddBookmark { parent: vec![], index: n, title: "Untitled".into(), page, left, top }); // Like Acrobat: the new bookmark starts in rename mode. - self.bookmark_rename = Some((vec![n], "Untitled".into())); + crate::panels::bookmarks::start_rename(ctx, id, &[n]); self.set_right(Some(crate::RightPanel::Bookmarks)); return; } A::StartRename(path) => { - let title = self.session.get(id).and_then(|d| bookmark_at(&d.info.outline, &path)).map(|b| b.title.clone()).unwrap_or_default(); - self.bookmark_rename = Some((path, title)); + crate::panels::bookmarks::start_rename(ctx, id, &path); return; } A::Rename(path, title) => Edit::RenameBookmark { path, title }, @@ -1365,12 +1364,6 @@ impl PdfCraftApp { } } -fn bookmark_at<'a>(items: &'a [pdfcraft_render::OutlineItem], path: &[usize]) -> Option<&'a pdfcraft_render::OutlineItem> { - let (first, rest) = path.split_first()?; - let item = items.get(*first)?; - if rest.is_empty() { Some(item) } else { bookmark_at(&item.children, rest) } -} - /// The open box's own Undo or Redo, as its keys do it: the box's text, selection and line /// alignments one step back (or forward) in its typing history. False when the history has no /// such step, and then nothing changes. diff --git a/crates/ui-egui/src/editing/tests.rs b/crates/ui-egui/src/editing/tests.rs index eb3be197c6..072b6b44d5 100644 --- a/crates/ui-egui/src/editing/tests.rs +++ b/crates/ui-egui/src/editing/tests.rs @@ -124,7 +124,7 @@ fn save_commits_the_open_text_box() { assert_eq!(added.len(), 1, "the open text box was committed before the save"); assert!(app.views[0].session.content.draft.is_none()); answer_save(&mut h, &files, &jobs, &dest); - assert!(std::fs::read(&dest).unwrap().starts_with(b"%PDF"), "the document with its text went where the user chose"); + assert!(files.file(&dest).unwrap_or_default().starts_with(b"%PDF"), "the document with its text went where the user chose"); assert!(!h.state().session.get(id).unwrap().dirty); let _ = std::fs::remove_dir_all(&dir); } @@ -198,7 +198,7 @@ fn save_asks_where_to_keep_an_email_attachment_and_leaves_the_temporary_copy_alo assert!(!app.save_active(&egui::Context::default(), SaveTarget::InPlace), "Save asks instead of writing the temporary copy"); answer_save(&mut h, &files, &jobs, &kept); assert_eq!(std::fs::read(&attachment).unwrap(), original, "the attachment's copy is untouched"); - assert!(std::fs::read(&kept).unwrap().starts_with(b"%PDF"), "the document went where the user chose"); + assert!(files.file(&kept).unwrap_or_default().starts_with(b"%PDF"), "the document went where the user chose"); // The chosen file is the document's file now: the next Save writes it without asking. let app = h.state_mut(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index b16e9184fd..6e33da5c9c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -633,8 +633,6 @@ pub struct PdfCraftApp { /// Changes whenever what injected input aims at changes, so the control channel withdraws /// input aimed at what was there before. pub(crate) control_epoch: u64, - /// A bookmark being renamed in the Bookmarks panel: (path, text so far). - pub bookmark_rename: Option<(Vec, String)>, /// Bookmarks copied or cut in the Bookmarks panel, with their subtrees, ready to paste into /// any document. Destinations are page indices. pub bookmark_clipboard: Option>, diff --git a/crates/ui-egui/tests/it/control.rs b/crates/ui-egui/tests/it/control.rs index f309bba7c8..4c79911f55 100644 --- a/crates/ui-egui/tests/it/control.rs +++ b/crates/ui-egui/tests/it/control.rs @@ -419,7 +419,12 @@ fn bookmark_titles_can_be_searched_over_control() { #[test] fn theme_commands_and_options_report_preference_and_effective_colours() { let (mut h, c) = harness(); - h.input_mut().system_theme = Some(egui::Theme::Dark); + // The desktop reports its scheme as the windowing integration does: the raw field and an event. + let desktop = |h: &mut Harness<'static, PdfCraftApp>, theme: egui::Theme| { + h.input_mut().system_theme = Some(theme); + h.input_mut().events.push(egui::Event::SystemTheme(theme)); + }; + desktop(&mut h, egui::Theme::Dark); h.run_steps(2); for (id, preference, effective) in [("view.theme.system", "System", "Dark"), ("view.theme.light", "Light", "Light"), ("view.theme.dark", "Dark", "Dark")] @@ -430,7 +435,7 @@ fn theme_commands_and_options_report_preference_and_effective_colours() { assert_eq!(state["theme"], effective); } ok(&mut h, &c, "ui.set", json!({ "key": "theme", "value": "system" })); - h.input_mut().system_theme = Some(egui::Theme::Light); + desktop(&mut h, egui::Theme::Light); h.run_steps(2); let state = ok(&mut h, &c, "ui.state", json!({})); assert_eq!(state["theme_preference"], "System"); @@ -1421,12 +1426,9 @@ fn ui_panel_opens_closes_and_sizes_panes_and_survives_restore() { let (mut h, c) = harness(); ok(&mut h, &c, "ui.set", json!({"key":"panel", "value":"bookmarks"})); h.run_steps(3); - let state = ok(&mut h, &c, "ui.panel", json!({"panel":"side", "width": 401.6})); - assert_eq!(state["side_panels"]["side_width"], 401.6f32 as f64); - // Widths are clamped to the panel's limits. - let state = ok(&mut h, &c, "ui.panel", json!({"panel":"tools", "width": 9000})); - assert_eq!(state["side_panels"]["tools_width"], 520.0); - ok(&mut h, &c, "ui.panel", json!({"panel":"tools", "width": 300, "open": false})); + // Sizes are the dock's: dragged dividers or `ui.dock.apply`, never a `ui.panel` parameter. + assert!(call(&mut h, &c, "ui.panel", json!({"panel":"side", "width": 401.6})).is_err()); + ok(&mut h, &c, "ui.panel", json!({"panel":"tools", "open": false})); h.run_steps(3); assert_eq!(dock(&mut h, &c)["tools_open"], false); ok(&mut h, &c, "ui.panel", json!({"panel":"side", "open": false})); @@ -1445,19 +1447,15 @@ fn ui_panel_opens_closes_and_sizes_panes_and_survives_restore() { let (mut reloaded, client) = harness(); reloaded.state_mut().apply_settings(&saved); reloaded.run_steps(4); - let state = ok(&mut reloaded, &client, "ui.state", json!({}))["side_panels"].clone(); - assert_eq!( - state, - json!({"tools_side":"left", "tools_open":false, "tools_width":300.0, "side_open":true, "side_panel":"Bookmarks", "side_width":401.6f32 as f64}) - ); + assert_eq!(ok(&mut reloaded, &client, "ui.state", json!({}))["side_panels"], dock(&mut h, &c), "the restored panes are the saved ones"); // The ui.command form and the reset command. ok(&mut reloaded, &client, "ui.command", json!({"id":"ui.panel", "params":{"panel":"tools", "open":true}})); 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"})); + assert_eq!(dock(&mut reloaded, &client)["tools_side"], "right"); ok(&mut reloaded, &client, "ui.command", json!({"id":"ui.dock.reset"})); let state = ok(&mut reloaded, &client, "ui.state", json!({}))["side_panels"].clone(); - assert_eq!((state["tools_side"].clone(), state["tools_width"].clone(), state["side_width"].clone()), (json!("left"), json!(272.0), json!(330.0))); + assert_eq!((state["tools_side"].clone(), state["tools_open"].clone()), (json!("left"), json!(true)), "reset puts the Tools pane back"); assert_eq!(ok(&mut reloaded, &client, "ui.state", json!({}))["documents"][0]["pages"], 5); } @@ -1497,7 +1495,6 @@ fn a_script_opened_panel_shows() { 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 = dock(&mut h, &c); for combine in [false, true] { if combine { diff --git a/crates/ui-egui/tests/it/forms.rs b/crates/ui-egui/tests/it/forms.rs index 7fba4644ea..222880f072 100644 --- a/crates/ui-egui/tests/it/forms.rs +++ b/crates/ui-egui/tests/it/forms.rs @@ -12,10 +12,16 @@ use craft::ui::runtime::env::WindowKey; use craft::ui::runtime::toast; /// The app with `name` open from `bytes` at `zoom` percent, on a host whose file picker answers the -/// first save or export with `out`, as the user choosing that file would. -fn scripted_harness(name: &'static str, bytes: Vec, zoom: &'static str, out: &std::path::Path) -> Harness<'static, PdfCraftApp> { +/// first save or export with `out`, as the user choosing that file would. The host keeps what the +/// app writes in the returned store, which is where a test reads it back. +fn scripted_harness( + name: &'static str, + bytes: Vec, + zoom: &'static str, + out: &std::path::Path, +) -> (Harness<'static, PdfCraftApp>, Arc) { let files = Arc::new(ScriptedFiles::answering([Picked::Paths(vec![out.to_path_buf()])])); - let host = Arc::new(Host::builder(AppInfo { id: "pdfcraft", name: "PdfCraft", version: "0" }).files(files).build()); + let host = Arc::new(Host::builder(AppInfo { id: "pdfcraft", name: "PdfCraft", version: "0" }).files(files.clone()).build()); let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |cc| { crate::support::install_runtime(&cc.egui_ctx); { @@ -28,7 +34,7 @@ fn scripted_harness(name: &'static str, bytes: Vec, zoom: &'static str, out: } }); crate::support::settle(&mut h); - h + (h, files) } /// The text of the newest notice on screen, if one is shown. @@ -892,19 +898,20 @@ fn lithuanian_calendar_localizes_months_and_weekdays_without_changing_field_valu assert_eq!(value(&h, "due"), vec![format!("{nm:02}/15/{ny}")], "the PDF field keeps its own date format"); } -/// The value of `name` in a saved PDF, read back by opening it in a fresh app. -fn saved_value(path: &std::path::Path, name: &str) -> Vec { +/// The value of `name` in the PDF saved at `path` in `files`, read back by opening it in a fresh app. +fn saved_value(files: &ScriptedFiles, path: &std::path::Path, name: &str) -> Vec { let mut app = crate::control::new_app(); app.set_option(&egui::Context::default(), "language", "en").unwrap(); - app.open_bytes(&egui::Context::default(), "saved.pdf", None, std::fs::read(path).unwrap()).unwrap(); + let bytes = files.file(path).unwrap_or_else(|| panic!("nothing was saved at {}", path.display())); + app.open_bytes(&egui::Context::default(), "saved.pdf", None, bytes).unwrap(); app.session.get(app.views[0].id).unwrap().form.iter().find(|f| f.name == name).unwrap().value.clone() } -/// Step frames until the save has written `path`, instead of assuming it is there after a fixed -/// number of frames. The write is atomic, so the file appears only when it is complete. -fn wait_for_file(h: &mut Harness<'static, PdfCraftApp>, path: &std::path::Path) { +/// Step frames until the save has written `path` in `files`, instead of assuming it is there after +/// a fixed number of frames. The write is whole, so the file appears only when it is complete. +fn wait_for_file(h: &mut Harness<'static, PdfCraftApp>, files: &ScriptedFiles, path: &std::path::Path) { let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); - while !path.exists() { + while files.file(path).is_none() { assert!(std::time::Instant::now() < deadline, "the save never wrote {}", path.display()); h.run_steps(1); std::thread::sleep(std::time::Duration::from_millis(10)); @@ -930,14 +937,14 @@ fn saving_while_still_typing_in_a_field_saves_the_text() { // Issue #166: ⌘S with the field still focused saved it blank. let dir = scratch("save-focused"); let out = dir.join("saved.pdf"); - let mut h = scripted_harness("form.pdf", include_bytes!("../data/form.pdf").to_vec(), "150", &out); + let (mut h, files) = scripted_harness("form.pdf", include_bytes!("../data/form.pdf").to_vec(), "150", &out); click_field(&mut h, "name", 0); h.event(egui::Event::Text("Browser Form 123".into())); h.run_steps(2); assert!(h.state().views[0].session.forms.focus.is_some(), "still typing"); h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::S); h.run_steps(3); - assert_eq!(saved_value(&out, "name"), ["Browser Form 123"], "the saved PDF has the typed text"); + assert_eq!(saved_value(&files, &out, "name"), ["Browser Form 123"], "the saved PDF has the typed text"); assert_eq!(value(&h, "name"), ["Browser Form 123"]); let doc = h.state().session.get(h.state().views[0].id).unwrap(); assert!(!doc.dirty, "and the document is saved, not left with an unsaved change"); @@ -970,7 +977,7 @@ fn tabbing_back_to_the_same_field_then_saving_keeps_the_committed_value() { } else { validated_form() }; - let mut h = scripted_harness("tab.pdf", bytes, "150", &out); + let (mut h, files) = scripted_harness("tab.pdf", bytes, "150", &out); click_field(&mut h, "qty", 0); h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); h.event(egui::Event::Text("42".into())); @@ -983,8 +990,8 @@ fn tabbing_back_to_the_same_field_then_saving_keeps_the_committed_value() { h.run_steps(3); h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::S); } - wait_for_file(&mut h, &out); - assert_eq!(saved_value(&out, "qty"), ["42"], "{case}: saving cannot restore the old value"); + wait_for_file(&mut h, &files, &out); + assert_eq!(saved_value(&files, &out, "qty"), ["42"], "{case}: saving cannot restore the old value"); assert_eq!(value(&h, "qty"), ["42"], "{case}"); // One typing action is one history entry, even after saving. Escape closes the // untouched editor before undoing the document rather than the TextEdit buffer. @@ -1014,7 +1021,7 @@ fn closing_while_still_typing_in_a_field_asks_to_save() { fn close_all_saves_text_typed_in_a_tab_that_is_no_longer_active() { let dir = scratch("close-all"); let out = dir.join("first.pdf"); - let mut h = scripted_harness("form.pdf", include_bytes!("../data/form.pdf").to_vec(), "150", &out); + let (mut h, files) = scripted_harness("form.pdf", include_bytes!("../data/form.pdf").to_vec(), "150", &out); click_field(&mut h, "name", 0); h.event(egui::Event::Text("Typed in tab one".into())); h.run_steps(2); @@ -1027,8 +1034,8 @@ fn close_all_saves_text_typed_in_a_tab_that_is_no_longer_active() { h.run_steps(2); assert!(asks_to_save(&h), "the first document has an unsaved change"); h.get_all_by_label("Save").last().expect("the prompt's Save button").click(); - wait_for_file(&mut h, &out); - assert_eq!(saved_value(&out, "name"), ["Typed in tab one"]); + wait_for_file(&mut h, &files, &out); + assert_eq!(saved_value(&files, &out, "name"), ["Typed in tab one"]); let _ = std::fs::remove_dir_all(&dir); } @@ -1056,9 +1063,9 @@ fn type_then_save_in_one_frame(h: &mut Harness<'static, PdfCraftApp>, name: &str fn typing_and_saving_in_the_same_frame_saves_the_last_keystrokes() { let dir = scratch("same-frame"); let out = dir.join("saved.pdf"); - let mut h = scripted_harness("form.pdf", include_bytes!("../data/form.pdf").to_vec(), "150", &out); + let (mut h, files) = scripted_harness("form.pdf", include_bytes!("../data/form.pdf").to_vec(), "150", &out); type_then_save_in_one_frame(&mut h, "name", "Browser", egui::Event::Text(" Form 123".into())); - assert_eq!(saved_value(&out, "name"), ["Browser Form 123"]); + assert_eq!(saved_value(&files, &out, "name"), ["Browser Form 123"]); let _ = std::fs::remove_dir_all(&dir); } @@ -1066,7 +1073,7 @@ fn typing_and_saving_in_the_same_frame_saves_the_last_keystrokes() { fn escape_and_save_in_the_same_frame_discards_the_draft() { let dir = scratch("escape"); let out = dir.join("saved.pdf"); - let mut h = scripted_harness("form.pdf", include_bytes!("../data/form.pdf").to_vec(), "150", &out); + let (mut h, _files) = scripted_harness("form.pdf", include_bytes!("../data/form.pdf").to_vec(), "150", &out); let before = value(&h, "name"); type_then_save_in_one_frame(&mut h, "name", "Discard me", key(egui::Key::Escape, egui::Modifiers::NONE)); assert_eq!(value(&h, "name"), before, "Escape cancels typing, even with ⌘S right after it"); @@ -1091,13 +1098,14 @@ fn an_unrelated_command_leaves_the_field_being_typed_in_alone() { fn exporting_form_data_while_typing_includes_the_text() { let dir = scratch("export"); let out = dir.join("data.xfdf"); - let mut h = scripted_harness("form.pdf", include_bytes!("../data/form.pdf").to_vec(), "150", &out); + let (mut h, files) = scripted_harness("form.pdf", include_bytes!("../data/form.pdf").to_vec(), "150", &out); click_field(&mut h, "name", 0); h.event(egui::Event::Text("Exported value".into())); h.run_steps(2); let ctx_h = h.ctx.clone(); h.state_mut().export_data_dialog(&ctx_h, false, true); - assert!(std::fs::read_to_string(&out).unwrap().contains("Exported value")); + wait_for_file(&mut h, &files, &out); + assert!(String::from_utf8_lossy(&files.file(&out).unwrap_or_default()).contains("Exported value")); let _ = std::fs::remove_dir_all(&dir); } @@ -1255,13 +1263,13 @@ fn buttons_over_text_show_the_pointing_hand_not_the_i_beam() { fn a_rejected_value_keeps_the_typing_and_stops_the_save() { let dir = scratch("rejected"); let out = dir.join("saved.pdf"); - let mut h = scripted_harness("order.pdf", validated_form(), "150", &out); + let (mut h, files) = scripted_harness("order.pdf", validated_form(), "150", &out); click_field(&mut h, "qty", 0); h.event(egui::Event::Text("500".into())); h.run_steps(2); h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::S); h.run_steps(4); - assert!(!out.exists(), "nothing is saved without the typed value"); + assert!(files.file(&out).is_none(), "nothing is saved without the typed value"); assert_eq!(value(&h, "qty"), ["4"], "the field keeps its valid value"); let focus = h.state().views[0].session.forms.focus.clone().expect("the editor stays open"); assert_eq!(focus.text, "4500", "with the text (typed after the 4), so the user can fix it"); @@ -1277,17 +1285,17 @@ fn a_rejected_value_keeps_the_typing_and_stops_the_save() { fn a_save_shortcut_pressed_while_typing_saves_only_the_document_it_was_pressed_in() { let dir = scratch("deferred-doc"); let out = dir.join("saved.pdf"); - let mut h = scripted_harness("form.pdf", include_bytes!("../data/form.pdf").to_vec(), "150", &out); + let (mut h, files) = scripted_harness("form.pdf", include_bytes!("../data/form.pdf").to_vec(), "150", &out); click_field(&mut h, "name", 0); h.event(egui::Event::Text("Tab one".into())); h.run_steps(2); one_frame(&mut h, vec![key(egui::Key::S, egui::Modifiers::COMMAND)]); - assert!(!out.exists(), "⌘S while typing waits a frame for the field"); + assert!(files.file(&out).is_none(), "⌘S while typing waits a frame for the field"); // Before the deferred ⌘S runs, another document becomes active. let ctx_h = h.ctx.clone(); h.state_mut().open_bytes(&ctx_h, "other.pdf", None, include_bytes!("../data/form.pdf").to_vec()).unwrap(); h.run_steps(3); - assert!(!out.exists(), "the other document is not saved by a shortcut pressed in the first"); + assert!(files.file(&out).is_none(), "the other document is not saved by a shortcut pressed in the first"); let _ = std::fs::remove_dir_all(&dir); } @@ -1304,19 +1312,19 @@ fn a_value_refused_on_tab_keeps_save_in_the_same_frame_from_running() { fn refused_value_stops_save(commit_key: egui::Key, case: &str) { let dir = scratch(case); let out = dir.join("saved.pdf"); - let mut h = scripted_harness("order.pdf", validated_form(), "150", &out); + let (mut h, files) = scripted_harness("order.pdf", validated_form(), "150", &out); click_field(&mut h, "qty", 0); h.event(egui::Event::Text("500".into())); h.run_steps(2); one_frame(&mut h, vec![key(commit_key, egui::Modifiers::NONE), key(egui::Key::S, egui::Modifiers::COMMAND)]); h.run_steps(3); assert_eq!(value(&h, "qty"), ["4"]); - assert!(!out.exists(), "nothing is saved right after the field refused its value"); + assert!(files.file(&out).is_none(), "nothing is saved right after the field refused its value"); // The refused text is back in the field, so a later ⌘S stops again instead of saving 4. assert_eq!(h.state().views[0].session.forms.focus.as_ref().map(|f| f.text.as_str()), Some("4500")); h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::S); h.run_steps(4); - assert!(!out.exists()); + assert!(files.file(&out).is_none()); let _ = std::fs::remove_dir_all(&dir); } @@ -1372,7 +1380,7 @@ mod revert_tests { fn reverting_rejected_input_saves_the_original_field_and_appearance() { let dir = RevertDir::new(); let path = dir.0.join("saved.pdf"); - let mut h = scripted_harness("form.pdf", include_bytes!("../data/form.pdf").to_vec(), "150", &path); + let (mut h, files) = scripted_harness("form.pdf", include_bytes!("../data/form.pdf").to_vec(), "150", &path); let ctx_h = h.ctx.clone(); assert!(h.state_mut().apply_edit( &ctx_h, @@ -1382,7 +1390,7 @@ mod revert_tests { // A document with no file asks where to save: the scripted answer arrives on a later pass. h.state_mut().save_active(&ctx_h, pdfcraft_ui_egui::SaveTarget::InPlace); crate::support::wait_until(&mut h, "the save", |s| s.views.first().and_then(|v| s.session.get(v.id)).is_some_and(|d| !d.dirty)); - let saved = std::fs::read(&path).unwrap(); + let saved = files.file(&path).expect("the save wrote the file"); let ctx_h = h.ctx.clone(); assert!(h.state_mut().apply_edit( &ctx_h, @@ -1402,7 +1410,7 @@ mod revert_tests { h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::S); h.run_steps(4); assert_eq!(h.state().views[0].session.forms.focus.as_ref().unwrap().text, "99"); - assert_eq!(std::fs::read(&path).unwrap(), saved, "rejection leaves the saved file untouched"); + assert_eq!(files.file(&path), Some(saved.clone()), "rejection leaves the saved file untouched"); assert!(h.execute("file.revert")); h.run_steps(2); h.get_all_by_label("Revert").last().expect("confirmation button").click(); @@ -1412,8 +1420,8 @@ mod revert_tests { assert_eq!(value(&h, "name"), ["Saved original"]); let ctx_h = h.ctx.clone(); assert!(h.state_mut().save_active(&ctx_h, pdfcraft_ui_egui::SaveTarget::InPlace)); - assert_eq!(saved_value(&path, "name"), ["Saved original"]); - let bytes = std::fs::read(&path).unwrap(); + assert_eq!(saved_value(&files, &path, "name"), ["Saved original"]); + let bytes = files.file(&path).expect("the save wrote the file"); assert_eq!(bytes, saved, "later Save cannot resurrect the discarded draft"); let mut renderer = pdfcraft_render::PageRenderer::new(std::sync::Arc::new(bytes), Default::default()); let output = renderer.render(pdfcraft_render::RenderRequest { page: 0, kind: pdfcraft_render::RequestKind::Text, ..Default::default() }); @@ -1622,7 +1630,7 @@ fn a_list_box_click_picks_one_of_two_options_with_the_same_export_value() { ]); let dir = scratch("duplicate-exports"); let out = dir.join("saved.pdf"); - let mut h = scripted_harness("dup.pdf", bytes, "100", &out); + let (mut h, files) = scripted_harness("dup.pdf", bytes, "100", &out); assert_eq!(selected(&h, "dup"), [1], "One-B is selected, not One-A too"); let r = { @@ -1642,9 +1650,9 @@ fn a_list_box_click_picks_one_of_two_options_with_the_same_export_value() { assert_eq!(selected(&h, "dup"), [0]); h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::S); - wait_for_file(&mut h, &out); + wait_for_file(&mut h, &files, &out); let mut app = crate::control::new_app(); - app.open_bytes(&egui::Context::default(), "saved.pdf", None, std::fs::read(&out).unwrap()).unwrap(); + app.open_bytes(&egui::Context::default(), "saved.pdf", None, files.file(&out).unwrap()).unwrap(); let reopened = app.session.get(app.views[0].id).unwrap().form.iter().find(|f| f.name == "dup").unwrap().clone(); assert_eq!(reopened.value, ["1"], "/V is the one export value"); assert_eq!(reopened.selected, [0], "/I keeps One-A through the save"); @@ -1903,10 +1911,11 @@ fn guide_fixture() -> Vec { fn a_form_button_opens_only_a_real_pdf_and_returns_to_the_tab_it_opened() { let saved = std::env::temp_dir().join(format!("pdfcraft-fake-{}.pdf", std::process::id())); let files = Arc::new(ScriptedFiles::answering([Picked::Paths(vec![saved.clone()])])); + let host_files = files.clone(); let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |cc| { crate::support::install_runtime(&cc.egui_ctx); { - let mut app = crate::control::app_with_files(files); + let mut app = crate::control::app_with_files(host_files); app.set_option(&egui::Context::default(), "language", "en").unwrap(); app.open_bytes(&egui::Context::default(), "form.pdf", None, guide_fixture()).unwrap(); // Another document named like the attachment, its bytes the attachment's and an update. @@ -1921,9 +1930,9 @@ fn a_form_button_opens_only_a_real_pdf_and_returns_to_the_tab_it_opened() { // A text file named .pdf is offered to save, not opened. let _ = std::fs::remove_file(&saved); run_button_script(&mut h, id, "go", "this.exportDataObject({cName: 'fake.pdf', nLaunch: 2});"); - wait_for_file(&mut h, &saved); + wait_for_file(&mut h, &files, &saved); assert_eq!(tabs(&h), 2, "no tab for a file that isn't a PDF: {:?}", notice(&h)); - assert_eq!(std::fs::read(&saved).ok().as_deref(), Some(&b"not a PDF at"[..]), "offered to save instead"); + assert_eq!(files.file(&saved).as_deref(), Some(&b"not a PDF at"[..]), "offered to save instead"); let _ = std::fs::remove_file(&saved); // The real attached PDF opens in a tab of its own, though another inner.pdf starts with it. h.state_mut().active = Some(0); @@ -2024,7 +2033,7 @@ fn combo_harness() -> Harness<'static, PdfCraftApp> { fn an_editable_combo_box_takes_a_typed_value() { let dir = scratch("editable-combo"); let out = dir.join("saved.pdf"); - let mut h = scripted_harness("combo.pdf", combo_form(), "150", &out); + let (mut h, files) = scripted_harness("combo.pdf", combo_form(), "150", &out); click_field(&mut h, "fruit", 0); assert_eq!(focused(&h), Some(("fruit".into(), 0))); h.event(egui::Event::Text("Cherry".into())); @@ -2048,8 +2057,8 @@ fn an_editable_combo_box_takes_a_typed_value() { h.run_steps(4); assert_eq!(value(&h, "fruit"), ["Damson"], "Tab commits the typed value"); h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::S); - wait_for_file(&mut h, &out); - assert_eq!(saved_value(&out, "fruit"), ["Damson"]); + wait_for_file(&mut h, &files, &out); + assert_eq!(saved_value(&files, &out, "fruit"), ["Damson"]); // Undo takes the typing back as one step. undo(&mut h); h.run_steps(2); diff --git a/crates/ui-egui/tests/it/pinned_tools.rs b/crates/ui-egui/tests/it/pinned_tools.rs index ec0f29333c..b3f75de5dc 100644 --- a/crates/ui-egui/tests/it/pinned_tools.rs +++ b/crates/ui-egui/tests/it/pinned_tools.rs @@ -109,13 +109,13 @@ fn clicking_pinned_tool_card_selects_it() { #[test] fn pin_tool_dialog_workflow() { - let mut h = harness(|app| { - app.set_option(&egui::Context::default(), "dialog", "pin-tool").unwrap(); - }); + let mut h = harness(|_| {}); + // Home's Pin a tool… opens it. + h.get_by_label("Pin a tool…").click(); h.run_steps(3); - // Modal is open - h.get_by_label_contains("Pin tools to Home"); + // Modal is open (its heading carries the same name, so the dialog is found by its role). + h.get_by_role_and_label(egui::accesskit::Role::Dialog, "Pin tools to Home"); h.get_by_label("Done"); // Pin a tool from inside the dialog diff --git a/crates/ui-egui/tests/it/support/input.rs b/crates/ui-egui/tests/it/support/input.rs index 0030c463d4..9dd503781a 100644 --- a/crates/ui-egui/tests/it/support/input.rs +++ b/crates/ui-egui/tests/it/support/input.rs @@ -63,3 +63,19 @@ pub fn double_click(h: &mut Harness<'_, S>, p: Pos2) { } h.run_steps(2); } + +/// Drops `files` on the window as the platform does: a frame with them held over the window, then +/// the frame of the drop, which no longer holds them (egui-winit clears the hovered files on a +/// drop). A drop with no hover before it starts no drag session, so nothing would take it. +pub fn drop_files(h: &mut Harness<'_, S>, files: impl IntoIterator) { + let files: Vec = files.into_iter().collect(); + let held = files.iter().map(|file| { + let path = file.path(); + egui::HoveredFile { path: (!path.as_os_str().is_empty()).then(|| path.to_path_buf()), mime: String::new() } + }); + h.input_mut().hovered_files = held.collect(); + h.step(); + h.input_mut().hovered_files.clear(); + h.input_mut().dropped_files.extend(files); + h.step(); +} diff --git a/crates/ui-egui/tests/it/ui.rs b/crates/ui-egui/tests/it/ui.rs index 3bd0e3974e..819e5b3822 100644 --- a/crates/ui-egui/tests/it/ui.rs +++ b/crates/ui-egui/tests/it/ui.rs @@ -983,7 +983,7 @@ fn dropping_a_pdf_on_the_window_opens_it() { h.run_steps(3); assert!(h.state().views.is_empty()); let file: egui::DroppedFileHandle = std::sync::Arc::new(Dropped { path: "dropped.pdf".into(), bytes: FIXTURE.to_vec() }); - h.input_mut().dropped_files.push(file); + support::input::drop_files(&mut h, [file]); support::wait_until(&mut h, "dropped document", |app| app.views.len() == 1 && app.password_prompt.is_none()); assert_eq!(h.state().views.len(), 1, "the dropped PDF opens in a tab"); h.get_by_label_contains("dropped.pdf"); @@ -1010,11 +1010,11 @@ fn dropping_an_open_pdf_again_focuses_its_tab() { }); h.run_steps(3); let file: egui::DroppedFileHandle = std::sync::Arc::new(Dropped { path: path.clone(), bytes: FIXTURE.to_vec() }); - h.input_mut().dropped_files.push(file.clone()); + support::input::drop_files(&mut h, [file.clone()]); // The drop opens through the background worker on a live window; wait for the tab. support::wait_until(&mut h, "dropped document", |app| app.views.len() == 1); assert_eq!(h.state().views.len(), 1, "the dropped PDF opens in a tab"); - h.input_mut().dropped_files.push(file); + support::input::drop_files(&mut h, [file]); h.run_steps(3); assert_eq!(h.state().views.len(), 1, "dropping it again adds no tab"); std::fs::remove_dir_all(&dir).unwrap(); @@ -1048,7 +1048,7 @@ fn a_file_dropped_on_the_page_grid_is_read_from_disk_and_inserted() { }; assert_eq!(pages(&h), 1); let file: egui::DroppedFileHandle = std::sync::Arc::new(Dropped { path: path.clone(), bytes: Vec::new() }); - h.input_mut().dropped_files.push(file); + support::input::drop_files(&mut h, [file]); for _ in 0..300 { h.run_steps(1); if pages(&h) == 2 { @@ -1079,7 +1079,7 @@ fn pdfs_dropped_on_the_combine_tab_join_its_list() { std::fs::write(&path, FIXTURE).unwrap(); let on_disk: egui::DroppedFileHandle = std::sync::Arc::new(Dropped { path: path.clone(), bytes: Vec::new() }); let in_memory: egui::DroppedFileHandle = std::sync::Arc::new(Dropped { path: "second.pdf".into(), bytes: FIXTURE.to_vec() }); - h.input_mut().dropped_files.extend([on_disk, in_memory]); + support::input::drop_files(&mut h, [on_disk, in_memory]); h.run_steps(3); std::fs::remove_file(&path).ok(); let app = h.state(); @@ -1107,7 +1107,7 @@ fn a_folder_dropped_on_the_combine_tab_adds_its_pdfs() { h.execute("page.combine"); h.run_steps(2); let folder: egui::DroppedFileHandle = std::sync::Arc::new(Dropped { path: dir.clone(), bytes: Vec::new() }); - h.input_mut().dropped_files.push(folder); + support::input::drop_files(&mut h, [folder]); h.run_steps(3); let _ = std::fs::remove_dir_all(&dir); let names: Vec<_> = h.state().combine_draft.iter().map(|f| f.name.clone()).collect(); @@ -1151,7 +1151,7 @@ fn files_dropped_on_the_combine_tab_join_the_end_of_its_list_in_the_order_droppe let in_memory = |name: &str, bytes: &[u8]| -> egui::DroppedFileHandle { std::sync::Arc::new(Dropped { path: name.into(), bytes: bytes.to_vec() }) }; let dropped = [on_disk("c.pdf"), in_memory("a.pdf", FIXTURE), in_memory("notes.txt", b"Some notes"), on_disk("b.pdf")]; - h.input_mut().dropped_files.extend(dropped); + support::input::drop_files(&mut h, dropped); h.run_steps(3); let _ = std::fs::remove_dir_all(&dir); assert!(h.state().views.is_empty(), "nothing opens"); @@ -1178,7 +1178,7 @@ fn a_file_combine_does_not_take_is_left_out_of_a_drop_and_named() { // A PDF without the name of one is still a PDF. std::sync::Arc::new(Dropped { path: "scan".into(), bytes: FIXTURE.to_vec() }), ]; - h.input_mut().dropped_files.extend(dropped); + support::input::drop_files(&mut h, dropped); h.run_steps(3); std::fs::remove_file(&path).ok(); assert_eq!(combine_names(&h), ["first.pdf", "one.pdf", "scan"]); @@ -1195,14 +1195,14 @@ fn a_pdf_dropped_on_a_document_opens_while_the_combine_tab_waits_behind_it() { h.run_steps(2); assert!(!h.state().combine_showing() && h.state().combine_tab.open); let file: egui::DroppedFileHandle = std::sync::Arc::new(Dropped { path: "dropped.pdf".into(), bytes: FIXTURE.to_vec() }); - h.input_mut().dropped_files.push(file); + support::input::drop_files(&mut h, [file]); support::wait_until(&mut h, "dropped document", |app| app.views.len() == 2); assert_eq!(combine_names(&h), ["first.pdf"], "the Combine files list is left as it was"); } -/// An app on a host whose jobs wait for the test (`ManualJobs`), taking its file requests from -/// `intake`, with an inline file watcher. -fn host_app(jobs: std::sync::Arc, intake: craft::platform::open::FileIntake) -> PdfCraftApp { +/// An app on a host whose jobs run on `jobs`, taking its file requests from `intake`, with an +/// inline file watcher. +fn host_app(jobs: std::sync::Arc, intake: craft::platform::open::FileIntake) -> PdfCraftApp { use craft::host::{AppInfo, Host, ScriptedFiles, Wake}; use craft::platform::clipboard::{Clipboard, SystemClipboard}; use craft::platform::watch::FileWatch; @@ -1219,7 +1219,8 @@ fn host_app(jobs: std::sync::Arc, intake: craft::platfo PdfCraftApp::with_host(std::sync::Arc::new(host), services) } -/// A window whose app takes the OS's file requests from the returned sender (`FileIntake`). +/// A window whose app takes the OS's file requests from the returned sender (`FileIntake`). Its +/// jobs run on threads, as the running app's do, so a requested file opens while the test steps. fn intake_harness() -> (Harness<'static, PdfCraftApp>, craft::platform::open::IntakeSender) { use craft::host::Wake; use craft::platform::open::FileIntake; @@ -1227,7 +1228,7 @@ fn intake_harness() -> (Harness<'static, PdfCraftApp>, craft::platform::open::In let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(move |cc| { crate::support::install_runtime(&cc.egui_ctx); { - let mut app = host_app(std::sync::Arc::new(craft::host::ManualJobs::new()), intake); + let mut app = host_app(std::sync::Arc::new(craft::host::ThreadJobs), intake); app.set_option(&egui::Context::default(), "language", "en").unwrap(); app }