PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Merge PR #2993: Render month and weekday names in XFA date patterns
aionggb2b42c89db9c
diff --cc crates/xfa/src/data.rsindex 4fe089a10,8462465aa..7c2efaf5e--- a/crates/xfa/src/data.rs+++ b/crates/xfa/src/data.rs@@@ -345,8 -238,34 +345,34 @@@ fn date_pattern_of(doc: &Document, f: &Some(body[..body.find('"')?].to_string())}- /// The tokens of a date pattern: `yyyy`, `yy`, `mm`, `m`, `dd`, `d`, or a literal character.+ const MONTHS: [&str; 12] = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];+ const WEEKDAYS: [&str; 7] = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];++ /// The weekday (0 = Sunday) of a proleptic Gregorian date.+ fn weekday(y: u32, m: u32, d: u32) -> usize {+ const T: [i64; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];+ let y = i64::from(y) - i64::from(m < 3);+ let t = T.get((m as usize).wrapping_sub(1)).copied().unwrap_or(0);+ ((y + y / 4 - y / 100 + y / 400 + t + i64::from(d)).rem_euclid(7)) as usize+ }++ /// The index and length of the name in `names` that `text` starts with (ignoring case),+ /// cut to `abbr` letters when that is set.+ fn name_at(text: &str, names: &[&str], abbr: bool) -> Option<(usize, usize)> {+ names.iter().enumerate().find_map(|(i, n)| {+ let n = if abbr { n.get(..3)? } else { n };+ text.get(..n.len()).filter(|t| t.eq_ignore_ascii_case(n)).map(|_| (i, n.len()))+ })+ }++ /// Whether `token` is a run of the date letters (`y`, `m`, `d`) rather than a literal.+ fn is_date_run(token: &str) -> bool {+ token.starts_with(['y', 'm', 'd'])+ }++ /// The tokens of a date pattern: runs of `y`, `m` and `d` (`yyyy`, `yy`, `mmmm`, `mmm`, `mm`,+ /// `m`, `dddd`, `ddd`, `dd`, `d` are understood), or a literal character.-fn date_tokens(pattern: &str) -> Vec<String> {+pub(crate) fn date_tokens(pattern: &str) -> Vec<String> {let mut out = Vec::new();let chars: Vec<char> = pattern.chars().collect();let mut i = 0;diff --cc crates/xfa/src/tests.rsindex b3f79accb,c1edf8184..5d91bce11--- a/crates/xfa/src/tests.rs+++ b/crates/xfa/src/tests.rs@@@ -479,135 -336,22 +479,151 @@@ fn dates_convert_between_iso_and_acrobaassert_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);+}++/// 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 month_and_weekday_names_in_date_patterns() {+ // 2001-02-03 was a Saturday.+ assert_eq!(iso_to_pattern("2001-02-03", "mmm d, yyyy"), "Feb 3, 2001");+ assert_eq!(iso_to_pattern("2001-02-03", "mmmm d, yyyy"), "February 3, 2001");+ assert_eq!(iso_to_pattern("2001-02-03", "ddd, mmm d"), "Sat, Feb 3");+ assert_eq!(iso_to_pattern("2001-02-03", "dddd, mmmm dd, yyyy"), "Saturday, February 03, 2001");+ assert_eq!(pattern_to_iso("Feb 3, 2001", "mmm d, yyyy").as_deref(), Some("2001-02-03"));+ assert_eq!(pattern_to_iso("February 3, 2001", "mmmm d, yyyy").as_deref(), Some("2001-02-03"));+ assert_eq!(pattern_to_iso("Saturday, February 03, 2001", "dddd, mmmm dd, yyyy").as_deref(), Some("2001-02-03"));+ assert_eq!(pattern_to_iso("Smarch 3, 2001", "mmm d, yyyy"), None);+ // A token the converter can't render leaves the value as it is.+ assert_eq!(iso_to_pattern("2001-02-03", "mmmmm d"), "2001-02-03");+ assert_eq!(pattern_to_iso("Feb 3", "mmmmm d"), None);+ }+#[test]fn data_fills_the_fields_and_adds_rows() {let form = layout_xml(&template_with_data(1, DATA)).unwrap();