Interactive Dynamic XFA Widget Runtime

Version 2.1207.12 adds JavaScript and compiled FormCalc execValidate() parity across Form, subform, exclusion-group and field scopes, target errorText exposure in validationState listeners, and post-barrier session journal replay and rollback; versions 2.1207.2 through 2.1207.11 cover native explicit, interactive, lifecycle, topology-mutating and remerging validation

Version 2.1206.0 adds native validation-picture matching before scriptTest, with independent policies, inherited messages and rollback on refusal

Version 2.1205.7 skips validate/script execution for empty or explicitly null field and exclusion-group values, including direct HPDFXFAEvaluateFieldScript calls and prepared standalone contexts; skipped results succeed with no executed script

Nonempty values, including a preserved space, retain normal script validation; valueless subform containers are not treated as empty scalar fields, and foreign or detached field/data nodes retain their live-document diagnostic

This empty-value rule does not add full nullTest or calculated-input override handling: ordinary clearing is not an explicit nullTest trigger, and the script API remains distinct from complete form validation

Code39 and Extended Code39 fields share the native vector appearance and committed-value workflow, with authored width ratios and optional Mod43 checksum legends

Code128 barcode fields generate vector bars and legends, preserve module sizing and refresh appearances from committed runtime values

TXFAWidgetRuntime provides a host-neutral interaction model for dynamic XFA forms without converting them into AcroForm fields or flattening their content

The runtime exposes deterministic widget bounds and state so a desktop, service, or custom renderer can supply its own input, painting, accessibility, and event loop

Create a runtime

Create the runtime directly from XDP bytes or call THotPDF.CreateLoadedXFAWidgetRuntime after loading a PDF whose AcroForm contains a single-stream or packet-array /XFA entry

var
  Runtime: TXFAWidgetRuntime;
  State: TXFAWidgetState;
begin
  Runtime := PDF.CreateLoadedXFAWidgetRuntime;
  try
    if (Runtime <> nil) and (Runtime.WidgetCount > 0) then
    begin
      State := Runtime.Widgets[0];
      Runtime.FocusWidget(State.ID);
      Runtime.BeginEdit(State.ID);
      Runtime.ReplaceSelection(0, Length(State.Value), 'Updated value');
      if not Runtime.CommitEdit then
        raise Exception.Create(Runtime.LastDiagnostic);
    end;
  finally
    Runtime.Free;
  end;
end;

The loaded-document factory is read-only with respect to the PDF object graph and existing XFAFlattenWarnings; saving the document retains its original /XFA and /NeedsRendering entries

Configure TXFAWidgetRuntimeOptions.MediumResolution, or the component's XFAMediumResolutionOptions before its factory call, for one-time medium prototypes and supplied stock sizes; expanded prototype state survives SaveToBytes, while a new stock-backed session needs an equivalent provider/configuration

Interaction model

Ancestor input listeners receive eligible descendant dispatch and pending text changes while retaining the original source target and the listener's own accepted context

Ancestor focus events execute matching subform and exclusion-group handlers only when focus crosses their boundaries, with parent validation and accepted per-instance contexts

Interactive commits synchronize existing native scalar values in hidden and invisible aliases, including actual repeated data scopes and byte-exact rollback

Typing and paste change events

Version 2.1161.0 executes the edited field's change script during ReplaceSelection, before accepting the new editing buffer; handlers can transform the inserted text and selection window through the interactive event payload

The event exposes stable prevText, writable change, selStart and selEnd, and a read-only newText that reflects those properties immediately; indices count UTF-16 code units and cannot split a surrogate pair

A failed change transaction restores the native XML, widget state, editing buffer, focus and script state; successful ordinary typing remains pending until CommitEdit or a focus-driven commit

CommitRichTextEdit validates and commits the full body using the same calculation and reflow transaction as CommitEdit. The widget's plain text uses line feeds before and after XHTML paragraphs and divisions when they separate visible text. Adjacent block boundaries share one line feed, and a final block adds no trailing line feed. Explicit br breaks remain in the plain value. Whitespace-only text directly under body and content in head, style or script stay out of the plain value. XDP save and reload preserve the styled body. Failed validation or invalid XHTML leaves the edit open for retry. Hosts supply the rich editing UI and submit the markup directly

For a bound edit, the XHTML body is stored on the dataset value. Widgets sharing that binding refresh together, and portable PDF export reads the bound XHTML for rich-enabled fields

When the current value is rich text, CommitEdit and commits triggered by moving focus preserve the XHTML if the submitted plain text matches its current plain value. A changed plain value replaces the XHTML, including when the edit clears the field. Use CommitRichTextEdit to submit new styling

Atomic validation and calculation

Explicit required-value validation for rich text uses the widget's plain text projection for local and bound values. A styled value containing visible text satisfies nullTest. A body containing only style or script content is empty for this check

When an external JavaScript evaluator runs field validation, the current rich field's event.value and this.rawValue contain the same plain text as the widget, including line breaks between blocks

The external evaluator's named field lookups, including xfa.resolveNode(name).rawValue, use matching Form fields before falling back to XML node names. xfa.values(name) returns matching fields in Form instance order, using each instance's own data binding even when the data element has a different name. Plain text and empty values occupy their original positions alongside projected XHTML values

A multi-select field bound to repeated data elements exposes its selected export values as one line-feed-delimited field value in data order. External JavaScript named lookups and the current field value use the same representation

External JavaScript named lookups also read the selected export value of a radio button exclusion group, including groups stored as separate bound member values. The member fields remain available by their own names

The callback also accepts absolute Form paths such as $form.main.row[1].amount[0] and xfa.form.main.row[*].amount[0] in its value lookups. A segment without a selector uses the first occurrence. Wildcard results follow Form order and retain empty field values. These paths read the Form snapshot supplied for the current call

Class steps such as #subform[0] and #field[*] select direct children by class. Named steps can pass through unnamed subforms, subform sets, and areas without an explicit class step

Use xfa.resolveNode("this.parent.amount[0]") or this.resolveNodes("parent.amount[*]") to read sibling values relative to the current Form instance. The receiver stays with its own repeated row. Unqualified names passed to xfa retain their Form-wide lookup

Use .. to search descendants in the Form snapshot, for example $form.main..amount[0] or parent..#field[*]. The resolver searches in Form order and applies the occurrence selector within the matching sibling group

A standalone * path step matches Form children in order. Add an occurrence selector such as *[1] to choose one child, or escape the asterisk to match a field literally named *

Signed selectors such as row[-1], row[+0], and row[+1] use the receiver's occurrence at that level to select the previous, current, or next row. In an absolute Form path, use unsigned indexes instead

When a relative named or class step matches multiple siblings, omitting its selector uses the receiver's occurrence at that level. An explicit unsigned index still selects the requested sibling, and an omitted selector in an absolute path starts at the first occurrence

Unqualified paths passed to this.resolveNode or this.resolveNodes search from the receiver outward through enclosing scopes. The nearest scope that matches the first path step supplies the lookup, even when its occurrence selector is out of range

Resolved Form nodes expose read-only name, className, and zero-based index properties. They include containers when a path selects them. The current script receiver exposes the same properties, and xfa.get and xfa.values continue to return field values

Call resolveNode or resolveNodes on a resolved Form node to use it as the starting point for another lookup. For example, a resolved row can read its own fields with row.resolveNode("amount"), and signed indexes are relative to that node

The receiver and resolved Form nodes expose a parent property for walking the snapshot. Repeated lookups of the same Form node share one read-only view during the callback. $form and xfa.form resolve to the same root, whose parent is null

The nodes collection exposes the direct children in the Form snapshot. It supports iteration, zero-based indexing, length, item(index), and namedItem(name). Collections are read-only and reuse the same node views as SOM queries

all lists same-name occurrences in the enclosing scope and uses the class for an unnamed node. classAll lists same-class children of the actual parent. classIndex is the zero-based position in that collection, including when used in a SOM filter. Anonymous containers stay distinct for these class-based lookups. Both collections are read-only and preserve Form order

xfa.form exposes the Form root directly. Collections returned by resolveNodes support item(index) and namedItem(name) as well as array indexing and iteration. Both methods return null for a missing match

A SOM path can end with rawValue, name, className, index, or classIndex. For example, xfa.get("$form.main.row[1].amount.rawValue") returns the field value. Escape the first character of a property name to select a child with that literal name

The current receiver and resolved Form nodes expose their snapshot presence and access. Both are also available at the end of a SOM path, including in wildcard queries. The defaults are visible and open

A SOM step can filter candidates by a literal name, className, index, classIndex, presence, access, or rawValue value. For example, amount[access="readOnly"] selects matching fields in Form order. Use a quoted string or a number after = or ==. An empty string matches a field with an empty value. Nodes without a value are skipped by rawValue filters

Single- or double-quoted predicate values accept escaped quotes, backslashes, forward slashes, \uXXXX, and the standard \b, \f, \n, \r, and \t escapes. JavaScript callers can use JSON.stringify(value) to quote a field value for a SOM query, including values with literal Unicode line or paragraph separators

Append a literal equality predicate with .(this.property==literal). For example, amount[*].(this.access=="open").(this.index==1) applies both predicates to the wildcard candidates. When the step uses a numeric selector such as [1], the resolver selects that occurrence before applying the predicates

Both absolute and relative SOM paths can use parent to move up one Form node, as in $form.main.row[1].amount.parent. Results include each matched parent once. The parent has one occurrence, so parent[0] matches and parent[1] does not. For example, xfa.resolveNode("parent[0]") starts from the current field. A property filter such as parent[index=1] instead checks the parent node's own occurrence among its siblings. Escape the first character to select a child literally named parent

A radio group's own validation script receives its selected export value in this.rawValue and event.value. Whole-form validation shares the operation budget across callback invocations and charges the host work for each call

calculate.override="disabled" skips calculation and preserves the current value; version 2.1206.4 also enforces user-input override policies on calculated fields: error refuses edits with the authored message, ignore retains the calculated value, and warning requests a typed Boolean decision through xhCalculateOverride and persists accepted instance value.override markers across save/reload until reset

validate.scriptTest="disabled" skips the script, warning records a warning and accepts an otherwise valid edit, and error rejects an invalid result; execution failures remain failures regardless of warning severity

Script validation selects message/text named scriptTest, or a sole unnamed text message; warnings are available in TXFAWidgetRuntime.Warnings, while a rejected edit exposes its message through LastDiagnostic

HPDFXFAEvaluateFieldScript uses the same disabled and warning policy for direct calls; a disabled script reports successful completion without executing a script or consuming script operations

These execution switches do not implement every user-input override policy, format/null validation rule or host-specific script execution location

A commit resolves explicit SOM bindings and the current repeated-row data context before running validate and calculate scripts

The edited value, calculated values, data nodes, widget model, focus and edit state, warnings, and pass counters publish together only after validation and layout stabilize

Rejected scripts, exhausted budgets, invalid UTF-16 selection boundaries, and layout or host-measurement exceptions restore the complete previous state and set LastDiagnostic

Whitespace-only value/text content in the Form and Template namespaces survives XML loading, saving and transaction restoration; spaces, tabs and line breaks remain field values rather than structural indentation

Budgets

TXFAWidgetRuntimeOptions limits widget count, edited value length, calculation passes, reflow passes, layout operations, script operations, elapsed script time, and other FormCalc or JavaScript resources

The widget cap applies while layout items and pagination fragments are appended, while loaded XFA decompression and packet assembly stop at the XFA DOM input limit before parsing

MaxLayoutOperations defaults to 200000 and bounds both the document walk and layout work; layout depth is limited to 128, event target and instance-initialization depth to 64, and recursive event dispatch is rejected

Default literal dynamic events

DispatchEvent accepts semicolon-separated literal operations in matching field event scripts with FormCalc or JavaScript content types; these operations are parsed directly and do not require a JavaScript DLL

row.instanceManager.addInstance(true);
row.instanceManager.removeInstance(0);
target.presence = "hidden";

addInstance appends one instance and accepts true, false, 1, or 0 as its merge argument; an omitted argument uses true, and the shorthand _row.addInstance(1) is also accepted. Literal add/remove scripts accept qualified shorthand such as main._row and this.parent._row; only the terminal manager prefix is removed, preserving underscores in parent names

For ordinary implicit named bindings in the live Form, addInstance(true) and insertInstance(index,true) first reuse an eligible same-name data group that has not been consumed by another live Form binding, preserving its existing values. Passing false creates a new data group initialized from template defaults; creation does not copy the previous row's entered values

Instance indices and occurrence limits count live Form occurrences rather than all matching data siblings. removeInstance uses a zero-based Form index, and mutations enforce the group's effective minimum and repeatable maximum, including max="-1"

Unused data does not create extra Form occurrences after a manager mutation. Nested implicit initialization skips same-name scalars and groups already consumed by an external live binding; field writes retain the selected group's identity during native reconstruction and direct save/reload

A repeated subform can use implicit named dataset binding or an explicit bind match="dataRef" collection ending in [*], such as items.entry[*]; add, insert, move and remove use the resolved data parent and element name even when the form subform has a different name

The explicit collection resolves to siblings under one parent with the same namespace URI and an ASCII XML local name; add and insert create missing named or index-zero intermediate parents when the binding path permits creation. The collection may be empty initially or become empty after removal, and a declared zero-minimum repeated subform retains its _name manager without adding a visible phantom instance

A manager obtained from any instance can clear the collection and add again, including within one event; saving and reloading an empty collection also preserves the ability to add instances. An empty collection inherits the existing parent's namespace for its first new element

HPDFXFAResolveBoundCollectionParent resolves the parent and local element name of a terminal-wildcard binding, using the normal record/root scope rules and supplied operation/deadline budgets; its optional final CreateParents argument defaults to false. Passing true permits creation of supported missing intermediate parents; the instance manager first completes read-only target and parent lookup so an existing record fallback takes precedence

New outer instances initialize nested explicit collections by reusing existing members and filling their minimum count, preserving existing implicit and explicit field values, including empty values. The nested Form view includes existing members up to the declared maximum; initialization does not duplicate shared collections. A zero-minimum nested manager is available immediately, without creating an absent data parent until its first addition

Child subforms may bind to one explicit target, such as details.item or an existing $record.shared.item[1], with repeatable or unlimited maxima and minimum counts above one. Required Form occurrences share that selected data node while retaining independent Form identities and unbound local field values. Outer instance creation preserves existing data and creates supported missing plain or index-zero paths when required; an absent zero-minimum target remains absent, and a zero maximum suppresses the child

For these plain and fixed-index bindings, addInstance, insertInstance, moveInstance, removeInstance and setInstances manage Form occurrences separately from data siblings. Both merge arguments still resolve the explicit target; moving an occurrence leaves the shared data order unchanged. Removal preserves the target while another live Form occurrence or field binds to it or one of its descendants

Direct save/reload preserves managed counts, order, local values and bindings, including a zero count after removal. Empty ordinary managed groups retain their effective occurrence limits and expose a usable _name manager after reload; a revived instance's live occur changes update the manager limits. An existing occurrence retains its selected data object when another data sibling is removed and indices shift. Explicit xfa.form.remerge() instead rebuilds Form occurrences from the template, occurrence limits and current data; it does not preserve manually added occurrences or their unbound local state

For supported terminal-wildcard bindings, both merge arguments resolve an eligible unconsumed data group before creating another group. Instance limits count live Form occurrences, so unused data siblings do not prevent an addition. Reusing a target preserves its data order while the Form occurrence takes the requested insertion position; exact bindings and ordinary nested values survive reconstruction and direct save/reload

Collection parent paths can select an existing group by class and fixed index, such as $record.#dataGroup[1].entry[*]; #subform addresses the same group class, and an omitted index selects the first match. Ordinary named intermediate parents after that selection can be created when needed, but a missing class-selected parent is never synthesized

Ordinary nested groups under the new occurrence consume eligible data, while nested explicit bindings retain their separate target-sharing rules. Explicit remerge applies the template and current data again instead of preserving managed occurrence counts

Collection refs with additional wildcard or descendant prefixes remain outside this profile; explicit dataValue parents or members and implicit scalar nodes with non-whitespace content cannot become containers. Move, remove and virtual-instance lookup do not create missing parents

Instance mutations preserve unrelated XML siblings and expose the new field/data-node links within the same event; independent parent scopes, direct save/reload and transaction rollback retain the resolved collection mapping

Fields inside a new instance may use bind match="dataRef", including relative, rooted, indexed and escaped paths supported by the binding resolver; existing targets retain their values, including empty values, while newly created targets receive the declared defaults

A field with match="none" creates no data node even when a ref is present, and an unnamed field may initialize an explicit dataRef target; unresolved creation paths fail the event transaction without falling back to a field-name binding

Targets resolve through named template children in the event's enclosing scopes, including dotted paths and this.parent; a manager nested inside a repeated scope uses the event's own data group

Literal manager targets such as main.row.instanceManager and this.parent.row.instanceManager can address a repeated terminal subform group. Intermediate path components must resolve uniquely, and terminal occurrences must belong to the same declaration; a failed resolution rolls back earlier actions in the event. This group resolution applies to instance-manager actions, while ordinary property targets retain their single-node resolution rules

presence accepts visible, hidden, and invisible on template fields, draws, subforms, and exclusion groups; hidden content occupies no flow space, while invisible content retains its space and is omitted from widgets and flatten output

With the default literal parser, presence changes apply to the selected template node and therefore all its repeated occurrences; indexed per-instance presence, inactive, arbitrary expressions, variables, conditionals, loops, and other event-script operations require an additional event host

An event batch publishes data changes, calculations, layout, focus, and editing state together after reflow stabilizes; any rejected operation or exhausted input, operation, instance, value, widget, layout, or elapsed-time budget restores the complete previous document and interaction state

Removing a row preserves focus and pending edits for surviving data groups even when their widget indices change; removing or concealing the focused widget clears focus and publishes the corresponding focus callback after success

General JavaScript and FormCalc event execution

Set TXFAWidgetRuntimeOptions.ScriptOptions.EnableJavaScript to enable the shipped bounded QuickJS bridge for event execution; JavaScript events then support functions, closures, arrays, conditions, loops and exceptions rather than the default literal grammar

Options := TXFAWidgetRuntimeOptions.Default;
Options.ScriptOptions.EnableJavaScript := True;
Runtime := TXFAWidgetRuntime.Create(XDPBytes, 595, 842, Options);

The event host exposes this, enclosing named fields and subforms, parent, writable rawValue, presence and access, instanceManager.count/min/max, addInstance, removeInstance, insertInstance, moveInstance and setInstances, xfa.resolveNode, xfa.resolveNodes, node-level resolution and xfa.layout.relayout

Node lists support numeric indexing, length and item; repeated field values retain their own dataset targets, and SOM paths accept named children with numeric or wildcard indices for live host nodes

const values = xfa.resolveNodes("main.row[*].amount[*]");
let total = 0;
for (const field of values) total += Number(field.rawValue);
xfa.resolveNode("main.total").rawValue = total;
if (total > 100) this.parent.warning.presence = "visible";

Each repeated subform has its own live object and child fields; index, parent child getters and subsequent SOM queries follow insert, move and remove operations immediately inside the script

addInstance and insertInstance return a live subtree whose fields reflect reused data or new template defaults according to the binding and merge argument, so the script can read and write the selected values before the event publishes; removed handles reject subsequent reads or writes

General script presence and access changes persist in the standard XFA form packet per occurrence, while field values and repeat operations persist in datasets; insert, move and remove keep the corresponding form state aligned with the data groups

With the same opt-in, FormCalc event scripts compile to the bounded engine and support var, if/elseif/else, for with upto or downto, while, foreach, func with implicit results, arithmetic and comparisons, string concatenation, wildcard node aggregation and implicit field-value assignment

The event function library includes Sum, Count, Avg, Min, Max, Round, common math functions, string slicing, case conversion, trimming, replacement, HasValue, Exists, Within, Oneof and Choose; built-in names are case insensitive, At(source, search) follows XFA argument order including empty-search behavior, financial functions follow XFA parameter order, and the date and finance catalogues are described in FormCalc Functions

Script mutations are recorded inside the engine, validated and replayed inside the runtime transaction; exceptions, interruption, invalid Unicode, invalid host operations and exhausted budgets publish no partial document changes

Nested remerge hydration omits retired node payloads that live nodes no longer need while preserving binding indices, retained-handle diagnostics and required instance prototypes; retained dependency graphs and response metadata remain subject to the existing transaction budgets

Retirement history stores consecutive native identities in compact exact intervals without expiring old references or filling identity gaps. Retained handles keep their retired-node diagnostic, and failed transactions restore the prior identity state; sparse identities and other historical metadata can still grow during long sessions

Instance-group lookup skips bindings before the parent, and instance creation shares capacity accounting across graph mutations to reduce repeated work after nested remerge; node, byte, depth and operation limits remain enforced

Record-window changes and retained-record reconciliation check old node addresses without invoking methods on evicted nodes, allowing streamed navigation and remerge to preserve the existing transactional rollback behavior

General script execution remains off by default, uses no browser or external process, and exposes no filesystem, network or application APIs; the caller may supply JavaScriptEvaluator instead of the bridge

Persistent script objects

JavaScript script objects inside a subform's variables element expose their variables and functions through the script name; lexical variables, object state and nested closures remain alive for the runtime session, with normal lexical shadowing and strict directives preserved

<variables>
  <script name="Helpers" contentType="application/x-javascript"><![CDATA[
    let count = 0;
    const nextPrivate = (() => { let value = 0; return () => ++value; })();
    function next() { return ++count + ":" + nextPrivate(); }
  ]]></script>
</variables>

Event code can call Helpers.next(); repeated subform occurrences own independent script objects, and functions resolve named fields against the current live form context

Captured field nodes and managers follow stable data identity across moves and publication of newly created instances; accessing a removed node rejects the event and rolls back its module state

General calculate and validate scripts share the session and script objects; JavaScript supports implicit completion values and explicit return, while FormCalc returns its final expression

Failed transactions restore lexical and closure state by replaying the committed virtual journal, with recorded time and random inputs; replay and current execution share the transaction deadline, and the default journal limits are 64 MiB of scripts, results and bookkeeping and 8192 entries

After an outer runtime transaction fails and all event responses have unwound, its snapshot restoration releases newly published internal replay entries that have no remaining owner. Ordinary nested rollback retains response-owned entries until their enclosing transaction finishes. Reclaimed logical replay IDs are never reused, and the next event rebuilds the engine from the retained history

Public TXFAJavaScriptSession.ReplaySince fragments remain valid after rollback, including their indirect replay dependencies. Integrators using ReplaySinceOwned must instead discard those fragments with their failed transaction; ReclaimOwnedReplaySince requires paired pool/history checkpoints captured before that same transaction, completed history rollback, no active event and no remaining owner of its discarded fragments. The runtime manages these conditions internally; public fragments and successful retained history continue to consume journal storage

Script-object state lives in the runtime session and is initialized again after XDP reload; standard document values and form overrides continue to persist through SaveToBytes

Custom JavaScriptEvaluator callbacks retain the existing native calculate/validate envelope; the persistent session is supplied by the shipped engine

Configure explicit host transport

Set HostTransport and optional OnHostTransactionCompleted in TXFAWidgetRuntimeOptions to execute host dialogs, printing, navigation, submission and data transfer through application callbacks

Explicit XFA Host Transport supplies xfa.host.messageBox, response, beep, print, gotoURL, submitForm, importData, exportData and FormCalc Get, Post and Put; the application returns typed results and controls external effects

Retries and session replay use recorded responses, so callbacks execute once per dispatched request; failure completion lets the application discard staged effects or compensate reversible operations

Positive HostTransportLimits bound request count, argument count and aggregate request/response bytes across the enclosing runtime transaction

Locale and picture execution

General FormCalc events, calculate and validate scripts support locale and picture functions, including Format, Parse, localized date/time conversions, units, encoding, UUIDs and English number words

Dynamic FormCalc Eval executes dynamically supplied calculations with isolated variables and functions, relative field access, native compilation, recorded responses and transactional rollback

Explicit FormCalc references support write-through assignment, rebind, null detachment, function arguments and stable handles retained by script objects across repeated-instance movement

Native binding predicates evaluate JavaScript and FormCalc filters in candidate order, preserve accepted scalar and repeated-group identities, and coordinate supported Data mutation with bounded merge replanning

Live SOM paths support inferred, absolute and relative occurrence indices, class and descendant selectors, transparent containers, candidate predicates and direct FormCalc indexed assignment

The native Data DOM exposes datasets through $data and $record, synchronizes bound form reads and writes immediately, mirrors repeated instances and preserves retained data references through native identity publication

The native Property DOM exposes declared value, font, UI and other property children, synchronizes typed field values and persists per-instance attributes used by font measurement and supported flatten styling

The executing node inherits its nearest locale attribute; document localeSet entries override system symbols and patterns, while computed locale names are resolved through bounded internal requests and preserved in the session journal

Num2Date without a picture now uses the ambient default date pattern; supply YYYY-MM-DD explicitly when ISO output is required

Stateful host model

XFA Host Model supplies application metadata, actual page count, page navigation, Unicode title, calculation/validation flags, scoped reset and field focus with transactional enter/exit lifecycle

TXFAWidgetRuntimeOptions.HostModel configures initial application state; TXFAWidgetRuntime.HostModel returns current state, and failed events restore it together with document and interaction snapshots

A focus move with no enter/exit script, pending edit or initialized lifecycle changes focus without starting script calculation or deadline processing; scripted focus and pending edit commits still use transactional budgets, validation and recalculation

Advanced picture clauses execute through the same runtime transactions, locale retry journal and calculation lifecycle, with bounded compound parsing

Initialize and maintain the lifecycle

Call InitializeForm after configuring the runtime and callbacks to execute initialize events in template order, then calculate and validate, form-ready events and layout-ready events; the call is idempotent after success

New instances created by initialization or ready events receive their own initialize events before their ready handlers; layout-ready execution repeats only when layout changes, within the reflow and transaction budgets

After initialization, successful event dispatch and edit commit initialize newly created instances and execute calculate, validate and layout-ready; existing occurrences retain their initialization state across moves and transaction rollback

Lifecycle failures roll back document bytes, widget interaction and initialization bookkeeping together, and callbacks publish only after the enclosing transaction succeeds

Save the updated form

SaveToBytes returns the runtime's complete updated XDP, including modified datasets and standard per-instance form state; literal-parser presence changes remain template attributes; use these bytes with SetXFADocument when writing a PDF or with HPDFXFAFlatten for the updated flatten output

The loaded-document factory creates an independent runtime, so runtime events do not automatically modify the source PDF's object graph

Optional instance presentation profile

Dynamic XFA Instance Presentation adds explicit repeated bindings, stable per-instance IDs, indexed presence and access, bounded conditional events, host canvas painting, and accessibility through an independent helper; the default runtime and its restricted event grammar remain compatible

UpdateDocument provides transactional document actions; optional runtime property, binding-scope, identity, resolution-started, and document-validation callbacks support the helper while nil defaults preserve existing callers

Lower-level event and form APIs

HPDFXFACompileFormCalcEvent compiles event syntax; HPDFXFAExecuteJavaScriptEvent executes the virtual context described by TXFAEventBinding and TXFAEventBindings

TXFAJavaScriptSession supplies persistent execution and bounded checkpoints for lower-level callers

Returned TXFAEventAction values use TXFAEventActionKind; transactional replay is supplied by the runtime

HPDFXFAResolveFormInstanceNode and HPDFXFAResolveFormInstanceProperty provide bounded standard form-packet lookup

Current boundaries

The runtime is a single-thread host object; GUI and painting remain the responsibility of the host or the optional presentation helper

The supported host state, live form DOM and lifecycle do not yet cover every Acrobat host property, alternate-era and localized digit pictures, synchronous dynamic reflow queries, or every SOM operator

See Bounded XFA FormCalc and JavaScript, XFA Packet DOM, and Interactive Document Processing