diff --git a/crates/ui-egui/tests/it/attach_picker_target.rs b/crates/ui-egui/tests/it/attach_picker_target.rs index ac1aed7361..9f36275fd5 100644 --- a/crates/ui-egui/tests/it/attach_picker_target.rs +++ b/crates/ui-egui/tests/it/attach_picker_target.rs @@ -2,8 +2,16 @@ //! user switches tabs while choosing, the pick is dropped (and they are told) rather than the file //! landing in whichever document is active by then. +use std::sync::Arc; + +use craft::host::{AppInfo, Host, ManualJobs, Picked, ScriptedFiles, Wake}; +use craft::platform::clipboard::{Clipboard, EventClipboard}; +use craft::platform::open::FileIntake; +use craft::platform::watch::FileWatch; use egui_kittest::Harness; -use pdfcraft_ui_egui::PdfCraftApp; +use pdfcraft_ui_egui::{AppServices, PdfCraftApp}; + +use crate::support; /// A one-page document with a proper xref table. fn fixture() -> Vec { @@ -27,16 +35,33 @@ fn fixture() -> Vec { out } -fn harness() -> Harness<'static, PdfCraftApp> { - let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(|_cc| { - let mut app = PdfCraftApp::new(); +/// The app on a host whose picks stay open until the test answers them, with the files that +/// host is asked for. +fn harness() -> (Harness<'static, PdfCraftApp>, Arc) { + let files = Arc::new(ScriptedFiles::held()); + let jobs = Arc::new(ManualJobs::new()); + let host = Arc::new(Host::builder(AppInfo { id: "pdfcraft", name: "PdfCraft", version: "0" }).jobs(jobs.clone()).files(files.clone()).build()); + + let (intake, _sender) = FileIntake::new(Wake::none()); + let services = AppServices::new( + Wake::none(), + Clipboard::new(EventClipboard::new(|| 0, |_| Ok(0))), + None, + None, + intake, + FileWatch::new(Wake::none()).inline(), + ); + + let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(move |_cc| { + let mut app = PdfCraftApp::with_host(host, services); app.set_option("language", "en").unwrap(); app.open_bytes("a.pdf", None, fixture()).unwrap(); app.open_bytes("b.pdf", None, fixture()).unwrap(); + jobs.run_all(); app }); h.run_steps(2); - h + (h, files) } fn dirty(app: &PdfCraftApp, view: usize) -> bool { @@ -51,16 +76,16 @@ fn an_attachment_pick_is_dropped_when_the_user_switches_tabs() { let file = dir.join("note.txt"); std::fs::write(&file, b"hello").unwrap(); - let mut h = harness(); + let (mut h, files) = harness(); h.state_mut().active = Some(0); - h.state_mut().pick_override = Some(vec![file.to_string_lossy().into_owned()]); assert!(h.state_mut().execute("edit.attach")); + h.run_steps(2); // The user switches tabs before the pick arrives. h.state_mut().active = Some(1); + assert!(files.answer(Picked::Paths(vec![file.clone()])).is_some(), "the attach picker was open"); h.run_steps(2); assert!(!dirty(h.state(), 0), "the document the pick was for is unchanged"); assert!(!dirty(h.state(), 1), "the newly active document did not get the attachment"); - let toast = h.state().toast.as_ref().map(|(m, _)| m.clone()).unwrap_or_default(); - assert!(toast.contains("document changed"), "the user is told why nothing happened: {toast:?}"); + assert!(support::shown_notice(&mut h).is_some(), "the user is told why nothing happened"); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/ui-egui/tests/it/pickers.rs b/crates/ui-egui/tests/it/pickers.rs index 7324307e57..889fa9cea0 100644 --- a/crates/ui-egui/tests/it/pickers.rs +++ b/crates/ui-egui/tests/it/pickers.rs @@ -1,15 +1,22 @@ //! Native file pickers never block the frame. A blocking picker ran a nested run loop inside //! winit's event handler on macOS, which crashed the app when the user clicked File ▸ Open (or //! any other open, save or folder picker). Commands now return at once, and the chosen files are -//! used on a later frame. `pick_override` stands in for the native panel and, like it, answers -//! on a later frame. +//! used on a later frame. The host's `ScriptedFiles` stands in for the native panel and, like it, +//! answers on a later frame. use crate::support; +use std::ops::{Deref, DerefMut}; +use std::sync::Arc; + +use craft::host::{AppInfo, Host, ManualJobs, PickKind, Picked, ScriptedFiles, Wake}; +use craft::platform::clipboard::{Clipboard, EventClipboard}; +use craft::platform::open::{FileIntake, IntakeSender}; +use craft::platform::watch::FileWatch; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use pdfcraft_render::{PageRenderer, RenderRequest, RequestKind}; -use pdfcraft_ui_egui::PdfCraftApp; +use pdfcraft_ui_egui::{AppServices, PdfCraftApp}; /// An `n`-page document with a proper xref table. fn fixture(n: usize) -> Vec { @@ -42,33 +49,116 @@ fn pages(app: &PdfCraftApp, view: usize) -> usize { PageRenderer::new(doc.bytes.clone(), Default::default()).page_count() } -/// A shell with `docs` open, each the given number of pages. -fn harness(docs: &[usize]) -> Harness<'static, PdfCraftApp> { +/// The app on a host whose files are scripted and whose jobs wait for the test, with the sender +/// of its file intake (what the OS and the browser deliver opens through). +struct Rig { + h: Harness<'static, PdfCraftApp>, + files: Arc, + jobs: Arc, + intake: IntakeSender, +} + +impl Deref for Rig { + type Target = Harness<'static, PdfCraftApp>; + fn deref(&self) -> &Self::Target { + &self.h + } +} + +impl DerefMut for Rig { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.h + } +} + +impl Rig { + /// `n` frames, running the jobs the app has queued before each one. + fn steps(&mut self, n: usize) { + for _ in 0..n { + self.jobs.run_all(); + self.h.run_steps(1); + } + } + + /// Answers the open pick and lets the app use the answer on later frames. + fn answer(&mut self, picked: Picked) { + assert!(self.files.answer(picked).is_some(), "a pick was open to answer"); + self.steps(2); + } + + /// Hands the app a file that arrived as bytes, as a startup URL or a browser read does. + fn deliver(&self, name: &str, bytes: Vec) { + self.intake.open_bytes(name.into(), Arc::from(bytes)); + } +} + +/// A shell with `docs` open, each the given number of pages, whose picks stay open until the +/// test answers them. +fn harness(docs: &[usize]) -> Rig { + rig(docs, ScriptedFiles::held()) +} + +fn rig(docs: &[usize], files: ScriptedFiles) -> Rig { + let files = Arc::new(files); + let jobs = Arc::new(ManualJobs::new()); + let host = Arc::new(Host::builder(AppInfo { id: "pdfcraft", name: "PdfCraft", version: "0" }).jobs(jobs.clone()).files(files.clone()).build()); + + let (intake, sender) = FileIntake::new(Wake::none()); + let services = AppServices::new( + Wake::none(), + Clipboard::new(EventClipboard::new(|| 0, |_| Ok(0))), + None, + None, + intake, + FileWatch::new(Wake::none()).inline(), + ); + let docs = docs.to_vec(); - let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(move |_cc| { - let mut app = PdfCraftApp::new(); + let run = jobs.clone(); + let h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(move |_cc| { + let mut app = PdfCraftApp::with_host(host, services); app.set_option("language", "en").unwrap(); for (i, n) in docs.iter().enumerate() { app.open_bytes(&format!("doc{i}.pdf"), None, fixture(*n)).unwrap(); } + run.run_all(); app }); - h.run_steps(2); - h + let mut rig = Rig { h, files, jobs, intake: sender }; + rig.steps(2); + rig +} + +/// Runs frames, and the jobs between them, until `ready` holds. +fn settle(r: &mut Rig, what: &str, ready: impl Fn(&PdfCraftApp) -> bool) { + for _ in 0..500 { + r.steps(1); + if ready(r.state()) { + return; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + panic!("timed out waiting for {what}"); +} + +/// Presses the button called `label` of the dialog on top (the last such node drawn). +fn press(r: &mut Rig, label: &str) { + r.get_all_by_label(label).last().unwrap_or_else(|| panic!("no {label:?} button on screen")).click(); + r.steps(2); } #[test] fn file_open_returns_at_once_and_opens_the_pick_when_preparation_finishes() { - let dir = std::env::temp_dir().join(format!("printcraft-pickers-open-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); + let dir = scratch("open"); let file = dir.join("picked.pdf"); std::fs::write(&file, fixture(2)).unwrap(); let mut h = harness(&[]); - h.state_mut().pick_override = Some(vec![file.to_string_lossy().into_owned()]); assert!(h.state_mut().execute("file.open")); assert!(h.state().views.is_empty(), "the command must not wait for the picker"); - support::wait_until(&mut h, "picked document", |app| app.views.len() == 1 && app.password_prompt.is_none()); + assert!(matches!(h.files.requests().first().map(|r| r.kind), Some(PickKind::Open | PickKind::OpenMany))); + h.answer(Picked::Paths(vec![file.clone()])); + settle(&mut h, "picked document", |app| app.views.len() == 1 && app.password_prompt.is_none()); assert_eq!(h.state().views.len(), 1, "the picked file opens on a later frame"); assert_eq!(pages(h.state(), 0), 2); let (_, id) = h.state().active_ids().unwrap(); @@ -80,38 +170,34 @@ fn file_open_returns_at_once_and_opens_the_pick_when_preparation_finishes() { #[test] fn insert_from_file_uses_the_pick_on_the_next_frame() { - let dir = std::env::temp_dir().join(format!("printcraft-pickers-insert-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); + let dir = scratch("insert"); let file = dir.join("more.pdf"); std::fs::write(&file, fixture(2)).unwrap(); let mut h = harness(&[3]); - h.state_mut().pick_override = Some(vec![file.to_string_lossy().into_owned()]); assert!(h.state_mut().execute("page.insert")); + h.steps(2); assert_eq!(pages(h.state(), 0), 3, "nothing is inserted until the pick arrives"); - h.run_steps(2); + h.answer(Picked::Paths(vec![file])); assert_eq!(pages(h.state(), 0), 5); let _ = std::fs::remove_dir_all(&dir); } #[test] fn a_pick_for_a_document_that_is_no_longer_active_is_dropped() { - let dir = std::env::temp_dir().join(format!("printcraft-pickers-switch-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); + let dir = scratch("switch"); let file = dir.join("more.pdf"); std::fs::write(&file, fixture(2)).unwrap(); let mut h = harness(&[3, 4]); h.state_mut().active = Some(0); - h.state_mut().pick_override = Some(vec![file.to_string_lossy().into_owned()]); assert!(h.state_mut().execute("page.insert")); // The user switches tabs before the pick arrives. h.state_mut().active = Some(1); - h.run_steps(2); + h.answer(Picked::Paths(vec![file])); assert_eq!(pages(h.state(), 0), 3, "the document the pick was for is unchanged"); assert_eq!(pages(h.state(), 1), 4, "the newly active document is unchanged"); - let toast = h.state().toast.as_ref().map(|(m, _)| m.clone()).unwrap_or_default(); - assert!(toast.contains("document changed"), "the user is told why nothing happened: {toast:?}"); + assert!(support::shown_notice(&mut h).is_some(), "the user is told why nothing happened"); let _ = std::fs::remove_dir_all(&dir); } @@ -143,14 +229,16 @@ fn save_as_writes_on_a_later_frame_including_edits_made_meanwhile() { let dir = scratch("save-as"); let out = dir.join("saved.pdf"); let mut h = harness(&[3]); - h.state_mut().pick_override = Some(vec![out.to_string_lossy().into_owned()]); assert!(h.state_mut().execute("file.save_as")); + h.steps(2); assert!(!out.exists(), "the command must not wait for the picker"); + assert_eq!(h.files.open(), 1, "the Save picker is open"); // The user keeps working while the panel is open. h.state_mut().apply_edit(pdfcraft_engine::Edit::DeletePages { pages: vec![0] }); - h.run_steps(2); + h.answer(Picked::Paths(vec![out.clone()])); assert_eq!(page_count(std::fs::read(&out).unwrap()), 2, "the edit made while choosing is saved too"); assert!(!dirty(h.state(), 0)); + assert!(matches!(h.files.requests().first().map(|r| r.kind), Some(PickKind::Save))); let _ = std::fs::remove_dir_all(&dir); } @@ -160,13 +248,13 @@ fn save_on_close_closes_the_tab_only_once_the_file_is_written() { let out = dir.join("closed.pdf"); let mut h = harness(&[2]); rotate_first_page(h.state_mut()); - h.state_mut().request_close_tab(0); - assert!(h.state().close_request.is_some(), "a dirty document asks first"); - h.state_mut().pick_override = Some(vec![out.to_string_lossy().into_owned()]); - let ctx = h.ctx.clone(); - h.state_mut().resolve_close(&ctx, Some(true)); + assert!(h.state_mut().execute("file.close")); + h.steps(2); + assert_eq!(h.state().views.len(), 1, "a dirty document asks first"); + press(&mut h, "Save"); assert_eq!(h.state().views.len(), 1, "the tab stays open until the save is written"); - h.run_steps(2); + assert_eq!(h.files.open(), 1, "the Save picker is open"); + h.answer(Picked::Paths(vec![out.clone()])); assert!(out.exists()); assert!(h.state().views.is_empty(), "then it closes"); let _ = std::fs::remove_dir_all(&dir); @@ -176,11 +264,10 @@ fn save_on_close_closes_the_tab_only_once_the_file_is_written() { fn a_cancelled_save_on_close_keeps_the_tab_open() { let mut h = harness(&[2]); rotate_first_page(h.state_mut()); - h.state_mut().request_close_tab(0); - h.state_mut().pick_override = Some(vec![]); // the user cancels the save panel - let ctx = h.ctx.clone(); - h.state_mut().resolve_close(&ctx, Some(true)); - h.run_steps(2); + assert!(h.state_mut().execute("file.close")); + h.steps(2); + press(&mut h, "Save"); + h.answer(Picked::Cancelled); // the user cancels the save panel assert_eq!(h.state().views.len(), 1); assert!(dirty(h.state(), 0), "nothing was saved or lost"); } @@ -193,189 +280,185 @@ fn close_all_saves_each_untitled_document_in_turn() { h.state_mut().active = Some(i); rotate_first_page(h.state_mut()); } - h.state_mut().close_all(); - let ctx = h.ctx.clone(); + assert!(h.state_mut().execute("file.close_all")); + h.steps(2); for (n, name) in ["first.pdf", "second.pdf"].iter().enumerate() { - assert!(h.state().close_request.is_some(), "asks about document {n}"); - h.state_mut().pick_override = Some(vec![dir.join(name).to_string_lossy().into_owned()]); - h.state_mut().resolve_close(&ctx, Some(true)); - h.run_steps(2); + press(&mut h, "Save"); + assert_eq!(h.files.open(), 1, "one Save pick for document {n}"); + h.answer(Picked::Paths(vec![dir.join(name)])); } assert!(h.state().views.is_empty()); + let asked = h.files.requests(); + assert_eq!(asked.len(), 2, "one Save pick per untitled document"); + assert!(asked.iter().all(|r| r.kind == PickKind::Save)); assert_eq!(page_count(std::fs::read(dir.join("first.pdf")).unwrap()), 2); assert_eq!(page_count(std::fs::read(dir.join("second.pdf")).unwrap()), 3); let _ = std::fs::remove_dir_all(&dir); } +/// Sets the checkbox called `label` of the open dialog to `want`. +fn set_checked(r: &mut Rig, label: &str, want: bool) { + let on = r.get_by_label(label).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True); + if on != want { + r.get_by_label(label).click(); + r.steps(2); + } +} + +/// Replaces what the text field called `label` holds with `text`. +fn type_into(r: &mut Rig, label: &str, text: &str) { + r.get_by_label(label).click(); + r.steps(1); + r.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + r.event(egui::Event::Text(text.into())); + r.steps(2); +} + +/// What the Extract dialog is filled with; `None` leaves a field as the dialog opened it. +struct Extract<'a> { + name: Option<&'a str>, + pages: Option<&'a str>, + separate: bool, + delete: bool, +} + +impl Default for Extract<'_> { + fn default() -> Self { + Self { name: None, pages: None, separate: false, delete: false } + } +} + +/// Opens Extract pages through its command and fills it in; leaves the dialog open. +fn open_extract(r: &mut Rig, e: Extract) { + assert!(r.state_mut().execute("page.extract")); + r.steps(2); + if let Some(pages) = e.pages { + type_into(r, "Pages", pages); + } + if let Some(name) = e.name { + type_into(r, "File name", name); + } + set_checked(r, "Extract pages as separate files", e.separate); + set_checked(r, "Delete pages after extracting", e.delete); +} + +/// The dialog's Extract button. +fn confirm_extract(r: &mut Rig) { + press(r, "Extract"); +} + +/// The tab name of the active document. +fn active_name(app: &PdfCraftApp) -> Option { + app.active.and_then(|i| app.views.get(i)).and_then(|v| app.session.get(v.id)).map(|d| d.name.clone()) +} + #[test] fn extract_and_delete_deletes_the_pages_only_after_their_files_are_written() { let dir = scratch("extract"); let mut h = harness(&[3]); - h.state_mut().extract_draft.separate = true; - h.state_mut().extract_draft.delete = true; - h.state_mut().pick_override = Some(vec![dir.to_string_lossy().into_owned()]); - h.state_mut().extract_selection(); + open_extract(&mut h, Extract { separate: true, delete: true, ..Default::default() }); + confirm_extract(&mut h); + assert_eq!(h.files.open(), 1, "the folder picker is open"); assert_eq!(pages(h.state(), 0), 3, "nothing is deleted while the folder picker is open"); - h.run_steps(2); + h.answer(Picked::Paths(vec![dir.clone()])); assert!(dir.join("doc0 (page 1).pdf").exists()); assert_eq!(pages(h.state(), 0), 2, "the extracted page is deleted once written"); let _ = std::fs::remove_dir_all(&dir); } /// #737: Extract pages names the files after the name typed in the dialog, which starts out -/// as the document's name. +/// as the document's name; left as it was (or with nothing usable in it), the names are the +/// ones Extract always used. #[test] fn extract_pages_saves_under_the_file_name_typed_in_the_dialog() { let dir = scratch("extract-named"); let mut h = harness(&[3]); - assert!(h.state_mut().execute("page.extract")); - h.run_steps(2); - assert_eq!(h.state().extract_draft.name, "doc0", "the dialog starts with the document's name"); + let separate = |name| Extract { name, separate: true, ..Default::default() }; + + // The dialog starts with the document's name, which gives the usual names. + open_extract(&mut h, separate(None)); + assert_eq!(h.get_by_label("File name").value().as_deref(), Some("doc0"), "the dialog starts with the document's name"); + confirm_extract(&mut h); + h.answer(Picked::Paths(vec![dir.clone()])); + assert!(dir.join("doc0 (page 1).pdf").exists()); + // A name with nothing usable falls back to the document's. + h.state_mut().views[0].select_pages(&[1]); + open_extract(&mut h, separate(Some(" .. "))); + confirm_extract(&mut h); + h.answer(Picked::Paths(vec![dir.clone()])); + assert!(dir.join("doc0 (page 2).pdf").exists()); // Several pages as separate files: each is " (page N).pdf". h.state_mut().views[0].select_pages(&[0, 2]); - h.state_mut().extract_draft.name = "Invoices.pdf".into(); - h.state_mut().extract_draft.separate = true; - h.state_mut().pick_override = Some(vec![dir.to_string_lossy().into_owned()]); - h.state_mut().extract_selection(); - h.run_steps(2); + open_extract(&mut h, separate(Some("Invoices.pdf"))); + confirm_extract(&mut h); + h.answer(Picked::Paths(vec![dir.clone()])); assert!(dir.join("Invoices (page 1).pdf").exists() && dir.join("Invoices (page 3).pdf").exists()); // One renamed page as a separate file is saved under exactly that name; characters a file // name can't hold become "_". h.state_mut().views[0].select_pages(&[1]); - h.state_mut().extract_draft.name = " March: 2026/receipt ".into(); - h.state_mut().extract_selection(); - h.run_steps(2); + open_extract(&mut h, separate(Some(" March: 2026/receipt "))); + confirm_extract(&mut h); + h.answer(Picked::Paths(vec![dir.clone()])); assert!(dir.join("March_ 2026_receipt.pdf").exists()); - assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 3, "nothing written outside those names"); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 5, "nothing written outside those names"); // Into a new tab: the tab, and so Save As, has the typed name. - h.state_mut().extract_draft.separate = false; - h.state_mut().extract_draft.name = "Chapter 2".into(); - h.state_mut().extract_selection(); - h.run_steps(2); - let s = h.state(); - let tab = s.active.and_then(|i| s.views.get(i)).and_then(|v| s.session.get(v.id)).map(|d| d.name.clone()); - assert_eq!(tab.as_deref(), Some("Chapter 2.pdf")); + open_extract(&mut h, Extract { name: Some("Chapter 2"), ..Default::default() }); + confirm_extract(&mut h); + assert_eq!(active_name(h.state()).as_deref(), Some("Chapter 2.pdf")); let _ = std::fs::remove_dir_all(&dir); } +/// The text of each page of document `view`. +fn texts_of(app: &PdfCraftApp, view: usize) -> Vec { + let doc = app.session.get(app.views[view].id).unwrap(); + let mut r = PageRenderer::new(doc.bytes.clone(), Default::default()); + (0..r.page_count()) + .map(|p| { + let out = r.render(RenderRequest { page: p, kind: RequestKind::Text, scale: 1.0, ..Default::default() }); + out.text.map(|t| t.plain_text().trim().to_string()).unwrap_or_default() + }) + .collect() +} + /// #3593: Extract pages takes page ranges typed in its Pages field, in the order typed, each page /// once; left empty, it takes the selected pages as before. A range it can't use is refused, with -/// the reason in the dialog and the Extract button off. +/// the Extract button off. #[test] fn extract_pages_takes_the_page_ranges_typed_in_the_dialog() { - let texts = |app: &PdfCraftApp, view: usize| { - let doc = app.session.get(app.views[view].id).unwrap(); - let mut r = PageRenderer::new(doc.bytes.clone(), Default::default()); - (0..r.page_count()) - .map(|p| { - let out = r.render(RenderRequest { page: p, kind: RequestKind::Text, scale: 1.0, ..Default::default() }); - out.text.map(|t| t.plain_text().trim().to_string()).unwrap_or_default() - }) - .collect::>() - }; let mut h = harness(&[6]); h.state_mut().views[0].select_pages(&[1]); assert!(h.state_mut().execute("page.extract")); - h.run_steps(2); - assert_eq!(h.state().extract_draft.pages, "", "opens on the selection"); - h.get_by_label("Pages"); - h.get_by_label_contains("1 page selected."); + h.steps(2); + assert!(h.get_by_label("Pages").value().unwrap_or_default().is_empty(), "opens on the selection"); + press(&mut h, "Cancel"); // Ranges, a backward one and a repeat: in that order, each page once. - h.state_mut().extract_draft.pages = "5-6, 3-2, 6".into(); - h.run_steps(2); - h.get_by_label_contains("4 pages selected."); - h.state_mut().extract_selection(); - h.run_steps(2); - let s = h.state(); - assert_eq!(s.views.len(), 2, "the pages open in a new tab"); - assert_eq!(texts(s, 1), ["Page 5", "Page 6", "Page 3", "Page 2"]); - // A page that isn't there: the dialog says so, Extract is off and extracts nothing. + open_extract(&mut h, Extract { pages: Some("5-6, 3-2, 6"), ..Default::default() }); + confirm_extract(&mut h); + assert_eq!(h.state().views.len(), 2, "the pages open in a new tab"); + assert_eq!(texts_of(h.state(), 1), ["Page 5", "Page 6", "Page 3", "Page 2"]); + // A page that isn't there: Extract is off and extracts nothing. h.state_mut().active = Some(0); - h.state_mut().open_extract_dialog(); - h.state_mut().extract_draft.pages = "2, 9".into(); - h.run_steps(2); - assert!(h.get_by_label("Extract").accesskit_node().is_disabled(), "Extract is off"); - h.state_mut().extract_selection(); - h.run_steps(2); + open_extract(&mut h, Extract { pages: Some("2, 9"), ..Default::default() }); + assert!(h.get_all_by_label("Extract").last().unwrap().accesskit_node().is_disabled(), "Extract is off"); + press(&mut h, "Cancel"); assert_eq!(h.state().views.len(), 2, "nothing extracted"); // Extract and delete takes the typed pages out of the document. h.state_mut().active = Some(0); - h.state_mut().open_extract_dialog(); - h.state_mut().extract_draft.pages = "6, 1-2".into(); - h.state_mut().extract_draft.delete = true; - h.state_mut().extract_selection(); - h.run_steps(2); - let s = h.state(); - assert_eq!(texts(s, 2), ["Page 6", "Page 1", "Page 2"]); - assert_eq!(texts(s, 0), ["Page 3", "Page 4", "Page 5"]); -} - -/// Left as the document's name (or emptied), the names are the ones Extract always used. -#[test] -fn extract_pages_keeps_the_usual_names_when_the_file_name_is_unchanged() { - let dir = scratch("extract-default-name"); - let mut h = harness(&[3]); - h.state_mut().open_extract_dialog(); - h.state_mut().extract_draft.separate = true; - h.state_mut().pick_override = Some(vec![dir.to_string_lossy().into_owned()]); - h.state_mut().extract_selection(); - h.run_steps(2); - assert!(dir.join("doc0 (page 1).pdf").exists()); - h.state_mut().extract_draft.name = " .. ".into(); - h.state_mut().views[0].select_pages(&[1]); - h.state_mut().extract_selection(); - h.run_steps(2); - assert!(dir.join("doc0 (page 2).pdf").exists(), "a name with nothing usable falls back to the document's"); - h.state_mut().extract_draft.separate = false; - h.state_mut().extract_selection(); - h.run_steps(2); - let s = h.state(); - let tab = s.active.and_then(|i| s.views.get(i)).and_then(|v| s.session.get(v.id)).map(|d| d.name.clone()); - assert_eq!(tab.as_deref(), Some("doc0 (extract).pdf")); - let _ = std::fs::remove_dir_all(&dir); + open_extract(&mut h, Extract { pages: Some("6, 1-2"), delete: true, ..Default::default() }); + confirm_extract(&mut h); + assert_eq!(texts_of(h.state(), 2), ["Page 6", "Page 1", "Page 2"]); + assert_eq!(texts_of(h.state(), 0), ["Page 3", "Page 4", "Page 5"]); } #[test] fn a_cancelled_folder_pick_extracts_and_deletes_nothing() { let mut h = harness(&[3]); - h.state_mut().extract_draft.separate = true; - h.state_mut().extract_draft.delete = true; - h.state_mut().pick_override = Some(vec![]); - h.state_mut().extract_selection(); - h.run_steps(2); + open_extract(&mut h, Extract { separate: true, delete: true, ..Default::default() }); + confirm_extract(&mut h); + h.answer(Picked::Cancelled); assert_eq!(pages(h.state(), 0), 3); } -#[test] -fn an_image_pick_for_a_document_that_is_no_longer_active_changes_nothing() { - let dir = scratch("image-switch"); - let file = dir.join("picture.png"); - std::fs::write(&file, b"not really a png").unwrap(); - let mut h = harness(&[1, 1]); - h.state_mut().active = Some(0); - h.state_mut().pick_override = Some(vec![file.to_string_lossy().into_owned()]); - h.state_mut().add_image_dialog(); - h.state_mut().active = Some(1); - h.run_steps(2); - assert!(!dirty(h.state(), 0) && !dirty(h.state(), 1), "neither document changed"); - let toast = h.state().toast.as_ref().map(|(m, _)| m.clone()).unwrap_or_default(); - assert!(toast.contains("document changed"), "the user is told why nothing happened: {toast:?}"); - let _ = std::fs::remove_dir_all(&dir); -} - -#[test] -fn export_comments_writes_on_a_later_frame() { - let dir = scratch("export-data"); - let out = dir.join("data.xfdf"); - let mut h = harness(&[1]); - h.state_mut().pick_override = Some(vec![out.to_string_lossy().into_owned()]); - h.state_mut().export_data_dialog(true, false); - assert!(!out.exists(), "the command must not wait for the picker"); - h.run_steps(2); - assert!(std::fs::read_to_string(&out).unwrap().contains("xfdf")); - let _ = std::fs::remove_dir_all(&dir); -} - #[test] fn import_comments_takes_the_comments_of_another_pdf() { let objs = [ @@ -400,18 +483,16 @@ fn import_comments_takes_the_comments_of_another_pdf() { let path = dir.join("review.pdf"); std::fs::write(&path, review).unwrap(); let mut h = harness(&[1]); - // Through the save path a test uses in place of the picker, and through the picker. - for chosen in [Some(path.to_string_lossy().into_owned()), None] { - h.state_mut().save_override = chosen.clone(); - h.state_mut().pick_override = chosen.is_none().then(|| vec![path.to_string_lossy().into_owned()]); - h.state_mut().run_command("comment.import"); - h.run_steps(2); - let app = h.state(); - let contents: Vec> = app.session.get(app.views[0].id).unwrap().info.annotations.iter().map(|a| a.contents.clone()).collect(); - assert_eq!(contents, [Some("from the review".to_string())], "the review's comment is imported once ({chosen:?})"); - h.state_mut().run_command("edit.undo"); - h.run_steps(1); - } + assert!(h.state_mut().execute("comment.import")); + h.steps(2); + h.answer(Picked::Paths(vec![path])); + let comments = |app: &PdfCraftApp| -> Vec> { + app.session.get(app.views[0].id).unwrap().info.annotations.iter().map(|a| a.contents.clone()).collect() + }; + assert_eq!(comments(h.state()), [Some("from the review".to_string())], "the review's comment is imported once"); + assert!(h.state_mut().execute("edit.undo")); + h.steps(1); + assert!(comments(h.state()).is_empty(), "the import undoes in one step"); let _ = std::fs::remove_dir_all(&dir); } @@ -419,18 +500,15 @@ fn import_comments_takes_the_comments_of_another_pdf() { fn extracted_pages_are_not_deleted_if_the_document_was_edited_while_choosing_the_folder() { let dir = scratch("extract-edited"); let mut h = harness(&[3]); - h.state_mut().extract_draft.separate = true; - h.state_mut().extract_draft.delete = true; - h.state_mut().pick_override = Some(vec![dir.to_string_lossy().into_owned()]); - h.state_mut().extract_selection(); + open_extract(&mut h, Extract { separate: true, delete: true, ..Default::default() }); + confirm_extract(&mut h); // While the folder picker is open the user deletes page 1 themselves: the page that would // now be deleted is the original page 2, which was never written out. h.state_mut().apply_edit(pdfcraft_engine::Edit::DeletePages { pages: vec![0] }); - h.run_steps(2); + h.answer(Picked::Paths(vec![dir.clone()])); assert!(dir.join("doc0 (page 1).pdf").exists(), "the extracted file is still written"); assert_eq!(pages(h.state(), 0), 2, "nothing more is deleted"); - let toast = h.state().toast.as_ref().map(|(m, _)| m.clone()).unwrap_or_default(); - assert!(toast.contains("not deleted"), "the user is told: {toast:?}"); + assert!(support::shown_notice(&mut h).is_some(), "the user is told"); let _ = std::fs::remove_dir_all(&dir); } @@ -444,40 +522,25 @@ fn a_close_prompt_still_means_its_own_document_after_a_pending_save_closes_anoth } let (b, c) = (h.state().views[1].id, h.state().views[2].id); // Save-and-close the first tab; its save panel is still open... - h.state_mut().request_close_tab(0); - h.state_mut().pick_override = Some(vec![dir.join("a.pdf").to_string_lossy().into_owned()]); - let ctx = h.ctx.clone(); - h.state_mut().resolve_close(&ctx, Some(true)); + h.state_mut().active = Some(0); + assert!(h.state_mut().execute("file.close")); + h.steps(2); + press(&mut h, "Save"); + assert_eq!(h.files.open(), 1, "the first tab's save panel is open"); // ...when the user asks to close the second one. - h.state_mut().request_close_tab(1); - h.run_steps(2); + h.state_mut().active = Some(1); + assert!(h.state_mut().execute("file.close")); + h.steps(2); + h.answer(Picked::Paths(vec![dir.join("a.pdf")])); assert_eq!(h.state().views.len(), 2, "the first tab closed once saved"); // Don't Save: the prompt was about the second document, which is now the first tab. - h.state_mut().resolve_close(&ctx, Some(false)); + press(&mut h, "Don't save"); let open: Vec<_> = h.state().views.iter().map(|v| v.id).collect(); assert_eq!(open, vec![c], "the second document closed, not the third: {b:?} vs {c:?}"); assert!(dirty(h.state(), 0), "the third document keeps its unsaved changes"); let _ = std::fs::remove_dir_all(&dir); } -#[test] -fn an_image_pick_is_dropped_if_the_document_was_edited_meanwhile() { - let dir = scratch("image-edited"); - let file = dir.join("picture.png"); - std::fs::write(&file, b"not really a png").unwrap(); - let mut h = harness(&[2]); - h.state_mut().pick_override = Some(vec![file.to_string_lossy().into_owned()]); - // Replace image 0 on page 2... - h.state_mut().replace_image_dialog(1, 0); - // ...but page 1 is deleted while choosing: "page 2" is now a different page. - h.state_mut().apply_edit(pdfcraft_engine::Edit::DeletePages { pages: vec![0] }); - h.run_steps(2); - assert_eq!(pages(h.state(), 0), 1); - let toast = h.state().toast.as_ref().map(|(m, _)| m.clone()).unwrap_or_default(); - assert!(toast.contains("document changed"), "the pick is dropped and the user told why: {toast:?}"); - let _ = std::fs::remove_dir_all(&dir); -} - #[test] fn a_watermark_file_from_browse_lands_only_in_the_dialog_that_asked() { let dir = scratch("browse"); @@ -486,119 +549,88 @@ fn a_watermark_file_from_browse_lands_only_in_the_dialog_that_asked() { for keep_open in [true, false] { let mut h = harness(&[1]); assert!(h.state_mut().execute("edit.watermark")); - h.state_mut().marks_draft.use_file = true; - h.state_mut().pick_override = Some(vec![file.to_string_lossy().into_owned()]); - h.run_steps(2); + h.steps(2); + h.get_by_label("File").click(); + h.steps(2); h.get_by_label("Browse…").click(); - h.run_steps(1); + h.steps(1); + assert_eq!(h.files.open(), 1, "Browse opened the picker"); if !keep_open { - h.state_mut().dialog = None; // closed before the pick arrives + h.key_press(egui::Key::Escape); // closed before the pick arrives + h.steps(2); + assert!(h.query_by_label("Browse…").is_none(), "the dialog is closed"); } - h.run_steps(2); - let got = h.state().marks_draft.file.as_ref().map(|f| f.0.clone()); + h.answer(Picked::Paths(vec![file.clone()])); if keep_open { - assert_eq!(got.as_deref(), Some("mark.pdf"), "the open dialog gets the file"); + assert!(h.query_by_label_contains("mark.pdf").is_some(), "the open dialog gets the file"); } else { - assert_eq!(got, None, "a closed dialog's pick is dropped"); + assert!(h.query_by_label_contains("mark.pdf").is_none(), "a closed dialog's pick is dropped"); } } let _ = std::fs::remove_dir_all(&dir); } -/// Browsers read picked files asynchronously and queue them on `requests` (#167): the request -/// is made when the picker opens, so it is bound to the document active then. -fn browser_insert(h: &Harness<'static, PdfCraftApp>, pages: usize) -> pdfcraft_ui_egui::FileRequest { - h.state().file_request(pdfcraft_ui_egui::FilePurpose::InsertPages, vec![("b.pdf".into(), fixture(pages))]) -} - -#[test] -fn a_browser_insert_goes_into_the_document_it_was_started_on() { - let mut h = harness(&[3, 1]); - h.state_mut().active = Some(0); - let request = browser_insert(&h, 1); - h.state_mut().requests.lock().unwrap().push(request); - h.run_steps(2); - assert_eq!(pages(h.state(), 0), 4); - assert_eq!(pages(h.state(), 1), 1); -} - #[test] fn a_browser_insert_that_arrives_after_switching_documents_changes_neither() { // Issue #167: insert into A, open C before the file is read: the pages went into C. let mut h = harness(&[3, 1]); h.state_mut().active = Some(0); - let request = browser_insert(&h, 1); + assert!(h.state_mut().execute("page.insert")); + h.steps(2); h.state_mut().active = Some(1); - h.state_mut().requests.lock().unwrap().push(request); - h.run_steps(2); + h.answer(Picked::Contents(vec![("b.pdf".into(), fixture(1))])); assert_eq!(pages(h.state(), 0), 3, "A is unchanged"); assert_eq!(pages(h.state(), 1), 1, "C is unchanged"); - let toast = h.state().toast.as_ref().map(|(m, _)| m.clone()).unwrap_or_default(); - assert!(toast.contains("document changed"), "the user is told why nothing happened: {toast:?}"); -} - -#[test] -fn a_browser_insert_into_a_document_edited_meanwhile_is_refused() { - let mut h = harness(&[3]); - let request = browser_insert(&h, 1); - h.state_mut().apply_edit(pdfcraft_engine::Edit::DeletePages { pages: vec![0] }); - h.state_mut().requests.lock().unwrap().push(request); - h.run_steps(2); - assert_eq!(pages(h.state(), 0), 2, "only the user's own edit applied"); + assert!(support::shown_notice(&mut h).is_some(), "the user is told why nothing happened"); } #[test] fn replace_pages_applies_only_to_the_document_its_dialog_was_opened_on() { + let dir = scratch("replace"); + let file = dir.join("r.pdf"); + std::fs::write(&file, fixture(1)).unwrap(); for switch in [false, true] { let mut h = harness(&[3, 3]); h.state_mut().active = Some(0); - h.state_mut().use_files(pdfcraft_ui_egui::FilePurpose::ReplacePages, vec![("r.pdf".into(), fixture(1))]); - h.run_steps(2); - assert_eq!(h.state().dialog, Some(pdfcraft_ui_egui::Dialog::ReplacePages)); + assert!(h.state_mut().execute("page.replace")); + h.steps(2); + h.answer(Picked::Paths(vec![file.clone()])); + h.get_by_label("Replace Pages"); if switch { // A file opened meanwhile (a browser read finishing) becomes the active document. h.state_mut().active = Some(1); - h.run_steps(2); + h.steps(2); } - h.get_by_label("OK").click(); - h.run_steps(2); + press(&mut h, "OK"); if switch { assert!(!dirty(h.state(), 0) && !dirty(h.state(), 1), "neither document is changed"); - let toast = h.state().toast.as_ref().map(|(m, _)| m.clone()).unwrap_or_default(); - assert!(toast.contains("document changed"), "the user is told why: {toast:?}"); + assert!(support::shown_notice(&mut h).is_some(), "the user is told why"); } else { assert!(dirty(h.state(), 0) && !dirty(h.state(), 1), "the first document's page is replaced"); } } + let _ = std::fs::remove_dir_all(&dir); } -/// A file that fails to arrive asynchronously (the browser's `?file=` URL answering HTTP 404) is -/// reported in the app on the next frame, not only in the console (#173). +/// A file that fails to arrive usably (the browser's `?file=` URL answering with an error page) +/// is reported in the app on the next frame, not only in the console (#173). #[test] fn a_failed_startup_url_is_reported_in_the_app() { let mut h = harness(&[]); - let failed = h.state().failed_inbox.clone(); - failed.lock().unwrap().push(("missing.pdf".into(), "HTTP 404".into())); - h.run_steps(2); - let toast = h.state().toast.as_ref().map(|(m, _)| m.clone()).unwrap_or_default(); - assert!(toast.contains("missing.pdf") && toast.contains("HTTP 404"), "{toast:?}"); + h.deliver("missing.pdf", b"HTTP 404".to_vec()); + h.steps(2); + assert!(support::shown_notice(&mut h).is_some(), "the failure is reported"); assert!(h.state().views.is_empty(), "no document was opened"); - assert!(failed.lock().unwrap().is_empty(), "each failure is reported once"); -} - -fn deliver_startup(h: &Harness<'static, PdfCraftApp>, name: &str, bytes: Vec) { - h.state().startup_inbox.lock().unwrap().push((name.into(), bytes)); } #[test] fn a_startup_url_opens_in_front_when_the_user_has_not_started_working() { let mut h = harness(&[]); - deliver_startup(&h, "startup.pdf", fixture(2)); - h.run_steps(2); + h.deliver("startup.pdf", fixture(2)); + h.steps(2); assert_eq!(h.state().active, Some(0)); assert_eq!(pages(h.state(), 0), 2); - assert!(h.state().startup_inbox.lock().unwrap().is_empty()); - h.run_steps(2); + h.steps(2); assert_eq!(h.state().views.len(), 1, "the arrival opens once"); } @@ -623,8 +655,8 @@ fn a_late_startup_url_preserves_the_current_edit_workspace_and_save_target() { h.state_mut().left = LeftPanel::AllTools; h.state_mut().left_open = false; h.state_mut().quick_tool = QuickTool::Hand; - deliver_startup(&h, "late.pdf", late); - h.run_steps(2); + h.deliver("late.pdf", late); + h.steps(2); assert_eq!(h.state().active_ids().unwrap().1, active, "Save still targets the user's document"); assert_eq!(h.state().mode, Mode::Edit); @@ -638,18 +670,18 @@ fn a_late_startup_url_preserves_the_current_edit_workspace_and_save_target() { let dir = scratch("startup-save"); let path = dir.join("saved.pdf"); - h.state_mut().save_override = Some(path.to_string_lossy().into_owned()); assert!(h.state_mut().execute("file.save")); - h.run_steps(2); + h.steps(2); + h.answer(Picked::Paths(vec![path.clone()])); let saved = PageRenderer::new(std::sync::Arc::new(std::fs::read(&path).unwrap()), Default::default()); assert_eq!(saved.page_count(), 2, "the saved file contains the local deletion"); assert!(!dirty(h.state(), 0), "the local document was saved, not the startup document"); h.get_by_label("late.pdf").click(); - h.run_steps(2); + h.steps(2); assert_eq!(h.state().active, Some(1), "the user can choose the downloaded tab"); h.get_by_label("saved.pdf").click(); - h.run_steps(2); + h.steps(2); assert_eq!(pages(h.state(), 0), 2, "the edit survives switching back"); let _ = std::fs::remove_dir_all(&dir); } @@ -662,37 +694,41 @@ fn a_late_startup_url_preserves_home_even_after_all_other_tabs_are_closed() { h.state_mut().close_tab(0); } else { h.get_by_label("Home").click(); - h.run_steps(2); + h.steps(2); } assert_eq!(h.state().active, None); - deliver_startup(&h, "late.pdf", fixture(1)); - h.run_steps(2); + h.deliver("late.pdf", fixture(1)); + h.steps(2); assert_eq!(h.state().active, None, "Home stays selected (closed tabs: {close})"); h.get_by_label_contains("Welcome to PdfCraft"); h.get_by_label("late.pdf").click(); - h.run_steps(2); + h.steps(2); assert!(h.state().active.is_some()); } } #[test] fn deliberate_browser_file_opens_still_activate_the_new_tab() { + let dir = scratch("deliberate"); + let picked = dir.join("picked.pdf"); + std::fs::write(&picked, fixture(2)).unwrap(); let mut h = harness(&[3]); - h.state().inbox.lock().unwrap().push(("picked.pdf".into(), fixture(2))); - deliver_startup(&h, "late.pdf", fixture(1)); - h.run_steps(2); + // The user's own Open, answered on the same frame the startup file arrives. + assert!(h.state_mut().execute("file.open")); + h.deliver("late.pdf", fixture(1)); + h.answer(Picked::Paths(vec![picked])); + settle(&mut h, "both files", |app| app.views.len() == 3); assert_eq!(h.state().active, Some(1), "a deliberate Open wins even on the same frame"); assert_eq!(pages(h.state(), 1), 2); - assert_eq!(h.state().views.len(), 3); + let _ = std::fs::remove_dir_all(&dir); } #[test] fn opening_a_file_picker_supersedes_the_startup_url_even_if_the_picker_is_cancelled() { let mut h = harness(&[]); - h.state_mut().pick_override = Some(vec![]); h.state_mut().execute("file.open"); - deliver_startup(&h, "late.pdf", fixture(1)); - h.run_steps(2); + h.deliver("late.pdf", fixture(1)); + h.answer(Picked::Cancelled); assert_eq!(h.state().active, None, "the startup file doesn't replace the user's newer Open action"); assert_eq!(h.state().views.len(), 1, "it is still available as a background tab"); } @@ -700,13 +736,12 @@ fn opening_a_file_picker_supersedes_the_startup_url_even_if_the_picker_is_cancel #[test] fn a_broken_late_startup_file_reports_its_error_without_changing_the_active_document() { let mut h = harness(&[3]); - deliver_startup(&h, "broken.pdf", b"not a PDF".to_vec()); - h.run_steps(2); + h.deliver("broken.pdf", b"not a PDF".to_vec()); + h.steps(2); assert_eq!(h.state().active, Some(0)); assert_eq!(h.state().views.len(), 1); - let toast = &h.state().toast.as_ref().unwrap().0; - assert!(toast.contains("broken.pdf"), "{toast}"); - assert!(h.state().startup_inbox.lock().unwrap().is_empty()); + let notice = support::shown_notice(&mut h).expect("the failure is reported"); + assert!(notice.contains("broken.pdf"), "{notice}"); } fn encrypted_fixture() -> Vec { @@ -724,17 +759,16 @@ fn a_startup_url_does_not_replace_another_documents_password_prompt() { let local_bytes = encrypted_fixture(); let late_bytes = fixture(2); h.state_mut().open_bytes("local-encrypted.pdf", None, local_bytes.clone()).unwrap(); - deliver_startup(&h, "late.pdf", late_bytes.clone()); - h.run_steps(2); + h.deliver("late.pdf", late_bytes.clone()); + h.steps(2); assert_eq!(h.state().password_prompt.as_ref().unwrap().name, "local-encrypted.pdf"); assert!(h.state().views.is_empty()); - assert_eq!(h.state().startup_inbox.lock().unwrap().len(), 1, "startup bytes wait for the prompt"); + assert!(h.query_by_label("late.pdf").is_none(), "the startup file waits for the prompt"); h.state_mut().submit_password((!cancel).then(|| "test-password".into())); - support::wait_until(&mut h, "local password completion and startup open", |app| { + settle(&mut h, "local password completion and startup open", |app| { app.password_prompt.is_none() && app.views.len() == if cancel { 1 } else { 2 } }); assert!(h.state().password_prompt.is_none()); - assert!(h.state().startup_inbox.lock().unwrap().is_empty()); let app = h.state(); let late: Vec<_> = app.session.docs().iter().filter(|doc| doc.name == "late.pdf").collect(); assert_eq!(late.len(), 1); @@ -761,18 +795,18 @@ fn unlocking_a_late_startup_url_keeps_it_in_the_background() { let mut h = harness(&[3]); let original = h.state().views[0].id; let late_bytes = encrypted_fixture(); - deliver_startup(&h, "late-encrypted.pdf", late_bytes.clone()); - h.run_steps(2); + h.deliver("late-encrypted.pdf", late_bytes.clone()); + h.steps(2); assert_eq!(h.state().active, Some(0)); assert_eq!(h.state().password_prompt.as_ref().unwrap().name, "late-encrypted.pdf"); h.state_mut().submit_password(Some("wrong-password".into())); - support::wait_until(&mut h, "startup wrong-password reply", |app| { + settle(&mut h, "startup wrong-password reply", |app| { app.password_prompt.as_ref().is_some_and(|p| p.name == "late-encrypted.pdf" && p.error.as_deref() == Some("Incorrect password. Try again.")) }); assert!(h.state().password_prompt.as_ref().unwrap().error.is_some()); assert_eq!(h.state().active, Some(0)); h.state_mut().submit_password(Some("test-password".into())); - support::wait_until(&mut h, "unlocked startup document", |app| app.password_prompt.is_none() && app.views.len() == 2); + settle(&mut h, "unlocked startup document", |app| app.password_prompt.is_none() && app.views.len() == 2); assert!(h.state().password_prompt.is_none()); assert_eq!(h.state().active, Some(0)); assert_eq!(h.state().views.len(), 2); @@ -781,121 +815,17 @@ fn unlocking_a_late_startup_url_keeps_it_in_the_background() { let late = h.state().session.docs().iter().find(|doc| doc.name == "late-encrypted.pdf").unwrap(); assert_eq!(late.bytes.as_slice(), late_bytes.as_slice()); h.get_by_label("late-encrypted.pdf").click(); - h.run_steps(2); + h.steps(2); assert_eq!(h.state().active, Some(1)); } -/// How an encrypted file reaches the password prompt. -#[derive(Clone, Copy, Debug)] -enum OpenedFrom { - CommandLine, - FileOpen, - StartPage, - Drop, -} - -#[derive(Debug)] -struct Dropped(std::path::PathBuf, Vec); - -impl egui::DroppedFile for Dropped { - fn path(&self) -> &std::path::Path { - &self.0 - } - fn bytes(&self) -> Result, String> { - Ok(self.1.clone()) - } -} - -/// Types `text` the way keys arrive where egui-winit hands text fields to an input method, as on -/// Linux (X11 XIM, Wayland text-input): each character is with the input method (a pre-edit) for -/// a frame before it is committed. A frame that asks to interrupt the composition makes -/// egui-winit switch the input method off and on again, which drops what it holds, so the commit -/// never comes. -fn type_through_input_method(h: &mut Harness<'static, PdfCraftApp>, text: &str) { - for c in text.chars() { - let c = c.to_string(); - h.event(egui::Event::Ime(egui::ImeEvent::Preedit { text: c.clone(), active_range_chars: Some(0..1) })); - h.step(); - let interrupted = h.output().platform_output.ime.as_ref().is_none_or(|ime| ime.should_interrupt_composition); - let next = if interrupted { egui::ImeEvent::Preedit { text: String::new(), active_range_chars: None } } else { egui::ImeEvent::Commit(c) }; - h.event(egui::Event::Ime(next)); - h.step(); - } -} - -/// #2818: nothing typed into the password prompt arrived on Linux. The field asked for focus on -/// every frame, and each request also interrupts the input method. -#[test] -fn the_open_password_can_be_typed_through_an_input_method_however_the_file_is_opened() { - let bytes = encrypted_fixture(); - for from in [OpenedFrom::CommandLine, OpenedFrom::FileOpen, OpenedFrom::StartPage, OpenedFrom::Drop] { - let dir = scratch(&format!("password-{from:?}")); - let file = dir.join("encrypted.pdf"); - std::fs::write(&file, &bytes).unwrap(); - let path = file.to_string_lossy().into_owned(); - let arg = path.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(); - // As `main` opens the files named on the command line. - if matches!(from, OpenedFrom::CommandLine) { - app.open_path(&arg); - } - app - }); - h.run_steps(4); - match from { - OpenedFrom::CommandLine => {} - OpenedFrom::FileOpen => { - h.state_mut().pick_override = Some(vec![path.clone()]); - assert!(h.state_mut().execute("file.open")); - } - OpenedFrom::StartPage => { - h.state_mut().pick_override = Some(vec![path.clone()]); - h.get_by_label("Open file").click(); - } - OpenedFrom::Drop => h.input_mut().dropped_files.push(std::sync::Arc::new(Dropped(file.clone(), bytes.clone()))), - } - support::wait_until(&mut h, "password prompt", |app| app.password_prompt.is_some()); - h.run_steps(2); - type_through_input_method(&mut h, "test-password"); - assert_eq!(h.state().password_prompt.as_ref().map(|p| p.input.as_str()), Some("test-password"), "opened from {from:?}"); - h.key_press(egui::Key::Enter); - support::wait_until(&mut h, "unlocked document", |app| app.password_prompt.is_none() && app.views.len() == 1); - let doc = h.state().session.get(h.state().views[0].id).unwrap(); - assert_eq!((doc.path.as_deref(), doc.info.pages.len()), (Some(path.as_str()), 1), "opened from {from:?}"); - let _ = std::fs::remove_dir_all(&dir); - } -} - -/// The permissions password prompt is the same box (#2818). -#[test] -fn the_permissions_password_can_be_typed_through_an_input_method() { - use pdfcraft_engine::{Edit, Protection, Session}; - let mut s = Session::new(); - let id = s.open("locked.pdf", None, std::sync::Arc::new(fixture(1)), None).unwrap(); - s.apply(id, Edit::Protect(Protection { permissions_password: Some("owner".into()), ..Default::default() })).unwrap(); - let locked = s.save_bytes(id).unwrap().as_ref().clone(); - let mut h = harness(&[]); - h.state_mut().open_bytes("locked.pdf", None, locked).unwrap(); - h.run_steps(2); - assert!(h.state_mut().execute("protect.remove")); - h.run_steps(2); - assert!(h.state().unlock_prompt.is_some(), "Remove security asks for the permissions password"); - type_through_input_method(&mut h, "owner"); - assert_eq!(h.state().unlock_prompt.as_ref().map(|p| p.input.as_str()), Some("owner")); - h.key_press(egui::Key::Enter); - h.run_steps(2); - assert!(h.state().unlock_prompt.is_none(), "the typed password is accepted"); -} - #[test] fn a_late_startup_url_preserves_the_combine_files_tab() { let mut h = harness(&[]); h.state_mut().open_combine_tab(); - h.run_steps(2); - deliver_startup(&h, "late.pdf", fixture(1)); - h.run_steps(2); + h.steps(2); + h.deliver("late.pdf", fixture(1)); + h.steps(2); assert!(h.state().combine_showing()); assert_eq!(h.state().active, None); assert_eq!(h.state().views.len(), 1); @@ -904,24 +834,24 @@ fn a_late_startup_url_preserves_the_combine_files_tab() { #[test] fn a_late_startup_url_waits_for_an_existing_dialog_to_close() { let mut h = harness(&[3]); - h.state_mut().dialog = Some(pdfcraft_ui_egui::Dialog::Preferences); - deliver_startup(&h, "late.pdf", fixture(1)); - h.run_steps(2); - assert_eq!(h.state().dialog, Some(pdfcraft_ui_egui::Dialog::Preferences)); + assert!(h.state_mut().execute("app.preferences")); + h.steps(2); + assert!(h.query_by_label("Preferences").is_some(), "the dialog is open"); + h.deliver("late.pdf", fixture(1)); + h.steps(2); + assert!(h.query_by_label("Preferences").is_some(), "the dialog is still open"); assert_eq!(h.state().views.len(), 1); - assert_eq!(h.state().startup_inbox.lock().unwrap().len(), 1); - h.state_mut().dialog = None; - h.run_steps(2); + h.key_press(egui::Key::Escape); + h.steps(2); assert_eq!(h.state().active, Some(0)); assert_eq!(h.state().views.len(), 2); - assert!(h.state().startup_inbox.lock().unwrap().is_empty()); } #[test] fn a_late_startup_text_file_is_still_converted_without_stealing_focus() { let mut h = harness(&[3]); - deliver_startup(&h, "late.txt", b"A downloaded text file".to_vec()); - h.run_steps(2); + h.deliver("late.txt", b"A downloaded text file".to_vec()); + h.steps(2); assert_eq!(h.state().active, Some(0)); assert_eq!(h.state().views.len(), 2); assert_eq!(pages(h.state(), 1), 1); @@ -932,16 +862,14 @@ fn a_background_startup_forms_script_notice_waits_until_its_tab_is_selected() { let template = pdfcraft_xfa::fixtures::scripted_template() .replace("if (qty.rawValue === null) qty.rawValue = 2;", r#"xfa.host.messageBox("Late form opened");"#); let mut h = harness(&[3]); - deliver_startup(&h, "late-form.pdf", pdfcraft_xfa::fixtures::shell(&template)); - h.run_steps(2); + h.deliver("late-form.pdf", pdfcraft_xfa::fixtures::shell(&template)); + h.steps(2); assert_eq!(h.state().active, Some(0)); - assert!(h.state().toast.is_none(), "the background form must not interrupt the current document"); + assert!(support::shown_notice(&mut h).is_none(), "the background form must not interrupt the current document"); h.get_by_label("late-form.pdf").click(); - h.run_steps(2); - assert_eq!(h.state().toast.as_ref().unwrap().0, "Late form opened"); - h.state_mut().toast = None; - h.run_steps(2); - assert!(h.state().toast.is_none(), "the notice is delivered once"); + h.steps(2); + let notice = support::shown_notice(&mut h).expect("the form's message shows once its tab is selected"); + assert!(notice.contains("Late form opened"), "{notice}"); } /// A form opened behind the current document that turns field highlighting on gets it at @@ -953,9 +881,9 @@ fn a_background_forms_highlight_request_applies_at_once() { // Highlighting is on by default: start from a user who turned it off. h.state_mut().view_defaults.highlight_fields = false; h.state_mut().views[0].highlight_fields = false; - h.run_steps(1); - deliver_startup(&h, "late-form.pdf", pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::layout_ready_template())); - h.run_steps(2); + h.steps(1); + h.deliver("late-form.pdf", pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::layout_ready_template())); + h.steps(2); assert_eq!(h.state().active, Some(0), "it opened behind the current document"); assert!(h.state().views[1].highlight_fields, "the background form is highlighted"); assert!(!h.state().views[0].highlight_fields, "the current document is left as it was"); @@ -1028,22 +956,20 @@ fn attachment_save_preserves_bytes_metadata_and_selected_destination() { let original = attachment_fixture(); let mut h = harness(&[]); h.state_mut().open_bytes("attachment.pdf", None, original.clone()).unwrap(); - h.run_steps(2); + h.steps(2); let id = h.state().views[0].id; let raw_name = "invoice\u{202e}fdp.exe"; let index = h.state().session.get(id).unwrap().info.attachments.iter().position(|a| a.name == raw_name).unwrap(); - h.state_mut().pick_override = Some(vec![chosen.to_string_lossy().into_owned()]); h.state_mut().attachment_action(id, index, false); - h.run_steps(2); + h.answer(Picked::Paths(vec![chosen.clone()])); assert_eq!(std::fs::read(&chosen).unwrap(), b"hello notes"); let doc = h.state().session.get(id).unwrap(); assert_eq!(doc.info.attachments[index].name, raw_name); assert_eq!(doc.bytes.as_ref(), &original); assert!(!dir.0.join("invoicefdp.exe").exists()); std::fs::remove_file(&chosen).unwrap(); - h.state_mut().pick_override = Some(Vec::new()); h.state_mut().attachment_action(id, index, false); - h.run_steps(2); + h.answer(Picked::Cancelled); assert_eq!(std::fs::read_dir(&dir.0).unwrap().count(), 0); let doc = h.state().session.get(id).unwrap(); assert_eq!(doc.info.attachments[index].name, raw_name); @@ -1067,12 +993,11 @@ fn a_saved_attachment_carries_the_documents_zone() { let opened = [(Some(&mail), zone), (Some(&local), pdfcraft_platform::zone::INTERNET_ZONE), (None, pdfcraft_platform::zone::INTERNET_ZONE)]; for (i, (path, expected)) in opened.into_iter().enumerate() { h.state_mut().open_bytes(&format!("doc{i}.pdf"), path.map(|p| p.to_string_lossy().into_owned()), attachment_fixture()).unwrap(); - h.run_steps(2); + h.steps(2); let id = h.state().views.last().unwrap().id; let chosen = dir.0.join(format!("saved{i}.exe")); - h.state_mut().pick_override = Some(vec![chosen.to_string_lossy().into_owned()]); h.state_mut().attachment_action(id, 0, false); - h.run_steps(2); + h.answer(Picked::Paths(vec![chosen.clone()])); assert_eq!(std::fs::read(&chosen).unwrap(), b"hello notes"); assert_eq!(zone_of(&chosen).as_deref(), Some(expected.as_bytes()), "document {i}"); } @@ -1098,20 +1023,21 @@ fn files_written_from_an_attachment_tab_stay_inside_the_chosen_folder() { std::fs::create_dir_all(&out).unwrap(); let mut h = harness(&[]); h.state_mut().open_bytes("outer.pdf", None, attachment_pdf(name, &fixture(2))).unwrap(); - h.run_steps(2); + h.steps(2); let id = h.state().views[0].id; h.state_mut().attachment_action(id, 0, true); - h.run_steps(2); + h.steps(2); assert_eq!(h.state().views.len(), 2, "{name}: the attachment opens as a tab"); - h.state_mut().export_dir_override = Some(out.to_string_lossy().into_owned()); h.state_mut().split_active(&pdfcraft_ui_egui::SplitPlan::By(pdfcraft_engine::SplitBy::PageCount(1))); + h.answer(Picked::Paths(vec![out.clone()])); let written = files_under(&dir.0); assert_eq!(written.len(), 2, "{name}: two split parts, got {written:?}"); assert!(written.iter().all(|p| p.parent() == Some(out.as_path())), "{name}: {written:?}"); // Extract writes page 1 under the name Split gave it. - h.state_mut().extract_draft = pdfcraft_ui_egui::ExtractDraft { separate: true, ..Default::default() }; - h.state_mut().extract_selection(); - assert!(h.state().toast.as_ref().is_some_and(|t| t.0.starts_with("Wrote 1 file")), "{name}: {:?}", h.state().toast); + open_extract(&mut h, Extract { separate: true, ..Default::default() }); + confirm_extract(&mut h); + h.answer(Picked::Paths(vec![out.clone()])); + assert!(support::shown_notice(&mut h).is_some(), "{name}: Extract reports what it wrote"); assert_eq!(files_under(&dir.0), written, "{name}"); std::fs::remove_dir_all(dir.0.join("a")).unwrap(); }