* M12: run XFA forms' JavaScript: calculations, validation, rows, visibility (#60) Laid-out XFA forms had their fields but none of their behaviour: totals didn't compute, "Add row" buttons did nothing, and subforms a check box should reveal stayed hidden. The js crate gains the XFA scripting object model as native boa objects over a snapshot of the form tree: xfa.form navigation by name, SOM resolution (absolute, relative with the containing-subform search, descendants, indexes and wildcards), rawValue/presence/access, instance managers (_name, addInstance, removeInstance, setInstances, count), xfa.host (messageBox, resetData, print, setFocus, gotoURL), xfa.layout page numbers, xfa.event, app, console and util, plus unqualified sibling names as XFA resolves them. Scripts run with `this` bound to the node and yield their completion value; everything they change or ask for comes back as effects. The xfa crate builds the live form tree (instances from the data, values, presence and access with overrides) and the event table from the template, keeps presence and access overrides on the AcroForm (/PCXfaOverrides) so undo and reopening preserve them, adds and removes row instances in the datasets packet through the existing merge pipeline, and lays the form out again on demand. The engine runs initialize and calculate scripts on open (an appended revision, nothing dirty), exit, validate and calculate after a field changes (a failing validate shows its message and keeps the value, as Acrobat does), and click scripts for buttons through run_javascript, so the app's buttons and the js_run tool work unchanged. Values a script sets go to the fields and the data at once; rows and visibility changes re-lay the form out. All of it is one undo step. JavaScript off turns it off. FormCalc scripts are recognised and reported, not run. Bounds: script length and nesting as before, loop and recursion limits, at most 1000 instances added per run, 2000 scripts and 50 re-layouts per event; a calculate script that adds rows, or a click script looping on addInstance/setInstances, ends quickly with a bounded form (tested). Checked on IRCC's IMM 5669: opens with its page-number scripts, the Print button's xfa.host.print runs through js_run, fill and save keep the original bytes. * M12: Save and SaveAs named actions run the file commands (#60) XFA forms' Save buttons are app.execMenuItem("SaveAs"), which the layout turns into a SaveAs named action; the shell answered it with "the SaveAs action isn't supported yet". Named Save and SaveAs now run file.save and file.save_as, like Named Print opens the print dialog. The buttons test covers Save against a file on disk (SaveAs opens the native dialog, which a headless test must not). * M12: bound XFA form scripts against hostile forms (#60) Review fixes for the XFA scripting PR (#230): - Effects: values, presence and access set again on the same object merge (last wins, behind order-dependent effects); 10k effects, 100 message boxes and 1000 console lines per script and per event, reported when hit. An event's data writes are kept in memory and written as one rewrite of the datasets packet; later writes in the same edit replace that stream in place. - form_tree stops at 200k objects and says so; forms without scripts build no live form and run nothing. - Only click scripts may print, save, open links or move the focus; others are noted in the console. Open-time messages and errors show right after open. - Lower loop limits for initialize/calculate/validate, a time budget per event after which remaining scripts are skipped and reported, and a per-script time limit after which a runaway script is abandoned and the document's scripts turned off. - What open-time scripts change is noted in the XFA warnings. - A document's Named /Save no longer writes the file on click (SaveAs opens the Save As dialog, as a script's execMenuItem does). - XFA click scripts are no longer written as /S /JavaScript actions: the button carries /PCXfaClick and runs by SOM path. Private keys documented. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Brandon Thomas <echelon@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
pdfcraft-xfa
XFA forms (XFA 3.3, the template and layout parts). Layer L3; depends on pdfcraft-cos and
pdfcraft-fonts only.
A dynamic XFA form is a PDF shell around an XML template (/AcroForm /XFA): one placeholder page
("requires Adobe Reader") and /NeedsRendering true. Viewers without an XFA engine show the
placeholder. This crate reads the template, lays it out, and writes ordinary pages and AcroForm
fields into the document, so everything else in PdfCraft (rendering, filling, saving, printing,
the automation tools) works on it unchanged. The engine does this when it opens such a form.
What it does
-
Packets (
read_packets): the XDP from one stream or the(name, stream)array; UTF-8 and UTF-16; capped at 64 MB. -
Template (
parse): subforms, areas, fields, draws, exclusion groups, page sets with page areas, content areas and media; measurements in mm, cm, in, pt and px; fonts, paragraphs, margins, borders (edge order rules), captions with reserves, check-button items, pictures, rich text (exDataXHTML: paragraphs,br, bold/italic/underline/size spans, embedded fields), inline JPEG images, lines, rectangles, occurrences,breakBefore/breakAfter, overflow leaders,columnWidthsandcolSpan. -
Layout (
layout): positioned,tb,lr-tb/rl-tb,tableandrowlayouts; a container without a width is as wide as its content; flow across content areas and pages with page masters chosen by occurrence; a table's header row repeats after a break; presencehiddentakes no space,invisibletakes space; repeating subforms get their initial instances; fields that compute the page number or count on layout show the numbers. -
PDF (
pdf::write_form): pages with content streams in the standard 14 fonts (Arial and friends → Helvetica, Courier New → Courier, serif faces → Times; nothing is embedded), JPEG XObjects, and widgets: text (multi-line, max length, alignment), date (Acrobat'sAFDateformat and keystroke actions from the picture clause), check boxes and radio groups (fromexclGroup), push buttons with Reset / Print / Save As / URI actions recognised from their scripts. Appearance streams are left empty for the forms layer to generate. Each field keeps its SOM path in/PCSom; the AcroForm gets/PCXfaLayoutso a saved form is not laid out twice. The XFA packets stay, so Adobe's viewers keep rendering the form from them. -
Data (
data): thedatasetspacket. On layout, a field takes its value from the data node at its SOM path (dates in ISO form, check and radio states by their on values), and a repeating subform or row gets as many instances as the data has.write_datasetsmerges the AcroForm fields' values (by/PCSom, or by the Designer field names of a static form) into the existingxfa:data: only the bound nodes' text changes and missing nodes are added, so unbound data, other namespaces, attributes and comments stay byte for byte. Values it can't write (a node holding structured content, absurd SOM indices, a packet that is neither UTF-8 nor UTF-16) come back as warnings; UTF-16 packets are written back as UTF-16.read_valuesgoes the other way, so a form filled here shows its values in Adobe's viewers and a form filled there shows them here. The engine does both: values on open (recorded in the document's warnings), the packet after every form edit.
Layout measures each container once per (node, width): width-less containers would otherwise be measured exponentially often in their nesting. A measurement budget backs this up.
-
Scripts (
script): the live form as scripts see it (form_tree: the instance tree with values, presence and access, and theScriptEvents in document order, built withinMAX_FORM_NODESobjects and cut short, withtruncatedset, past that;has_scriptssays whether a template has any, and the engine skips all of this for forms without), the presence and access overrides scripts make, rows added and removed in the data (DataOps, applied to the in-memoryDataNodewhile an event runs and written bywrite_data_opsas one rewrite of the datasets packet per event), andrerender, which lays the form out again from template, data and overrides. The scripts themselves run in thejscrate's XFA object model; the engine runs initialize and calculate on open, change, exit, validate and calculate after a field changes, and click for buttons.Private keys PdfCraft writes (other viewers ignore them):
Key Where Holds /PCSomgenerated fields the field's SOM path, so values go back to the data /PCXfaLayoutAcroForm what laying out produced, so a saved form is not laid out again /PCXfaOverridesAcroForm << /Presence << /som (hidden) … >> /Access << /som (readOnly) … >> >>: presence and access scripts set, by SOM path (instance 0 of a repeating subform stands for all); applied to the template before every layout, so undo, save and reopen keep them. Adobe's viewers draw from the XFA packets and don't read it; at most 10 000 entries are read or written/PCXfaClickgenerated push buttons true: the template has a click script for this button. Such buttons carry no/A: XFA JavaScript is not Acrobat JavaScript, so it is never written as a/S /JavaScriptaction other viewers would run. PdfCraft finds the script by the field's/PCSom
API sketch
if pdfcraft_xfa::is_dynamic(&doc) {
let report = pdfcraft_xfa::render_into(&mut doc)?; // pages, fields, warnings
for f in pdfcraft_forms::fields(&doc) { pdfcraft_forms::redraw_field(&mut doc, &f.name)?; }
}
let form = pdfcraft_xfa::layout_xml(template_xml)?; // pages of items, for tests
Deliberately not done (yet)
- Data binding is the default one only: explicit
bind refexpressions, global binding and data descriptions are not followed, and no standalone XML or XDP data file is imported or exported. - Scripting. JavaScript only: FormCalc scripts (the default language of older forms) are
detected and reported, not run. The object model covers what forms commonly use (
xfa.formnavigation and SOM resolution,rawValue,presence,access, instance managers,xfa.hostmessages, reset, print, focus and URLs,xfa.layoutpage numbers,xfa.event); notxfa.template, data descriptions,xfa.connectionSet,border/font/uiproperties (reads give a sink that accepts writes),execEvent, or the change event per keystroke. Validate failures show their message and keep the value, as Acrobat does for scripts. A hidden instance of a repeating subform hides every instance (overrides apply to the template). A repeating subform shows what its data holds once the data holds any instance, else itsinitialcount, and never fewer than one (occur min="0"still shows one row). Each script runs in a fresh engine on its own thread; a form with hundreds of calculate scripts pays that on every field change (a shared engine per event is the obvious next step). - Script limits. Forms run their scripts on open without being asked, so the engine bounds each event: a script's effects (values set again on the same object merge, the last wins; 10 000 effects, 100 message boxes, 1 000 console lines per script and per event), its loop iterations (100 000 per call frame for initialize, calculate and validate, 1 000 000 for click and change), 2 000 scripts and 50 relayouts per event, and 3 s (open, changes) or 5 s (click) of scripts per event, after which the rest are skipped and reported. Only a click may print, save, open a link or move the focus; other events asking are noted in the console. What open-time scripts change is noted in the document's XFA warnings. Known gaps: the engine's loop limit is per call frame, so loops inside nested calls can run far longer; such a script is abandoned after 1 s (3 s for a click) on its thread, which keeps running until the engine's own limits end it, and the document's scripts are turned off. Memory a script allocates is not capped (the same holds for AcroForm JavaScript).
- Static XFA forms (
/NeedsRenderingabsent, AcroForm fields present) keep their AcroForm; only their data is read and written. - Choice lists are text fields; signature, image, barcode and password fields are left blank;
PNG and GIF images,
keepconstraints,subformSetrelations,rl-tbis mirroredlr-tb, font metrics are the approximate Helvetica ones, and line heights are 1.15 × size. - Acrobat cannot be an oracle here (clean-room rules): layout follows the specification, and fidelity has been checked by eye on real government forms, not pixel-compared.