PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Merge remote-tracking branch 'upstream/main' into fix/exec-menu-attachments
Eric Kaden4665685446e0
diff --cc crates/engine/src/tests.rsindex 6b0a97e98,0df176226..aebb74093--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@@ -6107,56 -6666,437 +6666,491 @@@ fn undo_never_makes_an_unsaved_documentassert!(!s.get(new).unwrap().dirty, "once saved, undo back to the saved state is clean");}+ #[test]+ fn undo_and_redo_roll_back_on_a_refresh_panic_or_error() {+ let (mut s, id) = session_with(1);+ s.apply(id, Edit::RotatePages { pages: vec![0], degrees: 90 }).unwrap();+ let (bytes_90, gen_90) = {+ let d = s.get(id).unwrap();+ (d.bytes.clone(), d.generation)+ };++ // 1. A panic during undo's refresh catches the unwind and rolls back cos, undo/redo, info, and working bytes.+ panic_on_refresh(1);+ let err = s.undo(id).unwrap_err();+ assert_eq!(err, EditError::Reopen("injected refresh panic".into()));+ {+ let d = s.get(id).unwrap();+ let ed = d.editor.as_ref().unwrap();+ assert_eq!(d.info.pages[0].rotation, 90);+ assert_eq!(d.bytes, bytes_90);+ assert_eq!(d.generation, gen_90);+ assert!(d.dirty);+ assert!(ed.cos.is_modified());+ assert_eq!(ed.undo.len(), 1);+ assert!(ed.redo.is_empty());+ }+ let _ = shown(&s, id, 0);++ // 2. If the rollback refresh also panics, `show_released` restores the renderer so the page still draws.+ panic_on_refresh(2);+ assert_eq!(s.undo(id), Err(EditError::Reopen("injected refresh panic".into())));+ assert_eq!(s.get(id).unwrap().editor.as_ref().unwrap().undo.len(), 1);+ let _ = shown(&s, id, 0);++ // Undo now succeeds cleanly.+ assert_eq!(s.undo(id).unwrap().as_str(), "Rotate page");+ let (bytes_0, gen_0) = {+ let d = s.get(id).unwrap();+ assert_eq!(d.info.pages[0].rotation, 0);+ assert!(!d.dirty);+ (d.bytes.clone(), d.generation)+ };++ // 3. A panic during redo's refresh catches the unwind and rolls back to the undone state.+ panic_on_refresh(1);+ let err = s.redo(id).unwrap_err();+ assert_eq!(err, EditError::Reopen("injected refresh panic".into()));+ {+ let d = s.get(id).unwrap();+ let ed = d.editor.as_ref().unwrap();+ assert_eq!(d.info.pages[0].rotation, 0);+ assert_eq!(d.bytes, bytes_0);+ assert_eq!(d.generation, gen_0);+ assert!(!d.dirty);+ assert!(!ed.cos.is_modified());+ assert!(ed.undo.is_empty());+ assert_eq!(ed.redo.len(), 1);+ }+ let _ = shown(&s, id, 0);++ // 4. If redo's rollback refresh also panics, `show_released` restores the renderer.+ panic_on_refresh(2);+ assert_eq!(s.redo(id), Err(EditError::Reopen("injected refresh panic".into())));+ assert_eq!(s.get(id).unwrap().editor.as_ref().unwrap().redo.len(), 1);+ let _ = shown(&s, id, 0);++ // Redo now succeeds cleanly.+ assert_eq!(s.redo(id).unwrap().as_str(), "Rotate page");+ assert_eq!(s.get(id).unwrap().info.pages[0].rotation, 90);++ // 5. Metadata scope: a panic after `doc.info.title` was written rolls back `info.title` and keeps `edit_notices`.+ s.apply(id, Edit::SetInfo { key: "Title".into(), value: "Draft".into() }).unwrap();+ let notice = TextNotice { field: None, page: 0, ch: '☺', redrawn_elsewhere: false };+ s.doc_mut(id).unwrap().edit_notices.push(notice.clone());+ panic_on_refresh(1);+ assert_eq!(s.undo(id), Err(EditError::Reopen("injected refresh panic".into())));+ assert_eq!(s.get(id).unwrap().info.title.as_deref(), Some("Draft"));+ assert_eq!(s.get(id).unwrap().edit_notices, [notice]);+ assert_eq!(s.undo(id).unwrap().as_str(), "Change Title");+ assert_eq!(s.get(id).unwrap().info.title, None);+ assert!(s.get(id).unwrap().edit_notices.is_empty());++ panic_on_refresh(1);+ assert_eq!(s.redo(id), Err(EditError::Reopen("injected refresh panic".into())));+ assert_eq!(s.get(id).unwrap().info.title, None);+ assert_eq!(s.redo(id).unwrap().as_str(), "Change Title");+ assert_eq!(s.get(id).unwrap().info.title.as_deref(), Some("Draft"));++ // 6. Protection keys: undo/redo rollback restores `editor.keys` and `doc.password` before re-inspecting.+ let protect = Protection { open_password: Some("u".into()), permissions_password: Some("o".into()), ..Protection::default() };+ s.apply(id, Edit::Protect(protect)).unwrap();+ assert!(s.get(id).unwrap().info.encrypted);+ panic_on_refresh(1);+ assert_eq!(s.undo(id), Err(EditError::Reopen("injected refresh panic".into())));+ assert!(s.get(id).unwrap().info.encrypted);+ assert_eq!(s.get(id).unwrap().password.as_deref(), Some("u"));+ assert_eq!(s.undo(id).unwrap().as_str(), "Protect with password");+ assert!(!s.get(id).unwrap().info.encrypted);+ assert_eq!(s.get(id).unwrap().password, None);++ panic_on_refresh(1);+ assert_eq!(s.redo(id), Err(EditError::Reopen("injected refresh panic".into())));+ assert!(!s.get(id).unwrap().info.encrypted);+ assert_eq!(s.get(id).unwrap().password, None);+ assert_eq!(s.redo(id).unwrap().as_str(), "Protect with password");+ assert!(s.get(id).unwrap().info.encrypted);+ assert_eq!(s.get(id).unwrap().password.as_deref(), Some("u"));+ }++ #[test]+ fn a_bookmark_added_at_a_point_goes_there_through_undo_and_save() {+ use pdfcraft_render::DestView;+ let (mut s, id) = session_with(3);+ let view = |s: &Session, i: usize| s.get(id).unwrap().info.outline.get(i).map(|o| (o.page, o.view));+ let add = |s: &mut Session, title: &str, page: usize, left: Option<f64>, top: Option<f64>| {+ s.apply(id, Edit::AddBookmark { parent: vec![], index: usize::MAX, title: title.into(), page, left, top })+ };+ add(&mut s, "Plain", 0, None, None).unwrap();+ add(&mut s, "Section", 1, None, Some(500.5)).unwrap();+ add(&mut s, "Table", 2, Some(72.0), Some(300.0)).unwrap();+ // The page top (no position) is what it always was; the others carry their place.+ assert_eq!(view(&s, 0), Some((Some(0), DestView::Xyz { left: None, top: None, zoom: None })));+ assert_eq!(view(&s, 1), Some((Some(1), DestView::Xyz { left: None, top: Some(500.5), zoom: None })));+ assert_eq!(view(&s, 2), Some((Some(2), DestView::Xyz { left: Some(72.0), top: Some(300.0), zoom: None })));++ // A position that is not a number fails the edit, which then changes nothing.+ for (left, top) in [(Some(f64::NAN), None), (None, Some(f64::INFINITY))] {+ assert!(matches!(add(&mut s, "Bad", 0, left, top), Err(EditError::Bookmark(_))), "{left:?} {top:?}");+ }+ assert_eq!(s.get(id).unwrap().info.outline.len(), 3);+ assert_eq!(s.get(id).unwrap().can_undo(), Some("Add bookmark"));++ s.undo(id).unwrap();+ assert_eq!(s.get(id).unwrap().info.outline.len(), 2);+ s.redo(id).unwrap();+ let saved = s.save_bytes(id).unwrap();+ let mut again = Session::new();+ let id2 = again.open("again.pdf", None, saved, None).unwrap();+ let outline = &again.get(id2).unwrap().info.outline;+ assert_eq!(outline[2].view, DestView::Xyz { left: Some(72.0), top: Some(300.0), zoom: None });+ assert_eq!(outline[1].view, DestView::Xyz { left: None, top: Some(500.5), zoom: None });+ }++ /// #3470: a filled form whose writer left the appearances to the viewer (`/NeedAppearances`):+ /// field A has an empty appearance, B none. The page as displayed (and printed) shows both+ /// values, and a comment without an appearance beside them still gets its own; the file itself+ /// is not changed, so saving writes it as it was.+ #[test]+ fn fields_left_to_the_viewer_are_displayed_from_their_values() {+ let pdf = |need: bool| {+ let flag = if need { "/NeedAppearances true " } else { "" };+ format!(+ "%PDF-1.7\n\+ 1 0 obj << /Type /Catalog /Pages 2 0 R /AcroForm 5 0 R >> endobj\n\+ 2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\+ 3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 400 200] /Annots [6 0 R 7 0 R 10 0 R] >> endobj\n\+ 10 0 obj << /Type /Annot /Subtype /Square /Rect [360 20 390 50] /C [1 0 0] /BS << /W 4 >> >> endobj\n\+ 5 0 obj << /Fields [6 0 R 7 0 R] {flag}/DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 8 0 R >> >> >> endobj\n\+ 6 0 obj << /Type /Annot /Subtype /Widget /FT /Tx /T (a) /V (MMMMMMMM) /DA (/Helv 12 Tf 0 g) /Rect [50 120 350 140] /F 4 /P 3 0 R /AP << /N 9 0 R >> >> endobj\n\+ 7 0 obj << /Type /Annot /Subtype /Widget /FT /Tx /T (b) /V (MMMMMMMM) /DA (/Helv 12 Tf 0 g) /Rect [50 60 350 80] /F 4 /P 3 0 R >> endobj\n\+ 8 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >> endobj\n\+ 9 0 obj << /Type /XObject /Subtype /Form /BBox [0 0 300 20] /Length 4 >> stream\nq\nQ\nendstream endobj\n\+ trailer << /Root 1 0 R >>\n%%EOF"+ )+ .into_bytes()+ };+ let red = |s: &Session, id: DocId| {+ let doc = s.get(id).unwrap();+ let mut r = pdfcraft_render::PageRenderer::new(doc.display.clone(), doc.config.clone());+ let page = r.render(pdfcraft_render::RenderRequest { page: 0, scale: 1.0, ..Default::default() });+ page.rgba.as_chunks::<4>().0.iter().filter(|p| p[0] > 200 && p[1] < 80 && p[2] < 80).count()+ };+ // Dark pixels inside a field's box (user-space rectangle, page drawn at scale 1).+ let ink = |s: &Session, id: DocId, y0: u32, y1: u32| {+ let doc = s.get(id).unwrap();+ let mut r = pdfcraft_render::PageRenderer::new(doc.display.clone(), doc.config.clone());+ let page = r.render(pdfcraft_render::RenderRequest { page: 0, scale: 1.0, ..Default::default() });+ let (px, _) = page.rgba.as_chunks::<4>();+ (200 - y1..200 - y0)+ .flat_map(|y| (55..345).map(move |x| (x, y)))+ .filter(|&(x, y)| px.get((y * page.width + x) as usize).is_some_and(|p| p[0] < 128))+ .count()+ };+ let mut s = Session::new();+ let id = s.open("form.pdf", None, Arc::new(pdf(true)), None).unwrap();+ let (a, b) = (ink(&s, id, 122, 138), ink(&s, id, 62, 78));+ assert!(a > 100 && b > 100, "both values are shown: a {a}, b {b}");+ assert!(red(&s, id) > 100, "the comment is drawn too");+ // The file is saved as it was: B still has no appearance, A its empty one.+ let saved = pdfcraft_cos::Document::open(s.save_bytes(id).unwrap()).unwrap();+ let fields = pdfcraft_forms::fields(&saved);+ let widget = |name: &str| saved.get(fields.iter().find(|f| f.name == name).unwrap().widgets[0].obj);+ assert!(widget("b").as_dict().is_some_and(|d| !d.contains(b"AP")), "B has no appearance");+ let n = widget("a").as_dict().and_then(|d| d.get(b"AP").and_then(|ap| saved.resolve(ap).as_dict().and_then(|ap| ap.reference(b"N")))).unwrap();+ let pdfcraft_cos::Object::Stream(n) = &*saved.get(n) else { panic!("A's appearance is a stream") };+ assert_eq!(n.decoded().unwrap().trim_ascii_end(), b"q\nQ", "A keeps its empty appearance");+ // Typing in one field redraws that field only, not the whole form, on each keystroke.+ let builds = |s: &Session| s.get(id).unwrap().editor.as_ref().unwrap().field_appearances.builds();+ let before = builds(&s);+ s.apply(id, Edit::SetFieldValue { name: "a".into(), value: pdfcraft_forms::FieldValue::Text("Typed".into()) }).unwrap();+ assert_eq!(builds(&s), before + 1);++ // Without the flag, the empty appearance is the file's own, and only B is drawn.+ let id = s.open("form.pdf", None, Arc::new(pdf(false)), None).unwrap();+ let (a, b) = (ink(&s, id, 122, 138), ink(&s, id, 62, 78));+ assert!(a == 0 && b > 100, "a {a}, b {b}");+ }+ /// Reproducible workload with 3,129 fields and 190 ordered custom calculations.+ /// No external PDF assets are needed; only in-memory contributor-original objects.+ fn synthetic_acroform(field_count: usize, calculation_count: usize) -> Vec<u8> {+ use pdfcraft_cos::{Dict, Object, PdfString};+ let mut doc = pdfcraft_cos::Document::open(Arc::new(fixture(6))).unwrap();+ let mut refs = Vec::new();+ let mut order = Vec::new();+ for i in 0..field_count {+ let name = match i {+ 0 => "ranks".to_string(),+ 1 => "trained".to_string(),+ 2 => "bonus".to_string(),+ _ => format!("field{i}"),+ };+ let mut d = Dict::new();+ d.set(b"Type".to_vec(), Object::name("Annot"));+ d.set(b"Subtype".to_vec(), Object::name("Widget"));+ d.set(b"FT".to_vec(), Object::name(if i == 1 { "Btn" } else { "Tx" }));+ d.set(b"T".to_vec(), PdfString::text(&name));+ d.set(b"V".to_vec(), if i == 1 { Object::name("Off") } else { Object::String(PdfString::text("0")) });+ d.set(b"Rect".to_vec(), Object::Array([20, 20, 100, 40].map(Object::Int).to_vec()));+ d.set(b"P".to_vec(), Object::Ref(pdfcraft_cos::ObjRef::new(4, 0)));+ if (2..calculation_count + 2).contains(&i) {+ let js = if i == 2 {+ "var r = Number(getField('ranks').value); event.value = r + (r > 0 && getField('trained').isBoxChecked(0) ? 3 : 0);".to_string()+ } else {+ format!("event.value = Number(getField('{}').value) + 1;", if i == 3 { "bonus".to_string() } else { format!("field{}", i - 1) })+ };+ let mut a = Dict::new();+ a.set(b"S".to_vec(), Object::name("JavaScript"));+ a.set(b"JS".to_vec(), PdfString::text(&js));+ let mut aa = Dict::new();+ aa.set(b"C".to_vec(), Object::Dict(a));+ d.set(b"AA".to_vec(), Object::Dict(aa));+ }+ let r = doc.add(Object::Dict(d));+ refs.push(Object::Ref(r));+ if (2..calculation_count + 2).contains(&i) {+ order.push(Object::Ref(r));+ }+ }+ doc.update_dict(pdfcraft_cos::ObjRef::new(4, 0), |d| d.set(b"Annots".to_vec(), Object::Array(refs.clone()))).unwrap();+ let mut af = Dict::new();+ af.set(b"Fields".to_vec(), Object::Array(refs));+ af.set(b"CO".to_vec(), Object::Array(order));+ doc.update_dict(doc.root().unwrap(), |d| d.set(b"AcroForm".to_vec(), Object::Dict(af))).unwrap();+ pdfcraft_cos::write_incremental(&doc, &Default::default()).unwrap()+ }++ #[test]+ #[ignore = "manual performance measurement: 3,129 fields, 190 scripts"]+ fn acroform_interaction_benchmark() {+ let bytes = Arc::new(synthetic_acroform(3129, 190));+ // Optional local export for comparing CLI build profiles. Never overwrite an input.+ if let Some(path) = std::env::var_os("PDFCRAFT_BENCH_EXPORT") {+ use std::io::Write;+ let mut file = std::fs::OpenOptions::new().write(true).create_new(true).open(path).unwrap();+ file.write_all(&bytes).unwrap();+ }+ let mut s = Session::new();+ let id = s.open("synthetic-large-form.pdf", None, bytes, None).unwrap();+ let value = |s: &Session, name: &str| s.get(id).unwrap().form.iter().find(|f| f.name == name).unwrap().value.clone();+ for (name, v) in [+ ("ranks", FieldValue::Text("1".into())),+ ("trained", FieldValue::Check(true)),+ ("ranks", FieldValue::Text("2".into())),+ ("trained", FieldValue::Check(false)),+ ("ranks", FieldValue::Text("0".into())),+ ] {+ let started = std::time::Instant::now();+ s.apply(id, Edit::SetFieldValue { name: name.into(), value: v }).unwrap();+ eprintln!("BENCH {name}: {:.3} ms", started.elapsed().as_secs_f64() * 1000.0);+ assert!(s.take_js_output(id).errors.is_empty());+ }+ assert_eq!(value(&s, "bonus"), ["0"]);+ assert_eq!(value(&s, "field191"), ["189"]);+ assert_eq!(value(&s, "field3128"), ["0"]);+ }++ #[test]+ fn checkbox_and_rank_changes_recalculate_ordered_dependents() {+ let mut s = Session::new();+ let id = s.open("skills.pdf", None, Arc::new(synthetic_acroform(8, 4)), None).unwrap();+ for (name, input, bonus) in [+ ("trained", FieldValue::Check(true), "0"),+ ("ranks", FieldValue::Text("1".into()), "4"),+ ("trained", FieldValue::Check(false), "1"),+ ("ranks", FieldValue::Text("2".into()), "2"),+ ("trained", FieldValue::Check(true), "5"),+ ("ranks", FieldValue::Text("0".into()), "0"),+ ] {+ s.apply(id, Edit::SetFieldValue { name: name.into(), value: input }).unwrap();+ let fields = &s.get(id).unwrap().form;+ let value = |name: &str| fields.iter().find(|f| f.name == name).unwrap().value.clone();+ assert_eq!(value("bonus"), [bonus]);+ assert_eq!(value("field5"), [(bonus.parse::<u32>().unwrap() + 3).to_string()]);+ assert_eq!(value("field7"), ["0"]);+ assert!(s.take_js_output(id).errors.is_empty());+ }+ s.undo(id).unwrap();+ assert_eq!(s.get(id).unwrap().form.iter().find(|f| f.name == "bonus").unwrap().value, ["5"]);+ let saved = s.save_bytes(id).unwrap();+ let reopened = s.open("saved.pdf", None, saved, None).unwrap();+ assert_eq!(s.get(reopened).unwrap().form.iter().find(|f| f.name == "bonus").unwrap().value, ["5"]);+ let appearance = |s: &Session| {+ let doc = s.get(id).unwrap();+ let widget = doc.form.iter().find(|f| f.name == "bonus").unwrap().widgets.first().unwrap().obj;+ doc.editor.as_ref().unwrap().cos.get(widget).as_dict().unwrap().get(b"AP").cloned()+ };+ let before = appearance(&s);+ assert!(before.is_some());+ s.apply(id, Edit::SetFieldValue { name: "field7".into(), value: FieldValue::Text("9".into()) }).unwrap();+ assert_eq!(appearance(&s), before, "unchanged calculated values keep their appearance streams");+ }++ #[test]+ fn dynamic_calculation_reads_and_side_effects_reach_later_fields() {+ use pdfcraft_cos::{Dict, Object, PdfString};+ let mut cos = pdfcraft_cos::Document::open(Arc::new(synthetic_acroform(8, 4))).unwrap();+ let fields = pdfcraft_forms::fields(&cos);+ let bonus = fields.iter().find(|f| f.name == "bonus").unwrap();+ let selector = fields.iter().find(|f| f.name == "field7").unwrap();+ cos.update_dict(selector.obj, |d| d.set(b"V".to_vec(), PdfString::text("ranks"))).unwrap();+ let mut a = Dict::new();+ a.set(b"S".to_vec(), Object::name("JavaScript"));+ a.set(b"JS".to_vec(), PdfString::text(+ "var key = getField('field7').value; var v = Number(getField(key).value); getField('field6').value = v * 2; getField('field6').readonly = true; event.value = v + 1;"+ ));+ let mut aa = Dict::new();+ aa.set(b"C".to_vec(), Object::Dict(a));+ cos.update_dict(bonus.obj, |d| d.set(b"AA".to_vec(), Object::Dict(aa))).unwrap();+ let bytes = pdfcraft_cos::write_incremental(&cos, &Default::default()).unwrap();+ let mut s = Session::new();+ let id = s.open("dynamic.pdf", None, Arc::new(bytes), None).unwrap();+ s.apply(id, Edit::SetFieldValue { name: "ranks".into(), value: FieldValue::Text("4".into()) }).unwrap();+ let fields = &s.get(id).unwrap().form;+ let field = |name: &str| fields.iter().find(|f| f.name == name).unwrap();+ assert_eq!(field("bonus").value, ["5"]);+ assert_eq!(field("field5").value, ["8"], "later calculations see the ordered result");+ assert_eq!(field("field6").value, ["8"], "side-effect value applied");+ assert!(field("field6").read_only(), "side-effect property applied");+ assert_eq!(field("field7").value, ["ranks"]);+ assert!(s.take_js_output(id).errors.is_empty());+ }++ #[test]+ fn scripted_display_changes_survive_warm_cache_and_new_edit() {+ use pdfcraft_forms::{FieldEvent, Scripts};+ let mut cos = pdfcraft_cos::Document::open(Arc::new(synthetic_acroform(2, 0))).unwrap();+ for (display, flags) in [(1, 6), (3, 36), (2, 0), (0, 4)] {+ let fields = pdfcraft_forms::fields(&cos);+ let target = fields.iter().find(|f| f.name == "ranks").unwrap();+ let other = fields.iter().find(|f| f.name == "trained").unwrap();+ let old_display = crate::js::field_state(&cos, other).display;+ let mut runner = crate::js::JsRunner::new(&cos, "synthetic.pdf");+ // Populate the display cache before a script writes the same field.+ let warm = runner.run(FieldEvent::Calculate, "event.value = getField('trained').display;", target, "", &fields);+ assert_eq!(warm.value, old_display.to_string());+ let result = runner.run(+ FieldEvent::Calculate,+ &format!("getField('trained').display = {display}; event.value = getField('trained').display;"),+ target,+ "",+ &fields,+ );+ assert_eq!(result.value, display.to_string());+ assert_eq!(result.changes.len(), 1);+ assert_eq!(result.changes.first().unwrap().display, Some(display));+ pdfcraft_forms::apply_script_changes(&mut cos, &result.changes, &mut pdfcraft_forms::NoScripts).unwrap();+ assert_eq!(cos.get(other.widgets.first().unwrap().obj).as_dict().unwrap().int(b"F").unwrap() & 38, flags);+ // Within an edit the original implementation reads an immutable pre-edit COS snapshot.+ let same_edit = runner.run(FieldEvent::Calculate, "event.value = getField('trained').display;", target, "", &fields);+ assert_eq!(same_edit.value, old_display.to_string());+ // The next edit must rebuild its cache from the newly written annotation flags.+ let mut next = crate::js::JsRunner::new(&cos, "synthetic.pdf");+ let read = next.run(FieldEvent::Calculate, "event.value = getField('trained').display;", target, "", &pdfcraft_forms::fields(&cos));+ assert_eq!(read.value, display.to_string());+ assert!(read.changes.is_empty());+ assert!(runner.output.errors.is_empty());+ assert!(next.output.errors.is_empty());+ }+ }++ /// #2992: a page coloured with Edit a PDF ▸ Background exports to Word with that page colour,+ /// behind its text.+ #[test]+ fn exporting_to_word_keeps_the_page_background() {+ let mut s = Session::new();+ let text = s.create_from_text("t", "Blue text on teal").unwrap();+ let id = s.open("t.pdf", None, text, None).unwrap();+ assert_eq!(s.get(id).unwrap().export_pages()[0].background, None, "no background yet");+ s.apply(+ id,+ Edit::AddBackground {+ pages: vec![0],+ settings: Background { color: [0.0, 0.5, 0.5], opacity: 1.0, ..Background::default() },+ replace: false,+ file: None,+ },+ )+ .unwrap();+ let d = s.get(id).unwrap();+ let page = &d.export_pages()[0];+ assert!(page.background.is_some_and(|c| c.iter().zip([0.0, 0.5, 0.5]).all(|(a, b)| (a - b).abs() < 1e-6)), "{:?}", page.background);+ assert!(page.blocks.iter().any(|b| b.text.contains("Blue text")), "the text is still there");+ let docx = d.export_office(compare::OfficeFormat::Docx);+ assert!(docx.windows(b"word/settings.xml".len()).any(|w| w == b"word/settings.xml"), "Word is told to show the page colour");+ }++ #[test]+ fn exporting_office_keeps_dotted_leader_entries_as_paragraphs() {+ let mut content = String::new();+ for (title, page, y) in [("Art.1. Scope", "3", 200), ("Art.2. Eligibility", "7", 180), ("Art.3. Application", "12", 160)] {+ content.push_str(&format!(+ "BT /F1 12 Tf 72 {y} Td ({title}) Tj ET \+ BT /F1 12 Tf 250 {y} Td (....................) Tj ET \+ BT /F1 12 Tf 500 {y} Td ({page}) Tj ET\n"+ ));+ }+ let pdf = one_line_page("/Font << /F1 4 0 R >>", &content);+ let mut session = Session::new();+ let id = session.open("contents.pdf", None, Arc::new(pdf), None).unwrap();+ let doc = session.get(id).unwrap();+ let html = String::from_utf8(doc.export_office(compare::OfficeFormat::Html)).unwrap();+ assert!(!html.contains("<table>"), "contents entries are paragraphs: {html}");+ let entries = ["Art.1. Scope .................... 3", "Art.2. Eligibility .................... 7", "Art.3. Application .................... 12"];+ let positions: Vec<_> = entries.iter().map(|entry| html.find(&format!("<p>{entry}</p>")).expect("one paragraph per entry")).collect();+ assert!(positions.windows(2).all(|pair| pair[0] < pair[1]), "reading order: {html}");+ }+++/// An XFA button's click script may show the attachments panel; a text field's exit script+/// asking the same is noted on the console and ignored.+#[test]+fn an_xfa_button_may_show_a_side_panel_and_other_events_may_not() {+ let xdp = r##"<?xml version="1.0" encoding="UTF-8"?>+<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/">+<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/">+<subform name="form" layout="tb">+ <pageSet><pageArea name="front"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>+ <field name="files" w="2in" h="0.3in"><ui><button/></ui><caption><value><text>Attachments</text></value></caption>+ <event activity="click"><script contentType="application/x-javascript">app.execMenuItem("ShowHideFileAttachment");</script></event></field>+ <field name="note" w="2in" h="0.3in"><ui><textEdit/></ui>+ <event activity="exit"><script contentType="application/x-javascript">app.execMenuItem("ShowHideFileAttachment");</script></event></field>+</subform>+</template>+</xdp:xdp>+"##;+ let mut s = Session::new();+ let id = s.open("files.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(xdp)), None).expect("opens");+ s.take_js_output(id);+ s.apply(id, Edit::XfaEvent { som: "form[0].files[0]".into(), activity: "click".into() }).unwrap();+ let out = s.take_js_output(id);+ assert_eq!(out.requests, [pdfcraft_js::Request::ShowPanel(pdfcraft_js::Panel::Attachments)], "{out:?}");+ s.apply(id, Edit::SetFieldValue { name: "note".into(), value: FieldValue::Text("x".into()) }).unwrap();+ let out = s.take_js_output(id);+ assert!(out.requests.is_empty(), "only a click shows a panel: {out:?}");+ assert!(out.console.iter().any(|c| c.contains("show a side panel")), "{:?}", out.console);+}++/// A validate script that asks for Save As and a side panel gets neither, with a console note+/// for each; a button's script may still open Save As.+#[test]+fn a_fields_own_script_may_not_save_as_or_show_a_panel() {+ let mut s = Session::new().with_clock(|| 1_700_000_000);+ let id = s.open("order.pdf", None, Arc::new(scripted_form()), None).unwrap();+ s.apply(+ id,+ Edit::SetFieldScript {+ name: "qty".into(),+ event: "validate".into(),+ script: Some("app.execMenuItem('SaveAs'); app.execMenuItem('ShowHideFileAttachment');".into()),+ },+ )+ .unwrap();+ s.take_js_output(id);+ s.apply(id, Edit::SetFieldValue { name: "qty".into(), value: FieldValue::Text("4".into()) }).unwrap();+ let out = s.take_js_output(id);+ assert!(out.requests.is_empty(), "a validate script runs unasked: {out:?}");+ assert_eq!(out.console.iter().filter(|c| c.contains("only a button may")).count(), 2, "{:?}", out.console);+ // A button's script may.+ let o = s.run_javascript(id, "app.execMenuItem('SaveAs');", Some("go")).unwrap();+ assert_eq!(o.requests, [js::Request::SaveAs]);+}diff --cc crates/js/src/tests.rsindex e3ce86efe,7a9efb5df..1cb6f7baa--- a/crates/js/src/tests.rs+++ b/crates/js/src/tests.rs@@@ -1143,48 -1208,36 +1218,82 @@@ mod session}}+ #[test]+ fn shared_field_snapshots_isolate_writes_errors_and_script_globals() {+ let initial = Arc::new(fields());+ let before = initial.as_ref().clone();+ let event = Event::field("Calculate", "total", "");+ let write = run_shared(+ "var scriptLocal = 1; getField('qty').value = 9; getField('agree').checkThisBox(0, true); event.value = getField('qty').value;",+ &event,+ &doc(),+ Arc::clone(&initial),+ &[],+ Limits::default(),+ );+ assert_eq!(write.error, None);+ assert_eq!(write.value, "9");+ assert_eq!(write.changed.iter().find(|f| f.name == "qty").unwrap().value, ["9"]);+ assert_eq!(write.changed.iter().find(|f| f.name == "agree").unwrap().value, ["Yes"]);+ assert_eq!(*initial, before, "script writes cannot mutate the caller's snapshot");+ let failed = run_shared("getField('qty').value = 99; throw new Error('rejected');", &event, &doc(), Arc::clone(&initial), &[], Limits::default());+ assert!(failed.error.is_some());+ assert_eq!(*initial, before, "an exception cannot leak partial writes into the initial snapshot");+ let read = run_shared(+ "event.value = typeof scriptLocal + ':' + getField('qty').value + ':' + getField('agree').isBoxChecked(0);",+ &event,+ &doc(),+ initial,+ &[],+ Limits::default(),+ );+ assert_eq!(read.error, None);+ assert_eq!(read.value, "undefined:4:false");+ assert!(read.changed.is_empty());+ }+++mod menu_items {+ use super::*;+ use crate::xfa::{XfaDoc, XfaEffect, XfaEvent, run_xfa};++ /// Every side panel has a fixed id in automation output.+ #[test]+ fn each_panel_has_a_fixed_id_for_automation() {+ let ids = [Panel::Bookmarks, Panel::Pages, Panel::Attachments, Panel::Signatures, Panel::Layers].map(Panel::id);+ assert_eq!(ids, ["bookmarks", "pages", "attachments", "signatures", "layers"]);+ }++ /// Each side panel item, Print and SaveAs make their request, in order; an unknown item+ /// makes none and is not an error.+ #[test]+ fn exec_menu_item_shows_side_panels_prints_and_saves() {+ let o = go(+ "app.execMenuItem('ShowHideFileAttachment'); app.execMenuItem('ShowHideBookmarks'); app.execMenuItem('ShowHideThumbnails'); \+ app.execMenuItem('ShowHideSignatures'); app.execMenuItem('ShowHideOptCont'); app.execMenuItem('Print'); \+ app.execMenuItem('SaveAs'); app.execMenuItem('NoSuchItem');",+ &Event::field("Mouse Up", "total", ""),+ );+ assert_eq!(o.error, None);+ assert_eq!(+ o.requests,+ [+ Request::ShowPanel(Panel::Attachments),+ Request::ShowPanel(Panel::Bookmarks),+ Request::ShowPanel(Panel::Pages),+ Request::ShowPanel(Panel::Signatures),+ Request::ShowPanel(Panel::Layers),+ Request::Print,+ Request::SaveAs,+ ]+ );+ }++ /// `app.execMenuItem` works in XFA scripts too: a click shows the attachments panel.+ #[test]+ fn xfa_scripts_show_the_attachments_panel() {+ let event = XfaEvent { activity: "click".into(), target: "form1[0].page1[0].go[0]".into(), ..Default::default() };+ let o = run_xfa("app.execMenuItem('ShowHideFileAttachment')", &event, &XfaDoc::default(), &super::xfa_model::form(), Limits::default());+ assert_eq!(o.error, None, "{o:?}");+ assert!(o.effects.contains(&XfaEffect::ShowPanel(Panel::Attachments)), "{:?}", o.effects);+ }+}diff --cc crates/ui-egui/tests/forms.rsindex 85b0ac03d,efc27dc83..373acc671--- a/crates/ui-egui/tests/forms.rs+++ b/crates/ui-egui/tests/forms.rs@@@ -1076,19 -1275,62 +1278,79 @@@ fn auto_size_fields_shrink_and_wrap_typassert_eq!(on_screen_fit(&h, "fixed", long).0, 10.0);}+ /// Where a mode bar tab is, by its label.+ fn mode_tab(h: &Harness<'static, PdfCraftApp>, label: &str) -> egui::Rect {+ use egui_kittest::kittest::Queryable;+ h.get_all_by_role_and_label(egui::accesskit::Role::Button, label).map(|n| n.rect()).find(|r| r.bottom() < 120.0).expect("a mode tab")+ }++ /// Scroll the page until `what` (on screen) lies across the mode bar, then the cursor over each+ /// tab it lies under: with the All tools panel closed, Edit, Convert and E-Sign (the name field+ /// starts right of All tools).+ fn mode_tab_cursors(+ h: &mut Harness<'static, PdfCraftApp>,+ what: impl Fn(&Harness<'static, PdfCraftApp>) -> egui::Rect,+ ) -> [(&'static str, egui::CursorIcon); 3] {+ let page = |h: &Harness<'static, PdfCraftApp>| h.state().views[0].page_screen_rect(0).expect("on screen");+ let y = what(h).center().y - page(h).top();+ let tabs = mode_tab(h, "Convert").center().y;+ h.state_mut().views[0].goto = Some((0, 0.0));+ h.run_steps(4);+ let top = page(h).top();+ h.state_mut().views[0].goto = Some((0, (top - (tabs - y)) / page(h).height()));+ h.run_steps(4);+ let under = what(h);+ ["Edit", "Convert", "E-Sign"].map(|label| {+ let at = mode_tab(h, label).center();+ assert!(under.contains(at), "{under:?} lies under {label} at {at:?}");+ h.hover_at(at);+ h.run_steps(2);+ (label, h.output().platform_output.cursor_icon)+ })+ }++ const HAND_ON_EVERY_TAB: [(&str, egui::CursorIcon); 3] =+ [("Edit", egui::CursorIcon::PointingHand), ("Convert", egui::CursorIcon::PointingHand), ("E-Sign", egui::CursorIcon::PointingHand)];++ /// A text field scrolled up under the mode bar leaves its tabs the hand (#2755). The field gave+ /// them its I-beam, and its open editor floated over them and took their clicks.+ #[test]+ fn mode_tabs_keep_the_hand_over_a_text_field_scrolled_under_them() {+ let mut h = harness();+ // The page across the window, so the name field reaches under the tabs.+ h.state_mut().views[0].fit = pdfcraft_ui_egui::canvas::Fit::Width;+ h.run_steps(4);+ let name = |h: &Harness<'static, PdfCraftApp>| {+ let s = h.state();+ let doc = s.session.get(s.views[0].id).unwrap();+ let f = doc.form.iter().find(|f| f.name == "name").unwrap();+ pdfcraft_ui_egui::forms_ui::field_screen_rect(&s.views[0], &doc.info, f, 0).expect("on screen")+ };+ assert_eq!(mode_tab_cursors(&mut h, name), HAND_ON_EVERY_TAB, "the field under the tabs");+ // Open it, where it shows.+ h.state_mut().views[0].goto = Some((0, 0.0));+ h.run_steps(4);+ click_field(&mut h, "name", 0);+ assert!(h.state().views[0].forms.focus.is_some(), "the editor opened");+ assert_eq!(mode_tab_cursors(&mut h, name), HAND_ON_EVERY_TAB, "the open field under the tabs");+ let convert = mode_tab(&h, "Convert").center();+ click_at(&mut h, convert);+ assert_eq!(h.state().mode, pdfcraft_ui_egui::Mode::Convert, "the tab takes the click, not the field's editor");+ }+++/// A button script's `ShowHideFileAttachment` opens the attachments panel, and running it again+/// closes it.+#[test]+fn a_form_button_shows_and_hides_the_attachments_panel() {+ let mut h = harness();+ h.state_mut().set_option("panel", "none").unwrap();+ h.run_steps(2);+ let id = h.state().views[0].id;+ h.state_mut().run_button_script(id, "size", "app.execMenuItem('ShowHideFileAttachment');");+ h.run_steps(2);+ assert_eq!(h.state().right, Some(pdfcraft_ui_egui::RightPanel::Attachments));+ // Show/Hide, as its name says: asked again, it closes.+ h.state_mut().run_button_script(id, "size", "app.execMenuItem('ShowHideFileAttachment');");+ h.run_steps(2);+ assert_eq!(h.state().right, None);+}