Files
pdfcraft/crates/engine
51d05efb63 M6: copy and paste selected form fields from the Edit menu (#1571) (#8604)
* 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]>
2026-12-04 17:52:12 +01:00
..

pdfcraft-engine

The façade every frontend talks to. It holds the open documents, their edit history and the tool catalogue; frontends never reach past it into the parsing, rendering or editing crates.

word_count::count provides cancellable, page-at-a-time Unicode word and character statistics with optional semantic exclusions; see word-count behavior and limits.

  • Layer: L6. It depends on most of L1–L4 and on nothing above itself. No UI toolkit — egui, winit, eframe and rfd are forbidden below L7, and xtask layers enforces it.
  • The crate denies unwrap/expect/panic!/todo!. Entry points that run untrusted-document code keep a last-resort catch_unwind guard so an escaped panic becomes an error and the user keeps their document.

Two frontends exist on top of it today: pdfcraft-ui-egui (desktop and web) and pdfcraft-automation (headless tools, the CLI and MCP). Anything one can do, the other must be able to do — see app-agents.md rule 14.

When dynamic XFA layout is active, JsRunner does not initialize Acrobat JavaScript with scripts from the PDF container's /Names /JavaScript tree. Those scripts belong to the fallback PDF view and can otherwise show a misleading viewer-compatibility warning. They remain in the document and in Document::document_scripts. Requested console scripts, field actions and XFA events can still show messages; ordinary PDFs, static XFA and shells without an active layout keep their document scripts. Converting XFA to a static form and undoing that conversion switches the context with the document state.

The editing model

Each open document holds a pdfcraft_cos::Document: the object graph plus a copy-on-write overlay.

  1. An edit runs on a clone. On success the previous state is pushed onto the undo stack. Clones share all unchanged data, so a snapshot is cheap — this is what makes 100 levels of undo affordable on a 200 MB file.
  2. After every edit the working file is produced by an incremental write: the original bytes plus one appended revision.
  3. The view is refreshed from those bytes, so what you see is exactly what Save will write.
  4. Saving rebases onto the written bytes, so the next save appends only new edits.

Consequences worth preserving: the original bytes of an opened file are never rewritten in place; a full rewrite happens only where it must (redaction, PDF/A conversion, print imposition, a changed password); and unknown data survives a round trip because nothing is reconstructed that wasn't understood.

API

let mut s = Session::new();
let id = s.open("report.pdf", Some(path), bytes, None)?;   // -> DocId

s.apply(id, Edit::RotatePages { pages: vec![0], degrees: 90 })?;
let label = s.undo(id)?;                                    // "Rotate pages"
s.redo(id)?;

let doc = s.get(id).ok_or("gone")?;                         // &Document: queries, never edits
doc.can_undo(); doc.editable(); doc.allows_printing();
doc.text_blocks(page); doc.page_boxes(page); doc.security_summary();

let bytes = s.save_bytes(id)?;        // incremental: keeps signatures over earlier revisions valid
let bytes = s.save_full_bytes(id)?;   // full rewrite, garbage-collected
s.mark_saved(id, bytes.clone(), path)?;

Edit is one enum of 75 variants — every undoable change in the product, from RotatePages to AddAnnotation, SetFieldValue, ApplyRedactions and AddWatermark. Adding a feature means adding a variant and handling it in apply, which is what keeps undo, the dirty flag, autosave and the automation tools consistent for free.

Session also owns the operations that produce a new document rather than editing one: create_blank, create_from_images, create_from_text, combine, extract, split, split_by_size, reduced_bytes, optimized_bytes, print_pdf, export_data, and the signing family (sign, sign_with_timestamp, timestamp_document, embed_ltv).

Modules

Module What it holds
commands The command registry: id, label, menu, shortcut, and a Needs precondition encoding document security. Menus, the ⌘K palette, shortcuts and the control channel all read it, so every surface agrees on what exists and when it is enabled
catalog Acrobat's "All tools" information architecture as data — groups, sections, icons, hues, and an Availability of Ready, Planned(milestone) or Provider. The UI renders what is not built yet, honestly
actions PDF action dispatch (go-to, URI, named, set-layer-state, JavaScript)
links Link creation, properties, and finding URLs in page text
open_parameters A path's PDF open parameters (manual.pdf#nameddest=Intro, #page=12): the file to open and where to show it. The app and doc_open both read them
js The bridge to pdfcraft-js. forms never depends on js directly; the engine injects it, so a build without JavaScript is possible
xfa, ocr, compare, export Façades over the L3/L4 crates of the same names

AcroForm Keystroke, Validate, Calculate and Format scripts run automatically. Their Print, ShowPanel and SaveAs requests are ignored with a JavaScript console diagnostic; field values, alerts and other requests are retained. Explicit button and console scripts can still request printing (#4088).

Command shortcuts are resolved with CommandSpec::shortcut_for(mac) before displaying or matching them. The Comments binding is Ctrl+M on Windows/Linux; macOS leaves Command+M available for the system Minimize action.

Not done here

  • Rendering is still borrowed. pdfcraft-render wraps hayro and inspects through lopdf (ADR-0004). The engine only sees inspect() -> DocInfo, RenderPool and text::PageText, and that API stays frozen while M2 replaces what is behind it.
  • Performance budgets (misc.performance-budgets) are not set or enforced.
  • Some shipped features are still reachable only from the UI, not through an automation tool; cargo xtask parity lists them; closing that gap is tracked in the execution plan (D4).

doc.text_edit_preview(page, block) prepares a read-only page background with the selected paragraph’s glyphs removed, preserving text positioning, images and colours. It shares the working document’s render configuration and never enters the undo history.