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 Kaden8f82bfccec26
diff --cc crates/engine/src/tests.rsindex aebb74093,afe6fd06c..24d51947b--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@@ -7101,56 -7284,48 +7284,102 @@@ fn exporting_office_keeps_dotted_leaderassert!(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]);+}+++ /// A page whose forms go past the reading limit and whose picture goes past the image budget is+ /// listed once among the truncated pages.+ #[test]+ fn a_page_truncated_for_forms_and_pictures_is_listed_once() {+ let depth = compare::MAX_FORM_DEPTH + 1;+ let mut objs: Vec<String> = vec![+ "<< /Type /Catalog /Pages 2 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 200] >>".into(),+ String::new(),+ "<< /Type /XObject /Subtype /Image /Width 2 /Height 2 /ColorSpace /DeviceGray /BitsPerComponent 8 /Length 4 >>\nstream\n\0\x20\x40\x7f\nendstream".into(),+ "<< /Length 34 >>\nstream\nq 10 0 0 10 0 0 cm /Im Do Q /D1 Do\nendstream".into(),+ ];+ // Forms D1..D{depth}, objects 6 onwards, each drawing the next.+ let xobjects: String = (1..=depth).map(|i| format!("/D{i} {} 0 R ", 5 + i)).collect();+ let resources = format!("<< /XObject << /Im 4 0 R {xobjects}>> >>");+ for i in 1..=depth {+ let body = if i == depth { "q Q".to_string() } else { format!("/D{} Do", i + 1) };+ objs.push(format!(+ "<< /Type /XObject /Subtype /Form /BBox [0 0 200 200] /Resources {resources} /Length {} >>\nstream\n{body}\nendstream",+ body.len()+ ));+ }+ objs[2] = format!("<< /Type /Page /Parent 2 0 R /Contents 5 0 R /Resources {resources} >>");+ let mut bytes = b"%PDF-1.7\n".to_vec();+ let mut offsets = Vec::new();+ for (i, o) in objs.iter().enumerate() {+ offsets.push(bytes.len());+ bytes.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());+ }+ let xref = bytes.len();+ bytes.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());+ for o in offsets {+ bytes.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());+ }+ bytes.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());+ let mut s = Session::new();+ let id = s.open("both.pdf", None, Arc::new(bytes), None).unwrap();+ let doc = s.get(id).unwrap();+ assert_eq!(doc.export_pages_checked(false, 0).1, [0], "the forms alone truncate the page");+ let (exported, _) = doc.export_pages_checked(true, 1 << 20);+ assert_eq!(exported[0].images.len(), 1, "the picture exports within a sufficient budget");+ let (pages, truncated) = doc.export_pages_checked(true, 0);+ assert!(pages[0].images.is_empty(), "the picture is past the budget");+ assert_eq!(truncated, [0]);+ }diff --cc crates/js/src/lib.rsindex 4a4b5e64b,f2221f750..aaacce0c9--- a/crates/js/src/lib.rs+++ b/crates/js/src/lib.rs@@@ -579,26 -624,21 +654,26 @@@ fn message(v: &JsValue, key: &str, ctx}}+/// `app.alert(cMsg)`: records the message, given as a string or as an object with `cMsg`, and+/// returns 1 (the OK button).fn alert(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {let m = message(&arg(args, 0), "cMsg", ctx)?;- host(ctx)?.borrow_mut().alerts.push(m);+ host(ctx)?.borrow_mut().alert(m);// The OK button.Ok(JsValue::from(1))}+/// `app.beep()`: queues a request to beep.fn beep(_: &JsValue, _: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {- host(ctx)?.borrow_mut().requests.push(Request::Beep);+ host(ctx)?.borrow_mut().request(Request::Beep);Ok(JsValue::undefined())}+/// `app.launchURL(cURL)`: queues a request to open the URL, given as a string or as an object+/// with `cURL`.fn launch_url(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {let u = message(&arg(args, 0), "cURL", ctx)?;- host(ctx)?.borrow_mut().requests.push(Request::LaunchUrl(u));+ host(ctx)?.borrow_mut().request(Request::LaunchUrl(u));Ok(JsValue::undefined())}diff --cc crates/js/src/xfa.rsindex 2c34e75be,8a60e8ba9..7c02dbbd3--- a/crates/js/src/xfa.rs+++ b/crates/js/src/xfa.rs@@@ -181,6 -182,47 +184,47 @@@ pub(crate) fn clip_value(v: String) ->}}+ /// The field names of a `resetData` list (comma-separated), each cut to [`MAX_LINE`] and+ /// named once, at most as many as a snapshot holds nodes.+ pub(crate) fn reset_names(list: &str) -> Vec<String> {+ let mut seen = HashSet::new();+ let mut out = Vec::new();+ for name in list.split(',').map(str::trim).filter(|s| !s.is_empty()) {+ if out.len() >= MAX_NODES {+ break;+ }+ let name = clip(name.to_string());+ if seen.insert(name.clone()) {+ out.push(name);+ }+ }+ out+ }++ /// The (property, SOM) an effect setting a property of an object is merged by, see+ /// [`XHost::set_at`].+ fn effect_key(e: &XfaEffect) -> Option<(u8, String)> {+ match e {+ XfaEffect::SetValue { som, .. } => Some((0, som.clone())),+ XfaEffect::SetPresence { som, .. } => Some((1, som.clone())),+ XfaEffect::SetAccess { som, .. } => Some((2, som.clone())),+ _ => None,+ }+ }++ /// Bytes of text `e` holds.+ fn payload(e: &XfaEffect) -> usize {+ match e {+ XfaEffect::SetValue { som, value: s } | XfaEffect::SetPresence { som, presence: s } | XfaEffect::SetAccess { som, access: s } => {+ som.len().saturating_add(s.len())+ }+ XfaEffect::AddInstance { som } | XfaEffect::RemoveInstance { som } => som.len(),+ XfaEffect::MessageBox(s) | XfaEffect::LaunchUrl(s) | XfaEffect::SetFocus(s) => s.len(),+ XfaEffect::ResetData(names) => names.iter().fold(0usize, |n, s| n.saturating_add(s.len()).saturating_add(std::mem::size_of::<String>())),- XfaEffect::Print | XfaEffect::SaveAs | XfaEffect::Beep | XfaEffect::Recalculate | XfaEffect::Relayout => 0,++ XfaEffect::Print | XfaEffect::SaveAs | XfaEffect::Beep | XfaEffect::Recalculate | XfaEffect::Relayout | XfaEffect::ShowPanel(_) => 0,+ }+ }+/// A script's completion value (what a calculate script puts in its field) cut to/// [`MAX_VALUE`] characters, as values a script sets are, with a note when it was.pub(crate) fn clip_result(out: &mut XfaOutcome) {@@@ -1027,12 -1142,9 +1147,11 @@@ fn message_box(_: &JsValue, args: &[JsVOk(JsValue::from(1.0))}+/// `xfa.host.resetData(names)`: asks to reset the comma-separated fields, or every field when+/// the list is empty.fn reset_data(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult<JsValue> {let list = text(&arg(args, 0), ctx)?;- let names: Vec<String> = list.split(',').map(str::trim).filter(|s| !s.is_empty()).map(str::to_string).collect();- effect(ctx, XfaEffect::ResetData(names))?;+ effect(ctx, XfaEffect::ResetData(reset_names(&list)))?;Ok(JsValue::undefined())}