pdfluent-forms 1.2.0

AcroForm engine for PDF interactive forms.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
//! Run AcroForm calculation (`/AA /C`) and format (`/AA /F`) scripts.
//!
//! Scripts run in the sandboxed QuickJS runtime of `xfa-js-sandboxed`: they
//! see the form's field values and the Acrobat helpers (`event.value`,
//! `this.getField(..).value`, `AFSimple_Calculate`, `AFMakeNumber`,
//! `AFNumber_Format`, `AFPercent_Format`) and nothing else. No network, no
//! file access, no host objects; a script that touches them fails with an
//! error and leaves the form unchanged.
//!
//! Two entry points:
//!
//! - [`recalculate`] works on a `lopdf::Document`, the same level as
//!   [`crate::apply_field_value`]. It runs the calculate scripts in the
//!   `/AcroForm /CO` order and writes each changed value into `/V` and a
//!   fresh `/AP` — also on read-only fields, because the usual calculated
//!   field is read-only. This is what an editor calls after a field changed.
//! - [`SandboxedJsHandler`] plugs the same runtime into
//!   [`crate::actions::run_calculations`] for code that holds a [`FieldTree`].
//!
//! # Semantics
//!
//! - One pass in `/CO` order; a field is calculated once per call. A field
//!   with a calculate action that `/CO` does not list is not run. A form with
//!   no usable `/CO` runs every calculate action in field order.
//! - The result is `event.value` after the script. `event.rc = false`
//!   discards it. A script may also assign other fields through
//!   `getField(..).value`; those writes are applied too.
//! - A script error leaves its target field as it was and is reported in
//!   [`CalcOutcome::failed`]; the other fields still calculate.
//! - A `/AA /F` format action on the target decides what the appearance
//!   draws (`AFNumber_Format` and friends); `/V` keeps the raw result.
//! - Only text fields are written. A calculated value for another field type
//!   is reported as failed.
//! - Scripts run in strict mode: an undeclared assignment throws.

// Copyright (c) 2026 Innovation Trigger B.V.
//
// PDFluent is available under two licences, at your option: the GNU AGPLv3, or
// the PDFluent Commercial Licence. See the LICENSE file in this repository --
// that file travels with the copy you received, which a URL does not.

use crate::actions::JsActionHandler;
use crate::facade::FormAccess;
use crate::tree::{FieldId, FieldTree, FieldValue};
use crate::writeback::{
    apply_text_with_display, collect_fields, effective_field_type, ensure_indirect_acroform,
    inherited, Located, WritebackError,
};
use lopdf::{Dictionary, Document, Object, ObjectId};
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use xfa_js_sandboxed::{ExecCtx, FieldValues, XfaJsError, XfaJsRuntime};

/// A field whose value a recalculation changed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CalcUpdate {
    /// Fully-qualified field name.
    pub name: String,
    /// The new `/V`.
    pub value: String,
}

/// A calculation that did not complete.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CalcFailure {
    /// Fully-qualified name of the field whose action failed.
    pub name: String,
    /// What went wrong, naming the cause.
    pub message: String,
}

/// What [`recalculate`] did.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct CalcOutcome {
    /// Fields whose value changed, in the order they were last written.
    pub updated: Vec<CalcUpdate>,
    /// Actions that failed; their fields were left alone.
    pub failed: Vec<CalcFailure>,
    /// Number of calculate scripts that ran, successful or not.
    pub scripts_run: usize,
}

fn new_runtime() -> Result<XfaJsRuntime, WritebackError> {
    XfaJsRuntime::new().map_err(|e| WritebackError::Malformed(format!("script engine: {e}")))
}

fn run_script(
    rt: &mut XfaJsRuntime,
    script: &str,
    fields: &mut FieldValues,
    event_value: &str,
) -> Result<Option<String>, XfaJsError> {
    let mut ctx = ExecCtx::new(fields, Arc::new(AtomicBool::new(false)));
    ctx.event_new_text = Some(event_value);
    rt.execute_acroform_event(script, ctx)
}

// ---------------------------------------------------------------------------
// Document level
// ---------------------------------------------------------------------------

/// Run the form's calculate actions in `/CO` order and write the results.
///
/// Returns an empty outcome for a document without an AcroForm or without
/// calculate actions. See the module docs for the exact rules.
pub fn recalculate(doc: &mut Document) -> Result<CalcOutcome, WritebackError> {
    let has_form = doc
        .catalog()
        .map(|c| c.get(b"AcroForm").is_ok())
        .unwrap_or(false);
    if !has_form {
        return Ok(CalcOutcome::default());
    }
    ensure_indirect_acroform(doc);
    let fields = collect_fields(doc)?;

    // Terminal fields only: a node with named kids is a group.
    let terminal: Vec<&Located> = fields.iter().filter(|l| !has_field_kids(doc, l)).collect();

    let mut values = FieldValues::new();
    for l in &terminal {
        values.set(l.fqn.clone(), stored_text(doc, l));
    }

    let order = calculation_order(doc, &terminal);
    let mut outcome = CalcOutcome::default();
    if order.is_empty() {
        return Ok(outcome);
    }
    let mut rt = new_runtime()?;

    for idx in order {
        let target = terminal[idx];
        let Some(script) = action_script(doc, target.id, b"C") else {
            continue;
        };
        outcome.scripts_run += 1;

        let snapshot = values.clone();
        let current = values.get(&target.fqn).unwrap_or("").to_string();
        let result = run_script(&mut rt, &script, &mut values, &current);
        let new_target = match result {
            Ok(Some(v)) => v,
            Ok(None) => {
                values = snapshot;
                continue;
            }
            Err(e) => {
                values = snapshot;
                outcome.failed.push(CalcFailure {
                    name: target.fqn.clone(),
                    message: e.to_string(),
                });
                continue;
            }
        };
        values.set(target.fqn.clone(), new_target);

        // Everything the script changed: the target and any field it wrote.
        let changed: Vec<(String, String)> = values
            .iter()
            .filter(|(name, v)| snapshot.get(name) != Some(*v))
            .map(|(n, v)| (n.to_string(), v.to_string()))
            .collect();
        for (name, value) in changed {
            let Some(l) = terminal.iter().find(|l| l.fqn == name) else {
                continue;
            };
            match write_text(doc, &mut rt, &values, l, &value) {
                Ok(()) => {
                    outcome.updated.retain(|u| u.name != name);
                    outcome.updated.push(CalcUpdate { name, value });
                }
                Err(message) => {
                    values.set(name.clone(), snapshot.get(&name).unwrap_or("").to_string());
                    outcome.failed.push(CalcFailure { name, message });
                }
            }
        }
    }
    Ok(outcome)
}

fn write_text(
    doc: &mut Document,
    rt: &mut XfaJsRuntime,
    values: &FieldValues,
    l: &Located,
    value: &str,
) -> Result<(), String> {
    let is_text = doc
        .get_object(l.id)
        .and_then(|o| o.as_dict())
        .ok()
        .and_then(|d| effective_field_type(doc, d))
        .is_some_and(|ft| ft == b"Tx");
    if !is_text {
        return Err("a calculated value can only be written to a text field".to_string());
    }
    if stored_text(doc, l) == value && has_appearance(doc, l) {
        return Ok(());
    }
    let display = format_display(doc, rt, values, l, value);
    apply_text_with_display(doc, l, value, display.as_deref())
        .map(|_| ())
        .map_err(|e| e.to_string())
}

/// The `/AA /F` rendering of `value`, when it differs from the value.
fn format_display(
    doc: &Document,
    rt: &mut XfaJsRuntime,
    values: &FieldValues,
    l: &Located,
    value: &str,
) -> Option<String> {
    let script = action_script(doc, l.id, b"F")?;
    let mut scratch = values.clone();
    match run_script(rt, &script, &mut scratch, value) {
        Ok(Some(shown)) if shown != value => Some(shown),
        _ => None,
    }
}

fn has_appearance(doc: &Document, l: &Located) -> bool {
    doc.get_object(l.id)
        .and_then(|o| o.as_dict())
        .map(|d| d.has(b"AP"))
        .unwrap_or(false)
        || l.kids.iter().any(|k| {
            doc.get_object(*k)
                .and_then(|o| o.as_dict())
                .map(|d| d.has(b"AP"))
                .unwrap_or(false)
        })
}

fn has_field_kids(doc: &Document, l: &Located) -> bool {
    l.kids.iter().any(|&k| {
        doc.get_object(k)
            .and_then(|o| o.as_dict())
            .map(|d| d.get(b"T").is_ok())
            .unwrap_or(false)
    })
}

/// Indices into `terminal`, in calculation order.
fn calculation_order(doc: &Document, terminal: &[&Located]) -> Vec<usize> {
    let has_script = |l: &Located| action_script(doc, l.id, b"C").is_some();
    let listed: Vec<usize> = co_ids(doc)
        .into_iter()
        .filter_map(|id| terminal.iter().position(|l| l.id == id))
        .filter(|&i| has_script(terminal[i]))
        .collect();
    if !listed.is_empty() {
        return listed;
    }
    terminal
        .iter()
        .enumerate()
        .filter(|(_, l)| has_script(l))
        .map(|(i, _)| i)
        .collect()
}

/// Object ids named by `/AcroForm /CO`, in order.
fn co_ids(doc: &Document) -> Vec<ObjectId> {
    let Some(af) = doc
        .catalog()
        .ok()
        .and_then(|c| c.get(b"AcroForm").ok())
        .and_then(|o| resolve_dict(doc, o))
    else {
        return Vec::new();
    };
    let arr = match af.get(b"CO") {
        Ok(Object::Array(a)) => a.clone(),
        Ok(Object::Reference(id)) => match doc.get_object(*id) {
            Ok(Object::Array(a)) => a.clone(),
            _ => return Vec::new(),
        },
        _ => return Vec::new(),
    };
    arr.iter().filter_map(|o| o.as_reference().ok()).collect()
}

fn resolve_dict<'a>(doc: &'a Document, obj: &'a Object) -> Option<&'a Dictionary> {
    match obj {
        Object::Dictionary(d) => Some(d),
        Object::Reference(id) => doc.get_object(*id).and_then(|o| o.as_dict()).ok(),
        _ => None,
    }
}

/// The text of a field's stored `/V` (inherited); first entry of an array.
fn stored_text(doc: &Document, l: &Located) -> String {
    let Some(dict) = doc.get_object(l.id).and_then(|o| o.as_dict()).ok() else {
        return String::new();
    };
    match inherited(doc, dict, b"V") {
        Some(Object::Array(items)) => items
            .first()
            .and_then(|o| lopdf::decode_text_string(o).ok())
            .unwrap_or_default(),
        Some(Object::Name(n)) => String::from_utf8_lossy(&n).into_owned(),
        Some(o @ Object::String(..)) => lopdf::decode_text_string(&o).unwrap_or_default(),
        _ => String::new(),
    }
}

/// JavaScript of `/AA /<trigger>` on the field dictionary itself (`/AA` is not
/// inherited). The action must be `/S /JavaScript`.
fn action_script(doc: &Document, field: ObjectId, trigger: &[u8]) -> Option<String> {
    let dict = doc.get_object(field).and_then(|o| o.as_dict()).ok()?;
    let aa = resolve_dict(doc, dict.get(b"AA").ok()?)?;
    let action = resolve_dict(doc, aa.get(trigger).ok()?)?;
    match action.get(b"S").ok()? {
        Object::Name(n) if n == b"JavaScript" => {}
        _ => return None,
    }
    let js = match action.get(b"JS").ok()? {
        Object::Reference(id) => doc.get_object(*id).ok()?,
        other => other,
    };
    match js {
        o @ Object::String(..) => lopdf::decode_text_string(o).ok(),
        Object::Stream(s) => {
            let bytes = s
                .decompressed_content()
                .unwrap_or_else(|_| s.content.clone());
            lopdf::decode_text_string(&Object::String(bytes, lopdf::StringFormat::Literal)).ok()
        }
        _ => None,
    }
}

// ---------------------------------------------------------------------------
// Field-tree level
// ---------------------------------------------------------------------------

/// A [`JsActionHandler`] that runs calculate and format actions in the
/// sandbox. Keystroke and validate actions are accepted without running.
pub struct SandboxedJsHandler {
    runtime: XfaJsRuntime,
}

impl SandboxedJsHandler {
    /// Start a sandboxed runtime.
    pub fn new() -> Result<Self, XfaJsError> {
        Ok(Self {
            runtime: XfaJsRuntime::new()?,
        })
    }
}

fn tree_values(tree: &FieldTree) -> (FieldValues, Vec<(String, FieldId)>) {
    let mut values = FieldValues::new();
    let mut ids = Vec::new();
    for id in tree.terminal_fields() {
        let name = tree.fully_qualified_name(id);
        values.set(name.clone(), tree.get_value(&name).unwrap_or_default());
        ids.push((name, id));
    }
    (values, ids)
}

impl JsActionHandler for SandboxedJsHandler {
    fn on_keystroke(&mut self, _: &mut FieldTree, _: FieldId, _: &str, _: &str) -> bool {
        true
    }

    fn on_validate(&mut self, _: &mut FieldTree, _: FieldId, _: &str) -> bool {
        true
    }

    fn on_format(&mut self, tree: &FieldTree, field_id: FieldId, js: &str) -> Option<String> {
        let (mut values, _) = tree_values(tree);
        let name = tree.fully_qualified_name(field_id);
        let current = values.get(&name).unwrap_or("").to_string();
        run_script(&mut self.runtime, js, &mut values, &current)
            .ok()
            .flatten()
    }

    fn on_calculate(
        &mut self,
        tree: &mut FieldTree,
        field_id: FieldId,
        js: &str,
    ) -> Option<String> {
        let (mut values, ids) = tree_values(tree);
        let before = values.clone();
        let name = tree.fully_qualified_name(field_id);
        let current = values.get(&name).unwrap_or("").to_string();
        let result = run_script(&mut self.runtime, js, &mut values, &current)
            .ok()
            .flatten()?;
        // Fields the script wrote besides its own.
        for (other, id) in ids {
            if other != name && values.get(&other) != before.get(&other) {
                tree.get_mut(id).value = Some(FieldValue::Text(
                    values.get(&other).unwrap_or("").to_string(),
                ));
            }
        }
        Some(result)
    }
}