Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

Merge PR #3397: M12: XFA dates are written and read in the field's data picture

aionggdbc2647f48a2
diff --cc crates/engine/src/tests.rs
index b1c4b9240,27a6a3b4f..b104ef598
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@@ -4196,41 -4155,8 +4196,43 @@@ fn dynamic_xfa_forms_open_with_the_valu
assert!(!doc.dirty);
}
+/// #3180: an XFA form with no fields whose configuration says `dynamicRender` is `forbidden` is a
+/// static form: its pages are the form. Opening it used to lay the template out into new pages
+/// and write them as a revision, so even a save with no change replaced the pages.
+#[test]
+fn an_xfa_form_without_fields_that_forbids_dynamic_rendering_keeps_its_pages() {
+ // The fixture's own config packet gains `acrobat/acrobat7/dynamicRender`.
+ let template = pdfcraft_xfa::fixtures::template(1);
+ let forbidden = "<acrobat><acrobat7><dynamicRender>forbidden</dynamicRender></acrobat7></acrobat><present>";
+ let with_config = template.replacen("<present>", forbidden, 1);
+ assert_ne!(with_config, template, "the fixture has a config packet");
+ // The fixture shell without /NeedsRendering (blanked in place, so the offsets stay right).
+ let shell = |xdp: &str| {
+ let bytes = pdfcraft_xfa::fixtures::shell(xdp);
+ let at = bytes.windows(20).position(|w| w == b"/NeedsRendering true").expect("the fixture sets it");
+ let mut bytes = bytes;
+ bytes.splice(at..at + 20, *b" ");
+ Arc::new(bytes)
+ };
+ let mut s = Session::new().with_clock(|| 1_700_000_000);
+ let original = shell(&with_config);
+ let id = s.open("static.pdf", None, original.clone(), None).expect("opens");
+ let doc = s.get(id).unwrap();
+ assert_eq!(doc.info.xfa, Some(pdfcraft_render::Xfa::Static));
+ assert!(doc.xfa.is_none(), "nothing was laid out");
+ assert_eq!(doc.bytes[..], original[..], "no revision was appended on open");
+ assert_eq!(doc.info.pages.len(), 1);
+ // The same form without the config is still taken to be dynamic: laid out from the template
+ // into an appended revision.
+ let plain = shell(&template);
+ let id = s.open("dynamic.pdf", None, plain.clone(), None).expect("opens");
+ let doc = s.get(id).unwrap();
+ assert!(doc.xfa.is_some(), "laid out from the template");
+ assert!(doc.bytes.len() > plain.len() && doc.bytes.starts_with(&plain[..]), "the layout is a revision");
+}
+
+ /// A static XFA form's fields take their values from the datasets on opening, and edits are
+ /// written back there.
#[test]
fn static_xfa_forms_take_their_values_from_the_datasets_and_write_them_back() {
let original = Arc::new(pdfcraft_xfa::fixtures::static_shell("<form1><page1><name>Ada</name><agree>1</agree></page1></form1>"));
diff --cc crates/xfa/src/layout.rs
index 5a501fbf2,478936188..7527caab8
--- a/crates/xfa/src/layout.rs
+++ b/crates/xfa/src/layout.rs
@@@ -396,45 -396,11 +396,39 @@@ fn is_row(node: &Node) -> bool
/// The Acrobat date pattern for an XFA picture clause such as `date{YYYY-MM-DD}`.
fn date_pattern(picture: Option<&str>) -> String {
- let p = picture.unwrap_or("");
- let inner = p.find('{').and_then(|a| p[a + 1..].find('}').map(|b| &p[a + 1..a + 1 + b])).unwrap_or(p);
- let inner = inner.trim();
- if inner.is_empty() || inner.chars().any(|c| !"YMDEJ-/., :".contains(c)) {
- return "yyyy-mm-dd".into();
- }
- inner.replace('E', "d").to_ascii_lowercase()
+ picture.and_then(date_letters).unwrap_or_else(|| "yyyy-mm-dd".into())
}
-/// The PDF action a button's click script becomes: a native one for a single-statement idiom
-/// (reset, print, save, a link), else the script itself.
+/// What scripts read as a field's `formattedValue` when its display picture is `picture`: the
+/// ISO date `raw` shown in a date picture (`date{YYYYMMDD}` turns `2026-10-20` into
+/// `20261020`; of several alternatives, the first). `None` for other kinds of picture, for a
+/// clause this can't read or show (month and weekday names) and for a value that isn't an ISO
+/// date: the raw value stands then.
+pub fn formatted_value(picture: &str, raw: &str) -> Option<String> {
+ let first = picture.split('|').next()?.trim();
+ let rest = first.strip_prefix("date")?;
+ if !rest.starts_with(['{', '(']) {
+ return None;
+ }
+ let pattern = date_pattern(Some(first));
+ // A picture with parts this can't show yet (month or weekday names, `MMM` or `EEE`) would
+ // leave them as letters: the raw value stands then.
+ let shows = |t: &String| !t.chars().all(|c| c.is_ascii_alphabetic()) || matches!(t.as_str(), "yyyy" | "yy" | "mm" | "m" | "dd" | "d");
+ if !crate::data::date_tokens(&pattern).iter().all(shows) {
+ return None;
+ }
+ // Only the ISO date's own shape (`2026-10-20`): `2026-1-2` is not one, and stands.
+ let b = raw.as_bytes();
+ let iso = b.len() == 10 && b.iter().enumerate().all(|(i, c)| if i == 4 || i == 7 { *c == b'-' } else { c.is_ascii_digit() });
+ if !iso {
+ return None;
+ }
+ let shown = iso_to_pattern(raw, &pattern);
+ (shown != raw).then_some(shown)
+}
+
+/// The native PDF action a button's click script amounts to (a reset, print, save or link),
+/// else the script itself to run; `None` without a click script.
fn button_action(scripts: &[Script]) -> Option<Action> {
let s = scripts.iter().find(|s| s.activity == "click")?;
let t = &s.text;
diff --cc crates/xfa/src/script.rs
index f709a2754,f74293a67..e2efd62ea
--- a/crates/xfa/src/script.rs
+++ b/crates/xfa/src/script.rs
@@@ -243,9 -235,8 +243,9 @@@ impl Walker<'_>
self.ov.access.get(som).cloned().unwrap_or_else(|| access_name(a).to_string())
}
- /// The live node of field `f`, instance `index` under `parent_som`: its value from the data
- /// (as scripts read it) or its default, a radio button's from its group's choice `radio`.
+ /// The live node of field `f`, child `index` of `parent_som`, with its scripts recorded. In an
+ /// exclusion group (`radio` is the group's selected value) its value is its on value when picked,
- /// else empty; elsewhere it is its data value (as saved) or its template default.
++ /// else empty; elsewhere it is its data value (as saved, as scripts read it) or its template default.
fn field(&mut self, f: &Field, parent_som: &str, index: usize, radio: Option<&str>) -> FormNode {
let som = child_som(parent_som, f.common.name.as_deref().or(Some("field")), index);
let data_value = self.data.and_then(|d| d.value_at(&data_path(self.tpl, &som))).map(|t| t.trim().to_string()).filter(|t| !t.is_empty());
diff --cc crates/xfa/src/tests.rs
index d66f6f7cf,b6c861a53..0d4041859
--- a/crates/xfa/src/tests.rs
+++ b/crates/xfa/src/tests.rs
@@@ -8,7 -8,7 +8,8 @@@ use crate::data::
};
use crate::data::{add_data_instances, remove_data_instance, write_data_value};
use crate::fixtures::{
- TINY_GIF, fields_template, scripted_template, shell, static_shell, template, template_with_data, tiny_png, unnamed_hidden_template,
+ TINY_GIF, bound_date_template, fields_template, scripted_template, shell, static_shell, template, template_with_data, tiny_png,
++ unnamed_hidden_template,
};
use crate::layout::Item;
use crate::layout::WidgetKind;
@@@ -341,41 -339,101 +342,135 @@@ fn dates_convert_between_iso_and_acroba
assert_eq!(pattern_to_iso("hello", "mm/dd/yyyy"), None);
}
+/// What scripts read as `formattedValue`: a date display picture shows the ISO value in its
+/// pattern (the first of several alternatives); other kinds of picture, and values that aren't
+/// ISO dates, leave the raw value.
+#[test]
+fn formatted_values_follow_date_display_pictures() {
+ assert_eq!(crate::formatted_value("date{YYYYMMDD}", "2026-10-20").as_deref(), Some("20261020"));
+ assert_eq!(crate::formatted_value("date{MM/DD/YYYY}", "2026-10-20").as_deref(), Some("10/20/2026"));
+ assert_eq!(crate::formatted_value("date{YYYYMMDD}|date{DDMMMYY}", "2026-10-20").as_deref(), Some("20261020"));
+ assert_eq!(crate::formatted_value("date{YYYY-MM-DD}", "2026-10-20"), None, "shown as it is");
+ assert_eq!(crate::formatted_value("num{zzz9}", "2026-10-20"), None);
+ assert_eq!(crate::formatted_value("date{YYYYMMDD}", "20261020"), None, "not an ISO date");
+ assert_eq!(crate::formatted_value("date{YYYYMMDD}", ""), None);
+ // Month and weekday names aren't shown yet: the raw value stands rather than `20 mmm 2026`.
+ assert_eq!(crate::formatted_value("date{DD MMM YYYY}", "2026-10-20"), None);
+ assert_eq!(crate::formatted_value("date{EEE MM/DD/YYYY}", "2026-10-20"), None);
+ // Only the ISO date's own shape is formatted.
+ assert_eq!(crate::formatted_value("date{YYYYMMDD}", "2026-1-2"), None);
+ // Parentheses hold the picture's locale and braces its pattern: one without braces has none.
+ assert_eq!(crate::formatted_value("date(en_US){YYYYMMDD}", "2026-10-20").as_deref(), Some("20261020"));
+ assert_eq!(crate::formatted_value("date(YYYYMMDD)", "2026-10-20"), None);
+}
+
+/// A field's `<format><picture>` is its display picture, kept apart from its `<ui>` edit
+/// picture; a field without one has none.
+#[test]
+fn display_pictures_are_parsed_apart_from_edit_pictures() {
+ let (tpl, _) = parse(&crate::fixtures::date_row_template()).unwrap();
+ let Node::Subform(page) = &tpl.root.children[0] else { panic!() };
+ let Node::Field(from) = &page.children[0] else { panic!() };
+ assert_eq!((from.picture.as_deref(), from.display_picture.as_deref()), (Some("date{YYYYMMDD}"), Some("date{YYYYMMDD}")));
+ let Node::Field(days) = &page.children[1] else { panic!() };
+ assert_eq!(days.display_picture, None);
+}
+
- /// The datasets fill the fields they bind to and add the rows the data holds.
+ /// A date field's data picture (`<bind><picture>`) is how its value is written in the data:
+ /// `due` keeps `20261018` there and shows `10/18/2026`. The stored text used to be shown as it
+ /// was, because the data was taken to hold ISO dates only.
+ #[test]
+ fn a_date_is_read_from_the_data_in_its_data_picture() {
+ let form = layout_xml(&bound_date_template("<form><page><due>20261018</due><when>2026-10-18</when></page></form>")).unwrap();
+ let all: Vec<&Widget> = form.pages.iter().flat_map(widgets).collect();
+ let by = |n: &str| all.iter().find(|w| w.name == n).unwrap_or_else(|| panic!("no widget {n}"));
+ assert_eq!(by("due").value.as_deref(), Some("10/18/2026"));
+ assert_eq!(by("when").value.as_deref(), Some("10/18/2026"), "no data picture: the data holds ISO");
+ }
+
+ /// A SOM path names the template field its segment numbers count to, repeating rows included.
+ #[test]
+ fn som_paths_name_the_template_field_their_numbers_count_to() {
+ let xml = r#"<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/"><template xmlns="http://www.xfa.org/schema/xfa-template/3.3/">
+ <subform name="form">
+ <field name="x"><bind><picture>first</picture></bind></field>
+ <subform name="row"><occur min="1" max="-1"/><field name="d"><bind><picture>row</picture></bind></field></subform>
+ <field name="x"><bind><picture>second</picture></bind></field>
+ <subform><field name="u"><bind><picture>inner</picture></bind></field></subform>
+ </subform>
+ </template></xdp:xdp>"#;
+ let (tpl, _) = parse(xml).unwrap();
+ let picture = |som: &str| crate::data::template_field(&tpl, som).and_then(|f| f.data_picture.clone());
+ // Same-named siblings count up; each SOM number is its own field.
+ assert_eq!(picture("form[0].x[0]").as_deref(), Some("first"));
+ assert_eq!(picture("form[0].x[1]").as_deref(), Some("second"));
+ assert_eq!(picture("form[0].x[2]"), None, "no third x");
+ // The instances of a repeating subform follow its number: all are the one template node.
+ assert_eq!(picture("form[0].row[0].d[0]").as_deref(), Some("row"));
+ assert_eq!(picture("form[0].row[3].d[0]").as_deref(), Some("row"));
+ // An unnamed subform is looked through, as data paths do.
+ assert_eq!(picture("form[0].u[0]").as_deref(), Some("inner"));
+ }
+
+ /// Refreshing a value in place uses the field's own template field, not a same-named one's.
+ #[test]
+ fn a_refreshed_field_takes_its_value_from_its_own_template_field() {
+ // Two text fields named `x` with different defaults; the data holds only the first.
+ let xml = r#"<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/"><template xmlns="http://www.xfa.org/schema/xfa-template/3.3/">
+ <subform name="form">
+ <field name="x"><ui><textEdit/></ui><value><text>first</text></value></field>
+ <field name="x"><ui><textEdit/></ui><value><text>second</text></value></field>
+ </subform>
+ </template><xfa:datasets xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/"><xfa:data><form><x>a</x></form></xfa:data></xfa:datasets></xdp:xdp>"#;
+ let (tpl, _) = parse(xml).unwrap();
+ let data = parse_datasets(xml).unwrap();
+ let mut live = form_tree(&tpl, Some(&data), &Overrides::default()).root;
+ let value = |live: &crate::script::FormNode, som: &str| node_at(live, som).map(|n| n.value.clone());
+ assert_eq!(value(&live, "form[0].x[1]").as_deref(), Some("second"));
+ assert_eq!(crate::script::refresh_value(&mut live, &tpl, Some(&data), "form[0].x[1]"), Some(false), "nothing to change");
+ assert_eq!(value(&live, "form[0].x[1]").as_deref(), Some("second"), "not the first x's default");
+ }
+
+ /// Scripts read a date as the ISO date another viewer gives them as `rawValue`
+ /// (`2026-10-18`), whatever the field's data picture writes in the data (`20261018`), so a
+ /// script's `String(rawValue).length == 10` holds. A field without a data picture keeps the
+ /// data's ISO date, and refreshing a value in place reads it the same way.
+ #[test]
+ fn scripts_read_a_date_as_iso_whatever_its_data_picture_writes() {
+ let xml = bound_date_template("<form><page><due>20261018</due><when>2026-10-18</when></page></form>");
+ let (tpl, _) = parse(&xml).unwrap();
+ let data = parse_datasets(&xml).unwrap();
+ let mut live = form_tree(&tpl, Some(&data), &Overrides::default()).root;
+ let value = |live: &crate::script::FormNode, som: &str| node_at(live, som).map(|n| n.value.clone());
+ assert_eq!(value(&live, "form[0].page[0].due[0]").as_deref(), Some("2026-10-18"));
+ assert_eq!(value(&live, "form[0].page[0].when[0]").as_deref(), Some("2026-10-18"));
+ let later = parse_datasets(&bound_date_template("<form><page><due>20261019</due><when>2026-10-18</when></page></form>")).unwrap();
+ assert_eq!(crate::script::refresh_value(&mut live, &tpl, Some(&later), "form[0].page[0].due[0]"), Some(true));
+ assert_eq!(value(&live, "form[0].page[0].due[0]").as_deref(), Some("2026-10-19"));
+ }
+
+ /// The node of `live` at `som`.
+ fn node_at<'a>(live: &'a crate::script::FormNode, som: &str) -> Option<&'a crate::script::FormNode> {
+ if live.som == som {
+ return Some(live);
+ }
+ live.children.iter().find_map(|c| node_at(c, som))
+ }
+
+ /// A date its data picture can't hold (2050 in a two-digit year) is written as ISO and reads
+ /// back as written.
+ #[test]
+ fn a_date_its_data_picture_cant_hold_is_written_as_iso() {
+ use crate::data::{data_to_iso, iso_to_data};
+ assert_eq!(iso_to_data("2026-01-02".into(), Some("yymmdd")), "260102");
+ // A two-digit year reads back as 1950 to 2049: 2050 and 1949 keep ISO, and read back as written.
+ for iso in ["2050-01-02", "1949-12-31"] {
+ assert_eq!(iso_to_data(iso.into(), Some("yymmdd")), iso);
+ assert_eq!(data_to_iso(iso, Some("yymmdd")), iso);
+ }
+ }
+
+ /// The datasets fill the fields and add the rows of repeating subforms.
#[test]
fn data_fills_the_fields_and_adds_rows() {
let form = layout_xml(&template_with_data(1, DATA)).unwrap();