Technical Article

Dynamic XFA Form Runtime in Delphi: HotPDF Transactions

A user types 3 into the item-count field of an XFA claim form. The form's scripts add two rows to a repeating subform, recompute the total, and push the signature block onto a second page. Then a calculate script on one of the new rows fails, or the layout will not settle inside the reflow budget, and the question becomes what state the document is in now: three rows and a stale total, one row and a new total, or something in between. A dynamic XFA filler has to answer that for every keystroke it commits, and the only answer a user can trust is that a rejected edit leaves no trace at all

Why a dynamic XFA form has no fixed field list

ISO 32000-1 §12.7.8 places XFA in an /XFA entry on the AcroForm dictionary, holding an XDP packet stream, and ISO 32000-2 deprecates the mechanism. Deprecation took XFA off the roadmap; it did not take it out of circulation, and forms written against the XFA 3.3 specification are still issued for claims, tax and benefits work. Many of them open to a single placeholder page asking the reader to wait, because every real field lives in the XDP packets rather than in page content

Static XFA can be turned into ordinary widget annotations, and HotPDF does that through ApplyXFAAsAcroForm and FlattenLoadedXFA, with the trade-offs covered in flattening XFA forms into AcroForm fields. Dynamic XFA does not flatten cleanly. Its occur ranges, growable text areas and calculate scripts make the field set a function of the data, so the annotation list you would flatten to does not exist until the user stops typing. For that case HotPDF provides TXFAWidgetRuntime in the HPDFXFARuntime unit: it keeps the XFA DOM live, recomputes layout after every accepted change, and hands your VCL or FMX host a flat array of positioned widgets to paint and hit-test

Opening the form and listing what to draw

The runtime gives your host geometry and state and leaves painting, caret drawing and keyboard routing to you. WidgetCount and Widgets[I] return TXFAWidgetState records with ID, Name, Kind, PageIndex, Bounds in PDF points, Value, EditValue and the Focused, Editing, ReadOnly and Valid flags. Signature and button widgets always come back ReadOnly, and a UI kind the runtime does not edit arrives as xwkUnsupported, also read-only, so the host never offers a text box for a value it cannot store

Treat ID as an opaque string. For a plain field it reads name[n], where n counts earlier occurrences of the same name in layout order, so a second field named amount elsewhere in the layout shows up as amount[1]; instances of repeatable subforms and fields copied onto several pages carry longer, suffixed identities. FocusWidget, BeginEdit, DispatchEvent and HitTest all take that string, and a dynamic form can span several pages, which is why TryGetPageSize exists alongside it

For a PDF already loaded into THotPDF, CreateLoadedXFAWidgetRuntime extracts the XDP packets, uses the first page box as the layout page size and returns nil when the file has no XFA. It also copies the component's XFAJavaScriptEnabled, XFAJavaScriptDLLPath and XFAFormScriptBudgets settings into the runtime options

uses
  HPDFDoc, HPDFXFA, HPDFXFARuntime;

procedure ListXFAWidgets(const AFileName: string; ALines: TStrings);
var
  Pdf: THotPDF;
  Runtime: TXFAWidgetRuntime;
  W: TXFAWidgetState;
  WidgetID: AnsiString;
  PageW, PageH: Double;
  I: Integer;
begin
  Pdf := THotPDF.Create(nil);
  try
    Pdf.LoadFromFile(AFileName);
    Runtime := Pdf.CreateLoadedXFAWidgetRuntime;   // nil: no /XFA entry
    if Runtime = nil then
      Exit;
    try
      // run initialize and form-ready events once, as one transaction
      if not Runtime.InitializeForm then
        ALines.Add('initialize: ' + Runtime.LastDiagnostic);
      if Runtime.TryGetPageSize(0, PageW, PageH) then
        ALines.Add(Format('page 0 is %.0f x %.0f pt', [PageW, PageH]));
      for I := 0 to Runtime.WidgetCount - 1 do
      begin
        W := Runtime.Widgets[I];
        ALines.Add(Format('%s p%d [%.1f %.1f %.1f %.1f] = %s',
          [string(W.ID), W.PageIndex, W.Bounds.Left, W.Bounds.Top,
           W.Bounds.Right, W.Bounds.Bottom, string(W.Value)]));
      end;
      // page-space hit test; the topmost widget wins
      if Runtime.HitTest(0, 120.0, 96.0, WidgetID) then
        Runtime.BeginEdit(WidgetID);
    finally
      Runtime.Free;
    end;
  finally
    Pdf.Free;
  end;
end;

What has to roll back when a commit fails?

Everything the edit can reach, which is far more than the field value. CommitEdit takes a snapshot before it writes anything. The snapshot holds the serialised XFA DOM, every TXFAWidgetState interaction record, LastCalculationPasses and LastReflowPasses, the length of Warnings, the page sizes and page numbering of the current layout, the record cursor, and the script session's checkpoint when JavaScript is enabled

Saving the old field values and writing them back on failure looks like enough. It isn't. Writing to a field whose binding points at a data node that does not exist yet creates that node, and a calculate script targeting an unbound field does the same; a value-only restore puts the old text back but cannot delete the nodes that appeared in the datasets packet, and the next save carries them out of the program. That residue is why the snapshot is the whole serialised document

The commit order is fixed: write the candidate value, run the edited field's validate script, run calculate scripts until a full pass changes nothing, run any lifecycle events the change triggers, then reflow until the layout settles. A failure at any step restores the snapshot, sets LastDiagnostic to the reason, and marks the edited widget Valid = False if validation was the step that refused. A validate script refuses when its result is empty, the text false, or a number equal to zero

HotPDF treats an XFA field commit as one transaction, capturing the serialised DOM, every widget state, the pass counters and the warning count before validating, calculating and reflowing, then publishing or restoring the whole runtime state together
CommitEdit snapshots the document and the runtime state before it writes anything, so a failed validate, calculate or reflow leaves no structural residue behind
function EditAmount(Runtime: TXFAWidgetRuntime;
  const AWidgetID: AnsiString; const AText: UnicodeString): Boolean;
var
  Current: UnicodeString;
begin
  Result := False;
  if not Runtime.BeginEdit(AWidgetID) then
    Exit;                                    // read-only, or no such widget
  Current := Runtime.Widgets[Runtime.FocusedIndex].EditValue;
  if not Runtime.ReplaceSelection(0, Length(Current), AText) then
  begin
    Runtime.CancelEdit;                      // bad range or broken UTF-16
    Exit;
  end;
  Result := Runtime.CommitEdit;              // all or nothing
  if not Result then
    // the DOM, widget list, counters and warnings are back where they
    // were before BeginEdit; LastDiagnostic says which step refused
    ShowMessage(Runtime.LastDiagnostic);
end;

ReplaceSelection is the cheapest place to stop malformed input. It refuses a selection that starts or ends between the two halves of a UTF-16 surrogate pair, replacement text containing an unpaired surrogate, and any result longer than MaxValueChars, with diagnostics such as XFA edit selection splits a Unicode surrogate pair. By the time CommitEdit runs, the candidate is valid UTF-16 and within size

Reflow runs until the layout stops moving

An accepted edit can move every widget below it, so the runtime rebuilds the widget list and repeats until two consecutive layouts match. Each rebuild goes into a fresh list that the host cannot see. The layout pass calls your MeasureText function while it runs and can raise EXFAWidgetRuntimeError when it hits MaxWidgets or MaxLayoutOperations, so the finished list replaces the live one in a single assignment at the end. A host repainting from Widgets[I] sees the old layout or the new one, never half of each

Convergence is judged on a layout signature built from the page count and page sizes, page numbering, and every widget's ID, page index and bounding box rounded to four decimals. When the first rebuild already matches the pre-edit signature, LastReflowPasses stays 0, which is how a host tells a value-only edit from one that grew the form; after a commit, OnLayoutChanged fires only in the second case. Focus, editing state and the in-progress EditValue carry across each rebuild, so inserting a row above the focused field does not throw the caret away

Setting MaxReflowPasses to 0 has a specific meaning: the commit must not move anything. If the rebuilt signature differs from the old one, the commit rolls back with XFA reflow pass budget exceeded. That is a reasonable setting for a fixed-layout form you want to lock against growth; on a genuinely dynamic form it refuses the first edit that adds a row

The HotPDF XFA runtime rebuilds its widget list into a separate owning list while layout runs and calls back into host measurement code, then publishes the finished list with a single assignment that the host cannot observe half-done
The rebuild happens in a private list because layout can raise mid-flight, and the layout signature decides when two consecutive reflows have converged

Why would row two validate against row one?

Because the script ran without knowing which data record it belonged to. A repeating subform with <occur max="2"/> produces several widgets that share a name and differ only in their data row, and a field with <bind match="dataRef" ref="$record.actual"/> can point at the same value as another field named after that node. Evaluate validation and calculation against the document root and every one of those widgets resolves to the first matching node in the datasets packet — row two checks row one's number and passes or fails for the wrong reason

HotPDF records the data node the layout bound to each widget and passes it into every validate and calculate evaluation for that widget. The same context decides where a missing value node gets created when a calculation writes to it, and when nothing writable can be resolved the transaction fails with XFA field has no writable value instead of writing into a neighbouring row. After a write, every other widget bound to the same data value is refreshed, so the two fields in the dataRef example always show the same text. FormCalc semantics overlap with what AcroForm documents get from AcroForm format and calculate scripts, but resolution here follows XFA data binding; bindings that filter records with predicates are covered in XFA binding filters

One operation budget and one deadline per transaction

Script limits apply to the whole transaction, so a form with two hundred calculating fields cannot spend the time limit two hundred times over. CommitEdit starts one remaining-operations counter from ScriptOptions.Limits.MaxOperations and one deadline from MaxElapsedMilliseconds; each validate and calculate call draws from that counter and receives only the milliseconds still left. TXFAWidgetRuntimeOptions.Default sets MaxWidgets to 10000, MaxValueChars to 1048576, MaxCalculationPasses to 16, MaxReflowPasses to 4 and MaxLayoutOperations to 200000, while TXFAFormScriptLimits.Default allows 100000 operations, 500 ms and 64 KB of script text. Below that, TXFADOMLimits caps decompressed input and output at 128 MB, packets at 1024, nodes at 1000000 and nesting depth at 256

The trap is the value 0. CommitEdit reads MaxOperations = 0 as no operation limit and MaxElapsedMilliseconds = 0 as no deadline, so a host that zeroes both to "turn scripts off" removes the brakes instead. Turning scripts off means leaving EnableJavaScript False and keeping the limits positive. For an interactive editor, tighten the elapsed budget below the default rather than raising it: a commit is supposed to finish between two keystrokes, and a form that needs more than half a second per edit is better refused with a diagnostic than left to freeze the UI

Budget layers in the HotPDF XFA runtime, from widget and value limits through script operation and time limits down to the XFA DOM caps, with one operation counter and one deadline shared by every call in a transaction
Script budgets are transaction-wide rather than per script, so two hundred calculating fields cannot each claim a fresh 500 ms
var
  Options: TXFAWidgetRuntimeOptions;
  Runtime: TXFAWidgetRuntime;
begin
  Options := TXFAWidgetRuntimeOptions.Default;
  Options.MaxWidgets := 2000;                             // default 10000
  Options.MaxCalculationPasses := 8;                      // default 16
  Options.MaxReflowPasses := 2;                           // default 4
  Options.ScriptOptions.Limits.MaxOperations := 20000;    // whole transaction; 0 = unlimited
  Options.ScriptOptions.Limits.MaxElapsedMilliseconds := 200;  // 0 = no deadline
  Options.MeasureText :=
    function(const AText: UnicodeString; const AFont: TXFAFontSpec;
      AMaxWidth: Double): TXFATextExtent
    begin
      // MeasureWithHostCanvas is your own routine, returning points
      Result := MeasureWithHostCanvas(AText, AFont.Typeface, AFont.SizePt,
        AFont.Bold, AFont.Italic, AMaxWidth);
    end;
  // in a unit test, inject a fake clock so deadline behaviour is repeatable
  // Options.MonotonicMilliseconds := function: Int64 begin Result := FakeClock; end;
  Runtime := TXFAWidgetRuntime.Create(XDPBytes, 612, 792, Options);
  try
    Runtime.OnLayoutChanged :=
      procedure
      begin
        RepaintAllPages;                                  // your own repaint routine
      end;
    // ... drive the form, then write the filled XDP back out
    XDPBytes := Runtime.SaveToBytes;
  finally
    Runtime.Free;
  end;
end;

The injectable MonotonicMilliseconds clock is there for test suites. With the real clock, a 200 ms budget passes on a developer machine and trips on a loaded build agent; with a fake clock the same test fails or passes every time

Event scripts, JavaScript and threads

DispatchEvent runs a field's event script as the same kind of transaction: snapshot, run the script, rebuild, recalculate, reflow, then publish or restore. The enter and exit activities are handled directly as focus changes. With ScriptOptions.EnableJavaScript left False, which is the default, event scripts are read by a small literal parser that accepts presence assignments to 'visible', 'invisible' or 'hidden', and addInstance, removeInstance, insertInstance and moveInstance calls made through instanceManager or the _name shorthand with integer literal arguments. Anything outside that set fails with a diagnostic such as Unsupported XFA event script syntax and the document stays as it was

Forms that drive their behaviour from general JavaScript need the embedded engine: set EnableJavaScript to True and point QuickJSDLLPath at the engine DLL, or set XFAJavaScriptEnabled and XFAJavaScriptDLLPath on THotPDF before calling CreateLoadedXFAWidgetRuntime. The same transaction budgets still apply, plus the engine's own memory and stack limits in TXFAFormScriptLimits

Two rules keep the host honest. Transactions do not nest: calling CommitEdit from inside an OnLayoutChanged or OnWidgetInvalidated handler returns False with XFA recursive edit transaction is not supported, so queue the follow-up edit and run it after the handler returns. And the class has no internal locking, while layout calls back into your MeasureText code, so create, drive and free each runtime on one thread, normally the UI thread that owns the canvas it measures with. Rich text inside fields is handled as described in XFA exData rich text and hyperlinks

If a claims, tax or benefits project has landed dynamic XFA on your desk, TXFAWidgetRuntime is part of the HotPDF Delphi PDF component, which also covers the AcroForm filling, XFA flattening and rendering work those projects tend to need next