diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 6b793458d7..fb5cba9d8f 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -6170,6 +6170,52 @@ fn stripping_xfa_takes_a_radio_items_pcon_as_the_fields_value() { assert_eq!(lost(&s, id), Vec::::new()); } +/// Opening reads a radio group's data as saving writes it: with `/PCOn` items `4` `1` next to +/// `/Opt [(1) (2)]` and states `/0` `/1`, a click on the second button saves its item `1`, and +/// reopening turns the second button on again, not the first one whose `/Opt` entry is `1`; the +/// first button saves `4` and comes back too. Taking the XFA out then notes no lost data. +#[test] +fn a_radio_item_that_is_another_buttons_export_reopens_on_its_own_button() { + let lang = "form1[0].page1[0].lang[0]"; + let data_of = |bytes: Arc>| { + let cos = pdfcraft_cos::Document::open(bytes).unwrap(); + let data = pdfcraft_xfa::parse_datasets(&pdfcraft_xfa::read_packets(&cos).unwrap().unwrap().xdp).unwrap(); + data.text_at(&pdfcraft_xfa::som_to_path(lang)).map(str::to_owned) + }; + let value = |s: &Session, id: DocId| s.get(id).unwrap().form.iter().find(|f| f.name == lang).unwrap().value.clone(); + let form = Arc::new(pdfcraft_xfa::fixtures::static_radio_shell_with_pcon("", ["4", "1"])); + let mut s = Session::new().with_clock(|| 1_700_000_000); + for (state, item) in [("1", "1"), ("0", "4")] { + let id = s.open("blank.pdf", None, form.clone(), None).unwrap(); + s.apply(id, Edit::SetFieldValue { name: lang.into(), value: FieldValue::Radio(Some(state.into())) }).unwrap(); + let saved = s.save_bytes(id).unwrap(); + assert_eq!(data_of(saved.clone()).as_deref(), Some(item), "clicked {state}"); + let again = s.open("again.pdf", None, saved, None).unwrap(); + assert_eq!(value(&s, again), [state], "clicked {state}"); + s.apply(again, Edit::XfaToStatic).unwrap(); + assert!(!s.get(again).unwrap().info.warnings.iter().any(|w| w.contains("held a value other than the form's XFA data")), "clicked {state}"); + } + // Data from elsewhere that no button saves is still read as an export value, then a state. + let id = s + .open( + "two.pdf", + None, + Arc::new(pdfcraft_xfa::fixtures::static_radio_shell_with_pcon("2", ["4", "1"])), + None, + ) + .unwrap(); + assert_eq!(value(&s, id), ["1"]); + let id = s + .open( + "zero.pdf", + None, + Arc::new(pdfcraft_xfa::fixtures::static_radio_shell_with_pcon("0", ["4", "1"])), + None, + ) + .unwrap(); + assert_eq!(value(&s, id), ["0"]); +} + /// A radio group whose buttons carry `/PCOn` items `1` `2` next to `/Opt [(1) (2)]` and on /// states named by position (`/0`, `/1`): a click on either button saves that button's own item /// to the datasets, reopening turns the same button on with nothing rewritten, and taking the XFA diff --git a/crates/engine/src/xfa_form.rs b/crates/engine/src/xfa_form.rs index 96ab91e6c6..6b8f918982 100644 --- a/crates/engine/src/xfa_form.rs +++ b/crates/engine/src/xfa_form.rs @@ -120,6 +120,18 @@ pub(crate) fn decode_data_file(bytes: &[u8]) -> Option> { } } +/// The on state a radio group's XFA data `item` selects: the button saving writes `item` for +/// (`/PCOn`, else its `/Opt` entry, else its state; `pdfcraft_xfa::radio_state_for_item`), so a +/// saved selection reopens on the same button; else `item` read as an export value, then as an +/// on-state name ([`pdfcraft_forms::Field::state_for_export`]), as data from elsewhere is; else +/// `item` itself. +fn radio_button(doc: &pdfcraft_cos::Document, f: &pdfcraft_forms::Field, datum: Option<&pdfcraft_xfa::FieldDatum>, item: &str) -> String { + datum + .and_then(|d| pdfcraft_xfa::radio_state_for_item(doc, d, item)) + .or_else(|| f.state_for_export(item).map(str::to_owned)) + .unwrap_or_else(|| item.to_owned()) +} + /// Take the XFA out of `doc` and note what went with it: the packets, data no field showed, /// buttons that did nothing but run scripts, and fields whose value differs from the form's /// data (data PdfCraft could not read into them, now lost). @@ -135,11 +147,12 @@ pub(crate) fn strip_xfa(doc: &mut pdfcraft_cos::Document, cx: &mut EditCtx) -> R pdfcraft_xfa::FieldData::Check(on) => f.value.is_empty() == *on, // The field holds an on-state name; the data names a button by its item. They agree // when the data holds what saving writes (`/PCOn`, the `/Opt` entry or the state - // name), or an export value or state that selects the same button. + // name), or names the same button as opening reads it ([`radio_button`]). pdfcraft_xfa::FieldData::Radio(sel) => { let state = f.value.first().map(String::as_str); - let same_button = sel.as_deref().map(|s| f.state_for_export(s).unwrap_or(s)) == state; - let written = data.iter().find(|d| d.name == *name).map(|d| pdfcraft_xfa::radio_dataset_value(doc, d, &f.value.first().cloned())); + let datum = data.iter().find(|d| d.name == *name); + let same_button = sel.as_deref().map(|s| radio_button(doc, f, datum, s)).as_deref() == state; + let written = datum.map(|d| pdfcraft_xfa::radio_dataset_value(doc, d, &f.value.first().cloned())); !same_button && written.as_deref() != Some(sel.as_deref().unwrap_or_default()) } pdfcraft_xfa::FieldData::None => false, @@ -291,10 +304,11 @@ pub(crate) fn xfa_values_from_datasets(doc: &mut pdfcraft_cos::Document) -> Resu } pdfcraft_xfa::FieldData::Text(t) => (f.value.join("\n") != t).then_some(FieldValue::Text(t)), pdfcraft_xfa::FieldData::Check(on) => (f.value.is_empty() == on).then_some(FieldValue::Check(on)), - // The data holds the item (the export value); the field takes the on state that - // exports it, which with `/Opt` may be a position (`1` is the state `/0`). + // The data holds the item; the field takes the on state of the button saving writes it + // for ([`radio_button`]), which with `/Opt` may be a position (`1` is the state `/0`). pdfcraft_xfa::FieldData::Radio(sel) => { - let state = sel.map(|v| f.state_for_export(&v).map_or(v.clone(), str::to_owned)); + let datum = data.iter().find(|d| d.name == name); + let state = sel.map(|v| radio_button(doc, f, datum, &v)); (f.value.first() != state.as_ref()).then_some(FieldValue::Radio(state)) } pdfcraft_xfa::FieldData::None => None, diff --git a/crates/xfa/src/data.rs b/crates/xfa/src/data.rs index 64b3272e18..d8a636a7ce 100644 --- a/crates/xfa/src/data.rs +++ b/crates/xfa/src/data.rs @@ -36,7 +36,7 @@ pub use import::{DataImport, ImportNode, export_data, import_data, parse_data_fi pub use passwords::{clear_password_values, has_password_values}; pub(crate) use path::template_field; pub use path::{data_path, parse_datasets, som_to_path}; -pub use values::{FieldData, FieldDatum, is_on, radio_dataset_value, read_values, read_values_with}; +pub use values::{FieldData, FieldDatum, is_on, radio_dataset_value, radio_state_for_item, read_values, read_values_with}; #[cfg(test)] pub(crate) use write::ENSURED; pub use write::{ diff --git a/crates/xfa/src/data/values.rs b/crates/xfa/src/data/values.rs index 2fef49e85c..82fd83e80c 100644 --- a/crates/xfa/src/data/values.rs +++ b/crates/xfa/src/data/values.rs @@ -34,16 +34,10 @@ fn som_of(doc: &Document, f: &FieldDatum) -> String { doc.get(f.obj).as_dict().and_then(|d| text_of(doc, d, crate::pdf::SOM_KEY)).unwrap_or_else(|| f.name.clone()) } -/// The datasets text for a radio group. The AcroForm value is an appearance-state name -/// (`New York` is stored as `New_York`); `/PCOn` on the selected widget is the original item. -/// Without it, a group with one `/Opt` entry per widget exports that entry: its state names may -/// be positions (`/0`, `/1`; ISO 32000-2 Table 230), and the data holds the item (`1`, `2`). -/// `sel` is the selected on-state name; with none selected the text is empty. -pub fn radio_dataset_value(doc: &Document, f: &FieldDatum, sel: &Option) -> String { - let Some(selected) = sel.as_deref().filter(|s| !s.is_empty() && *s != "Off") else { - return String::new(); - }; - let Some(group) = doc.get(f.obj).as_dict().cloned() else { return selected.to_string() }; +/// Each button of a radio group, in `/Kids` order: its (`/PCOn` item, on-state name, `/Opt` +/// entry). A group without `/Kids` is its own one widget. +fn radio_widgets(doc: &Document, f: &FieldDatum) -> Vec<(Option, Option, Option)> { + let Some(group) = doc.get(f.obj).as_dict().cloned() else { return Vec::new() }; let kids = group.get(b"Kids").map(|k| doc.resolve(k)).and_then(|k| k.as_array().cloned()).unwrap_or_else(|| vec![Object::Ref(f.obj)]); // One export value per widget, as the field's `/Opt` lists them (an entry may be an // `[export display]` pair, as a choice field's are). @@ -60,9 +54,7 @@ pub fn radio_dataset_value(doc: &Document, f: &FieldDatum, sel: &Option) .collect() }) .filter(|opt: &Vec>| opt.len() == kids.len()); - // Each widget's (`/PCOn` item, on-state name, `/Opt` entry). - let widgets: Vec<(Option, Option, Option)> = kids - .iter() + kids.iter() .enumerate() .filter_map(|(i, kid)| { let widget = doc.resolve(kid).as_dict().cloned()?; @@ -76,7 +68,20 @@ pub fn radio_dataset_value(doc: &Document, f: &FieldDatum, sel: &Option) let export = exports.as_ref().and_then(|e| e.get(i).cloned().flatten()); Some((original, state, export)) }) - .collect(); + .collect() +} + +/// The datasets text for a radio group. The AcroForm value is an appearance-state name +/// (`New York` is stored as `New_York`); `/PCOn` on the selected widget is the original item. +/// Without it, a group with one `/Opt` entry per widget exports that entry: its state names may +/// be positions (`/0`, `/1`; ISO 32000-2 Table 230), and the data holds the item (`1`, `2`). +/// `sel` is the selected on-state name; with none selected the text is empty. +/// [`radio_state_for_item`] reads it back. +pub fn radio_dataset_value(doc: &Document, f: &FieldDatum, sel: &Option) -> String { + let Some(selected) = sel.as_deref().filter(|s| !s.is_empty() && *s != "Off") else { + return String::new(); + }; + let widgets = radio_widgets(doc, f); // `sel` is an on-state name, so every widget's state is compared before any `/PCOn`: with // states `/0` `/1` and items `1` `2`, the state `1` is the second widget, not the first // one's item. @@ -88,6 +93,19 @@ pub fn radio_dataset_value(doc: &Document, f: &FieldDatum, sel: &Option) } } +/// The on-state name of the radio button whose item is `item` in the datasets, as +/// [`radio_dataset_value`] writes it: the first button whose `/PCOn`, else its `/Opt` entry, +/// else its on-state name, equals `item`. So a saved selection reopens on the same button even +/// when one button's `/PCOn` equals another's `/Opt` entry. `None` when no button writes `item` +/// (data from elsewhere); the caller then reads it as an export value or state name. +pub fn radio_state_for_item(doc: &Document, f: &FieldDatum, item: &str) -> Option { + radio_widgets(doc, f).into_iter().find_map(|(original, state, export)| { + let state = state?; + let written = original.or(export).unwrap_or_else(|| state.clone()); + (written == item).then_some(state) + }) +} + /// The on and off item values of a check box (`/PCItems`), or the widget's on state. fn items_of(doc: &Document, f: &FieldDatum) -> (String, String) { let d = doc.get(f.obj); diff --git a/crates/xfa/src/lib.rs b/crates/xfa/src/lib.rs index 28e8dd09e7..efdc6d8808 100644 --- a/crates/xfa/src/lib.rs +++ b/crates/xfa/src/lib.rs @@ -93,8 +93,8 @@ pub(crate) fn xml_nesting_depth(text: &str) -> usize { pub use data::{DataImport, ImportNode, export_data, import_data, parse_data_file, write_data_image}; pub use data::{ DataNode, DataOp, DataPath, DatasetsWrite, FieldData, FieldDatum, add_data_instances, build_data, clear_password_values, data_path, - has_password_values, iso_to_pattern, parse_datasets, pattern_to_iso, radio_dataset_value, read_values, read_values_with, remove_data_instance, - som_to_path, write_data_ops, write_data_value, write_datasets, write_datasets_reusing, write_datasets_with, + has_password_values, iso_to_pattern, parse_datasets, pattern_to_iso, radio_dataset_value, radio_state_for_item, read_values, read_values_with, + remove_data_instance, som_to_path, write_data_ops, write_data_value, write_datasets, write_datasets_reusing, write_datasets_with, }; pub use layout::{Action, BorderShape, Form, Item, MAX_PAGES, Page, Widget, WidgetKind, formatted_value, layout}; pub use packets::{Encoding, Packets, decode as decode_packet, encode as encode_packet, read_packets};