laminapdf-model 0.7.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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
//! Form behaviour without JavaScript ([ADR 0021] §2): a field's `/AA` keystroke, format,
//! validate and calculate scripts read as tokens and matched against Acrobat's helper calls,
//! whose work native code then does. Nothing here evaluates a script.
//!
//! [ADR 0021]: https://github.com/laudebugs/laminapdf/blob/main/docs/decisions/0021-pdf-javascript-policy.md

mod date;
mod number;
mod recognise;
mod scripts;
mod special;
mod tokens;

pub use scripts::{FormScript, ScriptLocation, ScriptState};

pub(crate) use recognise::recognise;

use super::{FieldValue, Form};

/// The trigger of a field's `/AA` a behaviour belongs to (§12.6.3, Table 199).
///
/// Added in 0.6.0.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum FieldTrigger {
    /// `K`: a keystroke, or the value committed.
    Keystroke,
    /// `F`: what the field shows for its value.
    Format,
    /// `V`: whether a committed value is accepted.
    Validate,
    /// `C`: the value, from other fields'.
    Calculate,
}

impl FieldTrigger {
    /// The four, in `/AA`'s key order.
    pub(crate) const ALL: [Self; 4] = [Self::Keystroke, Self::Format, Self::Validate, Self::Calculate];

    /// The `/AA` key.
    ///
    /// Added in 0.6.0.
    #[must_use]
    pub const fn key(self) -> &'static str {
        match self {
            Self::Keystroke => "K",
            Self::Format => "F",
            Self::Validate => "V",
            Self::Calculate => "C",
        }
    }
}

/// One recognised helper call, as data ([ADR 0021] §2's list).
///
/// [ADR 0021]: https://github.com/laudebugs/laminapdf/blob/main/docs/decisions/0021-pdf-javascript-policy.md
///
/// Added in 0.6.0.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum FieldBehaviour {
    /// `AFNumber_Format` or `AFNumber_Keystroke`.
    NumberFormat(NumberFormat),
    /// `AFPercent_Format` or `AFPercent_Keystroke`.
    PercentFormat(PercentFormat),
    /// `AFDate_FormatEx`, `AFDate_Format` or their keystroke forms.
    DateFormat(DatePattern),
    /// `AFTime_Format`, `AFTime_FormatEx` or their keystroke forms.
    TimeFormat(DatePattern),
    /// `AFSpecial_Format` or `AFSpecial_Keystroke`.
    SpecialFormat(SpecialFormat),
    /// `AFRange_Validate`.
    RangeValidate(RangeValidate),
    /// `AFSimple_Calculate`.
    SimpleCalculate(SimpleCalculate),
}

/// A number with a fixed count of decimals, grouped, perhaps with a currency.
///
/// Added in 0.6.0.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct NumberFormat {
    /// Digits after the point.
    pub decimals: u8,
    /// How thousands are grouped and the point written.
    pub separator: SeparatorStyle,
    /// How a negative number shows.
    pub negative: NegativeStyle,
    /// The currency symbol, empty for none.
    pub currency: String,
    /// Whether the currency comes first.
    pub prepend: bool,
}

/// `sepStyle`.
///
/// Added in 0.6.0.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SeparatorStyle {
    /// 0: `1,234.56`.
    CommaDot,
    /// 1: `1234.56`.
    Dot,
    /// 2: `1.234,56`.
    DotComma,
    /// 3: `1234,56`.
    Comma,
    /// 4: `1'234.56`.
    ApostropheDot,
}

/// `negStyle`.
///
/// Added in 0.6.0.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum NegativeStyle {
    /// 0: a minus sign.
    Minus,
    /// 1: red, without a sign.
    Red,
    /// 2: in parentheses.
    Parentheses,
    /// 3: red, in parentheses.
    RedParentheses,
}

/// A percentage: the number times 100, with a `%`.
///
/// Added in 0.6.0.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct PercentFormat {
    /// Digits after the point.
    pub decimals: u8,
    /// How thousands are grouped and the point written.
    pub separator: SeparatorStyle,
    /// Whether the `%` comes first.
    pub prepend: bool,
}

/// A date or time pattern, as `util.printd` writes it (`mmmm d, yyyy`, `h:MM tt`).
///
/// Added in 0.6.0.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct DatePattern {
    /// The pattern.
    pub pattern: String,
}

/// `AFSpecial_Format`'s kinds.
///
/// Added in 0.6.0.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SpecialFormat {
    /// 0: `12345`.
    Zip,
    /// 1: `12345-6789`.
    ZipPlus4,
    /// 2: `(555) 123-4567`, or `123-4567` without an area code.
    Phone,
    /// 3: `123-45-6789`.
    Ssn,
}

/// Bounds a number must keep, each inclusive and optional.
///
/// Added in 0.6.0.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct RangeValidate {
    /// The least value accepted.
    pub min: Option<f64>,
    /// The greatest value accepted.
    pub max: Option<f64>,
}

/// A value computed from other fields'.
///
/// Added in 0.6.0.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct SimpleCalculate {
    /// What it computes.
    pub function: CalculateFunction,
    /// The fields it reads, by full name; a name of a field with kids reads every terminal
    /// field below it.
    pub fields: Vec<String>,
}

/// `AFSimple_Calculate`'s functions.
///
/// Added in 0.6.0.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum CalculateFunction {
    /// `SUM`.
    Sum,
    /// `AVG`.
    Average,
    /// `PRD`.
    Product,
    /// `MIN`.
    Minimum,
    /// `MAX`.
    Maximum,
}

/// What a field's scripts do, as far as they are helper calls.
///
/// Added in 0.6.0.
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct Behaviour {
    /// `K`, when it is a helper call.
    pub keystroke: Option<FieldBehaviour>,
    /// `F`, when it is a helper call.
    pub format: Option<FieldBehaviour>,
    /// `V`, when it is a helper call.
    pub validate: Option<FieldBehaviour>,
    /// `C`, when it is a helper call.
    pub calculate: Option<SimpleCalculate>,
    /// The triggers whose scripts aren't helper calls: the field is filled without them.
    pub not_handled: Vec<FieldTrigger>,
}

/// What a field shows for its value.
///
/// Added in 0.6.0.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ShownValue {
    /// The text.
    pub text: String,
    /// Whether a negative number's style draws it red.
    pub red: bool,
}

/// Why a committed value is refused.
///
/// Added in 0.6.0.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum InvalidValue {
    /// It isn't a number (`AFNumber_Keystroke`, `AFPercent_Keystroke`).
    NotANumber,
    /// It isn't a date or time in `pattern` (`AFDate_KeystrokeEx`, `AFTime_Keystroke`).
    NotADate {
        /// The pattern.
        pattern: String,
    },
    /// It doesn't fit the format's mask (`AFSpecial_Keystroke`).
    NotSpecial(SpecialFormat),
    /// It is outside the bounds (`AFRange_Validate`).
    OutOfRange(RangeValidate),
}

impl InvalidValue {
    /// The rule it broke, as `field-value-invalid`'s `reason` names it: `range` for a number
    /// outside its bounds, `format` for any other.
    ///
    /// Added in 0.6.0.
    #[must_use]
    pub const fn reason(&self) -> &'static str {
        match self {
            Self::OutOfRange(_) => "range",
            _ => "format",
        }
    }
}

impl ShownValue {
    /// `text` as it is, in the field's own colour.
    ///
    /// Added in 0.6.0.
    #[must_use]
    pub const fn plain(text: String) -> Self {
        Self { text, red: false }
    }
}

impl FieldBehaviour {
    /// What a format shows for `value`; `None` for a behaviour that isn't a format.
    ///
    /// A number shows nothing for text that holds no number, as pdf.js does, and a percent
    /// shows `%`; an empty field shows nothing either way (pdf.js shows `%` there too). A date
    /// it can't read shows as typed.
    ///
    /// Added in 0.6.0.
    #[must_use]
    pub fn show(&self, value: &str) -> Option<ShownValue> {
        let plain = ShownValue::plain;
        Some(match self {
            Self::NumberFormat(f) => match f.show(value) {
                Some((text, red)) => ShownValue { text, red },
                None => plain(String::new()),
            },
            Self::PercentFormat(f) => plain(match f.show(value) {
                Some(text) => text,
                None if value.is_empty() => String::new(),
                None => "%".to_owned(),
            }),
            Self::DateFormat(f) | Self::TimeFormat(f) => plain(if value.is_empty() {
                String::new()
            } else {
                date::parse(&f.pattern, value).map_or_else(|| value.to_owned(), |d| date::printd(&f.pattern, d))
            }),
            Self::SpecialFormat(f) => plain(f.show(value)),
            Self::RangeValidate(_) | Self::SimpleCalculate(_) => return None,
        })
    }

    /// Whether a keystroke behaviour takes `text` as the field's text while it is typed; every
    /// text, for a behaviour that isn't a keystroke check.
    ///
    /// Added in 0.6.0.
    #[must_use]
    pub fn accepts(&self, text: &str) -> bool {
        match self {
            Self::NumberFormat(NumberFormat { separator, .. })
            | Self::PercentFormat(PercentFormat { separator, .. }) => {
                number::keystroke_accepts(*separator, text, false)
            }
            Self::SpecialFormat(f) => f.accepts(text, false),
            _ => true,
        }
    }

    /// The value committing `text` stores, or why it is refused: the keystroke check at
    /// commit, then a range's bounds.
    ///
    /// # Errors
    /// [`InvalidValue`], what the check refuses.
    ///
    /// Added in 0.6.0.
    pub fn commit(&self, text: &str) -> Result<String, InvalidValue> {
        match self {
            Self::NumberFormat(NumberFormat { separator, .. })
            | Self::PercentFormat(PercentFormat { separator, .. }) => {
                if number::keystroke_accepts(*separator, text, true) {
                    Ok(number::committed(*separator, text))
                } else {
                    Err(InvalidValue::NotANumber)
                }
            }
            Self::DateFormat(f) | Self::TimeFormat(f) => {
                if text.is_empty() || date::parse(&f.pattern, text).is_some() {
                    Ok(text.to_owned())
                } else {
                    Err(InvalidValue::NotADate {
                        pattern: f.pattern.clone(),
                    })
                }
            }
            Self::SpecialFormat(f) => {
                if f.accepts(text, true) {
                    Ok(text.to_owned())
                } else {
                    Err(InvalidValue::NotSpecial(*f))
                }
            }
            Self::RangeValidate(r) => {
                let inside = number::make_number(text)
                    .is_none_or(|v| r.min.is_none_or(|min| v >= min) && r.max.is_none_or(|max| v <= max));
                if text.is_empty() || inside {
                    Ok(text.to_owned())
                } else {
                    Err(InvalidValue::OutOfRange(*r))
                }
            }
            Self::SimpleCalculate(_) => Ok(text.to_owned()),
        }
    }
}

impl Behaviour {
    /// What the field shows for `value`: its format's text, else the value.
    ///
    /// Added in 0.6.0.
    #[must_use]
    pub fn show(&self, value: &str) -> ShownValue {
        self.format
            .as_ref()
            .and_then(|f| f.show(value))
            .unwrap_or_else(|| ShownValue {
                text: value.to_owned(),
                red: false,
            })
    }

    /// The value committing `text` stores: the keystroke check, then validation.
    ///
    /// # Errors
    /// [`InvalidValue`], what a check refuses.
    ///
    /// Added in 0.6.0.
    pub fn commit(&self, text: &str) -> Result<String, InvalidValue> {
        let mut value = text.to_owned();
        for behaviour in [&self.keystroke, &self.validate].into_iter().flatten() {
            value = behaviour.commit(&value)?;
        }
        Ok(value)
    }
}

/// A form's values by full name, as a calculation reads them: text, a button's state or a
/// choice's first option.
///
/// Added in 0.6.0.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FormValues(std::collections::BTreeMap<String, String>);

impl FormValues {
    /// The values of `form`'s terminal fields.
    ///
    /// Added in 0.6.0.
    #[must_use]
    pub fn of(form: &Form) -> Self {
        Self(
            form.fields
                .iter()
                .map(|f| {
                    let text = match &f.value {
                        Some(FieldValue::Text(t)) => t.clone(),
                        Some(FieldValue::Button(Some(s))) => s.clone(),
                        Some(FieldValue::Choice(c)) => c.first().cloned().unwrap_or_default(),
                        _ => String::new(),
                    };
                    (f.name.clone(), text)
                })
                .collect(),
        )
    }

    /// Gives the field `name` the value `text`, as a calculation that changed it does.
    ///
    /// Added in 0.6.0.
    pub fn set(&mut self, name: &str, text: String) {
        self.0.insert(name.to_owned(), text);
    }

    /// The value of the field `name`.
    ///
    /// Added in 0.6.0.
    #[must_use]
    pub fn get(&self, name: &str) -> Option<&str> {
        self.0.get(name).map(String::as_str)
    }

    /// The values of the field `name` and of every field below it (`name.first`, …).
    fn under<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a str> + 'a {
        let own = self.0.get(name).map(String::as_str);
        let prefix = format!("{name}.");
        let below = self
            .0
            .range(prefix.clone()..)
            .take_while(move |(k, _)| k.starts_with(&prefix))
            .map(|(_, v)| v.as_str());
        own.into_iter().chain(below)
    }
}

impl SimpleCalculate {
    /// The value it computes from `values`, as `AFSimple_Calculate` does: each named field's
    /// terminal fields, a value that isn't a number counting 0, rounded to six places and
    /// written as JavaScript writes a number. A name the form doesn't have counts nothing.
    ///
    /// Added in 0.6.0.
    #[must_use]
    pub fn compute(&self, values: &FormValues) -> String {
        let mut numbers = Vec::new();
        for name in &self.fields {
            numbers.extend(values.under(name).map(|t| number::make_number(t).unwrap_or(0.0)));
        }
        if numbers.is_empty() {
            return "0".to_owned();
        }
        let sum = || {
            // Neumaier's compensated sum, close to `Math.sumPrecise`.
            let (mut total, mut carry) = (0.0_f64, 0.0_f64);
            for v in &numbers {
                let t = total + v;
                carry += if total.abs() >= v.abs() {
                    (total - t) + v
                } else {
                    (v - t) + total
                };
                total = t;
            }
            total + carry
        };
        let result = match self.function {
            CalculateFunction::Sum => sum(),
            #[expect(clippy::cast_precision_loss, reason = "a count of fields")]
            CalculateFunction::Average => sum() / numbers.len() as f64,
            CalculateFunction::Product => numbers.iter().product(),
            CalculateFunction::Minimum => numbers.iter().copied().fold(f64::INFINITY, f64::min),
            CalculateFunction::Maximum => numbers.iter().copied().fold(f64::NEG_INFINITY, f64::max),
        };
        // `Math.round(1e6 * x) / 1e6`: halves round up, towards positive infinity.
        let scaled = 1e6 * result;
        let rounded = if scaled - scaled.floor() >= 0.5 {
            scaled.floor() + 1.0
        } else {
            scaled.floor()
        };
        number::js_string(rounded / 1e6)
    }
}