XFA: time fields show and keep times through their time picture (#8411) (#8607)

* XFA: time fields are times, not dates (#8411)

A dateTimeEdit whose value is a <time/>, or whose picture is a time{…}
clause, became a date field formatted yyyy-mm-dd. It is now a time field:
its picture becomes an AFTime pattern, its canonical HH:MM:SS data value
shows in that pattern, a typed time goes back to the data canonically,
and text that isn't a time is kept as typed. Taking the XFA out makes a
time field typed in one pattern and shown in another hold its time as
shown, as date fields do.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* XFA time fields: keep untouched time data; read data canonically (#8411)

- A time field still showing the time its data holds keeps that data as
  it is, so a zone, a fraction or seconds the picture doesn't show
  survive a save (review on #8607).
- A data value is read as a canonical time first, whatever order the
  picture puts its fields in (`time{HH:SS:MM}`).
- A one-letter number in a time pattern takes one digit when the next
  number needs the other (`905` in `HMM`).
- Only a time clause alone makes a time field; `time{…} date{…}` stays a
  date field.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* XFA time fields: read a time pattern in bounded time and depth (#8411)

A pattern with more than one hour, minute, second or AM/PM isn't read, so the
one-or-two-digit search tries at most eight ways. Literal text is consumed in a
loop, so a long run of it no longer means a call per character. The pattern can
come from a file's AFTime_KeystrokeEx when the XFA is removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* XFA time fields: draw the meridiem in upper case, as the picture's A does (#8411)

Review on #8607: the value read 2:30 PM while the page drew 2:30 pm,
because the appearance went through Acrobat's lower-case tt. An XFA
time field (/PCXfaDate) now draws AM/PM; plain AcroForm tt is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Preserve ambiguous XFA times in static conversion

* Fix time conversion Clippy warning

---------

Co-authored-by: sixparks <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: FredApps <[email protected]>
Co-authored-by: FredApps <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-12-04 18:51:01 +01:00
1 parent 69d6f8316a
commit c2fcf77e9e
20 files changed
+801 -14

No files matched your search

Generated
+1
View File
@@ -6755,6 +6755,7 @@ dependencies = [
"craft-xml",
"pdfcraft-cos",
"pdfcraft-fonts",
"pdfcraft-model",
"sha2 0.11.1",
"thiserror 2.0.21",
]
+90
View File
@@ -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(
"<form><page><start>14:30:00</start><at>08:15:00</at></page></form>",
)));
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("<form><page><start>14:30:00</start></page></form>")));
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("<form><page><start>14:30:00</start></page></form>")));
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(
"<form><page><start>14:30:45Z</start><at>08:15:00.250</at></page></form>",
)));
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]
+41
View File
@@ -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<String>,
/// XFA time edit picture when it differs from the display picture.
pub edit_time: Option<String>,
}
/// 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<String, String> {
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<String> {
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<String> {
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<String> {
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<DateTime> {
let b = text.as_bytes();
+9 -2
View File
@@ -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<char> = 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;
+67
View File
@@ -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
+5
View File
@@ -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
{
+3
View File
@@ -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).
+139
View File
@@ -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<String> {
let chars: Vec<char> = 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<String> {
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<Vec<String>> {
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<u32>,
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"));
}
}
+1
View File
@@ -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"
+1 -1
View File
@@ -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` |
+2
View File
@@ -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;
+254
View File
@@ -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<String> {
// 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<char> = 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 `<time/>` or whose edit
/// or display picture is a time picture.
pub(crate) fn is_time_field(f: &Field) -> bool {
let time_picture = |p: &Option<String>| p.as_deref().is_some_and(is_time_picture);
f.ui == Ui::DateTimeEdit && (f.time || time_picture(&f.picture) || time_picture(&f.display_picture))
}
/// Whether the first alternative of `picture` is a time clause alone (`time{…}`), not a date and
/// time picture such as `time{HH:MM} date{YYYY-MM-DD}`, which stays a date field.
fn is_time_picture(picture: &str) -> bool {
let Some(first) = crate::picture::alternatives(picture).into_iter().next() else { return false };
let Some(body) = first.trim().strip_prefix("time").map(str::trim_start).and_then(|b| b.strip_prefix('{')) else { return false };
body.split_once('}').is_some_and(|(_, after)| after.trim().is_empty())
}
/// The pattern a time field is typed in: its edit picture's, else its display picture's, else
/// the canonical one.
pub(crate) fn time_pattern(f: &Field) -> String {
[&f.picture, &f.display_picture].into_iter().find_map(|p| p.as_deref().and_then(time_letters)).unwrap_or_else(|| CANONICAL_TIME.to_string())
}
/// A canonical time (`HH:MM:SS`, `HH:MM`, `HH`, their basic forms `HHMMSS` and `HHMM`, with
/// optional `.FFF` milliseconds and a zone, which are dropped) as hours, minutes and seconds.
fn read_canonical(text: &str) -> Option<(u32, u32, u32)> {
let t = text.trim();
let t = t.strip_suffix('Z').unwrap_or(t);
// A zone offset after the time: `+01:00`, `-0500`, `+01`.
let t = match t.find(['+', '-']) {
Some(at) => {
let zone = t[at + 1..].replace(':', "");
if !matches!(zone.len(), 2 | 4) || !zone.chars().all(|c| c.is_ascii_digit()) {
return None;
}
&t[..at]
}
None => t,
};
let t = t.split_once('.').map_or(t, |(time, ms)| if ms.len() == 3 && ms.chars().all(|c| c.is_ascii_digit()) { time } else { "" });
let parts: Vec<&str> = if t.contains(':') {
t.split(':').collect()
} else if matches!(t.len(), 2 | 4 | 6) && t.is_ascii() {
(0..t.len()).step_by(2).map(|i| &t[i..i + 2]).collect()
} else {
return None;
};
if parts.is_empty() || parts.len() > 3 || parts.iter().any(|p| p.len() != 2 || !p.chars().all(|c| c.is_ascii_digit())) {
return None;
}
let n = |i: usize| parts.get(i).map_or(Some(0), |p| p.parse::<u32>().ok());
let (h, m, s) = (n(0)?, n(1)?, n(2)?);
(h < 24 && m < 60 && s < 60).then_some((h, m, s))
}
/// The canonical time `canonical` shown in `pattern` (`14:30:00` in `h:MM tt` → `2:30 PM`). A
/// value that isn't a canonical time comes back as it is: XFA keeps input no picture reads
/// (p. 156), and a data value is read canonically first, whatever order the picture puts its
/// fields in.
pub(crate) fn canonical_to_pattern(canonical: &str, pattern: &str) -> String {
let Some((h, m, s)) = read_canonical(canonical) else { return canonical.to_string() };
let h12 = if h % 12 == 0 { 12 } else { h % 12 };
let mut out = String::new();
let tokens = time_tokens(pattern);
let numeric = |t: &str| matches!(t, "H" | "HH" | "h" | "hh" | "M" | "MM" | "s" | "ss");
for (i, t) in tokens.iter().enumerate() {
// Adjacent variable-width components otherwise have ambiguous boundaries: for
// example 1:11 as HM would become 111, which the reader takes as 11:01.
let adjacent = i.checked_sub(1).and_then(|j| tokens.get(j)).is_some_and(|t| numeric(t)) || tokens.get(i + 1).is_some_and(|t| numeric(t));
match t.as_str() {
"HH" => out.push_str(&format!("{h:02}")),
"H" if adjacent => out.push_str(&format!("{h:02}")),
"H" => out.push_str(&h.to_string()),
"hh" => out.push_str(&format!("{h12:02}")),
"h" if adjacent => out.push_str(&format!("{h12:02}")),
"h" => out.push_str(&h12.to_string()),
"MM" => out.push_str(&format!("{m:02}")),
"M" if adjacent => out.push_str(&format!("{m:02}")),
"M" => out.push_str(&m.to_string()),
"ss" => out.push_str(&format!("{s:02}")),
"s" if adjacent => out.push_str(&format!("{s:02}")),
"s" => out.push_str(&s.to_string()),
"tt" => out.push_str(if h < 12 { "AM" } else { "PM" }),
"t" => out.push_str(if h < 12 { "A" } else { "P" }),
lit => out.push_str(lit),
}
}
out
}
/// Whether a time field showing `text` in `pattern` still holds the data value `old`: `old` is a
/// canonical time and shows as `text`. Then `old` stays in the data as it is, with the seconds,
/// fraction or zone the pattern doesn't show.
pub(crate) fn shows_data_time(old: &str, text: &str, pattern: &str) -> bool {
read_canonical(old).is_some() && canonical_to_pattern(old, pattern) == text
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn time_pictures_become_acrobat_time_patterns() {
assert_eq!(time_letters("time{h:MM A}").as_deref(), Some("h:MM tt"));
assert_eq!(time_letters("time{HH:MM:SS}").as_deref(), Some("HH:MM:ss"));
assert_eq!(time_letters("time{hh.MM}").as_deref(), Some("hh.MM"));
assert_eq!(time_letters("time{HH:MM}|time{HHMM}").as_deref(), Some("HH:MM"), "the first alternative");
// The general pattern parser accepts these literals, but XFA picture conversion does not
// emit them as widget formats: unsupported pictures fall back to the canonical pattern.
assert_eq!(pattern_to_canonical("09m05S30", "HHmMMSss").as_deref(), Some("09:05:30"));
assert_eq!(time_letters("time{HHmMMSss}"), None);
let unsupported = Field { picture: Some("time{HHmMMSss}".into()), ..Field::default() };
assert_eq!(time_pattern(&unsupported), CANONICAL_TIME);
// Symbols this doesn't read, and pictures that aren't time pictures.
for p in ["time{HH:MM:SS.FFF}", "time{k:MM}", "time{HH:MM Z}", "date{YYYY-MM-DD}", "time{MM:SS}", "HH:MM", "date{YYYYMMDD}|time{HH:MM}"] {
assert_eq!(time_letters(p), None, "{p}");
}
}
#[test]
fn times_go_between_the_canonical_form_and_a_pattern() {
for (canonical, pattern, shown) in [
("14:30:00", "h:MM tt", "2:30 PM"),
("00:05:09", "h:MM:ss tt", "12:05:09 AM"),
("12:00:00", "hh:MM tt", "12:00 PM"),
("09:07:00", "HH:MM", "09:07"),
("23:59:59", "H.MM.ss", "23.59.59"),
] {
assert_eq!(canonical_to_pattern(canonical, pattern), shown, "{canonical} in {pattern}");
assert_eq!(pattern_to_canonical(shown, pattern).as_deref(), Some(canonical), "{shown} in {pattern}");
}
// Other canonical spellings read too: basic form, milliseconds, zones.
for canonical in ["143000", "14:30", "14:30:00.250", "14:30:00Z", "14:30:00+01:00", "14:30:00-0500", "1430"] {
assert_eq!(canonical_to_pattern(canonical, "h:MM tt"), "2:30 PM", "{canonical}");
}
for text in ["14:30:00.2", "14:30:00.25", "14:30:00.2500", "14:30:00.é00"] {
assert_eq!(canonical_to_pattern(text, "h:MM tt"), text, "invalid fraction stays as text");
}
// Adjacent short tokens must not change the meaning on a later read.
for (canonical, pattern, shown) in [("01:11:00", "HM", "0111"), ("11:01:00", "HM", "1101"), ("09:05:07", "HMs", "090507")] {
assert_eq!(canonical_to_pattern(canonical, pattern), shown);
assert_eq!(pattern_to_canonical(shown, pattern).as_deref(), Some(canonical));
}
// Typing is forgiving about case and the space before AM/PM.
assert_eq!(pattern_to_canonical("2:30pm", "h:MM tt").as_deref(), Some("14:30:00"));
assert_eq!(pattern_to_canonical("2:30 p", "h:MM tt").as_deref(), Some("14:30:00"));
// Not times: left as they are, and not read.
for text in ["", "soon", "25:00:00", "14:60", "2026-03-05"] {
assert_eq!(canonical_to_pattern(text, "h:MM tt"), text, "{text}");
}
// A one-letter number takes one digit when the next number needs the other.
for (text, pattern, canonical) in [
("905", "HMM", "09:05:00"),
("1430", "HMM", "14:30:00"),
("1430", "HHMM", "14:30:00"),
("9:05", "H:MM", "09:05:00"),
("959", "HM", "09:59:00"),
("230PM", "hMMtt", "14:30:00"),
] {
assert_eq!(pattern_to_canonical(text, pattern).as_deref(), Some(canonical), "{text} in {pattern}");
}
// A data value is read canonically, whatever order the picture puts its fields in.
assert_eq!(canonical_to_pattern("09:14:23", "HH:ss:MM"), "09:23:14");
assert_eq!(pattern_to_canonical("09:23:14", "HH:ss:MM").as_deref(), Some("09:14:23"));
for (text, pattern) in [("13:30 PM", "h:MM tt"), ("2:30", "h:MM tt"), ("24:00", "HH:MM"), ("2:30 PM extra", "h:MM tt")] {
assert_eq!(pattern_to_canonical(text, pattern), None, "{text} in {pattern}");
}
}
#[test]
fn a_pattern_from_a_file_is_read_in_bounded_time_and_depth() {
// Run where a hang or a stack overflow fails the test rather than stalling it.
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
// Repeated one-letter numbers once meant trying two widths each: some 2^31 ways here,
// none of which reads the `x`.
let repeated = pattern_to_canonical(&format!("{}x", "9".repeat(48)), &"HM".repeat(16));
// A long run of literal text once meant a call per character.
let colons = ":".repeat(200_000);
let long = pattern_to_canonical(&format!("9{colons}05"), &format!("H{colons}MM"));
let _ = tx.send((repeated, long));
});
let (repeated, long) = rx.recv_timeout(std::time::Duration::from_secs(20)).expect("reads in bounded time");
assert_eq!(repeated, None, "a pattern with more than one hour isn't read");
assert_eq!(long.as_deref(), Some("09:05:00"));
for p in ["HH:MM:HH", "h:MM tt tt", "HH:MM:ss:s"] {
assert_eq!(pattern_to_canonical("09:05:00", p), None, "{p}");
}
// Literal letters aren't numbers: one `S` or `m` beside the seconds and minutes is fine.
assert_eq!(pattern_to_canonical("09m05S30", "HHmMMSss").as_deref(), Some("09:05:30"));
}
#[test]
fn a_field_showing_its_data_time_keeps_that_data() {
for (old, text) in [("14:30:00Z", "2:30 PM"), ("08:15:00.250", "8:15 AM"), ("14:30:45", "2:30 PM"), ("1430", "2:30 PM")] {
assert!(shows_data_time(old, text, "h:MM tt"), "{old} as {text}");
}
// Changed, or not a canonical time in the data.
for (old, text) in [("14:30:00", "2:31 PM"), ("9:05 PM", "9:05 PM"), ("", "")] {
assert!(!shows_data_time(old, text, "h:MM tt"), "{old} as {text}");
}
}
#[test]
fn only_a_time_clause_alone_makes_a_time_field() {
for p in ["time{h:MM A}", " time {HH:MM}", "time{HH:MM}|date{YYYY-MM-DD}", "time{k:MM}"] {
assert!(is_time_picture(p), "{p}");
}
for p in ["time{HH:MM} date{YYYY-MM-DD}", "date{YYYY-MM-DD} time{HH:MM}", "date{YYYY-MM-DD}", "HH:MM", ""] {
assert!(!is_time_picture(p), "{p}");
}
}
}
+31
View File
@@ -1,5 +1,6 @@
use super::dates::{data_date_pattern, data_to_iso, iso_to_data, iso_to_pattern, pattern_to_iso};
use super::path::{data_path, parse_datasets, som_to_path};
use super::times::{canonical_to_pattern, pattern_to_canonical, shows_data_time};
use super::{DataPath, Dict, Document, ObjRef, Object, Template};
/// What a field holds, for writing the datasets.
@@ -150,6 +151,26 @@ fn date_pattern_of(doc: &Document, f: &FieldDatum) -> Option<String> {
named(b"K", "AFDate_KeystrokeEx(").or_else(|| named(b"F", "AFDate_FormatEx("))
}
/// The time patterns of a time field PdfCraft laid out (#8411): its `AFTime_KeystrokeEx`, which
/// it holds the time in, then its `AFTime_FormatEx`, which a time may also be typed in.
fn time_patterns_of(doc: &Document, f: &FieldDatum) -> Option<Vec<String>> {
let d = doc.get(f.obj);
let d = d.as_dict()?;
// Only the fields PdfCraft generated: another form's time script says nothing of its data.
d.get(crate::DATE_KEY)?;
let aa = doc.resolve(d.get(b"AA")?);
let aa = aa.as_dict()?;
let named = |key: &[u8], call: &str| -> Option<String> {
let action = doc.resolve(aa.get(key)?);
let js = text_of(doc, action.as_dict()?, b"JS")?;
let rest = js.get(js.find(call)? + call.len()..)?;
let body = rest.get(rest.find('"')? + 1..)?;
Some(body.get(..body.find('"')?)?.to_string())
};
let patterns: Vec<String> = [named(b"K", "AFTime_KeystrokeEx("), named(b"F", "AFTime_FormatEx(")].into_iter().flatten().collect();
(!patterns.is_empty()).then_some(patterns)
}
/// A value to write: where (the field's SOM path, and the data path it binds to) and what.
pub(super) struct Want {
pub(super) som: String,
@@ -182,6 +203,9 @@ pub(super) fn path_of(tpl: Option<&Template>, som: &str) -> DataPath {
/// picture (or ISO), check and radio states, choice values as saved.
pub(super) fn wanted(doc: &Document, fields: &[FieldDatum], tpl: Option<&Template>) -> Vec<Want> {
let mut out = Vec::new();
// The datasets as they are, read once and only for a time field.
let data = std::cell::OnceCell::new();
let data = || data.get_or_init(|| crate::read_packets(doc).ok().flatten().and_then(|p| parse_datasets(&p.xdp)));
for f in fields {
let som = som_of(doc, f);
let path = path_of(tpl, &som);
@@ -189,6 +213,12 @@ pub(super) fn wanted(doc: &Document, fields: &[FieldDatum], tpl: Option<&Templat
continue;
}
let text = match &f.data {
// A time goes into the data canonically (`HH:MM:SS`); text that isn't one, as typed. A
// field still showing the time its data holds keeps that data as it is.
FieldData::Text(t) if let Some(ps) = time_patterns_of(doc, f) => match data().as_ref().and_then(|d| d.value_at(&path)) {
Some(old) if shows_data_time(&old, t, &ps[0]) => old,
_ => ps.iter().find_map(|p| pattern_to_canonical(t, p)).unwrap_or_else(|| t.clone()),
},
FieldData::Text(t) => match date_pattern_of(doc, f) {
Some(p) => match pattern_to_iso(t, &p) {
// The date goes into the data in the field's data picture, or as an ISO date.
@@ -233,6 +263,7 @@ fn values_at(doc: &Document, tpl: Option<&Template>, fields: &[FieldDatum]) -> V
let Some(text) = data.value_at(&path) else { continue };
let text = text.as_str();
let value = match &f.data {
FieldData::Text(_) if let Some(ps) = time_patterns_of(doc, f) => FieldData::Text(canonical_to_pattern(text, &ps[0])),
FieldData::Text(_) => FieldData::Text(match date_pattern_of(doc, f) {
Some(pat) => iso_to_pattern(&data_to_iso(text, data_date_pattern(tpl, &som).as_deref()), &pat),
None => text.to_string(),
+28
View File
@@ -653,6 +653,34 @@ pub fn leave_template(data: &str) -> String {
)
}
/// Two time fields (#8411): `start` is typed and shown as `h:MM A` (`2:30 PM`), `at` has no
/// picture. Both hold a `<time/>`, which the data keeps as `HH:MM:SS`. `note` is a plain text
/// field.
pub fn time_template(data: &str) -> String {
let datasets = if data.is_empty() {
String::new()
} else {
format!("<xfa:datasets xmlns:xfa=\"http://www.xfa.org/schema/xfa-data/1.0/\"><xfa:data>{data}</xfa:data></xfa:datasets>")
};
format!(
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>
<subform name="page" layout="tb">
<field name="start" w="2in" h="0.3in"><ui><dateTimeEdit/><picture>time{{h:MM A}}</picture></ui><value><time/></value><format><picture>time{{h:MM A}}</picture></format></field>
<field name="at" w="2in" h="0.3in"><ui><dateTimeEdit/></ui><value><time/></value></field>
<field name="note" w="2in" h="0.3in"><ui><textEdit/></ui></field>
</subform>
</subform>
</template>
{datasets}
</xdp:xdp>
"##
)
}
/// Two date fields shown as `MM/DD/YYYY`: `due` binds its value to the data as `YYYYMMDD`
/// (`<bind><picture>`), `when` has no data picture, so its data holds ISO dates.
pub fn bound_date_template(data: &str) -> String {
+13 -1
View File
@@ -210,6 +210,13 @@ impl Layouter<'_> {
};
(WidgetKind::Button { caption }, rect, border, None, f.tooltip.clone())
}
Ui::DateTimeEdit if crate::data::is_time_field(f) => {
// A time of day (#8411): canonical in the data and as a template default, held in
// the field's pattern. Text that isn't a time stays as it is.
let pattern = crate::data::time_pattern(f);
let shown = plain_value.as_ref().map(|v| crate::data::canonical_to_pattern(v, &pattern));
(WidgetKind::Time(pattern), ui, widget_border(f.ui_border.as_ref(), false), shown, f.tooltip.clone())
}
Ui::DateTimeEdit => {
let pattern = date_pattern(f.picture.as_deref());
// The data holds the date in the field's data picture, or else as an ISO date; a
@@ -251,8 +258,13 @@ impl Layouter<'_> {
// A date field's default, like its value, in the field's own pattern.
let default = match &kind {
WidgetKind::Date(pattern) => template_default.map(|v| canonical_date_in(&v, pattern)),
WidgetKind::Time(pattern) => template_default.map(|v| crate::data::canonical_to_pattern(&v, pattern)),
_ => template_default,
};
let display_date = match &kind {
WidgetKind::Time(_) => f.display_picture.as_deref().and_then(crate::data::time_letters),
_ => (f.ui == Ui::DateTimeEdit).then(|| f.display_picture.as_deref().and_then(crate::data::date_letters)).flatten(),
};
let items: Vec<String> = match &kind {
WidgetKind::CheckBox { on, .. } => vec![on.clone(), f.items.get(1).cloned().unwrap_or_default()],
WidgetKind::Radio { on, .. } => vec![on.clone()],
@@ -276,7 +288,7 @@ impl Layouter<'_> {
action,
items,
no_scroll: f.no_scroll,
display_date: (f.ui == Ui::DateTimeEdit).then(|| f.display_picture.as_deref().and_then(crate::data::date_letters)).flatten(),
display_date,
// `push` sets where it shows.
views: Views::ALL,
required: f.required,
+5 -2
View File
@@ -86,6 +86,9 @@ pub enum WidgetKind {
Image,
/// A date field with its Acrobat format pattern (`yyyy-mm-dd`).
Date(String),
/// A time field (#8411) with its Acrobat time pattern (`h:MM tt`): it holds the time in that
/// pattern, and the data holds it canonically (`HH:MM:SS`).
Time(String),
CheckBox {
on: String,
round: bool,
@@ -150,8 +153,8 @@ pub struct Widget {
pub items: Vec<String>,
/// A text field that doesn't scroll: it takes no more text than it shows (`DoNotScroll`).
pub no_scroll: bool,
/// Date fields: the date letters of the display picture (`<format><picture>`), how the value
/// shows when it isn't being typed in. `None`: as the edit pattern writes it.
/// Date and time fields: the Acrobat pattern of the display picture (`<format><picture>`), how
/// the value shows when it isn't being typed in. `None`: as the edit pattern writes it.
pub display_date: Option<String>,
/// Where the field is shown: on screen, in print, or both (its annotation flags).
pub views: Views,
+2
View File
@@ -671,6 +671,8 @@ pub struct Field {
pub validate_message: Option<String>,
/// Numeric fields (numericEdit, or a decimal/integer/float value) give scripts numbers.
pub numeric: bool,
/// Its value is a time of day (`<value><time/>`), held in the data as `HH:MM:SS`.
pub time: bool,
/// The display picture clause (`<format><picture>`), e.g. `date{YYYYMMDD}`: how the value
/// shows when not being edited, and what scripts read as `formattedValue`.
pub display_picture: Option<String>,
+2
View File
@@ -824,6 +824,7 @@ fn parse_field(n: XmlNode, warnings: &mut Vec<String>) -> Field {
let scripts = parse_events(n);
let numeric = matches!(kind, Ui::NumericEdit)
|| value_el.is_some_and(|v| v.children().any(|c| c.is_element() && matches!(c.tag_name().name(), "decimal" | "integer" | "float")));
let time = value_el.is_some_and(|v| v.children().any(|c| c.is_element() && c.tag_name().name() == "time"));
let (items, item_values) = parse_items(n, warnings);
let choice = match (kind == Ui::ChoiceList, ui_el) {
(true, Some(e)) => {
@@ -876,6 +877,7 @@ fn parse_field(n: XmlNode, warnings: &mut Vec<String>) -> Field {
validate_message,
required: must_be_filled(validate_el),
numeric,
time,
display_picture: child(n, "format").and_then(|f| child(f, "picture")).map(text_of).map(|p| p.trim().to_string()).filter(|p| !p.is_empty()),
keep_intact: child(n, "keep").and_then(|k| k.attribute("intact")).is_some_and(|v| v == "contentArea" || v == "pageArea"),
}
+11 -1
View File
@@ -303,7 +303,7 @@ impl Emitter<'_> {
// SOM path.
let mut under: Option<String> = None;
match &w.kind {
WidgetKind::Text | WidgetKind::Date(_) | WidgetKind::Password => {
WidgetKind::Text | WidgetKind::Date(_) | WidgetKind::Time(_) | WidgetKind::Password => {
d.set(b"FT".to_vec(), Object::name("Tx"));
if w.multiline {
ff |= 1 << 12;
@@ -342,6 +342,16 @@ impl Emitter<'_> {
aa.set(b"K".to_vec(), js_action(&format!("AFDate_KeystrokeEx({pattern});")));
d.set(b"AA".to_vec(), Object::Dict(aa));
}
if let WidgetKind::Time(pattern) = &w.kind {
// Text the pattern doesn't read is kept as typed, as for a date (#8411).
d.set(DATE_KEY.to_vec(), Object::Bool(true));
let mut aa = Dict::new();
let shown = js_string(w.display_date.as_deref().unwrap_or(pattern));
let pattern = js_string(pattern);
aa.set(b"F".to_vec(), js_action(&format!("AFTime_FormatEx({shown});")));
aa.set(b"K".to_vec(), js_action(&format!("AFTime_KeystrokeEx({pattern});")));
d.set(b"AA".to_vec(), Object::Dict(aa));
}
}
WidgetKind::Choice { options, list_box, multi, editable } => {
d.set(b"FT".to_vec(), Object::name("Ch"));
+96 -7
View File
@@ -51,6 +51,8 @@ pub struct Stripped {
pub field_keys: usize,
/// Date fields now holding and typed in the pattern they show ([`static_date`]).
pub date_fields: usize,
/// Time fields now holding and typed in the pattern they show ([`static_date`]).
pub time_fields: usize,
}
impl Stripped {
@@ -80,6 +82,12 @@ impl Stripped {
self.date_fields
));
}
if self.time_fields > 0 {
out.push(format!(
"{} time field(s) now hold and take their times as they show them: a static form can't keep a time one way and show it another",
self.time_fields
));
}
out
}
}
@@ -121,15 +129,16 @@ pub fn xfa_shape(doc: &Document) -> Option<XfaShape> {
/// A field's values to write: the key (`/V` or `/DV`) and its new text.
type NewValues = Vec<(&'static [u8], String)>;
/// A date field PdfCraft laid out, made one a static form keeps working in other viewers. The
/// A date or time field PdfCraft laid out, made one a static form keeps working in other viewers. The
/// layout keeps its value as an ISO date (or as typed), types it in its edit pattern (`/AA /K`)
/// and shows it in its display pattern (`/AA /F`). A static form can do neither: another viewer
/// checks typing against the keystroke pattern but reads the value again in the format's, so
/// only dates that read both ways pass, and those show misread. So its keystroke takes the
/// format's pattern, and its value and default value, when they read as dates in the edit
/// pattern or as ISO dates, are written in it. The new `/AA` and values, or `None` when nothing
/// changes.
fn static_date(doc: &Document, d: &Dict) -> Option<(Dict, NewValues)> {
/// pattern or as ISO dates, are written in it. A time field's the same, its value read in the
/// edit pattern or canonically (`HH:MM:SS`). The new `/AA` and values, or `None` when nothing
/// changes, and whether it is a time field.
fn static_date(doc: &Document, d: &Dict) -> Option<(Dict, NewValues, bool)> {
let aa = doc.resolve(d.get(b"AA")?).as_dict()?.clone();
let pattern = |key: &[u8], call: &str| {
let action = doc.resolve(aa.get(key)?).as_dict()?.clone();
@@ -137,6 +146,32 @@ fn static_date(doc: &Document, d: &Dict) -> Option<(Dict, NewValues)> {
let rest = js.trim().strip_prefix(call)?.trim_start().strip_prefix("(\"")?;
rest.split_once("\")").map(|(p, _)| p.to_string())
};
// A legacy edit-picture value can have two distinct readings (e.g. "111" in HM).
// Preserve both values and actions rather than guessing which time the user intended.
// A time field (#8411): the same, its value read in the typed pattern or canonically.
if let (Some(shown), Some(typed)) = (pattern(b"F", "AFTime_FormatEx"), pattern(b"K", "AFTime_KeystrokeEx")) {
if [b"V".as_slice(), b"DV"]
.iter()
.filter_map(|key| d.get(key).and_then(|v| doc.resolve(v).as_string().map(|s| s.to_text())))
.any(|text| crate::data::time_pattern_is_ambiguous(&text, &typed))
{
return None;
}
let mut aa = aa;
if typed != shown {
aa.set(b"K".to_vec(), js_action(&format!("AFTime_KeystrokeEx(\"{shown}\");")));
}
let mut values = Vec::new();
for key in [b"V".as_slice(), b"DV"] {
let Some(text) = d.get(key).and_then(|v| doc.resolve(v).as_string().map(|s| s.to_text())) else { continue };
let canonical = crate::data::pattern_to_canonical(&text, &typed).unwrap_or_else(|| text.clone());
let written = crate::data::canonical_to_pattern(&canonical, &shown);
if written != text {
values.push((key, written));
}
}
return (typed != shown || !values.is_empty()).then_some((aa, values, true));
}
let shown = pattern(b"F", "AFDate_FormatEx")?;
let typed = pattern(b"K", "AFDate_KeystrokeEx")?;
let mut aa = aa;
@@ -151,7 +186,7 @@ fn static_date(doc: &Document, d: &Dict) -> Option<(Dict, NewValues)> {
values.push((key, iso));
}
}
(typed != shown || !values.is_empty()).then_some((aa, values))
(typed != shown || !values.is_empty()).then_some((aa, values, false))
}
/// Most field dictionaries walked for their private keys.
@@ -238,9 +273,13 @@ pub fn strip(doc: &mut Document) -> Result<Stripped, XfaError> {
out.image_fields += 1;
}
if d.contains(DATE_KEY)
&& let Some((aa, values)) = static_date(doc, &d)
&& let Some((aa, values, time)) = static_date(doc, &d)
{
out.date_fields += 1;
if time {
out.time_fields += 1;
} else {
out.date_fields += 1;
}
doc.update_dict(r, |d| {
d.set(b"AA".to_vec(), Object::Dict(aa));
for (k, v) in values {
@@ -405,4 +444,54 @@ mod tests {
assert_eq!(out.script_buttons, 1);
assert!(!doc.get(kid).as_dict().unwrap().contains(CLICK_KEY));
}
#[test]
fn static_time_conversion_preserves_ambiguous_value_and_actions() {
let doc = Document::new_empty();
for (value, default) in [("111", "0111"), ("0111", "111")] {
let mut aa = Dict::new();
aa.set(b"F".to_vec(), js_action("AFTime_FormatEx(\"h:MM tt\");"));
aa.set(b"K".to_vec(), js_action("AFTime_KeystrokeEx(\"HM\");"));
let mut d = Dict::new();
d.set(b"AA".to_vec(), Object::Dict(aa));
d.set(b"V".to_vec(), Object::String(PdfString::text(value)));
d.set(b"DV".to_vec(), Object::String(PdfString::text(default)));
assert!(static_date(&doc, &d).is_none(), "ambiguous value or default must preserve the entire field");
}
}
#[test]
fn static_time_conversion_keeps_adjacent_edit_components_unambiguous() {
let doc = Document::new_empty();
let mut aa = Dict::new();
aa.set(b"F".to_vec(), js_action("AFTime_FormatEx(\"h:MM tt\");"));
aa.set(b"K".to_vec(), js_action("AFTime_KeystrokeEx(\"HM\");"));
let mut d = Dict::new();
d.set(b"AA".to_vec(), Object::Dict(aa));
let edit_value = crate::data::canonical_to_pattern("01:11:00", "HM");
assert_eq!(edit_value, "0111");
d.set(b"V".to_vec(), Object::String(PdfString::text(&edit_value)));
let (_, values, _) = static_date(&doc, &d).expect("changes");
assert_eq!(values, vec![(b"V".as_slice(), "1:11 AM".to_string())]);
}
/// #8411: a time field typed in one pattern and shown in another is made one a static form
/// keeps: typed as it shows, its value written that way.
#[test]
fn a_time_field_takes_and_holds_its_time_as_it_shows_it() {
let doc = Document::new_empty();
let mut aa = Dict::new();
aa.set(b"F".to_vec(), js_action("AFTime_FormatEx(\"h:MM tt\");"));
aa.set(b"K".to_vec(), js_action("AFTime_KeystrokeEx(\"HH:MM\");"));
let mut d = Dict::new();
d.set(DATE_KEY.to_vec(), Object::Bool(true));
d.set(b"AA".to_vec(), Object::Dict(aa));
d.set(b"V".to_vec(), Object::String(PdfString::text("14:30")));
d.set(b"DV".to_vec(), Object::String(PdfString::text("not yet")));
let (aa, values, time) = static_date(&doc, &d).expect("changes");
assert!(time);
let k = aa.get(b"K").and_then(|k| k.as_dict()).and_then(|k| k.get(b"JS")).and_then(|j| j.as_string()).map(|j| j.to_text());
assert_eq!(k.as_deref(), Some("AFTime_KeystrokeEx(\"h:MM tt\");"));
assert_eq!(values, vec![(b"V".as_slice(), "2:30 PM".to_string())], "a time is written as shown; other text stays");
}
}