mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-12-04 13:03:19 -05:00
M6: copy form fields into a grid
Cherry-picked from #6012 (ef57ba58d) onto mainc34c6c5a0. 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.
This commit is contained in:
1 parent
c34c6c5a0b
commit
36b33e3363
14 files changed
+317
-9
No files matched your search
@@ -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
|
||||
|
||||
@@ -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<String> = 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)
|
||||
|
||||
@@ -596,7 +596,7 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
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<ToolDef> {
|
||||
"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"],
|
||||
)),
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -363,6 +363,14 @@ pub enum Edit {
|
||||
name: String,
|
||||
pages: Vec<usize>,
|
||||
},
|
||||
/// 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,
|
||||
},
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<Edit, TableError> {
|
||||
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();
|
||||
|
||||
@@ -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::{
|
||||
|
||||
@@ -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<Dict>, Option<Dict>) {
|
||||
(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
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -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<String> = 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();
|
||||
|
||||
@@ -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 { .. }
|
||||
|
||||
@@ -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"
|
||||
|
||||
Reference in new issue
Block a user