diff --git a/crates/automation/README.md b/crates/automation/README.md index a561d141df..4ccb03904e 100644 --- a/crates/automation/README.md +++ b/crates/automation/README.md @@ -94,9 +94,9 @@ semantics; they never silently act on partial text. `form_add_field_table` accepts `source_field` and the optional 1-based `source_widget` to create independent copies of an existing text field or check box instead of blank text fields. Each copy starts with the source's value and properties but has its own name and can be filled independently. -Radio groups, signatures, choice fields, buttons and check boxes with per-widget export values are -not supported by this option yet. The grid is one undoable edit and any invalid cell or name -refuses the entire operation. +Radio groups, signatures, choice fields, buttons and check boxes whose widgets export different +values are not supported by this option yet. The grid is one undoable edit and any invalid cell or +name refuses the entire operation. For an individual push button, `form_set_props` also edits its visible normal label: diff --git a/crates/engine/src/field_table.rs b/crates/engine/src/field_table.rs index 285f8215cc..833312129d 100644 --- a/crates/engine/src/field_table.rs +++ b/crates/engine/src/field_table.rs @@ -7,7 +7,7 @@ pub use pdfcraft_forms::table::*; use pdfcraft_forms::MIN_FIELD_SIDE; use pdfcraft_render::PageInfo; -use crate::{Edit, FormField, FormFieldKind as FieldKind, NewField}; +use crate::{Edit, FormField, NewField}; /// The edit's name in the history ("Undo Add text field table"), one of [`crate::BATCH_LABELS`]. pub const LABEL: &str = "Add text field table"; @@ -43,15 +43,10 @@ pub fn edit(table: &FieldTable, page: usize, info: &PageInfo, form: &[FormField] Ok(Edit::Batch { label: LABEL.to_owned(), edits }) } -/// Whether a grid can copy widget `widget` of `field`: a text field, or a check box whose -/// widgets share one export value (`pdfcraft_forms::copy_field` refuses the rest). +/// Whether a grid can copy widget `widget` of `field`: `pdfcraft_forms::copy_field`'s own test +/// ([`pdfcraft_forms::copyable_widget`]), so the preview and the copy agree. pub fn copyable(field: &FormField, widget: usize) -> bool { - let kind = match field.kind { - FieldKind::Text => true, - FieldKind::CheckBox => field.widgets.len() <= 1 || field.options.is_empty(), - _ => false, - }; - kind && widget < field.widgets.len() + pdfcraft_forms::copyable_widget(field, widget).is_ok() } /// The edit laying `table` out as independent copies of widget `widget` of the field `source`, @@ -142,7 +137,7 @@ mod tests { } #[test] - fn a_grid_refuses_a_check_box_whose_widgets_export_different_values() { + fn a_grid_copies_a_check_box_only_when_its_widgets_export_one_value() { let mut s = Session::new(); let bytes = s.create_blank(300.0, 400.0, 1).unwrap(); let id = s.open("boxes.pdf", None, bytes, None).unwrap(); @@ -157,6 +152,16 @@ mod tests { boxes.options = vec![("Yes".into(), "Yes".into()), ("No".into(), "No".into())]; let refused = copy_edit(&table, 0, &doc.info.pages[0], &form, "box", 0); assert_eq!(refused.err(), Some(TableError::Uncopyable("box".into())), "the preview can't call it valid"); + // One export value from every widget is a box a grid copies, `/Opt` or not. + let boxes = form.iter_mut().find(|f| f.name == "box").unwrap(); + boxes.options = vec![("Yes".into(), "Yes".into()); 2]; + assert!(copy_edit(&table, 0, &doc.info.pages[0], &form, "box", 0).is_ok()); + // Different on states without `/Opt` are different export values. + let boxes = form.iter_mut().find(|f| f.name == "box").unwrap(); + boxes.options.clear(); + boxes.widgets[1].on_state = Some("Other".into()); + let refused = copy_edit(&table, 0, &doc.info.pages[0], &form, "box", 0); + assert_eq!(refused.err(), Some(TableError::Uncopyable("box".into()))); } #[test] diff --git a/crates/forms/src/author.rs b/crates/forms/src/author.rs index fca138f022..2b39371ea2 100644 --- a/crates/forms/src/author.rs +++ b/crates/forms/src/author.rs @@ -20,7 +20,7 @@ pub(crate) use tree::ancestor_sets; pub use edit::set_props; pub(crate) use edit::set_props_object; -pub use lifecycle::{add_field, copy_field, delete_field, delete_field_object, delete_widget, duplicate_field}; +pub use lifecycle::{add_field, copy_field, copyable_widget, delete_field, delete_field_object, delete_widget, duplicate_field}; pub(crate) use look::button_appearance; pub(crate) use look::redraw_field_object; pub use look::{ diff --git a/crates/forms/src/author/lifecycle.rs b/crates/forms/src/author/lifecycle.rs index ae9910e2e3..b4b73f9c5e 100644 --- a/crates/forms/src/author/lifecycle.rs +++ b/crates/forms/src/author/lifecycle.rs @@ -370,6 +370,16 @@ pub fn copy_field(doc: &mut Document, name: &str, widget: usize, page: usize, re for key in COPY_DROPS { field.remove(key); } + // A check box's `/Opt` holds an export value per widget when it has one entry per widget + // (else the on state is the export value); the copy has one widget, this one. + if f.kind == FieldKind::CheckBox && field.contains(b"Opt") { + match f.options.get(widget).filter(|_| f.options.len() == f.widgets.len()) { + Some((export, _)) => field.set(b"Opt".to_vec(), Object::Array(vec![Object::String(PdfString::text(export))])), + None => { + field.remove(b"Opt"); + } + } + } // The appearance editor updates indirect /MK and /BS dictionaries in place. Make these // per-widget dictionaries direct so editing a copy cannot restyle the source or its siblings. for key in [&b"MK"[..], b"BS"] { @@ -395,13 +405,20 @@ pub fn copy_field(doc: &mut Document, name: &str, widget: usize, page: usize, re Ok(()) } -/// The widget `widget` of `f`, when `f` is a kind a grid can copy. -fn copyable_widget(f: &Field, widget: usize) -> Result<&Widget, FormError> { +/// The widget `widget` of `f`, when [`copy_field`] can copy it: a text field, or a check box +/// whose widgets all have one on state and one export value. A widget without an on state +/// counts as a different value. +pub fn copyable_widget(f: &Field, widget: usize) -> Result<&Widget, FormError> { if !matches!(f.kind, FieldKind::Text | FieldKind::CheckBox) { return invalid("only text fields and check boxes can be copied into a grid"); } - if f.kind == FieldKind::CheckBox && f.widgets.len() > 1 && !f.options.is_empty() { - return invalid("a check box with per-widget export values cannot yet be copied into a grid"); + if f.kind == FieldKind::CheckBox && f.widgets.len() > 1 { + let on = f.widgets.first().and_then(|w| w.on_state.as_deref()); + let export = f.export_of(0); + let one = on.is_some() && f.widgets.iter().enumerate().all(|(i, w)| w.on_state.as_deref() == on && f.export_of(i) == export); + if !one { + return invalid("a check box whose widgets export different values cannot yet be copied into a grid"); + } } f.widgets.get(widget).ok_or_else(|| FormError::Invalid(format!("{} has no widget {}", f.name, widget.saturating_add(1)))) } @@ -429,6 +446,11 @@ fn copy_source(doc: &Document, f: &Field, w: &Widget) -> Result field.set(key.to_vec(), value.clone()); } } + // A widget can be read-only on its own (`/Ff` in the widget); the copy's one dictionary keeps it. + if w.read_only { + let ff = field.get(b"Ff").and_then(|v| doc.resolve(v).as_int()).unwrap_or(0); + field.set(b"Ff".to_vec(), Object::Int(ff | i64::from(flags::READ_ONLY))); + } // Keep both field and widget event dictionaries when they were separate. let mut aa = field.get(b"AA").and_then(|a| doc.resolve(a).as_dict().cloned()).unwrap_or_default(); if let Some(widget_aa) = widget_dict.get(b"AA").and_then(|a| doc.resolve(a).as_dict().cloned()) { diff --git a/crates/forms/src/lib.rs b/crates/forms/src/lib.rs index 90cec27dc0..08428726f5 100644 --- a/crates/forms/src/lib.rs +++ b/crates/forms/src/lib.rs @@ -26,8 +26,9 @@ mod scripting; pub mod table; pub use actions::{FieldAction, Trigger, field_action_chains, field_actions, set_field_actions, widget_scripts}; pub use author::{ - BorderStyle, CheckStyle, FieldFont, FieldProps, Look, LookPatch, MIN_FIELD_SIDE, NewField, add_field, check_style, copy_field, delete_field, - delete_field_object, delete_widget, duplicate_field, look, redraw_field, redraw_fields, set_button_icon, set_button_icon_target, set_props, + BorderStyle, CheckStyle, FieldFont, FieldProps, Look, LookPatch, MIN_FIELD_SIDE, NewField, add_field, check_style, copy_field, copyable_widget, + delete_field, delete_field_object, delete_widget, duplicate_field, look, redraw_field, redraw_fields, set_button_icon, set_button_icon_target, + set_props, }; pub use calc_order::{CalculatedField, CalculationIssue, CalculationOrder, calculation_order, set_calculation_order}; pub use scripting::{ diff --git a/crates/forms/src/tests.rs b/crates/forms/src/tests.rs index 7ae5126f6a..f36e886ae1 100644 --- a/crates/forms/src/tests.rs +++ b/crates/forms/src/tests.rs @@ -151,6 +151,87 @@ fn grid_copy_keeps_widget_overrides_when_field_and_widget_are_separate() { assert_eq!(copy.da, "/Helv 8 Tf 1 0 0 rg"); } +/// One page with a check box `box` of two widgets drawing on states `first` and `second`, with +/// `opt` (`/Opt`, PDF array body) when given. +fn two_widget_box(first: &str, second: &str, opt: Option<&str>) -> Document { + let opt = opt.map_or(String::new(), |o| format!(" /Opt [{o}]")); + let kid = |state: &str, x: u32| { + format!( + "<< /Type /Annot /Subtype /Widget /Parent 4 0 R /AS /Off /Rect [{x} 300 {} 315] /P 3 0 R /AP << /N << /{state} 7 0 R /Off 7 0 R >> >> >>", + x + 15 + ) + }; + let objs: Vec = vec![ + "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] >> >>".into(), + "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >>".into(), + "<< /Type /Page /Parent 2 0 R /Annots [5 0 R 6 0 R] >>".into(), + format!("<< /FT /Btn /T (box) /V /Off{opt} /Kids [5 0 R 6 0 R] >>"), + kid(first, 20), + kid(second, 60), + "<< /Length 0 >> +stream + +endstream" + .into(), + ]; + document(&objs) +} + +#[test] +fn grid_copy_refuses_a_check_box_whose_widgets_export_different_values() { + for doc in [two_widget_box("A", "B", None), two_widget_box("Yes", "Yes", Some("(A) (B)"))] { + let mut doc = doc; + let before = fields(&doc).len(); + assert!(copy_field(&mut doc, "box", 0, 0, [20.0, 200.0, 35.0, 215.0], "box_copy").is_err()); + assert_eq!(fields(&doc).len(), before); + } +} + +#[test] +fn grid_copy_takes_a_check_box_whose_widgets_export_one_value() { + let mut doc = two_widget_box("Yes", "Yes", Some("(X) (X)")); + copy_field(&mut doc, "box", 1, 0, [20.0, 200.0, 35.0, 215.0], "box_copy").unwrap(); + let all = fields(&doc); + let copy = field(&all, "box_copy"); + assert_eq!(copy.export_of(0), Some("X"), "the copy exports what its source widget did"); + assert_eq!(copy.export_of(0), field(&all, "box").export_of(1)); +} + +#[test] +fn grid_copy_of_a_check_box_exports_its_on_state_when_opt_is_not_one_per_widget() { + let mut doc = two_widget_box("Yes", "Yes", Some("(A) (B) (C)")); + assert_eq!(field(&fields(&doc), "box").export_of(1), Some("Yes")); + copy_field(&mut doc, "box", 1, 0, [20.0, 200.0, 35.0, 215.0], "box_copy").unwrap(); + assert_eq!(field(&fields(&doc), "box_copy").export_of(0), Some("Yes"), "a stray /Opt entry must not become the copy's export value"); +} + +#[test] +fn grid_copy_of_a_check_box_exports_the_value_its_widget_did_past_an_unreadable_opt_entry() { + let mut doc = two_widget_box("Yes", "Yes", Some("5 (X) (X)")); + assert_eq!(field(&fields(&doc), "box").export_of(0), Some("X")); + copy_field(&mut doc, "box", 0, 0, [20.0, 200.0, 35.0, 215.0], "box_copy").unwrap(); + assert_eq!(field(&fields(&doc), "box_copy").export_of(0), Some("X")); +} + +#[test] +fn grid_copy_keeps_a_widget_that_is_read_only_on_its_own() { + let objs: Vec = vec![ + "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(), + "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 300 400] >>".into(), + "<< /Type /Page /Parent 2 0 R /Annots [6 0 R] >>".into(), + "<< /Fields [5 0 R] >>".into(), + format!("<< /FT /Tx /T (source) /Ff {} /DA (/Helv 12 Tf 0 g) /Kids [6 0 R] >>", flags::MULTILINE), + "<< /Type /Annot /Subtype /Widget /Parent 5 0 R /Ff 1 /P 3 0 R /Rect [20 300 120 320] >>".into(), + ]; + let mut doc = document(&objs); + assert!(field(&fields(&doc), "source").widgets[0].read_only); + copy_field(&mut doc, "source", 0, 0, [20.0, 250.0, 120.0, 270.0], "copy").unwrap(); + let all = fields(&doc); + let copy = field(&all, "copy"); + assert!(copy.widgets[0].read_only && copy.read_only(), "the copy is read-only as its source widget was"); + assert!(copy.has(flags::MULTILINE), "and keeps the field's own flags"); +} + #[test] fn grid_copy_keeps_a_transparent_borderless_multiline_look() { let mut doc = fixture(); diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index b628f7468c..38a4c286ae 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -5265,8 +5265,12 @@ evidence = [ "crates/forms/src/tests.rs::grid_copy_keeps_a_transparent_borderless_multiline_look", "crates/automation/tests/it/automation.rs::copying_a_field_into_a_grid_through_tools", "crates/ui-egui/tests/it/prepare.rs::copying_a_field_into_a_grid_from_its_context_menu", + "crates/engine/src/field_table.rs::a_grid_copies_a_check_box_only_when_its_widgets_export_one_value", + "crates/forms/src/tests.rs::grid_copy_refuses_a_check_box_whose_widgets_export_different_values", + "crates/forms/src/tests.rs::grid_copy_takes_a_check_box_whose_widgets_export_one_value", + "crates/forms/src/tests.rs::grid_copy_keeps_a_widget_that_is_read_only_on_its_own", ] -notes = "Prepare a form ▸ Text field table: drag an area, then set rows, columns, spacing, column widths (draggable dividers) and a name pattern per column in a movable window, with the table previewed on the page. Added as one undoable edit, or refused whole with the reason (a cell under 4 pt, a name with a period, a repeated or existing name). Copy into Grid in a text field or check box's menu uses the same window to repeat that field in rows and columns beside it: each copy is an independently named field with the source's flags, look and value and appearance streams of its own, previewed on the page and added as one undoable edit; form_add_field_table does the same with source_field. Missing: copying radio groups, choice fields, buttons, signatures and check boxes with per-widget export values (refused with the reason)." +notes = "Prepare a form ▸ Text field table: drag an area, then set rows, columns, spacing, column widths (draggable dividers) and a name pattern per column in a movable window, with the table previewed on the page. Added as one undoable edit, or refused whole with the reason (a cell under 4 pt, a name with a period, a repeated or existing name). Copy into Grid in a text field or check box's menu uses the same window to repeat that field in rows and columns beside it: each copy is an independently named field with the source's flags, look and value and appearance streams of its own, previewed on the page and added as one undoable edit; form_add_field_table does the same with source_field. Missing: copying radio groups, choice fields, buttons, signatures and check boxes whose widgets export different values (refused with the reason)." [[feature]] id = "form.rename-lock-fields"