mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-12-04 13:03:19 -05:00
* M6: copy and paste selected form fields (fixes #1571) [KenM76: rebased onto main. copy_field moves to crates/forms/src/author/copy.rs (author.rs is split), Edit::CopyField to crates/engine/src/edit.rs, labels.rs and run.rs, the tool to dispatch.rs, the test to tests/it/automation.rs. The i18n/*.tsv rows are dropped (catalogs now live in craft-i18n), and the Prepare ⌘C/⌘V key handling is dropped here because crates/ui-egui/src/prepare.rs and its raw key events are gone; it is rebuilt on the edit.copy and edit.paste commands in a later commit.] * M6: a copied field keeps an inherited MaxLen and its buttons' /Opt values, and a signature copies blank [KenM76: rebased onto main; applied to crates/forms/src/author/copy.rs.] * M6: a copied button keeps an inherited /Opt, and on states named after /Opt positions are renumbered [KenM76: rebased onto main; applied to crates/forms/src/author/copy.rs.] * M6: a pasted field has a look of its own copy_field shared the source's appearance streams, and its /MK and /BS when they were indirect. Restyling a copy, or filling in a copy whose look is redrawn in place (a password field), then changed the source. Each copied widget now gets its own copies of the streams its /AP reaches, and a direct /MK and /BS. The copy also drops /NM and the XFA binding keys, and takes what the field inherits from tree::inherited rather than a second walk of its own. Tests: a restyled or refilled copy leaves the source alone; a transparent, borderless multiline field (a calendar day) pastes onto another page with its flags, look and appearance. Co-authored-by: Marco Arnulfo <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]> * M6: copy and paste the selected fields from the Edit menu while preparing a form Copy (Edit menu, Ctrl+C) in Prepare a form takes the selected fields and puts their names on the clipboard as text; Paste (Ctrl+V) adds a copy of each on the current page as one undo step, "Paste fields", and selects the copies. On their own page the copies land 18 pt right and down, one step more per paste; on another page, in place. Paste brings the fields back only while the clipboard still holds their names, so pasting other text does not paste stale fields. The paste rides the edit.copy / edit.paste commands, so it works from the menu as well as the keys. It keeps Marco's paste guard (no paste under a dialog, none into a document that forbids changes). Parity: form.copy-paste-fields lists the UI tests, and its notes say what is still missing: Cut, and pasting into another PDF (#2543). Co-authored-by: Marco Arnulfo <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]> * M6: a pasted field moves right and down as the page is shown The Prepare paste step now goes through the page's view transform, as form_copy_field's dx/dy already did, so on a turned page the copies still land right and down on screen. Prepare keeps Paste for its fields: a paste whose fields have since been deleted, or a picture on the clipboard, pastes nothing there, as before. copy_field is split into helpers (picking the widgets, the field half, the /Opt renumbering, the widget half, attaching to the tree) with no change of behaviour, and form_copy_field looks its page up with get. Co-authored-by: Marco Arnulfo <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(forms): a field copy's /DV never names a button it lacks A check box or radio copy made without the widget its /DV names now gets /DV /Off. Before, reset sent that state to the copy, write_value refused it (Invalid), and reset_with_formatting stopped there, so Clear form failed for every field in the document. renumber_states also renames /AP /R with /N and /D, so a renumbered button keeps its rollover look. Tests: a_radio_copy_without_its_default_button_still_resets, a_radio_copy_with_its_default_button_keeps_it, copying_a_numbered_radio_button_renames_its_rollover_look. Each fix reverted on its own fails its test; with the /DV fix reverted, reset itself returns Invalid("\"size1\" has no option \"S\" (options: L)"). Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(forms,ui-egui): address #8604 review of field copy and paste - A one-widget copy merges the field's and the widget's /AA, so the field's calculate/format/keystroke/validate triggers survive the merge. - Copying fields in Prepare cancels a running whole-document text copy, so its older text cannot land over the field names. - Copy remembers each widget's object, not its index; paste finds its current position and skips one deleted since. - The paste step is turned back by the view rotation, so a paste in a turned view still moves right and down on screen. Each fix's test fails with that fix reverted. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(forms): compare a copied button's default as name bytes `off_unless_copied` compared the raw `/DV` name with the escaped text of each copied widget's on state, so a state such as `/A#23B` (text "A#23B", bytes "A#B") never matched and a copy that kept the default button lost its `/DV`. Compare against `name_bytes(on_state)`. `a_copy_keeps_a_default_whose_name_has_a_hash` fails with the old comparison (`/DV` became `/Off`). Also write the turned-view paste test's clipboard text as "consent\nshade", like the other paste tests. Co-Authored-By: Claude Opus 5.5 <[email protected]> * Keep radio copies and per-page paste offsets consistent --------- Co-authored-by: Marco Arnulfo <[email protected]> Co-authored-by: KenM76 <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: FredApps <[email protected]> Co-authored-by: FredApps <[email protected]>
pdfcraft-forms
Interactive forms (AcroForm, ISO 32000-2 §12.7). Layer L3; depends on pdfcraft-cos and
pdfcraft-fonts.
API
let all: Vec<Field> = fields(&doc); // terminal fields with widgets, options, flags, /DA
let snapshot = fields_with_adopted(&doc); // fields and page-only adoption count in one pass
let all = snapshot.items;
let adopted = snapshot.adopted_page_fields;
set_value(&mut doc, "name", &FieldValue::Text("Ada".into()))?;
set_value(&mut doc, "agree", &FieldValue::Check(true))?;
set_value(&mut doc, "size", &FieldValue::Radio(Some("L".into())))?;
set_value(&mut doc, "toppings", &FieldValue::Choice(vec!["Ham".into()]))?;
// Many values: as set_value one by one, but reading the form once and recalculating once.
let results: Vec<Result<(), FormError>> = set_values(&mut doc, &[("name".into(), FieldValue::Text("Ada".into()))])?;
reset(&mut doc, None)?; // Clear form (back to /DV)
// Prepare a form
let name = add_field(&mut doc, 0, [72.0, 700.0, 216.0, 722.0], &NewField::Text { multiline: false }, None)?; // "Text1"
set_props(&mut doc, &name, &FieldProps { name: Some("email".into()), required: Some(true), ..Default::default() })?;
// A partial appearance edit keeps each widget's other styles and custom /DA font.
set_props(&mut doc, "email", &FieldProps {
appearance: Some(LookPatch { width: Some(3.0), fill: Some(None), ..Default::default() }),
..Default::default()
})?;
delete_field(&mut doc, "email")?;
// A table of text fields (view space, y down), laid out and named before any of it is added:
// refused whole for a cell under MIN_FIELD_SIDE or a name with a period, repeated or taken.
let names = all.iter().map(|f| f.name.as_str());
let base = table::free_base(names.clone()); // "Table1", or the next one free
let mut grid = table::FieldTable::new([40.0, 240.0, 240.0, 360.0], &base);
grid.set_columns(2, &base);
let cells: Vec<table::Cell> = grid.cells_for(names)?; // "Table1_1", "Table1_c2_1", …
Behaviour
fieldsandfields_with_adoptedkeep their last reading on each thread with the state of the document it read (pdfcraft_cos::ReadState, which any change to the document replaces), and give a copy of it to a document that still reads as that state. A form edit reads the fields in several steps (filling, recalculating, the XFA data, the view), most with nothing changed in between, so it walks a form once (twice on a laid-out XFA form, whose data is written in between);form_reads_on_this_threadcounts the walks, for tests.- Automatic field detection considers the first 2,000 drawn rectangles in input order for combs, check boxes and empty text boxes. Check-box label detection considers at most 2,000 drawn/existing widget rectangles combined, before filtering or deduplication. Unusually complex pages may therefore have partial proposals, returned in reading order; existing widgets always exclude overlapping proposals, even beyond the label budget. A balanced spatial index avoids repeated full scans, with a shared 128,000-step query budget. If adversarial geometry exhausts it, unverified proposals are omitted, not accepted. As the input supplies widget geometry only, any existing small square widget can reserve a nearby label.
- Inheritable attributes (
/FT,/Ff,/V,/DV,/DA,/Q,/MaxLen) are resolved down the field tree; the form's/DAand/Qare the last fallback. - Text and choice fields get new appearance streams (
/Tx BMC … EMC): auto-size (0 Tf), comb (cells parted in the border colour), multiline wrapping, password masking, quadding,/MKbackground and border, list-box selection. The/DAfont is used when/DRhas it as a simple font or a composite font with a predefined Unicode CMap; otherwise Helvetica (WinAnsi). Thai in a text field or combo box that the font can't hold is drawn from the craft-fonts Thai face with Add text's writer (pdfcraft_fonts::shaped_text), beside the field's font, keeping/DA; a build without a Thai face refuses it. Any other value or button caption the font can't hold (Chinese in a Helvetica field, a character beyond U+FFFF in a UCS-2 CMap) is kept, as Acrobat keeps it:/Vis stored as typed, the appearance draws?for those characters, the widget is marked with the first one (pdfcraft_fonts::UNDRAWN_MARK, cleared once all of it can be drawn) and the form sets/NeedAppearances, so other viewers draw the field from its value with fonts that have them. Not in a document that declares PDF/A, which forbids that flag (declares_pdfa: the bytespdfaid:partin XMP metadata each filter stage of which decodes within 8 MiB, the cap preflight's Standards panel reads it with; preflight reads the identifier by its namespace, so a packet that gives that namespace another prefix declares PDF/A there and not here).undrawn_fieldslists the marked fields; the engine reports each edit that draws one, and flattening refuses to make that?permanent. - Displaying a form that leaves its appearances to the viewer (
/NeedAppearances, or a text or choice widget with no/AP /N):with_field_appearancesreturns a copy with those widgets drawn from their values, as typing them would draw them; the engine shows and prints that copy and saves the file as it was (#3470).with_field_appearances_cachedkeeps each widget's drawing while the objects it was drawn from are the same (FieldAppearanceCache), so typing in one field redraws that field, not the form. Check boxes and radio buttons with no appearance for their state are drawn from/MK(border, background, and when on the/MK /CAZapfDingbats symbol in the/DAcolour), and with/NeedAppearancesso is every one that has an/MK, over the appearance the file carries; push buttons with none are drawn from/MK,/BSand their caption. - Check boxes and radio buttons switch
/Vand each widget's/AS. Widgets with no appearances get PdfCraft's own (a drawn check mark or dot; no symbol font needed). - Imported
/MaxLen 0is treated as unlimited (also clearing an inherited limit), while the original entry is preserved. Positive limits still apply. - Values are validated (options,
MaxLen, single vs multi-select, NoToggleToOff, read-only) and a failed call changes nothing. - Native AF recognition stops at the first genuine matching function call. If its arguments
are unsupported, the complete action remains a custom script for the caller's
Scriptsinterpreter; a later literal call must not replace the original conditional validation. Async for-of loop headers and bodies do not expose AF-looking text inside regex literals. - Moving choice fields preserves their own options rather than copying an ancestor's
/Opt; inherited check-box and radio-button export mappings remain intact. FieldProps::appearanceapplies aLookPatchindependently to each widget.Nonekeeps a property;Some(None)removes a border/fill colour. Unchanged/DA, custom font resources, widget-specific/DAoverrides, indirect/MKand/BScontents, dash arrays and unknown dictionary keys are preserved. It is mutually exclusive with the completelookreplacement. Use the engine'sEdit::Batchto change several fields atomically in one undo step./RV(rich text) is removed when a value is set so it can't contradict/V.- New fields follow Acrobat: names Text1, Check Box1, Group1 (radio groups), Dropdown1, List Box1,
Button1, Date1, Signature1;
/Helvis added to/DR; appearances are drawn at once. Radio buttons joining a group become kid widgets with their own export state. Renaming changes only the last part of a dotted name. - Renaming a field renames it in every Calculate script that reads it
(
af::rename_in_calculation):AFSimple_Calculatefield lists, simplified field notation (theBVCALCcomment and its translation), andgetFieldcalls whose argument is the name as one string literal. The rest of each script is kept as written. Names built at run time, a script stream that isn't UTF-8, other events' scripts and a name another field still has are left alone.calculations_changedcompares two readings of a form to say which formulas an edit rewrote. - The calculation order (
/CO, §12.7.3):calculation_orderlists the calculated fields in the orderrecalculateruns them, each with its field object (two can share a name in a malformed form), with the fields each formula reads (Calculate::reads,af::calculation_reads; names built at run time aren't known) and what is wrong with the order: a field reading one that calculates later, a loop, a field/COleaves out, and/COentries that calculate nothing. Two issues are about the formula itself: it reads a field the form doesn't have (MissingField; the field of that name and a field under it count as there, as recalculation andgetFieldfind them, but not an Acrobat widget name such asprice.0, which neither resolves), or its script builds names at run time (BuiltNames,af::reads_built_names), so its reads are incomplete.CalculationOrder::fixedis Fix order: a stable topological sort that keeps the current order wherever it can and leaves loops as they are.set_calculation_orderwrites/COafresh. A field that gets a calculation joins the end of the order; one whose calculation changes keeps its place. Widget::captionreads a push button's normal label (/MK /CA, including indirect values).FieldProps { caption: Some((widget_index, text)), ..Default::default() }changes or clears that label, independently of the field name. The index is 0-based. A label-only edit redraws just that widget, copying shared/indirect/MKand appearance dictionaries before editing. Other widgets, actions, icons, rotation and unknown entries are preserved. Existing icon-only layouts keep hiding the caption; caption rendering retains the existing Helvetica/WinAnsi limits and reports unavailable characters as above.
Not yet
Rich-text values and exact appearance metrics/layout remain incomplete. JavaScript
execution and FDF/XFDF exchange are integrated through the engine; this crate provides
field actions and native AF rules. /MK /R rotation (0, 90, 180, 270) is drawn into the
appearance.
Button export values
FieldProps::export_value edits a zero-based widget's /Opt value while preserving appearance names, /AP, /AS, /V and /DV. Widgets sharing an on-state remain consistent. Export-only changes do not regenerate appearances. Invalid indices, empty/Off values and ambiguous/conflicting mappings are rejected. Field::export_values resolves selected states for data export.