From 36b33e33633ecacc791d8a78ffa36fcd2d37208b Mon Sep 17 00:00:00 2001 From: Karim Date: Tue, 3 Nov 2026 19:53:53 +0200 Subject: [PATCH 1/6] M6: copy form fields into a grid Cherry-picked from #6012 (ef57ba58d) onto main c34c6c5a0. Conflicts resolved: CopyField sits beside main's field edits and clears the form script snapshot like them; the copy label joins main's batch labels. The Prepare a form menu and window parts are left out here because main moved them onto the dialog host; the next commits port them. The ROADMAP.md, docs/roadmap.md and docs/gaps.md edits are dropped. --- crates/automation/README.md | 7 ++ crates/automation/src/forms.rs | 29 +++++- crates/automation/src/tools.rs | 4 +- crates/automation/tests/it/automation.rs | 24 +++++ crates/engine/src/edit.rs | 8 ++ crates/engine/src/edit/labels.rs | 2 + crates/engine/src/edit/run.rs | 5 ++ crates/engine/src/field_table.rs | 44 +++++++++ crates/forms/src/author.rs | 2 +- crates/forms/src/author/lifecycle.rs | 85 +++++++++++++++++- crates/forms/src/lib.rs | 2 +- crates/forms/src/tests.rs | 108 +++++++++++++++++++++++ crates/ui-egui/src/editing.rs | 1 + parity/acrobat-features.toml | 5 +- 14 files changed, 317 insertions(+), 9 deletions(-) diff --git a/crates/automation/README.md b/crates/automation/README.md index 6d835d8d1d..a561d141df 100644 --- a/crates/automation/README.md +++ b/crates/automation/README.md @@ -91,6 +91,13 @@ semantics; they never silently act on partial text. ## Shared field properties +`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. + For an individual push button, `form_set_props` also edits its visible normal label: ```json diff --git a/crates/automation/src/forms.rs b/crates/automation/src/forms.rs index 035aa49d33..59a9bc7585 100644 --- a/crates/automation/src/forms.rs +++ b/crates/automation/src/forms.rs @@ -547,12 +547,33 @@ impl Automation { table.column_gap = a.opt_num("column_gap")?.unwrap_or(0.0); table.first_row = a.opt_int("first_row")?.map_or(1, |n| usize::try_from(n).unwrap_or(usize::MAX)); let info = doc.info.pages.get(page).ok_or_else(|| bad(format!("page {} does not exist", page + 1)))?; - let edit = field_table::edit(&table, page, info, &doc.form).map_err(|e| bad(e.to_string()))?; + let edit = if let Some(source) = a.opt_str("source_field")? { + let widget = a.opt_int("source_widget")?.unwrap_or(1); + let widget = usize::try_from(widget).ok().and_then(|n| n.checked_sub(1)).ok_or_else(|| bad("source_widget must be at least 1"))?; + let field = doc.form.iter().find(|f| f.name == source).ok_or_else(|| bad(format!("field {source:?} does not exist")))?; + if !matches!(field.kind, pdfcraft_engine::FormFieldKind::Text | pdfcraft_engine::FormFieldKind::CheckBox) { + return Err(bad("only text fields and check boxes can be copied into a grid")); + } + if field.widgets.get(widget).is_none() { + return Err(bad("source_widget does not exist")); + } + field_table::copy_edit(&table, page, info, &doc.form, source, widget).map_err(|e| bad(e.to_string()))? + } else { + if a.get("source_widget").is_some() { + return Err(bad("source_widget requires source_field")); + } + field_table::edit(&table, page, info, &doc.form).map_err(|e| bad(e.to_string()))? + }; // The names the batch adds, in the order it adds them. let fields: Vec = match &edit { - Edit::Batch { edits, .. } => { - edits.iter().filter_map(|e| if let Edit::AddField { name, .. } = e { name.clone() } else { None }).collect() - } + Edit::Batch { edits, .. } => edits + .iter() + .filter_map(|e| match e { + Edit::AddField { name, .. } => name.clone(), + Edit::CopyField { name, .. } => Some(name.clone()), + _ => None, + }) + .collect(), _ => Vec::new(), }; (edit, fields) diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index b9da1dbed5..4c95f6a6f1 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -596,7 +596,7 @@ pub fn tools() -> Vec { t( "form_add_field_table", "Prepare form: add a table of text fields", - "Divide rect into rows and columns of text fields, one per cell, as one undo step. rect in points from the top-left of the displayed page [x0, y0, x1, y1]; rows 1-100 from the top; columns 1-50, or as many as names or widths list. Each column names its cells from its pattern in names: an N on its own after _ - / or : (price_N), # or {row} is the row number, {col} the column number, {seq} counts every cell along the rows, starting at first_row; with none of them the row number goes at the end. Rows count from first_row (default 1). Without names the columns are Table1_N, Table1_c2_N, … using the first free TableK. widths are relative (default equal); row_gap and column_gap are points between cells (default 0). Nothing is added if a cell would be under 4 points or a name would contain a period, repeat, or already exist; the error says which. Returns the fields' names. Undoable.", + "Divide rect into rows and columns of fields, one per cell, as one undo step. By default these are new text fields; source_field copies an existing text field or check box with its properties and initial value into independent fields. rect in points from the top-left of the displayed page [x0, y0, x1, y1]; rows 1-100 from the top; columns 1-50, or as many as names or widths list. Each column names its cells from its pattern in names: an N on its own after _ - / or : (price_N), # or {row} is the row number, {col} the column number, {seq} counts every cell along the rows, starting at first_row; with none of them the row number goes at the end. Rows count from first_row (default 1). Without names the columns are Table1_N, Table1_c2_N, … using the first free TableK. widths are relative (default equal); row_gap and column_gap are points between cells (default 0). Nothing is added if a cell would be under 4 points or a name would contain a period, repeat, or already exist; the error says which. Returns the fields' names. Undoable.", ) .cmd("form.add.text_table") .with(schema( @@ -611,6 +611,8 @@ pub fn tools() -> Vec { "row_gap": { "type": "number", "minimum": 0 }, "column_gap": { "type": "number", "minimum": 0 }, "first_row": { "type": "integer", "minimum": 0, "maximum": 99999 }, + "source_field": { "type": "string", "description": "Copy this existing text field or check box into each cell instead of creating blank text fields." }, + "source_widget": { "type": "integer", "minimum": 1, "description": "1-based widget of source_field (default 1)." }, }), &["doc", "page", "rect", "rows"], )), diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index f1ccd7ea73..40cc1db67d 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -6016,6 +6016,30 @@ fn adding_a_field_table_through_tools() { assert_eq!(count(&mut a), 8, "one undo takes back the whole last table"); } +#[test] +fn copying_a_field_into_a_grid_through_tools() { + let dir = workdir("copy-field-grid"); + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({"path": "a.pdf"}))["doc"].as_u64().unwrap(); + ok(&mut a, "form_add_field", json!({"doc": doc, "page": 1, "type": "text", "name": "source", "rect": [20, 20, 180, 50], "multiline": true})); + ok(&mut a, "form_fill", json!({"doc": doc, "values": {"source": "initial"}})); + let args = json!({"doc": doc, "page": 1, "rect": [20, 70, 180, 150], "rows": 2, "names": ["copy_N"], "source_field": "source"}); + assert_eq!(ok(&mut a, "form_add_field_table", args.clone())["fields"], json!(["copy_1", "copy_2"])); + ok(&mut a, "form_fill", json!({"doc": doc, "values": {"copy_1": "changed"}})); + let result = ok(&mut a, "form_fields", json!({"doc": doc})); + let fields = result["fields"].as_array().unwrap(); + let get = |name: &str| fields.iter().find(|f| f["name"] == name).unwrap(); + assert_eq!(get("source")["value"], "initial"); + assert_eq!(get("copy_1")["value"], "changed"); + assert_eq!(get("copy_2")["value"], "initial"); + assert_eq!(get("copy_1")["multiline"], true); + assert_eq!(get("copy_2")["multiline"], true); + ok(&mut a, "edit_undo", json!({"doc": doc})); // undo the fill + ok(&mut a, "edit_undo", json!({"doc": doc})); // undo the complete grid + let result = ok(&mut a, "form_fields", json!({"doc": doc})); + assert_eq!(result["fields"].as_array().unwrap().len(), 1); +} + #[test] fn redact_mark_respects_single_page_and_rejects_conflicting_selectors() { let dir = workdir("redact-single-page"); diff --git a/crates/engine/src/edit.rs b/crates/engine/src/edit.rs index bd65f1fa5f..df43b0292c 100644 --- a/crates/engine/src/edit.rs +++ b/crates/engine/src/edit.rs @@ -363,6 +363,14 @@ pub enum Edit { name: String, pages: Vec, }, + /// Copy one widget into a separately named field on a page. + CopyField { + source: String, + widget: usize, + page: usize, + rect: [f64; 4], + name: String, + }, DeleteField { name: String, }, diff --git a/crates/engine/src/edit/labels.rs b/crates/engine/src/edit/labels.rs index 829afea516..20a7747327 100644 --- a/crates/engine/src/edit/labels.rs +++ b/crates/engine/src/edit/labels.rs @@ -177,6 +177,7 @@ pub const BATCH_LABELS: &[&str] = &[ "Run JavaScript", "Recognize text", field_table::LABEL, + field_table::COPY_LABEL, "Style", crate::find_replace::REPLACE_ALL, ]; @@ -268,6 +269,7 @@ impl Edit { Edit::SetFieldProps { .. } => Label::of("Change field properties"), Edit::DeleteField { .. } | Edit::DeleteWidget { .. } => Label::of("Delete field"), Edit::DuplicateField { .. } => Label::of("Duplicate field"), + Edit::CopyField { .. } => Label::of("Duplicate field"), Edit::SetTabOrder { .. } | Edit::MoveInTabOrder { .. } => Label::of("Set tab order"), Edit::SetCalculationOrder { .. } => Label::of("Set calculation order"), Edit::SetInitialView(_) => Label::of("Change initial view"), diff --git a/crates/engine/src/edit/run.rs b/crates/engine/src/edit/run.rs index 8397e39655..3222734e9d 100644 --- a/crates/engine/src/edit/run.rs +++ b/crates/engine/src/edit/run.rs @@ -139,6 +139,7 @@ pub(crate) fn check_permission(edit: &Edit, p: &pdfcraft_cos::Permissions) -> Re | Edit::DeleteField { .. } | Edit::DeleteWidget { .. } | Edit::DuplicateField { .. } + | Edit::CopyField { .. } | Edit::SetTabOrder { .. } | Edit::MoveInTabOrder { .. } | Edit::SetCalculationOrder { .. } @@ -883,6 +884,10 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E pdfcraft_forms::delete_widget(doc, name, *widget)?; invalidate_form_script_snapshot(cx); } + Edit::CopyField { source, widget, page, rect, name } => { + pdfcraft_forms::copy_field(doc, source, *widget, *page, *rect, name)?; + invalidate_form_script_snapshot(cx); + } Edit::SetTabOrder { pages, order } => pdfcraft_forms::set_tab_order(doc, pages, *order)?, Edit::MoveInTabOrder { name, earlier } => pdfcraft_forms::move_in_tab_order(doc, name, *earlier)?, // As after a script edit: the values the new order gives show at once. diff --git a/crates/engine/src/field_table.rs b/crates/engine/src/field_table.rs index f3fd96551e..fa8262da89 100644 --- a/crates/engine/src/field_table.rs +++ b/crates/engine/src/field_table.rs @@ -12,6 +12,9 @@ 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"; +/// The history entry for a grid copied from an existing field. +pub const COPY_LABEL: &str = "Create multiple field copies"; + /// The edit adding `table`'s cells to `page` (0-based, shown as `info`) of a document whose /// fields are `form`. Refused, with nothing added, when a cell would be too small on the page or /// its name can't be used. @@ -40,6 +43,24 @@ pub fn edit(table: &FieldTable, page: usize, info: &PageInfo, form: &[FormField] Ok(Edit::Batch { label: LABEL.to_owned(), edits }) } +/// Lay out a grid of independent copies of one existing field widget. +pub fn copy_edit(table: &FieldTable, page: usize, info: &PageInfo, form: &[FormField], source: &str, widget: usize) -> Result { + let batch = edit(table, page, info, form)?; + Ok(match batch { + Edit::Batch { edits, .. } => Edit::Batch { + label: COPY_LABEL.to_owned(), + edits: edits + .into_iter() + .map(|edit| match edit { + Edit::AddField { page, rect, name: Some(name), .. } => Edit::CopyField { source: source.to_owned(), widget, page, rect, name }, + other => other, + }) + .collect(), + }, + other => other, + }) +} + #[cfg(test)] mod tests { use super::*; @@ -81,6 +102,29 @@ mod tests { assert!(s.get(id).unwrap().form.is_empty(), "one undo takes the whole table back"); } + #[test] + fn a_grid_of_field_copies_is_one_undoable_edit() { + let mut s = Session::new(); + let bytes = s.create_blank(300.0, 400.0, 1).unwrap(); + let id = s.open("copies.pdf", None, bytes, None).unwrap(); + s.apply( + id, + Edit::AddField { page: 0, rect: [30.0, 330.0, 130.0, 350.0], kind: NewField::Text { multiline: true }, name: Some("source".into()) }, + ) + .unwrap(); + let table = grid([30.0, 100.0, 230.0, 180.0], 2, &["a_N", "b_N"]); + let doc = s.get(id).unwrap(); + let edit = copy_edit(&table, 0, &doc.info.pages[0], &doc.form, "source", 0).unwrap(); + s.apply(id, edit).unwrap(); + let form = &s.get(id).unwrap().form; + assert_eq!(form.len(), 5); + for name in ["a_1", "b_1", "a_2", "b_2"] { + assert!(form.iter().find(|f| f.name == name).unwrap().has(pdfcraft_forms::flags::MULTILINE)); + } + assert_eq!(s.undo(id).unwrap().to_string(), COPY_LABEL); + assert_eq!(s.get(id).unwrap().form.len(), 1); + } + #[test] fn rows_run_down_a_turned_page_as_it_is_shown() { let mut s = Session::new(); diff --git a/crates/forms/src/author.rs b/crates/forms/src/author.rs index f347909b58..fca138f022 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, delete_field, delete_field_object, delete_widget, duplicate_field}; +pub use lifecycle::{add_field, copy_field, 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 b2de1321a0..9dabee1071 100644 --- a/crates/forms/src/author/lifecycle.rs +++ b/crates/forms/src/author/lifecycle.rs @@ -1,5 +1,5 @@ use super::look::redraw_field; -use super::tree::{add_to_page, attach, clash, detach, ensure_form, free_name, name_parts, top_names}; +use super::tree::{add_to_page, attach, clash, detach, ensure_form, free_name, inherited, name_parts, top_names}; use super::{ Dict, Document, Field, FieldKind, FormError, MIN_FIELD_SIDE, NewField, ObjRef, Object, PdfString, Widget, appearance, fields, flags, invalid, page_refs, rgb, @@ -343,6 +343,89 @@ pub(super) fn split_triggers(aa: &Dict) -> (Option, Option) { (some(widget), some(field)) } +/// Copy one widget into a new, independently named field on a page. +/// +/// The field's current value and properties are copied, but the new field has its own value. +/// Radio groups and signature fields require special handling and are not supported here. +pub fn copy_field(doc: &mut Document, name: &str, widget: usize, page: usize, rect: [f64; 4], new_name: &str) -> Result<(), FormError> { + let all = fields(doc); + let f = all.iter().find(|f| f.name == name).ok_or_else(|| FormError::NoSuchField(name.into()))?; + 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"); + } + let w = f.widgets.get(widget).ok_or_else(|| FormError::Invalid(format!("{name} has no widget {}", widget.saturating_add(1))))?; + let page_ref = *page_refs(doc).get(page).ok_or_else(|| FormError::Invalid(format!("page {} does not exist", page.saturating_add(1))))?; + let width = rect[2] - rect[0]; + let height = rect[3] - rect[1]; + if !rect.iter().all(|v| v.is_finite()) || !width.is_finite() || !height.is_finite() || width < MIN_FIELD_SIDE || height < MIN_FIELD_SIDE { + return invalid("the field is too small"); + } + let parts = name_parts(new_name)?; + if let Some(why) = all.iter().find_map(|other| clash(new_name, &other.name)) { + return invalid(why); + } + let mut field = doc.get(f.obj).as_dict().cloned().ok_or_else(|| FormError::Invalid("field is not a dictionary".into()))?; + let widget_dict = doc.get(w.obj).as_dict().cloned().ok_or_else(|| FormError::Invalid("widget is not a dictionary".into()))?; + for (k, v) in inherited(doc, f.obj).iter() { + field.set(k.to_vec(), v.clone()); + } + if w.obj != f.obj { + // Preserve widget entries that aren't in the field dictionary, including unfamiliar + // annotation keys, while the field's own attributes keep their precedence. + for (key, value) in widget_dict.iter() { + if !field.contains(key) && !matches!(key.as_slice(), b"Parent" | b"Kids" | b"T" | b"AA" | b"NM" | b"StructParent") { + field.set(key.clone(), value.clone()); + } + } + for key in WIDGET_KEYS { + if let Some(value) = widget_dict.get(key) { + field.set(key.to_vec(), value.clone()); + } + } + if let Some(da) = widget_dict.get(b"DA") { + field.set(b"DA".to_vec(), da.clone()); + } + // 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()) { + for (k, v) in widget_aa.iter() { + aa.set(k.to_vec(), v.clone()); + } + } + if aa.iter().next().is_some() { + field.set(b"AA".to_vec(), Object::Dict(aa)); + } + } + for key in [&b"Kids"[..], b"Parent", b"T", b"NM", b"StructParent"] { + field.remove(key); + } + // 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"] { + if let Some(value) = field.get(key).filter(|v| Object::as_ref(v).is_some()) + && let Some(dict) = doc.resolve(value).as_dict().cloned() + { + field.set(key.to_vec(), Object::Dict(dict)); + } + } + field.set(b"P".to_vec(), Object::Ref(page_ref)); + field.set(b"Rect".to_vec(), Object::Array(rect.iter().map(|v| Object::Real(*v)).collect())); + // Keep a custom appearance rather than replacing it with a generated approximation. + // A viewer scales its appearance stream to the new widget rectangle. + let has_appearance = field.get(b"AP").is_some_and(|o| matches!(&*doc.resolve(o), Object::Dict(d) if d.contains(b"N"))); + let af = ensure_form(doc)?; + let copied = doc.add(Object::Dict(field)); + attach(doc, af, copied, &parts)?; + add_to_page(doc, page_ref, copied)?; + if !has_appearance { + redraw_field(doc, new_name)?; + } + Ok(()) +} + /// Duplicate a field onto other pages (Acrobat: right-click a field ▸ Duplicate): each page /// gets a widget at the same place, belonging to the same field, so they share one value. /// A field that is its own widget is first split into a field and a widget kid. Returns how diff --git a/crates/forms/src/lib.rs b/crates/forms/src/lib.rs index 470d47ebe4..90cec27dc0 100644 --- a/crates/forms/src/lib.rs +++ b/crates/forms/src/lib.rs @@ -26,7 +26,7 @@ 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, delete_field, + 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, }; pub use calc_order::{CalculatedField, CalculationIssue, CalculationOrder, calculation_order, set_calculation_order}; diff --git a/crates/forms/src/tests.rs b/crates/forms/src/tests.rs index 4d859417a0..1deb85e7a4 100644 --- a/crates/forms/src/tests.rs +++ b/crates/forms/src/tests.rs @@ -39,6 +39,114 @@ fn fixture() -> Document { document(&objs) } +#[test] +fn grid_copy_preserves_properties_and_has_an_independent_value() { + let mut doc = fixture(); + let source = field(&fields(&doc), "notes").clone(); + copy_field(&mut doc, "notes", 0, 0, [50.0, 400.0, 250.0, 480.0], "notes_1").unwrap(); + let copied = field(&fields(&doc), "notes_1").clone(); + assert_eq!(copied.kind, source.kind); + assert_eq!(copied.flags, source.flags); + assert_eq!(copied.da, source.da); + assert_eq!(copied.widgets[0].rect, [50.0, 400.0, 250.0, 480.0]); + set_value(&mut doc, "notes_1", &FieldValue::Text("new value".into())).unwrap(); + let reopened = reopen(&doc); + let all = fields(&reopened); + assert_eq!(field(&all, "notes_1").value, ["new value"]); + assert_ne!(field(&all, "notes").value, ["new value"]); +} + +#[test] +fn grid_copy_checkbox_preserves_appearance_and_rejects_taken_names() { + let mut doc = fixture(); + copy_field(&mut doc, "agree", 0, 0, [350.0, 400.0, 370.0, 420.0], "agree_copy").unwrap(); + let all = fields(&doc); + assert_eq!(field(&all, "agree_copy").kind, FieldKind::CheckBox); + assert_eq!(field(&all, "agree_copy").widgets[0].on_state, field(&all, "agree").widgets[0].on_state); + let copied_ap = doc.get(field(&all, "agree_copy").widgets[0].obj).as_dict().unwrap().get(b"AP").cloned(); + let source_ap = doc.get(field(&all, "agree").widgets[0].obj).as_dict().unwrap().get(b"AP").cloned(); + assert_eq!(copied_ap, source_ap, "custom checkbox appearance is preserved"); + set_value(&mut doc, "agree_copy", &FieldValue::Check(true)).unwrap(); + let reopened = reopen(&doc); + let all = fields(&reopened); + assert_ne!(field(&all, "agree_copy").value, field(&all, "agree").value); + let before = all.len(); + assert!(copy_field(&mut doc, "agree", 0, 0, [0.0, 0.0, 20.0, 20.0], "agree_copy").is_err()); + assert_eq!(fields(&doc).len(), before); + assert!(copy_field(&mut doc, "size", 0, 0, [0.0, 0.0, 20.0, 20.0], "radio_copy").is_err()); +} + +#[test] +fn grid_copy_does_not_share_indirect_appearance_dictionaries() { + let mut doc = fixture(); + let source = field(&fields(&doc), "name").obj; + let source_dict = doc.get(source).as_dict().unwrap().clone(); + let mk = doc.add(source_dict.get(b"MK").unwrap().clone()); + let mut bs = pdfcraft_cos::Dict::new(); + bs.set(b"W".to_vec(), Object::Real(1.0)); + let bs = doc.add(Object::Dict(bs)); + doc.update_dict(source, |d| { + d.set(b"MK".to_vec(), Object::Ref(mk)); + d.set(b"BS".to_vec(), Object::Ref(bs)); + }) + .unwrap(); + copy_field(&mut doc, "name", 0, 0, [50.0, 400.0, 250.0, 420.0], "name_copy").unwrap(); + let before = look(&doc, field(&fields(&doc), "name")); + let props = FieldProps { + appearance: Some(LookPatch { fill: Some(Some([0.0, 0.0, 1.0])), width: Some(3.0), ..Default::default() }), + ..Default::default() + }; + set_props(&mut doc, "name_copy", &props).unwrap(); + let all = fields(&doc); + assert_eq!(look(&doc, field(&all, "name")), before); + assert_ne!(look(&doc, field(&all, "name_copy")), before); +} + +#[test] +fn grid_copy_preserves_inherited_properties_and_rejects_invalid_geometry() { + let mut doc = fixture(); + let source = field(&fields(&doc), "address.city").obj; + let parent = doc.get(source).as_dict().unwrap().reference(b"Parent").unwrap(); + doc.update_dict(source, |d| { + d.remove(b"FT"); + }) + .unwrap(); + doc.update_dict(parent, |d| { + d.set(b"FT".to_vec(), Object::name("Tx")); + d.set(b"Ff".to_vec(), Object::Int(i64::from(flags::MULTILINE))); + }) + .unwrap(); + copy_field(&mut doc, "address.city", 0, 0, [50.0, 400.0, 250.0, 420.0], "city_copy").unwrap(); + let all = fields(&doc); + assert!(field(&all, "city_copy").has(flags::MULTILINE)); + let before = all.len(); + for rect in [[f64::NAN, 0.0, 20.0, 20.0], [0.0, 0.0, f64::INFINITY, 20.0], [-f64::MAX, 0.0, f64::MAX, 20.0], [0.0; 4]] { + assert!(copy_field(&mut doc, "address.city", 0, 0, rect, "invalid_copy").is_err()); + assert_eq!(fields(&doc).len(), before); + } +} + +#[test] +fn grid_copy_keeps_widget_overrides_when_field_and_widget_are_separate() { + 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(), + "<< /FT /Tx /T (source) /DA (/Helv 12 Tf 0 g) /Kids [6 0 R] >>".into(), + "<< /Type /Annot /Subtype /Widget /Parent 5 0 R /P 3 0 R /Rect [20 300 120 320] /DA (/Helv 8 Tf 1 0 0 rg) /Foo (kept) /NM (unique) >>".into(), + ]; + let mut doc = document(&objs); + 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"); + let object = doc.get(copy.obj); + let dict = object.as_dict().unwrap(); + assert!(dict.contains(b"Foo")); + assert!(!dict.contains(b"NM"), "an annotation name must not be duplicated"); + assert_eq!(copy.da, "/Helv 8 Tf 1 0 0 rg"); +} + /// A PDF of the given objects (numbered from 1). fn document(objs: &[String]) -> Document { let mut out = b"%PDF-1.7\n".to_vec(); diff --git a/crates/ui-egui/src/editing.rs b/crates/ui-egui/src/editing.rs index 31d789ef80..343dfd0d3e 100644 --- a/crates/ui-egui/src/editing.rs +++ b/crates/ui-egui/src/editing.rs @@ -1239,6 +1239,7 @@ fn is_form_edit(edit: &Edit) -> bool { | Edit::DeleteField { .. } | Edit::DeleteWidget { .. } | Edit::DuplicateField { .. } + | Edit::CopyField { .. } | Edit::SetFieldProps { .. } | Edit::SetFieldImage { .. } | Edit::SetFieldImageTarget { .. } diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 6cbab8f6c8..2ffd5fa2d5 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -5261,8 +5261,11 @@ evidence = [ "crates/engine/src/field_table.rs::a_table_is_added_and_undone_as_one_step", "crates/automation/tests/it/automation.rs::adding_a_field_table_through_tools", "crates/ui-egui/tests/it/prepare.rs::a_text_field_table_is_drawn_set_up_and_added_in_one_step", + "crates/forms/src/tests.rs::grid_copy_preserves_properties_and_has_an_independent_value", + "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", ] -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); form_add_field_table does the same headlessly. Missing: copying an existing field of any type, with its properties, into a grid from its context menu, which is what this entry describes; the table only creates new text fields." +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). Create Multiple Copies in a text field or check box's context menu uses the same grid to copy its properties and initial value into independently named fields; form_add_field_table can do the same with source_field. Missing: copying radio groups, choice fields, buttons, signatures and check boxes with per-widget export values." [[feature]] id = "form.rename-lock-fields" From 9ecb1f882370d084ce6d3989cab7a753f8911d48 Mon Sep 17 00:00:00 2001 From: KenM76 Date: Fri, 27 Nov 2026 09:38:48 -0500 Subject: [PATCH 2/6] Grid copies: own appearances, no XFA keys, refuse what can't copy Review fixes on #6012's copy_field and copy_edit: - A copy no longer carries the source's private XFA keys (PCSom, PCXfaNode, PCItems), so it is not bound to the template node the source fills. - Each copy gets appearance streams of its own (/N, /D, /R and every check box state). Shared streams meant redrawing one in place, as a password field's edit does, redrew the source and every other copy. - copy_edit refuses a field a grid can't copy with TableError::Uncopyable, so a preview never shows a check box whose widgets export different values as valid. field_table::copyable is the same test for menus. - copy_field is split into helpers under 80 lines. New forms tests: a transparent, borderless, multi-line source keeps its look and flag in the copy after a save; a copy has no PCSom; filling a copy leaves the source's appearance stream unchanged. The check box test now asserts a different stream with equal content per state. Co-authored-by: Karim1125 Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/field_table.rs | 38 +++++++- crates/forms/src/author/lifecycle.rs | 135 ++++++++++++++++++--------- crates/forms/src/table.rs | 7 +- crates/forms/src/tests.rs | 67 ++++++++++++- 4 files changed, 199 insertions(+), 48 deletions(-) diff --git a/crates/engine/src/field_table.rs b/crates/engine/src/field_table.rs index fa8262da89..a0ec2e499a 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, NewField}; +use crate::{Edit, FormField, FormFieldKind as FieldKind, 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,8 +43,24 @@ pub fn edit(table: &FieldTable, page: usize, info: &PageInfo, form: &[FormField] Ok(Edit::Batch { label: LABEL.to_owned(), edits }) } -/// Lay out a grid of independent copies of one existing field widget. +/// 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). +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() +} + +/// The edit laying `table` out as independent copies of widget `widget` of the field `source`, +/// one copy in each cell. Refused, with nothing added, for a field a grid can't copy +/// ([`copyable`]) and for whatever [`edit`] refuses. pub fn copy_edit(table: &FieldTable, page: usize, info: &PageInfo, form: &[FormField], source: &str, widget: usize) -> Result { + if !form.iter().any(|f| f.name == source && copyable(f, widget)) { + return Err(TableError::Uncopyable(source.to_owned())); + } let batch = edit(table, page, info, form)?; Ok(match batch { Edit::Batch { edits, .. } => Edit::Batch { @@ -125,6 +141,24 @@ mod tests { assert_eq!(s.get(id).unwrap().form.len(), 1); } + #[test] + fn a_grid_refuses_a_check_box_whose_widgets_export_different_values() { + 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(); + s.apply(id, Edit::AddField { page: 0, rect: [30.0, 330.0, 50.0, 350.0], kind: NewField::CheckBox, name: Some("box".into()) }).unwrap(); + let doc = s.get(id).unwrap(); + let table = grid([30.0, 100.0, 230.0, 180.0], 2, &["a_N"]); + assert!(copy_edit(&table, 0, &doc.info.pages[0], &doc.form, "box", 0).is_ok()); + // The same box as two widgets with an export value each (`/Opt`), as the forms layer reads it. + let mut form = doc.form.to_vec(); + let boxes = form.iter_mut().find(|f| f.name == "box").unwrap(); + boxes.widgets.push(boxes.widgets[0].clone()); + 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"); + } + #[test] fn rows_run_down_a_turned_page_as_it_is_shown() { let mut s = Session::new(); diff --git a/crates/forms/src/author/lifecycle.rs b/crates/forms/src/author/lifecycle.rs index 9dabee1071..ae9910e2e3 100644 --- a/crates/forms/src/author/lifecycle.rs +++ b/crates/forms/src/author/lifecycle.rs @@ -343,20 +343,19 @@ pub(super) fn split_triggers(aa: &Dict) -> (Option, Option) { (some(widget), some(field)) } +/// Keys a grid copy never takes from its source: what ties a field into the tree, names it, or +/// binds it to an XFA template node (a new layout would replace or drop a field carrying them). +const COPY_DROPS: [&[u8]; 8] = [b"Kids", b"Parent", b"T", b"NM", b"StructParent", b"PCSom", b"PCXfaNode", b"PCItems"]; + /// Copy one widget into a new, independently named field on a page. /// -/// The field's current value and properties are copied, but the new field has its own value. -/// Radio groups and signature fields require special handling and are not supported here. +/// The field's current value and properties are copied, but the new field has its own value and +/// its own appearance streams. Radio groups and signature fields require special handling and are +/// not supported here. pub fn copy_field(doc: &mut Document, name: &str, widget: usize, page: usize, rect: [f64; 4], new_name: &str) -> Result<(), FormError> { let all = fields(doc); let f = all.iter().find(|f| f.name == name).ok_or_else(|| FormError::NoSuchField(name.into()))?; - 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"); - } - let w = f.widgets.get(widget).ok_or_else(|| FormError::Invalid(format!("{name} has no widget {}", widget.saturating_add(1))))?; + let w = copyable_widget(f, widget)?; let page_ref = *page_refs(doc).get(page).ok_or_else(|| FormError::Invalid(format!("page {} does not exist", page.saturating_add(1))))?; let width = rect[2] - rect[0]; let height = rect[3] - rect[1]; @@ -367,39 +366,8 @@ pub fn copy_field(doc: &mut Document, name: &str, widget: usize, page: usize, re if let Some(why) = all.iter().find_map(|other| clash(new_name, &other.name)) { return invalid(why); } - let mut field = doc.get(f.obj).as_dict().cloned().ok_or_else(|| FormError::Invalid("field is not a dictionary".into()))?; - let widget_dict = doc.get(w.obj).as_dict().cloned().ok_or_else(|| FormError::Invalid("widget is not a dictionary".into()))?; - for (k, v) in inherited(doc, f.obj).iter() { - field.set(k.to_vec(), v.clone()); - } - if w.obj != f.obj { - // Preserve widget entries that aren't in the field dictionary, including unfamiliar - // annotation keys, while the field's own attributes keep their precedence. - for (key, value) in widget_dict.iter() { - if !field.contains(key) && !matches!(key.as_slice(), b"Parent" | b"Kids" | b"T" | b"AA" | b"NM" | b"StructParent") { - field.set(key.clone(), value.clone()); - } - } - for key in WIDGET_KEYS { - if let Some(value) = widget_dict.get(key) { - field.set(key.to_vec(), value.clone()); - } - } - if let Some(da) = widget_dict.get(b"DA") { - field.set(b"DA".to_vec(), da.clone()); - } - // 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()) { - for (k, v) in widget_aa.iter() { - aa.set(k.to_vec(), v.clone()); - } - } - if aa.iter().next().is_some() { - field.set(b"AA".to_vec(), Object::Dict(aa)); - } - } - for key in [&b"Kids"[..], b"Parent", b"T", b"NM", b"StructParent"] { + let mut field = copy_source(doc, f, w)?; + for key in COPY_DROPS { field.remove(key); } // The appearance editor updates indirect /MK and /BS dictionaries in place. Make these @@ -411,6 +379,7 @@ pub fn copy_field(doc: &mut Document, name: &str, widget: usize, page: usize, re field.set(key.to_vec(), Object::Dict(dict)); } } + own_appearance(doc, &mut field); field.set(b"P".to_vec(), Object::Ref(page_ref)); field.set(b"Rect".to_vec(), Object::Array(rect.iter().map(|v| Object::Real(*v)).collect())); // Keep a custom appearance rather than replacing it with a generated approximation. @@ -426,6 +395,88 @@ 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> { + 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"); + } + f.widgets.get(widget).ok_or_else(|| FormError::Invalid(format!("{} has no widget {}", f.name, widget.saturating_add(1)))) +} + +/// The field dictionary of `f` with what it inherits and, when the widget `w` is separate, the +/// widget's own entries merged in: one merged field/widget dictionary for the copy. +fn copy_source(doc: &Document, f: &Field, w: &Widget) -> Result { + let mut field = doc.get(f.obj).as_dict().cloned().ok_or_else(|| FormError::Invalid("field is not a dictionary".into()))?; + let widget_dict = doc.get(w.obj).as_dict().cloned().ok_or_else(|| FormError::Invalid("widget is not a dictionary".into()))?; + for (k, v) in inherited(doc, f.obj).iter() { + field.set(k.to_vec(), v.clone()); + } + if w.obj == f.obj { + return Ok(field); + } + // Preserve widget entries that aren't in the field dictionary, including unfamiliar + // annotation keys, while the field's own attributes keep their precedence. + for (key, value) in widget_dict.iter() { + if !field.contains(key) && key.as_slice() != b"AA" && !COPY_DROPS.contains(&key.as_slice()) { + field.set(key.clone(), value.clone()); + } + } + for key in WIDGET_KEYS.iter().copied().chain([&b"DA"[..]]) { + if let Some(value) = widget_dict.get(key) { + field.set(key.to_vec(), value.clone()); + } + } + // 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()) { + for (k, v) in widget_aa.iter() { + aa.set(k.to_vec(), v.clone()); + } + } + if !aa.is_empty() { + field.set(b"AA".to_vec(), Object::Dict(aa)); + } + Ok(field) +} + +/// Give `field` appearance streams of its own: every stream its `/AP` reaches (`/N`, `/D`, `/R`, +/// directly or per state) is added again as a new object, so redrawing the copy, as a password +/// or value change does, can't rewrite the source's look. Resources the streams use stay shared. +fn own_appearance(doc: &mut Document, field: &mut Dict) { + let Some(ap) = field.get(b"AP").and_then(|o| doc.resolve(o).as_dict().cloned()) else { return }; + let mut fresh = Dict::new(); + for (key, look) in ap.iter() { + let owned = match &*doc.resolve(look) { + Object::Stream(_) => own_stream(doc, look), + Object::Dict(states) => { + let mut mine = Dict::new(); + for (state, stream) in states.iter() { + let value = own_stream(doc, stream); + mine.set(state.clone(), value); + } + Object::Dict(mine) + } + _ => look.clone(), + }; + fresh.set(key.clone(), owned); + } + field.set(b"AP".to_vec(), Object::Dict(fresh)); +} + +/// A new object holding the stream `look` refers to; anything else as it is. +fn own_stream(doc: &mut Document, look: &Object) -> Object { + match Object::as_ref(look) { + Some(r) if matches!(&*doc.get(r), Object::Stream(_)) => { + let stream = (*doc.get(r)).clone(); + Object::Ref(doc.add(stream)) + } + _ => look.clone(), + } +} + /// Duplicate a field onto other pages (Acrobat: right-click a field ▸ Duplicate): each page /// gets a widget at the same place, belonging to the same field, so they share one value. /// A field that is its own widget is first split into a field and a widget kid. Returns how diff --git a/crates/forms/src/table.rs b/crates/forms/src/table.rs index ae565052fc..3e886391c6 100644 --- a/crates/forms/src/table.rs +++ b/crates/forms/src/table.rs @@ -317,6 +317,8 @@ pub enum TableError { Twice(String), /// The form already has a field of this name. Taken(String), + /// The field a grid would copy is not a text field or a check box with one export value. + Uncopyable(String), } const ROWS: &str = "a table has 1 to {max} rows"; @@ -329,10 +331,11 @@ const COLUMN_TOO_NARROW: &str = const PERIOD: &str = "field names can't contain a period: {name}"; const TWICE: &str = "two cells would both be named {name}"; const TAKEN: &str = "a field named {name} already exists"; +const UNCOPYABLE: &str = "{name} can't be copied into a grid: only text fields and check boxes with one export value can"; /// Every sentence a [`TableError`] says, in English with its holes still in it, for an interface /// to translate; `wordings_are_said` keeps the list in step with the errors. -pub const WORDINGS: &[&str] = &[ROWS, COLUMNS, FIRST_ROW, NUMBERS, ROWS_TOO_SHORT, COLUMN_TOO_NARROW, PERIOD, TWICE, TAKEN]; +pub const WORDINGS: &[&str] = &[ROWS, COLUMNS, FIRST_ROW, NUMBERS, ROWS_TOO_SHORT, COLUMN_TOO_NARROW, PERIOD, TWICE, TAKEN, UNCOPYABLE]; /// How an interface says one of our wordings in its own language, holes and all: given the English /// in [`WORDINGS`], the same wording in that language. [`in_english`] keeps the English. @@ -361,6 +364,7 @@ impl TableError { TableError::Period(name) => named(PERIOD, name), TableError::Twice(name) => named(TWICE, name), TableError::Taken(name) => named(TAKEN, name), + TableError::Uncopyable(name) => named(UNCOPYABLE, name), } } } @@ -612,6 +616,7 @@ mod tests { TableError::Period("a.1".into()), TableError::Twice("a_1".into()), TableError::Taken("a_1".into()), + TableError::Uncopyable("a".into()), ]; assert_eq!(WORDINGS.len(), mistakes.len(), "one wording per mistake"); // Each mistake says one of the wordings: translated to a marker, only the values remain. diff --git a/crates/forms/src/tests.rs b/crates/forms/src/tests.rs index 1deb85e7a4..7ae5126f6a 100644 --- a/crates/forms/src/tests.rs +++ b/crates/forms/src/tests.rs @@ -63,9 +63,13 @@ fn grid_copy_checkbox_preserves_appearance_and_rejects_taken_names() { let all = fields(&doc); assert_eq!(field(&all, "agree_copy").kind, FieldKind::CheckBox); assert_eq!(field(&all, "agree_copy").widgets[0].on_state, field(&all, "agree").widgets[0].on_state); - let copied_ap = doc.get(field(&all, "agree_copy").widgets[0].obj).as_dict().unwrap().get(b"AP").cloned(); - let source_ap = doc.get(field(&all, "agree").widgets[0].obj).as_dict().unwrap().get(b"AP").cloned(); - assert_eq!(copied_ap, source_ap, "custom checkbox appearance is preserved"); + let (copied, source) = (normal_states(&doc, field(&all, "agree_copy")), normal_states(&doc, field(&all, "agree"))); + assert_eq!(copied.len(), source.len(), "every appearance state is copied"); + for ((state, copy_ref), (source_state, source_ref)) in copied.iter().zip(&source) { + assert_eq!(state, source_state); + assert_ne!(copy_ref, source_ref, "the copy has a stream of its own"); + assert_eq!(doc.get(*copy_ref), doc.get(*source_ref), "and it draws the same custom look"); + } set_value(&mut doc, "agree_copy", &FieldValue::Check(true)).unwrap(); let reopened = reopen(&doc); let all = fields(&reopened); @@ -147,6 +151,63 @@ fn grid_copy_keeps_widget_overrides_when_field_and_widget_are_separate() { assert_eq!(copy.da, "/Helv 8 Tf 1 0 0 rg"); } +#[test] +fn grid_copy_keeps_a_transparent_borderless_multiline_look() { + let mut doc = fixture(); + let bare = FieldProps { + appearance: Some(LookPatch { fill: Some(None), border: Some(None), width: Some(0.0), ..Default::default() }), + ..Default::default() + }; + set_props(&mut doc, "notes", &bare).unwrap(); + let source = field(&fields(&doc), "notes").clone(); + let styled = look(&doc, &source); + assert!(source.has(flags::MULTILINE) && styled.fill.is_none() && styled.border.is_none()); + copy_field(&mut doc, "notes", 0, 0, [50.0, 400.0, 250.0, 480.0], "notes_2").unwrap(); + set_value(&mut doc, "notes_2", &FieldValue::Text("one\ntwo".into())).unwrap(); + let reopened = reopen(&doc); + let all = fields(&reopened); + let copy = field(&all, "notes_2"); + assert!(copy.has(flags::MULTILINE), "the copy stays multi-line"); + assert_eq!(look(&reopened, copy), styled, "the copy keeps no background and no border"); +} + +#[test] +fn grid_copy_is_no_longer_part_of_an_xfa_template() { + let mut doc = fixture(); + let source = field(&fields(&doc), "notes").obj; + doc.update_dict(source, |d| d.set(b"PCSom".to_vec(), Object::String(PdfString::text("form1[0].notes[0]")))).unwrap(); + copy_field(&mut doc, "notes", 0, 0, [50.0, 400.0, 250.0, 480.0], "notes_3").unwrap(); + let all = fields(&doc); + assert!(doc.get(field(&all, "notes").obj).as_dict().unwrap().contains(b"PCSom")); + assert!(!doc.get(field(&all, "notes_3").obj).as_dict().unwrap().contains(b"PCSom"), "a new layout would drop a copy bound to the template"); +} + +#[test] +fn grid_copy_redraws_its_own_appearance_not_the_sources() { + let mut doc = fixture(); + // A password field's edited appearance is redrawn in place. + set_value(&mut doc, "pin", &FieldValue::Text("12".into())).unwrap(); + copy_field(&mut doc, "pin", 0, 0, [50.0, 400.0, 150.0, 420.0], "pin_copy").unwrap(); + let source = normal(&doc, field(&fields(&doc), "pin")); + let before = doc.get(source); + set_value(&mut doc, "pin_copy", &FieldValue::Text("123456".into())).unwrap(); + assert_eq!(normal(&doc, field(&fields(&doc), "pin")), source); + assert_eq!(doc.get(source), before, "setting the copy leaves the source's look as it was"); +} + +/// The widget's `/AP /N` stream. +fn normal(doc: &Document, f: &Field) -> pdfcraft_cos::ObjRef { + let ap = doc.resolve(doc.get(f.widgets[0].obj).as_dict().unwrap().get(b"AP").unwrap()); + ap.as_dict().unwrap().reference(b"N").unwrap() +} + +/// The widget's `/AP /N` states and their streams. +fn normal_states(doc: &Document, f: &Field) -> Vec<(Vec, pdfcraft_cos::ObjRef)> { + let ap = doc.resolve(doc.get(f.widgets[0].obj).as_dict().unwrap().get(b"AP").unwrap()); + let states = doc.resolve(ap.as_dict().unwrap().get(b"N").unwrap()); + states.as_dict().unwrap().iter().map(|(k, v)| (k.clone(), v.as_ref().unwrap())).collect() +} + /// A PDF of the given objects (numbered from 1). fn document(objs: &[String]) -> Document { let mut out = b"%PDF-1.7\n".to_vec(); From 54f1f92d324c9c0268ddea91770a8cf4546a5af0 Mon Sep 17 00:00:00 2001 From: KenM76 Date: Fri, 27 Nov 2026 12:54:32 -0500 Subject: [PATCH 3/6] Prepare a form: Copy into Grid from a field's menu Ports #6012's menu and window onto the dialog host. A text field's or one-value check box's right-click menu gains Copy into Grid...; it opens the text field table window with that widget as the source: - the grid starts as two copies below the field, else above, else to the right, else to the left, always on the page; with no room the app says so and nothing opens; - an Area group sets the grid's left, top, width and height in points, held on the page; - every column is named after the first free Copy, Copy2, ... base, so a column added in the window is a copy too (the review's naming point); - preview and Add fields run copy_edit, and the window's automation fields add source, source_widget and rect. The item is disabled with several fields selected or for a field a grid can't copy. "Create Multiple Copies" is another product's wording; the feature is called Copy into Grid here and in the parity notes. The UI test styles a field multi-line with no background or border, copies it from its menu, adds a column, and asserts every copy is named as a copy and has the source's flags and look (the review's point that a blank-field table would pass a count-only test), then that one undo removes them. Co-authored-by: Karim1125 Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas.rs | 27 +++- crates/ui-egui/src/canvas/page_menu.rs | 8 ++ crates/ui-egui/src/tools/field_table_ui.rs | 154 +++++++++++++++++++-- crates/ui-egui/tests/it/prepare.rs | 54 ++++++++ parity/acrobat-features.toml | 3 +- 5 files changed, 234 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index eff7d08b73..b621e46e43 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -2069,6 +2069,29 @@ struct FrameRequests { generation: u64, } +/// Opens what a field's menu item picked in view `index`; Properties is handled with the other property requests. +fn open_field_menu_pick( + app: &mut PdfCraftApp, + ctx: &egui::Context, + index: usize, + pick: FieldMenu, + form: &[pdfcraft_engine::FormField], + generation: u64, +) { + match pick { + FieldMenu::Duplicate(name) => crate::dialogs::duplicate_field::open(app, ctx, name), + FieldMenu::Copies(name, widget) => { + let doc = app.views[index].id; + // As for a drawn table: the window lasts while the form is prepared. + if crate::field_table_ui::open_copies(app, doc, name, widget, form, generation) { + app.left = crate::LeftPanel::Tool("form"); + app.reveal_tools(); + } + } + FieldMenu::Properties => {} + } +} + /// Opens the dialogs and runs the app commands the frame asked for. #[allow(clippy::cognitive_complexity)] fn apply_frame_requests(app: &mut PdfCraftApp, ctx: &egui::Context, index: usize, requests: FrameRequests) { @@ -2107,8 +2130,8 @@ fn apply_frame_requests(app: &mut PdfCraftApp, ctx: &egui::Context, index: usize if let Some((name, w)) = field_props { crate::prepare::dialog::open(app, &name, w, crate::prepare::FieldTab::General); } - if let Some(FieldMenu::Duplicate(name)) = field_menu { - crate::dialogs::duplicate_field::open(app, ctx, name); + if let Some(pick) = field_menu { + open_field_menu_pick(app, ctx, index, pick, &form, generation); } if let Some((page, rect)) = app.views[index].session.links.open_new.take() { app.open_link_props(page, Some(rect), None); diff --git a/crates/ui-egui/src/canvas/page_menu.rs b/crates/ui-egui/src/canvas/page_menu.rs index d6c4ab4b58..35af000533 100644 --- a/crates/ui-egui/src/canvas/page_menu.rs +++ b/crates/ui-egui/src/canvas/page_menu.rs @@ -55,6 +55,8 @@ pub(crate) struct PageMenuPerms { pub(crate) enum FieldMenu { Properties, Duplicate(String), + /// Copy into Grid: the field and the widget the press was on. + Copies(String, usize), } /// What a row of the default menu does when picked. @@ -265,6 +267,12 @@ fn field_rows( if MenuItem::new(tl!("Properties…").to_string()).show(ui).ran { pick.field = Some(FieldMenu::Properties); } + // One field at a time, of a kind a grid can copy. + let copyable = view.session.prepare.also.is_empty() + && form.iter().find(|f| f.name == name).is_some_and(|f| pdfcraft_engine::field_table::copyable(f, widget)); + if MenuItem::new(tl!("Copy into Grid…").to_string()).enabled(can_modify && copyable).show(ui).ran { + pick.field = Some(FieldMenu::Copies(name.clone(), widget)); + } if MenuItem::new(tl!("Duplicate…").to_string()).enabled(can_modify).show(ui).ran { pick.field = Some(FieldMenu::Duplicate(name)); } diff --git a/crates/ui-egui/src/tools/field_table_ui.rs b/crates/ui-egui/src/tools/field_table_ui.rs index e29e1add25..2a97d8452d 100644 --- a/crates/ui-egui/src/tools/field_table_ui.rs +++ b/crates/ui-egui/src/tools/field_table_ui.rs @@ -44,7 +44,9 @@ pub struct FieldTableDraft { /// The page it goes on, 0-based. pub page: usize, pub table: FieldTable, - /// What added columns are named after: the first free "TableK" when the window opened. + /// The field and widget each cell copies (Copy into Grid), or none for new text fields. + pub source: Option<(String, usize)>, + /// What added columns are named after: the first free "TableK" (or "CopyK") when the window opened. base: String, /// The document's edit generation when the window opened: any edit since closes it. generation: u64, @@ -55,7 +57,8 @@ pub struct FieldTableDraft { /// Two drafts are the same table in the same place; what is kept for the next frame isn't part of it. impl PartialEq for FieldTableDraft { fn eq(&self, other: &Self) -> bool { - (self.doc, self.page, &self.table, &self.base, self.generation) == (other.doc, other.page, &other.table, &other.base, other.generation) + (self.doc, self.page, &self.table, &self.source, &self.base, self.generation) + == (other.doc, other.page, &other.table, &other.source, &other.base, other.generation) } } @@ -63,7 +66,7 @@ impl PartialEq for FieldTableDraft { impl Default for FieldTableDraft { fn default() -> Self { let base = "Table1".to_owned(); - FieldTableDraft { doc: DocId(0), page: 0, table: FieldTable::new([0.0, 0.0, 1.0, 1.0], &base), base, generation: 0, laid: None } + FieldTableDraft { doc: DocId(0), page: 0, table: FieldTable::new([0.0, 0.0, 1.0, 1.0], &base), source: None, base, generation: 0, laid: None } } } @@ -94,7 +97,34 @@ impl FieldTableDraft { /// the first base `form` leaves free. pub(crate) fn new(doc: DocId, page: usize, rect: [f64; 4], form: &[FormField], generation: u64) -> Self { let base = field_table::free_base(form.iter().map(|f| f.name.as_str())); - FieldTableDraft { doc, page, table: FieldTable::new(rect, &base), base, generation, laid: None } + FieldTableDraft { doc, page, table: FieldTable::new(rect, &base), source: None, base, generation, laid: None } + } + + /// A grid of copies of widget `widget` of the field `source`, starting as two copies beside it + /// ([`copy_grid`]) on its page (`info`), every column named after the first "CopyK" `form` + /// leaves free. `None` when the widget isn't on a page or there is no room beside it. + pub(crate) fn copies(doc: DocId, info: &PageInfo, form: &[FormField], source: (String, usize), generation: u64) -> Option { + let widget = form.iter().find(|f| f.name == source.0)?.widgets.get(source.1)?; + let page = widget.page?; + let (rect, rows, columns) = copy_grid(info, widget.rect)?; + let base = free_copy_base(form); + let mut table = FieldTable::new(rect, &base); + table.rows = rows; + table.set_columns(columns, &base); + Some(FieldTableDraft { doc, page, table, source: Some(source), base, generation, laid: None }) + } + + /// The edit Add fields applies: new text fields, or copies of the source. + fn edit(&self, info: &PageInfo, form: &[FormField]) -> Result { + match &self.source { + Some((name, widget)) => field_table::copy_edit(&self.table, self.page, info, form, name, *widget), + None => field_table::edit(&self.table, self.page, info, form), + } + } + + /// The window's title, and its group's. + fn title(&self) -> &'static str { + if self.source.is_some() { tl!("Copy into Grid") } else { tl!("Text Field Table") } } /// The table laid out on its page (`info`, in a form whose fields are `form`), worked out again @@ -104,8 +134,7 @@ impl FieldTableDraft { if let Some(laid) = self.laid.as_ref().filter(|l| l.table == self.table) { return Arc::clone(laid); } - let laid = - Arc::new(Laid { table: self.table.clone(), cells: self.table.cells(), edit: field_table::edit(&self.table, self.page, info, form) }); + let laid = Arc::new(Laid { table: self.table.clone(), cells: self.table.cells(), edit: self.edit(info, form) }); self.laid = Some(Arc::clone(&laid)); laid } @@ -148,7 +177,7 @@ impl StackDialog for FieldTableDialog { let refusal = held.refusal().filter(|(_, refused)| **refused == *draft).map(|(reason, _)| reason.clone()); // The layout of a table that did not change this pass is kept in the draft, so the body asks for it again for free. draft.laid(info, form); - let shown = FormDialog::new(tl!("Text Field Table").to_owned(), Bind::bound(&mut *draft)) + let shown = FormDialog::new(draft.title().to_owned(), Bind::bound(&mut *draft)) .ok_label(tl!("Add fields").to_owned()) .enter_confirms(false) .accept_stays_open(true) @@ -197,8 +226,13 @@ impl StackDialog for FieldTableDialog { /// while it can't. fn json_fields(&self) -> Option { let t = &self.draft.table; - let reason = field_table::edit(t, self.draft.page, &self.info, &self.form).err().map(|e| e.said(&i18n::words)); + let reason = self.draft.edit(&self.info, &self.form).err().map(|e| e.said(&i18n::words)); let mut map = serde_json::Map::new(); + if let Some((name, widget)) = &self.draft.source { + map.insert("source".into(), json!(name)); + map.insert("source_widget".into(), json!(widget)); + map.insert("rect".into(), json!(t.rect)); + } map.insert("rows".into(), json!(t.rows)); map.insert("columns".into(), json!(t.columns.len())); map.insert("row_gap".into(), json!(t.row_gap)); @@ -221,6 +255,19 @@ pub(crate) fn open(app: &mut PdfCraftApp, doc: DocId, page: usize, rect: [f64; 4 crate::dialogs::host::open(app, FieldTableDialog { draft, info, form: form.to_vec(), held: HeldAnswer::new() }); } +/// Opens the window for copies of widget `widget` of the field `name` of `doc` in a grid beside it (Copy into Grid), or +/// says there is no room for them. Nothing opens when the field or its page is gone. Whether it opened. +pub(crate) fn open_copies(app: &mut PdfCraftApp, doc: DocId, name: String, widget: usize, form: &[FormField], generation: u64) -> bool { + let Some(page) = form.iter().find(|f| f.name == name).and_then(|f| f.widgets.get(widget)).and_then(|w| w.page) else { return false }; + let Some(info) = app.session.get(doc).and_then(|d| d.info.pages.get(page)).cloned() else { return false }; + let Some(draft) = FieldTableDraft::copies(doc, &info, form, (name, widget), generation) else { + app.notify_tr("There is not enough space beside this field for the copies."); + return false; + }; + crate::dialogs::host::open(app, FieldTableDialog { draft, info, form: form.to_vec(), held: HeldAnswer::new() }); + true +} + /// Closes the window when its page or document is no longer what it was opened on, and adds the table when asked to; once per /// pass from the dialogs' results. pub(crate) fn pass(app: &mut PdfCraftApp, ctx: &Context) { @@ -255,7 +302,10 @@ pub(crate) fn preview(dialogs: &mut DialogHost, doc: DocId) -> Option { /// The window's controls, the names the table will have, and why it can't be added if it can't. Returns whether it can. fn body(ui: &mut Ui, d: &mut FieldTableDraft, info: &PageInfo, form: &[FormField], refusal: Option<&Label>) -> bool { Stack::new().show(ui, |ui, _| { - FieldGroup::new(tl!("Text Field Table").to_owned()).show(ui, |ui, _| { + if d.source.is_some() { + copy_area(ui, d, info); + } + FieldGroup::new(d.title().to_owned()).show(ui, |ui, _| { whole(ui, "Rows", &mut d.table.rows, 1, MAX_ROWS); let mut columns = d.table.columns.len(); if whole(ui, "Columns", &mut columns, 1, MAX_COLUMNS) { @@ -290,6 +340,77 @@ fn body(ui: &mut Ui, d: &mut FieldTableDraft, info: &PageInfo, form: &[FormField laid.edit.is_ok() } +/// Where the copies go, in points from the displayed page's top-left. Each box is held so the area stays on the page. +fn copy_area(ui: &mut Ui, d: &mut FieldTableDraft, info: &PageInfo) { + let [x0, y0, x1, y1] = d.table.rect; + let (mut left, mut top) = (x0.min(x1), y0.min(y1)); + let (mut width, mut height) = ((x1 - x0).abs(), (y1 - y0).abs()); + let (page_width, page_height) = (f64::from(info.width), f64::from(info.height)); + if ![left, top, width, height, page_width, page_height].iter().all(|v| v.is_finite()) { + return; + } + FieldGroup::new(tl!("Area").to_owned()).show(ui, |ui, _| { + length(ui, "Left", &mut left, 0.0, page_width - width); + length(ui, "Top", &mut top, 0.0, page_height - height); + length(ui, "Width", &mut width, 1.0, page_width - left); + length(ui, "Height", &mut height, 1.0, page_height - top); + }); + d.table.rect = [left, top, left + width, top + height]; +} + +/// A length in points held to `least..=most` (to `least` when `most` is under it). +fn length(ui: &mut Ui, label: &str, value: &mut f64, least: f64, most: f64) { + let most = most.max(least); + let mut typed = Some(*value); + Field::new(tl!(label).to_owned()).show(ui, |ui, _| { + NumberField::new(tl!(label).to_owned(), Bind::bound(&mut typed)).range(least..=most).unit("pt").show(ui); + }); + // An emptied field keeps the length; `max` then `min` rather than `clamp`, which panics if the bounds cross. + if let Some(v) = typed.filter(|v| v.is_finite()) { + *value = v.max(least).min(most); + } +} + +/// The first of "Copy", "Copy2", … that no field in `form` is named after (`{base}_…`), so a grid's names start free. +fn free_copy_base(form: &[FormField]) -> String { + let taken: std::collections::HashSet<&str> = form.iter().filter_map(|f| f.name.split_once('_').map(|(head, _)| head)).collect(); + // One of the first `taken.len() + 1` is always free. + (1..=taken.len().saturating_add(1)) + .map(|k| if k == 1 { "Copy".to_owned() } else { format!("Copy{k}") }) + .find(|base| !taken.contains(base.as_str())) + .unwrap_or_else(|| "Copy".to_owned()) +} + +/// Points between a field and the grid of its copies. +const COPY_GAP: f64 = 8.0; + +/// Where a grid of copies of a widget at `rect` (user space) starts: two copies below the widget, else above, else to its +/// right, else to its left, [`COPY_GAP`] from it and wholly on the displayed page. A view-space area with its rows and +/// columns; `None` when there is no room on any side. +pub(crate) fn copy_grid(info: &PageInfo, rect: [f64; 4]) -> Option<([f64; 4], usize, usize)> { + let a = info.user_to_view_f64(rect[0], rect[1]); + let b = info.user_to_view_f64(rect[2], rect[3]); + let (left, right, top, bottom) = (a[0].min(b[0]), a[0].max(b[0]), a[1].min(b[1]), a[1].max(b[1])); + let (width, height) = (right - left, bottom - top); + let (page_width, page_height) = (f64::from(info.width), f64::from(info.height)); + if ![left, right, top, bottom, page_width, page_height].iter().all(|v| v.is_finite()) || width <= 0.0 || height <= 0.0 { + return None; + } + let (tall, wide) = (COPY_GAP + height * 2.0, COPY_GAP + width * 2.0); + let (fits_across, fits_down) = (left >= 0.0 && right <= page_width, top >= 0.0 && bottom <= page_height); + if fits_across && bottom + tall <= page_height { + Some(([left, bottom + COPY_GAP, right, bottom + tall], 2, 1)) + } else if fits_across && top >= tall { + Some(([left, top - tall, right, top - COPY_GAP], 2, 1)) + } else if fits_down && right + wide <= page_width { + Some(([right + COPY_GAP, top, right + wide, bottom], 1, 2)) + } else if fits_down && left >= wide { + Some(([left - wide, top, left - COPY_GAP, bottom], 1, 2)) + } else { + None + } +} + /// A whole number field held to `least..=most`. Whether the number changed. fn whole(ui: &mut Ui, label: &str, value: &mut usize, least: usize, most: usize) -> bool { let mut typed = Some(*value as f64); @@ -455,6 +576,21 @@ fn paint_table(draw: &Draw<'_>, xf: &PageXform, visible: Rect, preview: &Preview mod tests { use super::*; + /// The copies start beside their field, on the page, and say so when there is no room. + #[test] + fn a_copy_grid_starts_on_the_page_without_covering_the_source() { + let info = PageInfo { width: 400.0, height: 300.0, label: "1".into(), crop: [0.0, 0.0, 400.0, 300.0], rotation: 0 }; + let inside = |r: [f64; 4]| r[0] >= 0.0 && r[1] >= 0.0 && r[2] <= 400.0 && r[3] <= 300.0; + let apart = |a: [f64; 4], b: [f64; 4]| a[2] <= b[0] || b[2] <= a[0] || a[3] <= b[1] || b[3] <= a[1]; + // A field near the top of the page (user y up) gets its copies under it; one near the bottom, over it. + for (user, view) in [([10.0, 270.0, 110.0, 290.0], [10.0, 10.0, 110.0, 30.0]), ([10.0, 0.0, 110.0, 20.0], [10.0, 280.0, 110.0, 300.0])] { + let (grid, rows, columns) = copy_grid(&info, user).expect("room above or below"); + assert_eq!((rows, columns), (2, 1)); + assert!(inside(grid) && apart(grid, view), "{grid:?} is on the page and clear of {view:?}"); + } + assert!(copy_grid(&info, [0.0, 0.0, 400.0, 300.0]).is_none(), "a field filling the page leaves no room"); + } + fn draft(columns: usize) -> FieldTableDraft { let mut d = FieldTableDraft::new(DocId(1), 0, [0.0, 0.0, 400.0, 200.0], &[], 0); d.table.set_columns(columns, &d.base); diff --git a/crates/ui-egui/tests/it/prepare.rs b/crates/ui-egui/tests/it/prepare.rs index b8cf14885f..259115168f 100644 --- a/crates/ui-egui/tests/it/prepare.rs +++ b/crates/ui-egui/tests/it/prepare.rs @@ -1042,6 +1042,60 @@ fn duplicating_a_field_onto_every_page() { assert_eq!(doc.can_undo(), Some("Duplicate field")); } +/// Copy into Grid from a field's menu: a calendar day styled once (multi-line, no background, no +/// border) is repeated, and every copy looks and behaves as the day does. +#[test] +fn copying_a_field_into_a_grid_from_its_context_menu() { + use pdfcraft_engine::{Edit, FieldLookPatch, FieldProps}; + let mut h = harness(); + let bare = FieldLookPatch { fill: Some(None), border: Some(None), width: Some(0.0), ..Default::default() }; + let props = FieldProps { multiline: Some(true), appearance: Some(bare), ..Default::default() }; + let ctx_h = h.ctx.clone(); + assert!(h.state_mut().apply_edit(&ctx_h, Edit::SetFieldProps { name: "city".into(), props: Box::new(props) })); + h.execute("form.prepare"); + h.run_steps(3); + let before = names(&h); + let (styled, p) = { + let s = h.state(); + let doc = s.session.get(s.views[0].id).unwrap(); + let f = doc.form.iter().find(|f| f.name == "city").unwrap(); + let on_screen = pdfcraft_ui_egui::forms_ui::field_screen_rect(&s.views[0], &doc.info, f, 0).expect("on screen"); + ((f.flags, doc.field_look("city").unwrap()), on_screen.center()) + }; + h.hover_at(p); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() }); + h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() }); + h.run_steps(3); + h.get_by_label("Copy into Grid…").click(); + h.run_steps(2); + h.get_by_role_and_label(Role::Dialog, "Copy into Grid"); + assert!(table_open(&h)); + assert_eq!(table(&h)["source"], "city"); + assert!(table(&h).get("reason").is_none(), "the starting grid can be added: {}", table(&h)); + // A column added in the window is named as the first one is. + h.get_by_role_and_label(Role::SpinButton, "Columns").focus(); + h.run_steps(1); + h.key_press(egui::Key::ArrowUp); + h.run_steps(2); + h.get_by_label("Add fields").click(); + h.run_steps(3); + let after = names(&h); + let added: Vec<&String> = after.iter().filter(|n| !before.contains(n)).collect(); + assert_eq!(added.len(), 4, "two rows of two copies: {added:?}"); + assert!(added.iter().all(|n| n.starts_with("Copy")), "every column is named as a copy: {added:?}"); + let s = h.state(); + let doc = s.session.get(s.views[0].id).unwrap(); + for name in added { + let f = doc.form.iter().find(|f| &f.name == name).unwrap(); + assert_eq!((f.flags, doc.field_look(name).unwrap()), styled, "{name} keeps the day's multi-line flag, background and border"); + } + assert_eq!(doc.can_undo(), Some("Create multiple field copies")); + h.execute("edit.undo"); + h.run_steps(2); + assert_eq!(names(&h), before, "one undo takes every copy back"); +} + #[test] fn aligning_distributing_and_sizing_several_fields() { use pdfcraft_ui_egui::prepare::{Arrange, arrange}; diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 2ffd5fa2d5..0df9548605 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -5262,10 +5262,11 @@ evidence = [ "crates/automation/tests/it/automation.rs::adding_a_field_table_through_tools", "crates/ui-egui/tests/it/prepare.rs::a_text_field_table_is_drawn_set_up_and_added_in_one_step", "crates/forms/src/tests.rs::grid_copy_preserves_properties_and_has_an_independent_value", + "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", ] -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). Create Multiple Copies in a text field or check box's context menu uses the same grid to copy its properties and initial value into independently named fields; form_add_field_table can do the same with source_field. Missing: copying radio groups, choice fields, buttons, signatures and check boxes with per-widget export values." +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, actions and initial 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)." [[feature]] id = "form.rename-lock-fields" From cbe3eb63cbb21d3455ee7f49daa3f9d3a6d5bdbb Mon Sep 17 00:00:00 2001 From: KenM76 <172507185+KenM76@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:44:32 -0500 Subject: [PATCH 4/6] Copy into Grid: say why the item is off, test the tool's refusals - The undo label is "Copy field into grid" and the parity title "Copy a field into a grid", so no other product's wording is left. The parity notes and the tool text say "value" rather than "initial value", and the notes drop "actions", which no test checks. - form_add_field_table no longer repeats the text-or-check-box test: copy_edit refuses what field_table::copyable says no to, so the tool and the menu refuse the same fields with the same Uncopyable reason. The tool still checks the field and the widget exist. - A disabled Copy into Grid... row says why on hover: several fields are selected, or the field is not a text field or a check box with one export value. - New tests: the tool refuses source_widget without source_field, an unknown field, a radio group, source_widget 0 and a widget past the last, adding nothing; and the hostile-argument sweep sends every hostile value as source_widget, with and without source_field. Co-authored-by: Karim Co-Authored-By: Claude Opus 5.5 --- crates/automation/src/forms.rs | 4 +--- crates/automation/src/tools.rs | 2 +- crates/automation/tests/it/automation.rs | 26 ++++++++++++++++++++++ crates/automation/tests/it/hostile_args.rs | 26 ++++++++++++++++++++++ crates/engine/src/field_table.rs | 2 +- crates/ui-egui/src/canvas/page_menu.rs | 17 ++++++++++---- crates/ui-egui/tests/it/prepare.rs | 2 +- parity/acrobat-features.toml | 4 ++-- 8 files changed, 71 insertions(+), 12 deletions(-) diff --git a/crates/automation/src/forms.rs b/crates/automation/src/forms.rs index 59a9bc7585..abd7f61858 100644 --- a/crates/automation/src/forms.rs +++ b/crates/automation/src/forms.rs @@ -551,12 +551,10 @@ impl Automation { let widget = a.opt_int("source_widget")?.unwrap_or(1); let widget = usize::try_from(widget).ok().and_then(|n| n.checked_sub(1)).ok_or_else(|| bad("source_widget must be at least 1"))?; let field = doc.form.iter().find(|f| f.name == source).ok_or_else(|| bad(format!("field {source:?} does not exist")))?; - if !matches!(field.kind, pdfcraft_engine::FormFieldKind::Text | pdfcraft_engine::FormFieldKind::CheckBox) { - return Err(bad("only text fields and check boxes can be copied into a grid")); - } if field.widgets.get(widget).is_none() { return Err(bad("source_widget does not exist")); } + // `copy_edit` refuses, with the reason, a field `field_table::copyable` says no to. field_table::copy_edit(&table, page, info, &doc.form, source, widget).map_err(|e| bad(e.to_string()))? } else { if a.get("source_widget").is_some() { diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index 4c95f6a6f1..2f33e5de2c 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -596,7 +596,7 @@ pub fn tools() -> Vec { t( "form_add_field_table", "Prepare form: add a table of text fields", - "Divide rect into rows and columns of fields, one per cell, as one undo step. By default these are new text fields; source_field copies an existing text field or check box with its properties and initial value into independent fields. rect in points from the top-left of the displayed page [x0, y0, x1, y1]; rows 1-100 from the top; columns 1-50, or as many as names or widths list. Each column names its cells from its pattern in names: an N on its own after _ - / or : (price_N), # or {row} is the row number, {col} the column number, {seq} counts every cell along the rows, starting at first_row; with none of them the row number goes at the end. Rows count from first_row (default 1). Without names the columns are Table1_N, Table1_c2_N, … using the first free TableK. widths are relative (default equal); row_gap and column_gap are points between cells (default 0). Nothing is added if a cell would be under 4 points or a name would contain a period, repeat, or already exist; the error says which. Returns the fields' names. Undoable.", + "Divide rect into rows and columns of fields, one per cell, as one undo step. By default these are new text fields; source_field copies an existing text field or check box with its properties and value into independent fields. rect in points from the top-left of the displayed page [x0, y0, x1, y1]; rows 1-100 from the top; columns 1-50, or as many as names or widths list. Each column names its cells from its pattern in names: an N on its own after _ - / or : (price_N), # or {row} is the row number, {col} the column number, {seq} counts every cell along the rows, starting at first_row; with none of them the row number goes at the end. Rows count from first_row (default 1). Without names the columns are Table1_N, Table1_c2_N, … using the first free TableK. widths are relative (default equal); row_gap and column_gap are points between cells (default 0). Nothing is added if a cell would be under 4 points or a name would contain a period, repeat, or already exist; the error says which. Returns the fields' names. Undoable.", ) .cmd("form.add.text_table") .with(schema( diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs index 40cc1db67d..e044194379 100644 --- a/crates/automation/tests/it/automation.rs +++ b/crates/automation/tests/it/automation.rs @@ -6040,6 +6040,32 @@ fn copying_a_field_into_a_grid_through_tools() { assert_eq!(result["fields"].as_array().unwrap().len(), 1); } +#[test] +fn copying_into_a_grid_refuses_what_it_cannot_copy() { + let dir = workdir("copy-field-grid-refusals"); + let mut a = auto(&dir); + let doc = ok(&mut a, "doc_open", json!({"path": "a.pdf"}))["doc"].as_u64().unwrap(); + ok(&mut a, "form_add_field", json!({"doc": doc, "page": 1, "type": "text", "name": "source", "rect": [20, 20, 180, 50]})); + ok(&mut a, "form_add_field", json!({"doc": doc, "page": 1, "type": "radio", "rect": [20, 100, 34, 114], "group": "size", "export": "S"})); + ok(&mut a, "form_add_field", json!({"doc": doc, "page": 1, "type": "radio", "rect": [40, 100, 54, 114], "group": "size", "export": "L"})); + let grid = |extra: Value| { + let mut args = json!({"doc": doc, "page": 1, "rect": [20, 150, 180, 230], "rows": 2}); + args.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + args + }; + let refused = |a: &mut Automation, extra: Value, says: &str| match err(a, "form_add_field_table", grid(extra.clone())) { + ToolError::InvalidArgs(m) => assert!(m.contains(says), "{extra}: {m}"), + other => panic!("{extra}: expected InvalidArgs, got {other:?}"), + }; + refused(&mut a, json!({"source_widget": 1}), "source_widget requires source_field"); + refused(&mut a, json!({"source_field": "nowhere"}), "\"nowhere\" does not exist"); + refused(&mut a, json!({"source_field": "size"}), "can't be copied into a grid"); + refused(&mut a, json!({"source_field": "source", "source_widget": 0}), "source_widget must be at least 1"); + refused(&mut a, json!({"source_field": "source", "source_widget": 2}), "source_widget does not exist"); + // Each was refused before anything was added. + assert_eq!(ok(&mut a, "form_fields", json!({"doc": doc}))["fields"].as_array().unwrap().len(), 2); +} + #[test] fn redact_mark_respects_single_page_and_rejects_conflicting_selectors() { let dir = workdir("redact-single-page"); diff --git a/crates/automation/tests/it/hostile_args.rs b/crates/automation/tests/it/hostile_args.rs index 6364d232e7..fe30268b39 100644 --- a/crates/automation/tests/it/hostile_args.rs +++ b/crates/automation/tests/it/hostile_args.rs @@ -562,3 +562,29 @@ fn no_tool_panics_when_the_viewer_sees_fewer_pages_than_the_file_has() { let _ = std::fs::remove_dir_all(&root); assert!(failures.is_empty(), "{} failure(s); the first is: {}", failures.len(), failures.first().map_or("", String::as_str)); } + +/// `source_widget` is 1-based and counted against the source's widgets: no value of it but the +/// source's one widget (or null, which is the default), nor the key without `source_field`, +/// panics or adds a field. +#[test] +fn hostile_source_widgets_are_refused_without_a_panic() { + let mut a = Automation::new().with_root(tmp("grid-source-widget")).expect("root"); + let doc = blank_doc(&mut a); + a.call("form_add_field", &json!({"doc": doc, "page": 1, "type": "text", "name": "source", "rect": [20, 20, 180, 50]})).expect("add the source"); + let mut failures = Vec::new(); + for value in zoo().into_iter().chain([json!(2), json!(usize::MAX)]).filter(|v| *v != json!(1) && !v.is_null()) { + let rect = json!([20, 100, 180, 180]); + for args in [ + json!({"doc": doc, "page": 1, "rect": rect, "rows": 2, "source_field": "source", "source_widget": value}), + json!({"doc": doc, "page": 1, "rect": rect, "rows": 2, "source_widget": value}), + ] { + match catch_unwind(AssertUnwindSafe(|| a.call("form_add_field_table", &args))) { + Ok(Err(ToolError::InvalidArgs(_) | ToolError::Failed(_))) => {} + Ok(Ok(_)) => failures.push(format!("{args} was accepted")), + Ok(Err(e)) => failures.push(format!("{args}: {e:?}")), + Err(_) => failures.push(format!("{args} panicked")), + } + } + } + assert!(failures.is_empty(), "{failures:#?}"); +} diff --git a/crates/engine/src/field_table.rs b/crates/engine/src/field_table.rs index a0ec2e499a..285f8215cc 100644 --- a/crates/engine/src/field_table.rs +++ b/crates/engine/src/field_table.rs @@ -13,7 +13,7 @@ use crate::{Edit, FormField, FormFieldKind as FieldKind, NewField}; pub const LABEL: &str = "Add text field table"; /// The history entry for a grid copied from an existing field. -pub const COPY_LABEL: &str = "Create multiple field copies"; +pub const COPY_LABEL: &str = "Copy field into grid"; /// The edit adding `table`'s cells to `page` (0-based, shown as `info`) of a document whose /// fields are `form`. Refused, with nothing added, when a cell would be too small on the page or diff --git a/crates/ui-egui/src/canvas/page_menu.rs b/crates/ui-egui/src/canvas/page_menu.rs index 35af000533..5a61b218ef 100644 --- a/crates/ui-egui/src/canvas/page_menu.rs +++ b/crates/ui-egui/src/canvas/page_menu.rs @@ -267,10 +267,19 @@ fn field_rows( if MenuItem::new(tl!("Properties…").to_string()).show(ui).ran { pick.field = Some(FieldMenu::Properties); } - // One field at a time, of a kind a grid can copy. - let copyable = view.session.prepare.also.is_empty() - && form.iter().find(|f| f.name == name).is_some_and(|f| pdfcraft_engine::field_table::copyable(f, widget)); - if MenuItem::new(tl!("Copy into Grid…").to_string()).enabled(can_modify && copyable).show(ui).ran { + // One field at a time, of a kind a grid can copy; a disabled row says which it is not. + let why_not = if !view.session.prepare.also.is_empty() { + Some(tl!("Select one field to copy it into a grid")) + } else if !form.iter().find(|f| f.name == name).is_some_and(|f| pdfcraft_engine::field_table::copyable(f, widget)) { + Some(tl!("Only text fields and check boxes with one export value can be copied into a grid")) + } else { + None + }; + let mut copies = MenuItem::new(tl!("Copy into Grid…").to_string()).enabled(can_modify && why_not.is_none()); + if let Some(why) = why_not { + copies = copies.tooltip(craft::ui::contract::TooltipSpec::new(why).disabled_text(why)); + } + if copies.show(ui).ran { pick.field = Some(FieldMenu::Copies(name.clone(), widget)); } if MenuItem::new(tl!("Duplicate…").to_string()).enabled(can_modify).show(ui).ran { diff --git a/crates/ui-egui/tests/it/prepare.rs b/crates/ui-egui/tests/it/prepare.rs index 259115168f..caaca36562 100644 --- a/crates/ui-egui/tests/it/prepare.rs +++ b/crates/ui-egui/tests/it/prepare.rs @@ -1090,7 +1090,7 @@ fn copying_a_field_into_a_grid_from_its_context_menu() { let f = doc.form.iter().find(|f| &f.name == name).unwrap(); assert_eq!((f.flags, doc.field_look(name).unwrap()), styled, "{name} keeps the day's multi-line flag, background and border"); } - assert_eq!(doc.can_undo(), Some("Create multiple field copies")); + assert_eq!(doc.can_undo(), Some("Copy field into grid")); h.execute("edit.undo"); h.run_steps(2); assert_eq!(names(&h), before, "one undo takes every copy back"); diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index 0df9548605..b628f7468c 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -5249,7 +5249,7 @@ notes = "right-click a field ▸ Duplicate: all pages or a range; one field, sha [[feature]] id = "form.multiple-copies" -title = "Create multiple copies of a field in a grid" +title = "Copy a field into a grid" area = "F" tier = "P2" milestone = "M6" @@ -5266,7 +5266,7 @@ evidence = [ "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", ] -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, actions and initial 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 with per-widget export values (refused with the reason)." [[feature]] id = "form.rename-lock-fields" From 01ecdf2c17cbf122fbd3d19c8e6a73b8e44dd76f Mon Sep 17 00:00:00 2001 From: KenM76 <172507185+KenM76@users.noreply.github.com> Date: Fri, 27 Nov 2026 18:51:58 -0500 Subject: [PATCH 5/6] Grid copies: one export-value rule, keep a widget's read-only flag A check box with several widgets is copyable only when every widget has the same on state and the same export value. The forms layer's `copyable_widget` now holds that rule and the engine's `field_table::copyable` calls it, so the preview and the copy agree. Before, a box whose widgets drew different on states without /Opt was copied, and one whose /Opt repeated a single value was refused. A copied check box gets its widget's export value as its /Opt when /Opt lists one value per widget, and no /Opt otherwise, so the copy exports what its source widget did. A widget that is read-only through its own /Ff makes its copy read-only: the copy has one dictionary, and the field's /Ff used to hide the widget's. The automation README and the parity note say which check boxes are refused in the new rule's terms, and the parity entry lists the tests. Co-authored-by: Karim Co-Authored-By: Claude Opus 5.5 --- crates/automation/README.md | 6 +-- crates/engine/src/field_table.rs | 25 +++++---- crates/forms/src/author.rs | 2 +- crates/forms/src/author/lifecycle.rs | 30 +++++++++-- crates/forms/src/lib.rs | 5 +- crates/forms/src/tests.rs | 81 ++++++++++++++++++++++++++++ parity/acrobat-features.toml | 6 ++- 7 files changed, 134 insertions(+), 21 deletions(-) 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" From a591c026b9eefd28154db143247243c21ff72c16 Mon Sep 17 00:00:00 2001 From: KenM76 <172507185+KenM76@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:49:53 -0500 Subject: [PATCH 6/6] Grid copies: do not take a widget's /Ff into the copy When the field had no /Ff, the merge in copy_source copied the widget's /Ff into the copy's one dictionary. The reader takes a button's kind from the field's /FT and /Ff only, so a RADIO or PUSH_BUTTON bit on a check box's widget turned the copy into a radio button or push button. The merge now skips /Ff; the widget's read-only bit still reaches the copy through the read-only branch. Co-authored-by: Karim Co-Authored-By: Claude Opus 5.5 --- crates/forms/src/author/lifecycle.rs | 6 ++++-- crates/forms/src/tests.rs | 22 ++++++++++++++++++++++ parity/acrobat-features.toml | 1 + 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/crates/forms/src/author/lifecycle.rs b/crates/forms/src/author/lifecycle.rs index b4b73f9c5e..ecdaee365c 100644 --- a/crates/forms/src/author/lifecycle.rs +++ b/crates/forms/src/author/lifecycle.rs @@ -435,9 +435,11 @@ fn copy_source(doc: &Document, f: &Field, w: &Widget) -> Result return Ok(field); } // Preserve widget entries that aren't in the field dictionary, including unfamiliar - // annotation keys, while the field's own attributes keep their precedence. + // annotation keys, while the field's own attributes keep their precedence. A widget's /Ff + // is skipped: its radio or push-button bit would change the copy's kind, and its read-only + // bit is carried below. for (key, value) in widget_dict.iter() { - if !field.contains(key) && key.as_slice() != b"AA" && !COPY_DROPS.contains(&key.as_slice()) { + if !field.contains(key) && !matches!(key.as_slice(), b"AA" | b"Ff") && !COPY_DROPS.contains(&key.as_slice()) { field.set(key.clone(), value.clone()); } } diff --git a/crates/forms/src/tests.rs b/crates/forms/src/tests.rs index f36e886ae1..b9accfa616 100644 --- a/crates/forms/src/tests.rs +++ b/crates/forms/src/tests.rs @@ -232,6 +232,28 @@ fn grid_copy_keeps_a_widget_that_is_read_only_on_its_own() { assert!(copy.has(flags::MULTILINE), "and keeps the field's own flags"); } +#[test] +fn grid_copy_of_a_check_box_ignores_its_widgets_button_kind_bits() { + for bits in [flags::RADIO, flags::PUSH_BUTTON] { + let ff = bits | flags::READ_ONLY; + 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(), + "<< /FT /Btn /T (box) /V /Off /Kids [6 0 R] >>".into(), + format!("<< /Type /Annot /Subtype /Widget /Parent 5 0 R /Ff {ff} /AS /Off /P 3 0 R /Rect [20 300 35 315] >>"), + ]; + let mut doc = document(&objs); + assert_eq!(field(&fields(&doc), "box").kind, FieldKind::CheckBox); + copy_field(&mut doc, "box", 0, 0, [20.0, 250.0, 35.0, 265.0], "box_copy").unwrap(); + let all = fields(&doc); + let copy = field(&all, "box_copy"); + assert_eq!(copy.kind, FieldKind::CheckBox, "widget /Ff {ff} must not change the copy's kind"); + assert!(copy.read_only(), "the widget's read-only bit still reaches the copy"); + } +} + #[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 38a4c286ae..e1f6a4911b 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -5269,6 +5269,7 @@ evidence = [ "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", + "crates/forms/src/tests.rs::grid_copy_of_a_check_box_ignores_its_widgets_button_kind_bits", ] 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)."