diff --git a/Cargo.lock b/Cargo.lock index f9d5de635f..78345be496 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6755,6 +6755,7 @@ dependencies = [ "craft-xml", "pdfcraft-cos", "pdfcraft-fonts", + "pdfcraft-model", "sha2 0.11.1", "thiserror 2.0.21", ] diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 10f0e8cb02..9364bdcb8a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -9096,6 +9096,96 @@ fn xfa_dates_are_written_and_read_back_in_their_data_picture() { assert_eq!(value("when"), vec!["10/18/2026".to_string()]); } +/// #8411: an XFA time field is a time, not a date. Its data's canonical `HH:MM:SS` shows in the +/// field's time picture, a time typed there goes back to the data canonically, and text that +/// is no time is kept as typed. +#[test] +fn xfa_time_fields_show_their_picture_and_keep_canonical_times_in_the_data() { + let bytes = Arc::new(pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::time_template( + "
14:30:0008:15:00
", + ))); + let mut s = Session::new().with_clock(|| 1_700_000_000); + let id = s.open("form.pdf", None, bytes, None).expect("opens"); + let value = + |s: &Session, id, n: &str| s.get(id).unwrap().form.iter().find(|f| f.name == n).unwrap_or_else(|| panic!("no field {n}")).value.clone(); + assert_eq!(value(&s, id, "start"), vec!["2:30 PM".to_string()], "shown in its time picture"); + assert_eq!(value(&s, id, "at"), vec!["08:15:00".to_string()], "canonical without a picture"); + let actions = |s: &Session, id, n: &str| s.get(id).unwrap().form.iter().find(|f| f.name == n).unwrap().actions.clone(); + for name in ["start", "at"] { + let a = actions(&s, id, name); + assert!(matches!(a.format, pdfcraft_forms::af::Format::Time(_)), "{name} formats a time: {:?}", a.format); + assert!(a.xfa_date, "{name} keeps text its pattern doesn't read"); + } + s.apply(id, Edit::SetFieldValue { name: "start".into(), value: FieldValue::Text("9:05 PM".into()) }).unwrap(); + s.apply(id, Edit::SetFieldValue { name: "at".into(), value: FieldValue::Text("after lunch".into()) }).unwrap(); + let saved = s.save_bytes(id).unwrap(); + let cos = pdfcraft_cos::Document::open(saved.clone()).unwrap(); + let data = pdfcraft_xfa::parse_datasets(&pdfcraft_xfa::read_packets(&cos).unwrap().unwrap().xdp).unwrap(); + let at = |som: &str| data.text_at(&pdfcraft_xfa::som_to_path(som)).map(str::to_string); + assert_eq!(at("form[0].page[0].start[0]").as_deref(), Some("21:05:00"), "canonical in the data"); + assert_eq!(at("form[0].page[0].at[0]").as_deref(), Some("after lunch"), "no time: kept as typed"); + let id2 = s.open("again.pdf", None, saved, None).unwrap(); + assert_eq!(value(&s, id2, "start"), vec!["9:05 PM".to_string()]); + assert_eq!(value(&s, id2, "at"), vec!["after lunch".to_string()]); +} + +/// A time widget's appearance and saved XFA data retain text its time picture cannot read. +#[test] +fn an_xfa_time_field_draws_unrecognized_text_without_turning_it_into_midnight() { + let bytes = Arc::new(pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::time_template("
14:30:00
"))); + let mut s = Session::new().with_clock(|| 1_700_000_000); + let id = s.open("form.pdf", None, bytes, None).expect("opens"); + for text in ["after lunch", "after 2 hours", "13:30 PM", "2:30"] { + s.apply(id, Edit::SetFieldValue { name: "start".into(), value: FieldValue::Text(text.into()) }).unwrap(); + let saved = s.save_bytes(id).unwrap(); + let widget = s.get(id).unwrap().form.iter().find(|f| f.name == "start").expect("start").widgets[0].obj; + let cos = pdfcraft_cos::Document::open(saved.clone()).unwrap(); + let drawn = normal_appearance(&cos, widget.num); + assert!(drawn.contains(text), "the appearance retains {text:?}: {drawn}"); + let data = pdfcraft_xfa::parse_datasets(&pdfcraft_xfa::read_packets(&cos).unwrap().unwrap().xdp).unwrap(); + assert_eq!(data.text_at(&pdfcraft_xfa::som_to_path("form[0].page[0].start[0]")), Some(text)); + } +} + +/// The page draws an XFA time field's meridiem as its picture's `A` writes it, `PM`, not as +/// Acrobat's `tt` does (`pm`), so the drawn text matches the field's value (#8607 review). +#[test] +fn an_xfa_time_field_draws_its_meridiem_in_upper_case() { + let bytes = Arc::new(pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::time_template("
14:30:00
"))); + let mut s = Session::new().with_clock(|| 1_700_000_000); + let id = s.open("form.pdf", None, bytes, None).expect("opens"); + s.apply(id, Edit::SetFieldValue { name: "start".into(), value: FieldValue::Text("9:05 PM".into()) }).unwrap(); + let saved = s.save_bytes(id).unwrap(); + let widget = s.get(id).unwrap().form.iter().find(|f| f.name == "start").expect("start").widgets[0].obj; + let cos = pdfcraft_cos::Document::open(saved).unwrap(); + let drawn = normal_appearance(&cos, widget.num); + assert!(drawn.contains("PM"), "the meridiem is drawn as the value shows it: {drawn}"); + assert!(!drawn.contains("pm"), "not in Acrobat's lower case: {drawn}"); +} + +/// A time field nobody changed keeps its data as it is, with the seconds, fraction or zone its +/// picture doesn't show (#8607 review: `14:30:00Z` was saved as `14:30:00`). +#[test] +fn an_xfa_time_nobody_changed_keeps_its_data_as_it_is() { + let bytes = Arc::new(pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::time_template( + "
14:30:45Z08:15:00.250
", + ))); + let mut s = Session::new().with_clock(|| 1_700_000_000); + let id = s.open("form.pdf", None, bytes, None).expect("opens"); + let value = + |s: &Session, id, n: &str| s.get(id).unwrap().form.iter().find(|f| f.name == n).unwrap_or_else(|| panic!("no field {n}")).value.clone(); + assert_eq!(value(&s, id, "start"), vec!["2:30 PM".to_string()]); + assert_eq!(value(&s, id, "at"), vec!["08:15:00".to_string()]); + s.apply(id, Edit::SetFieldValue { name: "note".into(), value: FieldValue::Text("Tremblay".into()) }).unwrap(); + let saved = s.save_bytes(id).unwrap(); + let cos = pdfcraft_cos::Document::open(saved).unwrap(); + let data = pdfcraft_xfa::parse_datasets(&pdfcraft_xfa::read_packets(&cos).unwrap().unwrap().xdp).unwrap(); + let at = |som: &str| data.text_at(&pdfcraft_xfa::som_to_path(som)).map(str::to_string); + assert_eq!(at("form[0].page[0].note[0]").as_deref(), Some("Tremblay"), "the edit is saved"); + assert_eq!(at("form[0].page[0].start[0]").as_deref(), Some("14:30:45Z"), "seconds and zone kept"); + assert_eq!(at("form[0].page[0].at[0]").as_deref(), Some("08:15:00.250"), "fraction kept"); +} + /// Same-named date fields are each written in their own data picture, and a data picture /// without a day keeps the ISO date. #[test] diff --git a/crates/forms/src/af.rs b/crates/forms/src/af.rs index ca53869e69..87a30186ad 100644 --- a/crates/forms/src/af.rs +++ b/crates/forms/src/af.rs @@ -124,6 +124,8 @@ pub struct Actions { /// pattern [`Actions::format`] names: the value is typed and kept in this one, and shown in /// that one. pub edit_date: Option, + /// XFA time edit picture when it differs from the display picture. + pub edit_time: Option, } /// Field scripts that aren't AF calls, by event. @@ -148,6 +150,15 @@ impl Actions { /// The Keystroke event on commit ([`keystroke`]); an XFA date field checks the text against its /// edit pattern and keeps what that doesn't read, as typed. pub fn keystroke(&self, field: &str, value: &str) -> Result { + if let Format::Time(fmt) = &self.format + && self.xfa_date + && generated_time_format(fmt) + && !value.trim().is_empty() + { + // Save and display must agree on what is a time. The generic parser can trim text + // that the XFA data parser leaves as entered. + return Ok(if self.parse_xfa_time(value, fmt).is_some() { value.trim().to_string() } else { value.to_string() }); + } let edit = self.edit_pattern().map(|p| Format::Date(p.to_string())); match keystroke(edit.as_ref().unwrap_or(&self.format), field, value) { Err(_) if self.xfa_date => Ok(value.to_string()), @@ -175,10 +186,29 @@ impl Actions { None => iso_date(t).map_or_else(|| value.to_string(), |dt| format_date_in(dt, fmt, names)), } } + // An XFA time field shows its meridiem as its picture's `A` does, in upper case (#8411 review). + (Format::Time(fmt), _) if self.xfa_date => { + // Normal XFA widgets use formats produced by the XFA picture converter. Use + // the same bounded parser as XFA data saving, so the appearance never invents + // a time that the saved data will keep as unrecognized text. + let parsed = if generated_time_format(fmt) { + self.parse_xfa_time(value, fmt).and_then(|canonical| parse_date(&canonical, "HH:MM:ss")) + } else { + // Externally marked widgets can carry custom alphabetic formats; preserve + // their pre-existing behavior instead of reinterpreting their literals. + parse_date(value, fmt) + }; + parsed.map_or_else(|| value.to_string(), |dt| format::format_date_meridiem(dt, fmt, names, ["AM", "PM"])) + } (f, _) => format_value_in(f, value, names), } } + fn parse_xfa_time(&self, value: &str, fmt: &str) -> Option { + let typed = self.edit_time.as_deref().unwrap_or(fmt); + pdfcraft_model::time_picture::pattern_to_canonical(value, typed).or_else(|| pdfcraft_model::time_picture::pattern_to_canonical(value, fmt)) + } + /// An XFA date field's edit pattern: [`Actions::edit_date`], else its display pattern. fn edit_pattern(&self) -> Option<&str> { match &self.format { @@ -188,11 +218,22 @@ impl Actions { } } +// XFA's picture converter emits this subset; externally marked custom formats retain their +// existing generic parsing behavior, including alphabetic literals. +fn generated_time_format(fmt: &str) -> bool { + fmt.chars().any(|c| matches!(c, 'H' | 'h')) && fmt.chars().all(|c| matches!(c, 'H' | 'h' | 'M' | 's' | 't' | ':' | '.' | ' ' | '-' | ',')) +} + /// The pattern an `AFDate_KeystrokeEx("…")` keystroke script checks dates against. pub fn parse_date_keystroke(js: &str) -> Option { call(js, "AFDate_KeystrokeEx")?.first().and_then(Arg::string) } +/// The pattern an `AFTime_KeystrokeEx("…")` script checks times against. +pub fn parse_time_keystroke(js: &str) -> Option { + call(js, "AFTime_KeystrokeEx")?.first().and_then(Arg::string) +} + /// `text` as an ISO 8601 calendar date, `yyyy-mm-dd` or `yyyymmdd` (digits only, a real day). fn iso_date(text: &str) -> Option { let b = text.as_bytes(); diff --git a/crates/forms/src/af/format.rs b/crates/forms/src/af/format.rs index e81180422d..501b50cea8 100644 --- a/crates/forms/src/af/format.rs +++ b/crates/forms/src/af/format.rs @@ -518,6 +518,13 @@ pub fn format_date(dt: DateTime, fmt: &str) -> String { /// [`format_date`] with month and weekday names from `names`. pub fn format_date_in(dt: DateTime, fmt: &str, names: &DateNames) -> String { + format_date_meridiem(dt, fmt, names, ["am", "pm"]) +} + +/// [`format_date_in`] with `tt` written as `meridiem` (morning, afternoon) and `t` as their first letters: an +/// XFA time picture's `A` is upper case (`2:30 PM`), where Acrobat's `tt` is lower case. +pub(crate) fn format_date_meridiem(dt: DateTime, fmt: &str, names: &DateNames, meridiem: [&str; 2]) -> String { + let meridiem = meridiem[usize::from(dt.hh >= 12)]; let chars: Vec = fmt.chars().collect(); let mut out = String::new(); let mut i = 0; @@ -582,8 +589,8 @@ pub fn format_date_in(dt: DateTime, fmt: &str, names: &DateNames) -> String { ('s', _) => { let _ = write!(out, "{}", dt.ss); } - ('t', 2) => out.push_str(if dt.hh < 12 { "am" } else { "pm" }), - ('t', _) => out.push(if dt.hh < 12 { 'a' } else { 'p' }), + ('t', 2) => out.push_str(meridiem), + ('t', _) => out.extend(meridiem.chars().next()), (c, n) => out.extend(std::iter::repeat_n(c, n)), } i += n; diff --git a/crates/forms/src/af/tests.rs b/crates/forms/src/af/tests.rs index 54e0cb9d93..2704fd9c9e 100644 --- a/crates/forms/src/af/tests.rs +++ b/crates/forms/src/af/tests.rs @@ -337,6 +337,73 @@ fn numbers_format_like_acrobat() { assert_eq!(keystroke(&Format::None, "Name", " \t"), Ok(" \t".into())); } +#[test] +fn xfa_time_fields_keep_unrecognized_text_visible() { + for fmt in ["h:MM tt", "HH:MM:ss"] { + let xfa = Actions { format: Format::Time(fmt.into()), xfa_date: true, ..Actions::default() }; + assert_eq!(xfa.format_value("after lunch"), "after lunch"); + assert_eq!(xfa.format_value(" pending "), " pending "); + assert_eq!(xfa.format_value("after 2 hours"), "after 2 hours"); + assert_eq!(xfa.format_value("25:99"), "25:99"); + assert_eq!(xfa.keystroke("Time", "after lunch"), Ok("after lunch".into())); + } + let xfa = Actions { format: Format::Time("h:MM tt".into()), xfa_date: true, ..Actions::default() }; + assert_eq!(xfa.format_value("14:30"), "14:30"); + assert_eq!(xfa.format_value("13:30 PM"), "13:30 PM"); + assert_eq!(xfa.format_value("2:30"), "2:30"); + assert_eq!(xfa.format_value("0:30 AM"), "0:30 AM"); + assert_eq!(xfa.format_value("12:30 AM"), "12:30 AM"); + assert_eq!(xfa.format_value("12:30 PM"), "12:30 PM"); + assert_eq!(xfa.format_value("2:30p"), "2:30 PM"); + assert_eq!(xfa.format_value("2.30 pm"), "2.30 pm", "a separator not accepted by the XFA data parser stays visible"); + assert_eq!(format_value(&Format::Time("h:MM tt".into()), "14:30"), "2:30 pm"); + let fallback = Actions { format: Format::Time("HH:MM:ss".into()), xfa_date: true, ..Actions::default() }; + assert_eq!(fallback.format_value("09m05S30"), "09m05S30", "an unsupported picture's original text stays visible"); + let custom = Actions { format: Format::Time("HHxMM".into()), xfa_date: true, ..Actions::default() }; + assert_eq!(custom.format_value("9x5"), "09x05", "a marked widget's custom letter separator keeps its existing coercion"); +} + +#[test] +fn xfa_time_appearance_and_saved_data_share_the_same_parse_boundary() { + let fmt = "h:MM tt"; + let actions = Actions { format: Format::Time(fmt.into()), xfa_date: true, ..Actions::default() }; + for text in ["2:30p", "12:30 AM", "12:30 PM", "13:30 PM", "2:30", "2.30 pm", "after 2 hours"] { + let canonical = pdfcraft_model::time_picture::pattern_to_canonical(text, fmt); + let shown = actions.format_value(text); + match canonical { + Some(expected) => assert_eq!(pdfcraft_model::time_picture::pattern_to_canonical(&shown, fmt), Some(expected), "{text}"), + None => assert_eq!(shown, text, "unrecognized input stays visible: {text}"), + } + } +} + +#[test] +fn xfa_time_commit_preserves_unrecognized_text_without_changing_other_fields() { + let xfa = Actions { format: Format::Time("h:MM tt".into()), xfa_date: true, ..Actions::default() }; + for value in [" 13:30 PM ", " 2:30 ", " 2.30 pm ", " after 2 hours "] { + assert_eq!(xfa.keystroke("Time", value), Ok(value.to_string()), "{value}"); + assert_eq!(xfa.format_value(value), value); + } + assert_eq!(xfa.keystroke("Time", " 2:30p "), Ok("2:30p".into())); + assert_eq!(xfa.keystroke("Time", " "), Ok(String::new())); + let swapped = Actions { edit_time: Some("HH:MM".into()), ..xfa.clone() }; + assert_eq!(swapped.keystroke("Time", " 14:30 "), Ok("14:30".into())); + assert_eq!(swapped.keystroke("Time", " 13:30 PM "), Ok(" 13:30 PM ".into())); + let plain = Actions { xfa_date: false, ..xfa }; + assert_eq!(plain.keystroke("Time", " 13:30 PM "), Ok("13:30 PM".into())); + let custom = Actions { format: Format::Time("HHxMM".into()), xfa_date: true, ..Actions::default() }; + assert_eq!(custom.keystroke("Time", " 9x5 "), Ok("9x5".into())); +} + +#[test] +fn xfa_time_with_distinct_edit_and_display_patterns_uses_edit_first() { + let actions = Actions { format: Format::Time("h:MM tt".into()), xfa_date: true, edit_time: Some("HH:MM".into()), ..Actions::default() }; + assert_eq!(actions.format_value("14:30"), "2:30 PM"); + assert_eq!(actions.format_value("2:30 PM"), "2:30 PM", "display pattern is also accepted"); + assert_eq!(actions.format_value("13:30 PM"), "13:30 PM"); + assert_eq!(parse_time_keystroke("AFTime_KeystrokeEx(\"HH:MM\");").as_deref(), Some("HH:MM")); +} + /// A date field laid out for an XFA form keeps text its pattern doesn't read, as typed, and /// shows a date only for a value that is one: in the pattern already, or an ISO date. Another /// viewer keeps and shows such text the same way on a synthetic form; an ordinary date field diff --git a/crates/forms/src/read.rs b/crates/forms/src/read.rs index 0b87e7eaf0..9a0d831c6b 100644 --- a/crates/forms/src/read.rs +++ b/crates/forms/src/read.rs @@ -198,6 +198,11 @@ fn actions_of(doc: &Document, d: &Dict, widgets: &[ObjRef], scripts: &mut Decode { out.edit_date = k.as_deref().and_then(af::parse_date_keystroke).filter(|edit| edit != shown); } + if out.xfa_date + && let af::Format::Time(shown) = &out.format + { + out.edit_time = k.as_deref().and_then(af::parse_time_keystroke).filter(|edit| edit != shown); + } if let Some(k) = k && out.format == af::Format::None { diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs index 70661044d8..5aed20d179 100644 --- a/crates/model/src/lib.rs +++ b/crates/model/src/lib.rs @@ -2,6 +2,9 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +/// Bounded parsing of time-picture values. +pub mod time_picture; + use pdfcraft_cos::{Dict, Document, ObjRef, Object}; /// Attributes a page inherits from its ancestors (ISO 32000-2 §7.7.3.4). diff --git a/crates/model/src/time_picture.rs b/crates/model/src/time_picture.rs new file mode 100644 index 0000000000..9906c18ea9 --- /dev/null +++ b/crates/model/src/time_picture.rs @@ -0,0 +1,139 @@ +//! Shared bounded parser for time-picture values used by XFA display and data saving. + +/// The tokens of an Acrobat time pattern: runs of `H`, `h`, `M`, `s` or `t`, or a literal +/// character. +pub fn time_tokens(pattern: &str) -> Vec { + let chars: Vec = pattern.chars().collect(); + let mut out = Vec::new(); + let mut i = 0; + while i < chars.len() { + let c = chars[i]; + let mut j = i + 1; + if "HhMst".contains(c) { + while j < chars.len() && chars[j] == c { + j += 1; + } + } + out.push(chars[i..j].iter().collect()); + i = j; + } + out +} + +/// A time typed in `pattern` as the canonical `HH:MM:SS`, or `None` when it doesn't match. The +/// hour letters say whether it is a 12-hour (`h`, with `tt`) or a 24-hour (`H`) hour. A pattern +/// with more than one hour, minute, second or AM/PM isn't read: a time has one of each, and the +/// pattern can come from a file (`AFTime_KeystrokeEx`), where repeats would make reading it slow. +pub fn pattern_to_canonical(text: &str, pattern: &str) -> Option { + let tokens = checked_tokens(pattern)?; + let (h, m, s) = read_tokens(&tokens, text.trim(), Read::default(), None)?; + Some(format!("{h:02}:{m:02}:{s:02}")) +} + +/// Whether the same edit-picture value admits two distinct times. Uses the same bounded +/// parser and leaves the normal first-match typing behavior unchanged. +pub fn time_pattern_is_ambiguous(text: &str, pattern: &str) -> bool { + let Some(tokens) = checked_tokens(pattern) else { return false }; + let Some(first) = read_tokens(&tokens, text.trim(), Read::default(), None) else { return false }; + read_tokens(&tokens, text.trim(), Read::default(), Some(first)).is_some() +} + +fn checked_tokens(pattern: &str) -> Option> { + let tokens = time_tokens(pattern); + let kind = |t: &String| match t.chars().next() { + Some('H' | 'h') => Some('H'), + Some(c @ ('M' | 's' | 't')) => Some(c), + _ => None, + }; + for k in ['H', 'M', 's', 't'] { + if tokens.iter().filter(|t| kind(t) == Some(k)).count() > 1 { + return None; + } + } + Some(tokens) +} + +/// What [`read_tokens`] has read so far. +#[derive(Clone, Copy, Default)] +struct Read { + hour: Option, + minute: u32, + second: u32, + twelve: bool, + pm: bool, +} + +/// `rest` read against `tokens` as hours, minutes and seconds. A one-letter number (`H`, `M`, …) +/// takes two digits or one, whichever lets the rest match, so `905` reads in `HMM` as 9:05. Only +/// a number tries more than one way, so with one of each the search is at most eight ways deep +/// and three calls down, however long the literal text between them. +fn read_tokens(mut tokens: &[String], mut rest: &str, mut r: Read, excluded: Option<(u32, u32, u32)>) -> Option<(u32, u32, u32)> { + loop { + let Some((t, more)) = tokens.split_first() else { + if !rest.is_empty() { + return None; + } + let mut h = r.hour?; + if r.twelve { + if !(1..=12).contains(&h) { + return None; + } + h = h % 12 + if r.pm { 12 } else { 0 }; + } + let time = (h, r.minute, r.second); + return (h < 24 && r.minute < 60 && r.second < 60 && excluded != Some(time)).then_some(time); + }; + tokens = more; + match t.as_str() { + "HH" | "H" | "hh" | "h" | "MM" | "M" | "ss" | "s" => { + let digits = rest.chars().take_while(char::is_ascii_digit).count(); + let widths: &[usize] = if t.len() == 2 { &[2] } else { &[2, 1] }; + return widths.iter().filter(|&&w| w <= digits).find_map(|&w| { + let v: u32 = rest[..w].parse().ok()?; + let mut r = r; + match t.as_bytes()[0] { + b'H' => r.hour = Some(v), + b'h' => (r.hour, r.twelve) = (Some(v), true), + b'M' => r.minute = v, + _ => r.second = v, + } + read_tokens(tokens, &rest[w..], r, excluded) + }); + } + "tt" | "t" => { + let upper = rest.to_ascii_uppercase(); + let (pm, len) = if upper.starts_with("AM") { + (false, 2) + } else if upper.starts_with("PM") { + (true, 2) + } else if upper.starts_with('A') { + (false, 1) + } else if upper.starts_with('P') { + (true, 1) + } else { + return None; + }; + r.pm = pm; + rest = &rest[len..]; + } + // A space in the pattern matches any run of spaces, or none before AM/PM. + " " => rest = rest.trim_start(), + lit => rest = rest.strip_prefix(lit)?, + } + } +} + +#[cfg(test)] +mod ambiguity_tests { + use super::*; + + #[test] + fn reports_only_distinct_valid_readings_without_changing_normal_parse() { + assert_eq!(pattern_to_canonical("111", "HM").as_deref(), Some("11:01:00")); + assert!(time_pattern_is_ambiguous("111", "HM")); + assert!(!time_pattern_is_ambiguous("000", "HM")); + assert!(!time_pattern_is_ambiguous("0111", "HM")); + assert!(!time_pattern_is_ambiguous("999", "HM")); + assert!(!time_pattern_is_ambiguous("111", "HHMHH")); + } +} diff --git a/crates/xfa/Cargo.toml b/crates/xfa/Cargo.toml index 7b073f617f..01e42cd350 100644 --- a/crates/xfa/Cargo.toml +++ b/crates/xfa/Cargo.toml @@ -13,6 +13,7 @@ workspace = true [dependencies] craft-xfa = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9888a585552d872ec94734daf064f96a0a25c41e" } pdfcraft-cos = { workspace = true } +pdfcraft-model = { workspace = true } pdfcraft-fonts = { workspace = true } craft-xml = { workspace = true } base64 = "0.23" diff --git a/crates/xfa/README.md b/crates/xfa/README.md index f8c92f2348..3c9c047603 100644 --- a/crates/xfa/README.md +++ b/crates/xfa/README.md @@ -120,7 +120,7 @@ be measured exponentially often in their nesting. A measurement budget backs thi | `/PCSom` | generated fields | the field's SOM path, so values go back to the data | | `/PCXfaLayout` | AcroForm | what laying out produced, so a saved form is not laid out again | | `/PCXfaOverrides` | AcroForm | `<< /Presence << /som (hidden) … >> /Access << /som (readOnly) … >> >>`: presence and access scripts set, by SOM path (instance 0 of a repeating subform stands for all); applied to the template before every layout, so undo, save and reopen keep them. Adobe's viewers draw from the XFA packets and don't read it; at most 10 000 entries are read or written | - | `/PCXfaDate` | generated date fields | `true`: text the field's date pattern doesn't read is kept, and shown, as typed rather than refused, as an XFA form keeps it; the forms layer reads it | + | `/PCXfaDate` | generated date and time fields | `true`: text the field's date or time pattern doesn't read is kept, and shown, as typed rather than refused, as an XFA form keeps it; the forms layer reads it | | `/PCXfaNode` | generated fields above a signature field | `true`: the field names a step of the signature field's SOM path; a new layout replaces it with the fields it holds | | `/PCXfaClick` | generated push buttons | `true`: the template has a click script for this button. Such buttons carry no `/A`: XFA JavaScript is not Acrobat JavaScript, so it is never written as a `/S /JavaScript` action other viewers would run. PdfCraft finds the script by the field's `/PCSom` | diff --git a/crates/xfa/src/data.rs b/crates/xfa/src/data.rs index 4e7de4af74..00ff500af1 100644 --- a/crates/xfa/src/data.rs +++ b/crates/xfa/src/data.rs @@ -21,6 +21,7 @@ mod import; mod merge; mod passwords; mod path; +mod times; mod values; mod write; @@ -36,6 +37,7 @@ pub use import::{DataImport, ImportNode, export_data, import_data, parse_data_fi pub use passwords::{clear_password_values, has_password_values}; pub use path::{data_path, parse_datasets, som_to_path}; pub(crate) use path::{fields_with_ids, template_field, template_object}; +pub(crate) use times::{canonical_to_pattern, is_time_field, pattern_to_canonical, time_letters, time_pattern, time_pattern_is_ambiguous}; pub use values::{FieldData, FieldDatum, is_on, name_text, radio_dataset_value, radio_state_for_item, read_values, read_values_with}; #[cfg(test)] pub(crate) use write::ENSURED; diff --git a/crates/xfa/src/data/times.rs b/crates/xfa/src/data/times.rs new file mode 100644 index 0000000000..469eb2670e --- /dev/null +++ b/crates/xfa/src/data/times.rs @@ -0,0 +1,254 @@ +//! XFA time fields (#8411): a time picture clause as an Acrobat time pattern, and a time of day +//! between its canonical form in the data (`HH:MM:SS`, XFA 3.3 "Canonical Format", p. 1046) and +//! that pattern. + +use super::Field; +use crate::model::Ui; +use pdfcraft_model::time_picture::time_tokens; +pub(crate) use pdfcraft_model::time_picture::{pattern_to_canonical, time_pattern_is_ambiguous}; + +/// The pattern a time field without a time picture shows and is typed in: the canonical form. +pub(crate) const CANONICAL_TIME: &str = "HH:MM:ss"; + +/// The Acrobat time pattern (`AFTime_FormatEx` letters: `h`/`hh` and `H`/`HH` hours, `M`/`MM` +/// minutes, `s`/`ss` seconds, `tt` AM or PM) of an XFA time picture clause such as +/// `time{h:MM A}` (XFA 3.3, "Time Pictures", pp. 1173–1174), or `None` when it isn't one or has +/// a symbol this doesn't read (`k`, `K`, `FFF`, zones, quoted text). +pub(crate) fn time_letters(picture: &str) -> Option { + // Of several alternatives, the first: the one a field shows and keeps its value in. + let first = crate::picture::alternatives(picture).into_iter().next()?; + let inner = first.trim().strip_prefix("time")?.trim_start().strip_prefix('{')?.strip_suffix('}')?; + let chars: Vec = inner.chars().collect(); + let mut out = String::new(); + let mut i = 0; + while i < chars.len() { + let c = chars[i]; + let mut j = i; + while j < chars.len() && chars[j] == c { + j += 1; + } + let run = j - i; + match (c, run) { + ('H' | 'h' | 'M', 1 | 2) => out.extend(std::iter::repeat_n(c, run)), + // XFA's seconds are `S`; Acrobat's are `s`. + ('S', 1 | 2) => out.extend(std::iter::repeat_n('s', run)), + ('A', 1) => out.push_str("tt"), + (':' | '.' | ' ' | '-' | ',', _) => out.extend(std::iter::repeat_n(c, run)), + _ => return None, + } + i = j; + } + out.chars().any(|c| matches!(c, 'H' | 'h')).then_some(out) +} + +/// Whether `f` holds a time of day: a date-time widget whose value is a `