laminapdf-model 0.9.0

Typed views of a PDF document in Rust: pages, outline, document info, page labels, name trees and the structure tree, read tolerantly.
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
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Writing a behaviour as the helper calls Acrobat writes ([ADR 0021] §4): the same closed list
//! [`recognise`](super::recognise) reads, built from typed values only. No string a caller gives
//! is ever joined into a script but as a quoted, escaped literal, and nothing here runs one.
//!
//! The spelling follows Acrobat's: a call ends in `;`, `AFSimple_Calculate` takes `new Array (…)`
//! and a number format repeats its arguments in the keystroke call (Adobe's *JavaScript for
//! Acrobat API Reference*, `AFNumber_Format`, `AFPercent_Format`, `AFDate_FormatEx`,
//! `AFTime_Format`, `AFSpecial_Format`, `AFRange_Validate` and `AFSimple_Calculate`).
//!
//! [ADR 0021]: https://github.com/laudebugs/laminapdf/blob/main/docs/decisions/0021-pdf-javascript-policy.md

use std::fmt::Write as _;

use super::recognise::{MAX_DECIMALS, MAX_PATTERN, TIME_FORMATS};
use super::{
    CalculateFunction, FieldBehaviour, FieldTrigger, NegativeStyle, NumberFormat, PercentFormat, RangeValidate,
    SeparatorStyle, SimpleCalculate, SpecialFormat,
};

/// The longest script written, in bytes: well under [`Limits::max_script_length`] so that what is
/// written is read back.
///
/// [`Limits::max_script_length`]: laminapdf_cos::Limits::max_script_length
///
/// Added in 0.7.0.
pub const MAX_WRITTEN_SCRIPT: usize = 32 * 1024;

impl FieldBehaviour {
    /// The helper calls that write this behaviour, each under the `/AA` trigger it belongs to:
    /// a format as its `F` call and the matching `K` keystroke call, a range as its `V` call, a
    /// calculation as its `C` call. Reading each back with
    /// [`Document::field_behaviour`](crate::Document::field_behaviour) gives this behaviour again
    /// (a percent's keystroke call has no "percent first" argument, so reads back without it).
    ///
    /// `None` when the behaviour can't be written so that it reads back: more than 20 decimals,
    /// a pattern that is empty or too long (over 128 characters), a bound
    /// that is not a finite number, a calculation without fields, or a script past
    /// [`MAX_WRITTEN_SCRIPT`].
    ///
    /// Added in 0.7.0.
    #[must_use]
    pub fn helper_calls(&self) -> Option<Vec<(FieldTrigger, String)>> {
        let both = |format: String, keystroke: String| {
            vec![(FieldTrigger::Format, format), (FieldTrigger::Keystroke, keystroke)]
        };
        let calls = match self {
            Self::NumberFormat(f) => {
                let args = number_args(f)?;
                both(
                    format!("AFNumber_Format({args});"),
                    format!("AFNumber_Keystroke({args});"),
                )
            }
            Self::PercentFormat(f) => both(percent_format(*f)?, percent_keystroke(*f)?),
            Self::DateFormat(p) => {
                let pattern = pattern(&p.pattern)?;
                both(
                    format!("AFDate_FormatEx({pattern});"),
                    format!("AFDate_KeystrokeEx({pattern});"),
                )
            }
            Self::TimeFormat(p) => {
                if let Some(i) = TIME_FORMATS.iter().position(|t| *t == p.pattern) {
                    both(format!("AFTime_Format({i});"), format!("AFTime_Keystroke({i});"))
                } else {
                    let pattern = pattern(&p.pattern)?;
                    both(
                        format!("AFTime_FormatEx({pattern});"),
                        format!("AFTime_KeystrokeEx({pattern});"),
                    )
                }
            }
            Self::SpecialFormat(kind) => {
                let i = special_index(*kind);
                both(format!("AFSpecial_Format({i});"), format!("AFSpecial_Keystroke({i});"))
            }
            Self::RangeValidate(r) => vec![(FieldTrigger::Validate, range_call(r)?)],
            Self::SimpleCalculate(c) => vec![(FieldTrigger::Calculate, calculate_call(c)?)],
        };
        calls
            .iter()
            .all(|(_, script)| script.len() <= MAX_WRITTEN_SCRIPT)
            .then_some(calls)
    }
}

/// `AFNumber_Format`'s six arguments: decimals, separator, negative style, the unused currency
/// style, the currency and whether it comes first.
fn number_args(f: &NumberFormat) -> Option<String> {
    Some(format!(
        "{}, {}, {}, 0, {}, {}",
        decimals(f.decimals)?,
        separator_index(f.separator),
        negative_index(f.negative),
        literal(&f.currency),
        f.prepend
    ))
}

fn percent_format(f: PercentFormat) -> Option<String> {
    let (decimals, separator) = (decimals(f.decimals)?, separator_index(f.separator));
    Some(if f.prepend {
        format!("AFPercent_Format({decimals}, {separator}, true);")
    } else {
        format!("AFPercent_Format({decimals}, {separator});")
    })
}

fn percent_keystroke(f: PercentFormat) -> Option<String> {
    Some(format!(
        "AFPercent_Keystroke({}, {});",
        decimals(f.decimals)?,
        separator_index(f.separator)
    ))
}

fn range_call(r: &RangeValidate) -> Option<String> {
    let bound = |b: Option<f64>| match b {
        Some(n) => number(n).map(|n| format!("true, {n}")),
        None => Some("false, 0".to_owned()),
    };
    Some(format!("AFRange_Validate({}, {});", bound(r.min)?, bound(r.max)?))
}

fn calculate_call(c: &SimpleCalculate) -> Option<String> {
    if c.fields.is_empty() {
        return None;
    }
    let names: Vec<String> = c.fields.iter().map(|n| literal(n)).collect();
    Some(format!(
        "AFSimple_Calculate(\"{}\", new Array ({}));",
        function_name(c.function),
        names.join(", ")
    ))
}

/// `n` as an integer literal, when the recogniser takes that many decimals.
fn decimals(n: u8) -> Option<u8> {
    (f64::from(n) <= MAX_DECIMALS).then_some(n)
}

/// A finite number as a JavaScript literal the tokeniser reads back to the same value.
fn number(n: f64) -> Option<String> {
    n.is_finite().then(|| format!("{n}"))
}

/// A date or time pattern as a literal, when the recogniser reads one that long.
fn pattern(p: &str) -> Option<String> {
    (!p.is_empty() && p.chars().count() <= MAX_PATTERN).then(|| literal(p))
}

/// `text` as a double-quoted string literal: the quote, the backslash and every control
/// character escaped, so that the tokeniser reads the same text and no text ends the literal.
fn literal(text: &str) -> String {
    let mut out = String::with_capacity(text.len() + 2);
    out.push('"');
    for c in text.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if needs_escape(c) => {
                // Never fails: writing to a `String`.
                let _ = if u32::from(c) <= 0xFF {
                    write!(out, "\\x{:02x}", u32::from(c))
                } else {
                    write!(out, "\\u{:04x}", u32::from(c))
                };
            }
            c => out.push(c),
        }
    }
    out.push('"');
    out
}

/// Whether `c` is written as an escape: a control character, the line and paragraph separators
/// (a string literal holds neither raw in JavaScript before ES2019, which Acrobat's engine may
/// be), and the invisible format characters that make a literal read differently from how it is
/// written (the soft hyphen, zero-width and bidirectional marks, the byte-order mark).
fn needs_escape(c: char) -> bool {
    c.is_control()
        || matches!(
            c,
            '\u{ad}' | '\u{200b}'..='\u{200f}' | '\u{2028}'..='\u{202e}' | '\u{2060}'..='\u{2064}' | '\u{2066}'..='\u{206f}' | '\u{feff}'
        )
}

const fn separator_index(s: SeparatorStyle) -> u8 {
    match s {
        SeparatorStyle::CommaDot => 0,
        SeparatorStyle::Dot => 1,
        SeparatorStyle::DotComma => 2,
        SeparatorStyle::Comma => 3,
        SeparatorStyle::ApostropheDot => 4,
    }
}

const fn negative_index(s: NegativeStyle) -> u8 {
    match s {
        NegativeStyle::Minus => 0,
        NegativeStyle::Red => 1,
        NegativeStyle::Parentheses => 2,
        NegativeStyle::RedParentheses => 3,
    }
}

/// `AFSpecial_Format`'s index.
const fn special_index(kind: SpecialFormat) -> u8 {
    match kind {
        SpecialFormat::Zip => 0,
        SpecialFormat::ZipPlus4 => 1,
        SpecialFormat::Phone => 2,
        SpecialFormat::Ssn => 3,
    }
}

const fn function_name(f: CalculateFunction) -> &'static str {
    match f {
        CalculateFunction::Sum => "SUM",
        CalculateFunction::Average => "AVG",
        CalculateFunction::Product => "PRD",
        CalculateFunction::Minimum => "MIN",
        CalculateFunction::Maximum => "MAX",
    }
}

#[cfg(test)]
mod tests {
    use super::super::recognise::recognise;
    use super::*;
    use crate::forms::behaviour::DatePattern;

    fn calls(b: &FieldBehaviour) -> Vec<(FieldTrigger, String)> {
        b.helper_calls().unwrap_or_default()
    }

    /// Reading each call back gives the behaviour, as the property tests in `tests/` check on
    /// whole documents.
    fn reads_back(b: &FieldBehaviour) -> bool {
        let written = calls(b);
        !written.is_empty() && written.iter().all(|(t, s)| recognise(s, *t).is_some())
    }

    #[test]
    fn a_number_format_is_acrobats_call_for_its_format_and_its_keystroke() {
        let b = FieldBehaviour::NumberFormat(NumberFormat {
            decimals: 2,
            separator: SeparatorStyle::CommaDot,
            negative: NegativeStyle::Minus,
            currency: "$".into(),
            prepend: true,
        });
        assert_eq!(
            calls(&b),
            [
                (
                    FieldTrigger::Format,
                    r#"AFNumber_Format(2, 0, 0, 0, "$", true);"#.to_owned()
                ),
                (
                    FieldTrigger::Keystroke,
                    r#"AFNumber_Keystroke(2, 0, 0, 0, "$", true);"#.to_owned()
                ),
            ]
        );
        assert_eq!(recognise(&calls(&b)[0].1, FieldTrigger::Format), Some(b));
    }

    #[test]
    fn the_other_helpers_are_written_in_acrobats_spelling() {
        let at = |b: &FieldBehaviour, i: usize| calls(b)[i].1.clone();
        let percent = FieldBehaviour::PercentFormat(PercentFormat {
            decimals: 1,
            separator: SeparatorStyle::DotComma,
            prepend: false,
        });
        let date = FieldBehaviour::DateFormat(DatePattern {
            pattern: "mm/dd/yyyy".into(),
        });
        let time = FieldBehaviour::TimeFormat(DatePattern {
            pattern: "h:MM tt".into(),
        });
        let custom_time = FieldBehaviour::TimeFormat(DatePattern {
            pattern: "HH.MM".into(),
        });
        let special = FieldBehaviour::SpecialFormat(SpecialFormat::Phone);
        let range = FieldBehaviour::RangeValidate(RangeValidate {
            min: Some(0.0),
            max: Some(99.5),
        });
        let open = FieldBehaviour::RangeValidate(RangeValidate {
            min: None,
            max: Some(-1.0),
        });
        let sum = FieldBehaviour::SimpleCalculate(SimpleCalculate {
            function: CalculateFunction::Sum,
            fields: vec!["a".into(), "b.c".into()],
        });
        assert_eq!(
            [
                at(&percent, 0),
                at(&percent, 1),
                at(&date, 0),
                at(&date, 1),
                at(&time, 0),
                at(&custom_time, 0),
                at(&special, 0),
                at(&special, 1),
                at(&range, 0),
                at(&open, 0),
                at(&sum, 0),
            ],
            [
                "AFPercent_Format(1, 2);",
                "AFPercent_Keystroke(1, 2);",
                r#"AFDate_FormatEx("mm/dd/yyyy");"#,
                r#"AFDate_KeystrokeEx("mm/dd/yyyy");"#,
                "AFTime_Format(1);",
                r#"AFTime_FormatEx("HH.MM");"#,
                "AFSpecial_Format(2);",
                "AFSpecial_Keystroke(2);",
                "AFRange_Validate(true, 0, true, 99.5);",
                "AFRange_Validate(false, 0, true, -1);",
                r#"AFSimple_Calculate("SUM", new Array ("a", "b.c"));"#,
            ]
        );
        assert!(
            [&percent, &date, &time, &custom_time, &special, &range, &open, &sum]
                .into_iter()
                .all(reads_back)
        );
    }

    #[test]
    fn a_name_with_quotes_backslashes_and_line_breaks_reads_back_as_the_same_name() {
        let names = [
            "say \"hi\"",
            "back\\slash",
            "two\nlines\r",
            "tab\t",
            "\u{1}ctl",
            "é ü 日本",
        ];
        let b = FieldBehaviour::SimpleCalculate(SimpleCalculate {
            function: CalculateFunction::Maximum,
            fields: names.iter().map(|n| (*n).to_owned()).collect(),
        });
        let script = &calls(&b)[0].1;
        assert_eq!(recognise(script, FieldTrigger::Calculate), Some(b));
        assert!(!script.contains('\n') && !script.contains('\r'));
    }

    #[test]
    fn hostile_text_is_written_as_escapes_only_and_reads_back() {
        let hostile = [
            "\0",
            "a\u{2028}b\u{2029}c\u{85}d",
            "\u{202e}rtl\u{202c}\u{feff}\u{200b}\u{ad}",
            "\"); app.alert(\"x\"); (\"",
            "\\\"; evil(); //",
            "line\nbreak\r\n",
            "\u{1f600} \u{10ffff}",
        ];
        for text in hostile {
            let behaviours = [
                FieldBehaviour::NumberFormat(NumberFormat {
                    decimals: 0,
                    separator: SeparatorStyle::CommaDot,
                    negative: NegativeStyle::Minus,
                    currency: text.to_owned(),
                    prepend: false,
                }),
                FieldBehaviour::DateFormat(DatePattern {
                    pattern: text.to_owned(),
                }),
                FieldBehaviour::SimpleCalculate(SimpleCalculate {
                    function: CalculateFunction::Sum,
                    fields: vec![text.to_owned(), "b".to_owned()],
                }),
            ];
            for b in behaviours {
                for (trigger, script) in calls(&b) {
                    assert!(!script.chars().any(needs_escape), "{script:?} holds a raw character");
                    assert_eq!(recognise(&script, trigger), Some(b.clone()));
                }
            }
        }
    }

    #[test]
    fn what_cannot_be_read_back_is_not_written() {
        let too_precise = FieldBehaviour::NumberFormat(NumberFormat {
            decimals: 21,
            separator: SeparatorStyle::CommaDot,
            negative: NegativeStyle::Minus,
            currency: String::new(),
            prepend: false,
        });
        let empty_pattern = FieldBehaviour::DateFormat(DatePattern { pattern: String::new() });
        let nan = FieldBehaviour::RangeValidate(RangeValidate {
            min: Some(f64::NAN),
            max: None,
        });
        let nothing = FieldBehaviour::SimpleCalculate(SimpleCalculate {
            function: CalculateFunction::Sum,
            fields: Vec::new(),
        });
        let huge = FieldBehaviour::SimpleCalculate(SimpleCalculate {
            function: CalculateFunction::Sum,
            fields: vec!["x".repeat(MAX_WRITTEN_SCRIPT)],
        });
        assert!(
            [too_precise, empty_pattern, nan, nothing, huge]
                .iter()
                .all(|b| b.helper_calls().is_none())
        );
    }
}