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
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
//! Actions and scripts (§12.6): what each trigger fires, followed through `/Next`, once each.

use std::collections::BTreeMap;

use laminapdf_cos::{Dict, Object, Result, tolerant};

use super::{Action, Owner, Scan, Trigger, len, name_of};
use crate::document::Document;
use crate::outline::ActionKind;

/// Actions listed at most, so a report of a file with a huge `/Next` graph stays small. The walk
/// goes on past it without listing, each action object once, and notes any active one it finds
/// ([`Disclosure::actions_truncated`](super::Disclosure::actions_truncated)).
const MAX_ACTIONS: usize = 10_000;

/// Bookmarks read at most, so a hostile outline stays bounded.
const MAX_OUTLINE_ITEMS: usize = 10_000_000;

impl Scan<'_> {
    /// Each bookmark's `/A` (§12.3.3), the tree walked through `/First` and `/Next`, each item
    /// once, within [`MAX_OUTLINE_ITEMS`]; past it, the walk counts as cut short.
    pub(super) fn outlines(&mut self, catalog: &Dict) -> Result<()> {
        let Some(root) = catalog.get("Outlines") else {
            return Ok(());
        };
        let Some(root) = self.read(root)? else {
            return Ok(());
        };
        let mut stack: Vec<Object> = root
            .as_dict()
            .and_then(|d| d.get("First").cloned())
            .into_iter()
            .collect();
        let mut seen = std::collections::BTreeSet::new();
        let mut steps = 0_usize;
        while let Some(item) = stack.pop() {
            steps += 1;
            if steps > MAX_OUTLINE_ITEMS {
                self.out.actions_truncated = true;
                return Ok(());
            }
            let object = item.as_ref().map(|r| r.num);
            if object.is_some_and(|n| !seen.insert(n)) {
                continue;
            }
            let Some(value) = self.read(&item)? else { continue };
            let Some(dict) = value.as_dict() else { continue };
            if let Some(a) = dict.get("A") {
                self.actions(a, &Trigger::Activate, &Owner::Outline(object))?;
            }
            stack.extend(dict.get("Next").cloned());
            stack.extend(dict.get("First").cloned());
        }
        Ok(())
    }

    /// The catalog's `/OpenAction` and `/AA`, and the `/JavaScript` name tree.
    pub(super) fn document_actions(&mut self, catalog: &Dict) -> Result<()> {
        if let Some(open) = catalog.get("OpenAction") {
            // An array is a destination, not an action (§12.3.2).
            if self.read(open)?.is_some_and(|o| o.as_dict().is_some()) {
                self.actions(open, &Trigger::OpenAction, &Owner::Document)?;
            }
        }
        self.additional(catalog, &Owner::Document)?;
        if let Some(tree) = self.doc.name_tree("JavaScript")? {
            for (name, action) in tree.entries()? {
                let trigger = Trigger::NamedScript(String::from_utf8_lossy(&name).into_owned());
                self.actions(&action, &trigger, &Owner::Document)?;
            }
        }
        Ok(())
    }

    /// The actions of `dict`'s `/AA` dictionary, each under its key.
    pub(super) fn additional(&mut self, dict: &Dict, owner: &Owner) -> Result<()> {
        let Some(aa) = dict.get("AA") else {
            return Ok(());
        };
        let Some(aa) = self.read(aa)? else {
            return Ok(());
        };
        let Some(aa) = aa.as_dict() else {
            return Ok(());
        };
        for (key, action) in aa.iter() {
            let trigger = Trigger::Additional(String::from_utf8_lossy(key.as_bytes()).into_owned());
            self.actions(action, &trigger, owner)?;
        }
        Ok(())
    }

    /// The action at `start` and those its `/Next` reaches (a dictionary or an array of
    /// them), each listed once.
    pub(super) fn actions(&mut self, start: &Object, trigger: &Trigger, owner: &Owner) -> Result<()> {
        let mut stack = vec![start.clone()];
        while let Some(obj) = stack.pop() {
            let object = obj.as_ref().map(|r| r.num);
            if let Some(num) = object
                && !self.seen_actions.insert(num)
            {
                continue;
            }
            let Some(action) = self.read(&obj)? else { continue };
            if let Some(items) = action.as_array() {
                stack.extend(items.iter().rev().cloned());
                continue;
            }
            let Some(dict) = action.as_dict() else { continue };
            // `/S` may be a reference to the name (pdf.js follows it); one that can't be read as a
            // name is still an action, of a type no one knows.
            let Some(s) = dict.get("S") else { continue };
            let kind = self
                .read(s)?
                .as_deref()
                .and_then(name_of)
                .unwrap_or_else(|| "?".to_owned());
            let kind = ActionKind::from_name(kind.as_bytes());
            let script_bytes = match kind {
                ActionKind::JavaScript => self.script_bytes(dict)?,
                _ => None,
            };
            let reaches_outside = self.doc.action_reaches_outside(dict, &mut self.targets)?;
            let action = Action {
                kind,
                trigger: trigger.clone(),
                owner: owner.clone(),
                object,
                script_bytes,
                reaches_outside,
            };
            if self.out.actions.len() < MAX_ACTIONS {
                self.out.actions.push(action);
            } else if action.is_active_content() {
                self.out.actions_truncated = true;
            }
            if let Some(next) = dict.get("Next") {
                stack.push(next.clone());
            }
        }
        Ok(())
    }

    /// The length of a JavaScript action's `/JS`: a string's bytes, or a stream decoded (its
    /// stored length when decoding fails or passes `max_stream_decoded`).
    fn script_bytes(&self, action: &Dict) -> Result<Option<u64>> {
        let Some(js) = action.get("JS") else {
            return Ok(None);
        };
        let Some(js) = self.read(js)? else {
            return Ok(None);
        };
        Ok(match &*js {
            Object::String(s) => Some(len(s.bytes.len())),
            Object::Stream(s) => Some(len(
                tolerant(self.doc.decode_stream(s))?.map_or(s.data.len(), |d| d.len())
            )),
            _ => None,
        })
    }
}

/// What checking action targets has learned and cost, kept across the actions of one scan: the
/// verdict for each target object already read, so many actions sharing one target read it once,
/// and the steps taken (each value looked at), which a caller may charge to a budget.
///
/// Added in 0.7.0.
#[derive(Debug, Default)]
pub struct TargetCheck {
    steps: u64,
    /// Past this many steps every check answers yes (`u64::MAX` unless a caller sets one).
    limit: Option<u64>,
    /// Each target object's verdict: a dictionary's by object, an array's by object and what a
    /// string in it is.
    verdict: BTreeMap<(u32, Slot), bool>,
}

impl TargetCheck {
    /// A check that has read nothing yet.
    ///
    /// Added in 0.7.0.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// How many steps the checks have taken so far: one for each dictionary, reference and
    /// array item looked at, counted before it is read.
    ///
    /// Added in 0.7.0.
    #[must_use]
    pub const fn steps(&self) -> u64 {
        self.steps
    }

    /// Sets the step count past which every check answers yes without reading further, so a
    /// caller's work budget bounds the checks as they run.
    ///
    /// Added in 0.7.0.
    pub const fn set_limit(&mut self, limit: u64) {
        self.limit = Some(limit);
    }

    /// Takes one step; true when the limit is passed.
    fn tick(&mut self) -> bool {
        self.steps += 1;
        self.limit.is_some_and(|limit| self.steps > limit)
    }
}

/// Whether a file name (a file specification string) beside an embedded copy may name a file
/// elsewhere: anything but a plain relative name. A plain name is readable text whose segments,
/// split at `/` and `\\`, are none of them empty, `.`, `..` or a Windows device name, nor start
/// or end with a space. It has no colon, no percent escape (`%` and two hex digits; a bare `50%`
/// is fine), doesn't start with `~`, and holds no control character, no invisible format
/// character (a zero-width joiner or non-joiner only between two letters or marks), and no
/// character that looks like a separator or a colon ([`LOOKALIKES`]). Full-width and other
/// look-alike dots, tildes, percent signs, digits and Latin letters are read as the ones they
/// look like ([`fold`]). Letters, marks, numbers, spaces, punctuation and symbols of any script
/// are fine.
fn names_elsewhere(bytes: &[u8]) -> bool {
    let text = fold(&laminapdf_syntax::text::decode_text_string(bytes));
    let chars: Vec<char> = text.chars().collect();
    let wordy = |c: Option<&char>| c.is_some_and(|c| c.is_alphanumeric() || is_mark(*c));
    let bad_char = chars.iter().enumerate().any(|(i, &c)| {
        let joiner = matches!(c, '\u{200c}' | '\u{200d}');
        if joiner {
            return !(wordy(i.checked_sub(1).and_then(|p| chars.get(p))) && wordy(chars.get(i + 1)));
        }
        c == ':' || c == '\u{fffd}' || c.is_control() || is_format(c) || LOOKALIKES.contains(&c)
    });
    let escape = chars
        .windows(3)
        .any(|w| matches!(w, ['%', a, b] if a.is_ascii_hexdigit() && b.is_ascii_hexdigit()));
    let bad_segment = text.split(['/', '\\']).any(|segment| {
        segment.is_empty()
            || segment == "."
            || segment == ".."
            || segment.starts_with(char::is_whitespace)
            || segment.ends_with(char::is_whitespace)
            || is_device(segment)
    });
    bad_char || escape || bad_segment || text.starts_with('~')
}

/// `name` with the characters that compatibility normalisation (NFKC) turns into a dot, a tilde,
/// a percent sign, a digit or a Latin letter turned into it, so a name that a file system or viewer
/// may normalise is judged as what it would become.
fn fold(name: &str) -> String {
    let mut out = String::with_capacity(name.len());
    for c in name.chars() {
        match c {
            '\u{2024}' | '\u{fe52}' | '\u{ff0e}' => out.push('.'),
            '\u{2025}' | '\u{fe30}' => out.push_str(".."),
            '\u{2026}' | '\u{fe19}' => out.push_str("..."),
            '\u{fe6a}' | '\u{ff05}' => out.push('%'),
            '\u{ff5e}' => out.push('~'),
            // The full-width digits and Latin letters sit one block up from ASCII's.
            '\u{ff10}'..='\u{ff19}' | '\u{ff21}'..='\u{ff3a}' | '\u{ff41}'..='\u{ff5a}' => {
                out.push(char::from_u32(u32::from(c) - 0xfee0).unwrap_or(c));
            }
            _ => out.push(c),
        }
    }
    out
}

/// Whether Windows reads the path segment `segment` as a device rather than a file: a reserved
/// name, alone or before a dot, in either case.
fn is_device(segment: &str) -> bool {
    let stem = segment
        .split('.')
        .next()
        .unwrap_or_default()
        .trim_end()
        .to_ascii_uppercase();
    let numbered = ["COM", "LPT"].iter().any(|device| {
        stem.strip_prefix(device).is_some_and(|n| {
            let mut digits = n.chars();
            matches!(digits.next(), Some('1'..='9' | '\u{b9}' | '\u{b2}' | '\u{b3}')) && digits.next().is_none()
        })
    });
    numbered || matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$")
}

/// Characters that look like a path separator or a colon, which a viewer or file system may
/// read as one: fullwidth, small and mathematical solidi and reverse solidi, the yen and won
/// signs (a backslash in Japanese and Korean code pages), and colon-like letters and marks.
const LOOKALIKES: [char; 30] = [
    '\u{ff0f}', '\u{ff3c}', '\u{fe68}', '\u{2215}', '\u{2216}', '\u{2044}', '\u{29f5}', '\u{29f8}', '\u{29f9}',
    '\u{a5}', '\u{20a9}', '\u{ffe5}', '\u{ffe6}', '\u{2571}', '\u{2572}', '\u{ff1a}', '\u{fe55}', '\u{fe13}',
    '\u{2236}', '\u{a789}', '\u{2d0}', '\u{2f8}', '\u{589}', '\u{5c3}', '\u{703}', '\u{704}', '\u{16ec}', '\u{205a}',
    '\u{2e2c}', '\u{a4fd}',
];

/// Whether `c` is an invisible format character (Unicode category Cf) or a line or paragraph
/// separator.
fn is_format(c: char) -> bool {
    matches!(c,
        '\u{ad}' | '\u{600}'..='\u{605}' | '\u{61c}' | '\u{6dd}' | '\u{70f}' | '\u{890}'..='\u{891}'
        | '\u{8e2}' | '\u{180e}' | '\u{200b}'..='\u{200f}' | '\u{2028}'..='\u{202e}'
        | '\u{2060}'..='\u{2064}' | '\u{2066}'..='\u{206f}' | '\u{feff}' | '\u{fff9}'..='\u{fffb}'
        | '\u{110bd}' | '\u{110cd}' | '\u{13430}'..='\u{1343f}' | '\u{1bca0}'..='\u{1bca3}'
        | '\u{1d173}'..='\u{1d17a}' | '\u{e0001}' | '\u{e0020}'..='\u{e007f}')
}

/// Whether `c` is a combining mark (Unicode category M), in the blocks file names use: combining
/// diacritics, and the vowel signs and viramas of the Indic, Arabic and other scripts (which
/// [`char::is_alphanumeric`] doesn't count), so a joiner beside one sits inside a word.
fn is_mark(c: char) -> bool {
    matches!(c,
        '\u{300}'..='\u{36f}' | '\u{483}'..='\u{489}' | '\u{591}'..='\u{5c7}' | '\u{610}'..='\u{61a}'
        | '\u{64b}'..='\u{65f}' | '\u{670}' | '\u{6d6}'..='\u{6ed}' | '\u{900}'..='\u{903}'
        | '\u{93a}'..='\u{94f}' | '\u{951}'..='\u{957}' | '\u{962}'..='\u{963}' | '\u{981}'..='\u{9fe}'
        | '\u{a01}'..='\u{d4d}' | '\u{e31}'..='\u{e3a}' | '\u{e47}'..='\u{e4e}' | '\u{1ab0}'..='\u{1aff}'
        | '\u{1dc0}'..='\u{1dff}' | '\u{20d0}'..='\u{20ff}' | '\u{fe00}'..='\u{fe0f}' | '\u{fe20}'..='\u{fe2f}')
}

/// The keys of a stream dictionary that read its data from another file (§7.3.8.2).
pub(super) const EXTERNAL_DATA: [&str; 3] = ["F", "FFilter", "FDecodeParms"];

/// The standard named actions (ISO 32000-2 Table 203): page moves. Any other name is a viewer's
/// own command (`/Print`, `/SaveAs`), which acts outside the page.
const STANDARD_NAMES: [&[u8]; 4] = [b"NextPage", b"PrevPage", b"FirstPage", b"LastPage"];

/// The action types whose target can be another file or the web while the type itself only moves
/// within the document or shows media (§12.6.4).
const MAY_LEAVE: [&[u8]; 7] = [
    b"GoTo",
    b"GoToE",
    b"Thread",
    b"Rendition",
    b"Movie",
    b"Sound",
    b"GoToDp",
];

/// A file specification's file names (§7.11.3): a string here names a file outside the document,
/// unless the specification embeds it.
const FILE_KEYS: [&str; 5] = ["F", "UF", "Unix", "DOS", "Mac"];

/// The keys an action's target is reached through: renditions and their selector arrays (`/R`),
/// media clips (`/C`, and a clip's or section's `/D`), file specifications (`/F`, `/UF`, `/FS`),
/// sounds, movies, a `GoToE` target (`/T`) and media criteria. A destination, a page, `/Next` and
/// `/P` are not followed.
const TARGET_KEYS: [&str; 12] = [
    "R",
    "C",
    "D",
    "F",
    "UF",
    "FS",
    "Sound",
    "Movie",
    "Annotation",
    "MH",
    "BE",
    "SP",
];

/// Target objects read at most for one action (each once per [`TargetCheck`]), and how deep the
/// walk goes: past either, the answer is yes.
const MAX_TARGET_OBJECTS: usize = 64;
const MAX_TARGET_DEPTH: usize = 16;

/// What a cached verdict is for: a dictionary (or stream), whose verdict is its own, or an array,
/// whose verdict depends on what a string in it is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Slot {
    Dict,
    Array(FileName),
}

/// One action's target walk, which caches each object's verdict with Tarjan's algorithm for
/// strongly connected components. Each object gets an index as its walk begins and stays on the
/// walk's stack until its component is complete. Meeting an object on the stack (an object of a
/// cycle still open) answers no for now and records the lowest index met. An object whose walk
/// met nothing below its own index is the root of its component: the component's members are
/// exactly the objects above it on the stack, they reach what it reaches, and they all take its
/// verdict, which is the OR of every member's own findings and edges out of the component. Every
/// object is walked once per [`TargetCheck`], however many times a cycle meets it.
struct Target<'a> {
    doc: &'a Document,
    check: &'a mut TargetCheck,
    objects: usize,
    /// The index the next object walked gets.
    next: usize,
    /// The objects on the stack (walk under way, or done and waiting for their component's
    /// root), by index.
    open: BTreeMap<(u32, Slot), usize>,
    /// The lowest index of an object on the stack met since the current object's walk began.
    back: usize,
    /// The stack's objects done and waiting for their component's root, in the order done.
    waiting: Vec<(u32, Slot)>,
}

impl Target<'_> {
    /// The name at `key` of `d`, resolved through a reference.
    fn name(&mut self, d: &Dict, key: &str) -> Result<Option<Vec<u8>>> {
        let Some(value) = d.get(key) else { return Ok(None) };
        if let Object::Name(n) = value {
            return Ok(Some(n.as_bytes().to_vec()));
        }
        Ok(match self.doc.read(value)?.as_deref() {
            Some(Object::Name(n)) => Some(n.as_bytes().to_vec()),
            _ => None,
        })
    }

    /// Whether `d` (the action itself when `action`) reaches outside the document.
    fn dict(&mut self, d: &Dict, action: bool, depth: usize) -> Result<bool> {
        if self.check.tick() || depth > MAX_TARGET_DEPTH {
            return Ok(true);
        }
        if self.name(d, "FS")?.as_deref() == Some(b"URL") {
            return Ok(true);
        }
        let s = self.name(d, "S")?;
        // A media clip or section names its data in `/D`; elsewhere `/D` is a destination.
        let clip = matches!(s.as_deref(), Some(b"MCD" | b"MCS"));
        let data = s.as_deref() == Some(b"MCD");
        let embedded = if action || d.contains_key("S") {
            false
        } else {
            match self.embeds(d)? {
                Embeds::Outside => return Ok(true),
                Embeds::Yes => true,
                Embeds::No => false,
            }
        };
        for key in TARGET_KEYS.iter().chain(&FILE_KEYS[2..]) {
            if *key == "D" && !clip {
                continue;
            }
            let Some(value) = d.get(key) else { continue };
            let file_name = if FILE_KEYS.contains(key) {
                // Beside an embedded copy, only a name that may point elsewhere still reaches out.
                if embedded { FileName::Elsewhere } else { FileName::Any }
            } else if *key == "D" && data {
                FileName::Any
            } else {
                FileName::No
            };
            if self.value(value, file_name, depth)? {
                return Ok(true);
            }
        }
        Ok(false)
    }

    /// Whether `value`, under a key where a string is a file name as `file_name` says, reaches
    /// outside the document.
    fn value(&mut self, value: &Object, file_name: FileName, depth: usize) -> Result<bool> {
        if self.check.tick() {
            return Ok(true);
        }
        match value {
            Object::String(s) => Ok(file_name.reaches(&s.bytes)),
            Object::Dict(d) => self.dict(d, false, depth + 1),
            Object::Array(items) => self.array(items, file_name, depth + 1),
            Object::Ref(r) => self.reference(r.num, value, file_name, depth),
            _ => Ok(false),
        }
    }

    /// The verdict kept for object `num` read as a dictionary or as an array under `file_name`.
    fn known(&self, num: u32, file_name: FileName) -> Option<bool> {
        [Slot::Dict, Slot::Array(file_name)]
            .iter()
            .find_map(|slot| self.check.verdict.get(&(num, *slot)).copied())
    }

    /// [`Target::value`] for a reference: each object walked once per check (see [`Target`]).
    fn reference(&mut self, num: u32, value: &Object, file_name: FileName, depth: usize) -> Result<bool> {
        if let Some(known) = self.known(num, file_name) {
            return Ok(known);
        }
        if let Some(&at) = [Slot::Dict, Slot::Array(file_name)]
            .iter()
            .find_map(|slot| self.open.get(&(num, *slot)))
        {
            // In a component still open: what it reaches counts at the component's root.
            self.back = self.back.min(at);
            return Ok(false);
        }
        self.objects += 1;
        if self.objects > MAX_TARGET_OBJECTS {
            return Ok(true);
        }
        let Some(read) = self.doc.read(value)? else {
            return Ok(false);
        };
        let slot = match &*read {
            Object::Dict(_) | Object::Stream(_) => Slot::Dict,
            Object::Array(_) => Slot::Array(file_name),
            Object::String(s) => return Ok(file_name.reaches(&s.bytes)),
            _ => return Ok(false),
        };
        let key = (num, slot);
        let index = self.next;
        self.next += 1;
        self.open.insert(key, index);
        let outer = std::mem::replace(&mut self.back, usize::MAX);
        let waiting = self.waiting.len();
        let out = match &*read {
            Object::Dict(d) => self.dict(d, false, depth + 1)?,
            Object::Stream(st) => self.dict(&st.dict, false, depth + 1)?,
            Object::Array(items) => self.array(items, file_name, depth + 1)?,
            _ => false,
        };
        let back = std::mem::replace(&mut self.back, outer);
        if out || back >= index {
            // The root of its component (or a yes, which holds for whatever reaches this
            // object): it and the members done since it began take its verdict.
            for member in self.waiting.drain(waiting..) {
                self.open.remove(&member);
                self.check.verdict.insert(member, out);
            }
            self.open.remove(&key);
            self.check.verdict.insert(key, out);
        } else {
            // A member of a component whose root is below it: it stays on the stack.
            self.back = self.back.min(back);
            self.waiting.push(key);
        }
        Ok(out)
    }

    /// Whether any item of an array under a target key reaches outside the document.
    fn array(&mut self, items: &[Object], file_name: FileName, depth: usize) -> Result<bool> {
        if depth > MAX_TARGET_DEPTH {
            return Ok(true);
        }
        for item in items {
            if self.value(item, file_name, depth)? {
                return Ok(true);
            }
        }
        Ok(false)
    }

    /// Whether the file specification `d` embeds its file: an `/EF` whose `/F` or `/UF` is a
    /// stream; [`Embeds::Outside`] when that stream's own data is read from elsewhere (`/F`).
    fn embeds(&mut self, d: &Dict) -> Result<Embeds> {
        let Some(ef) = d.get("EF") else { return Ok(Embeds::No) };
        if self.check.tick() {
            return Ok(Embeds::Outside);
        }
        let Some(ef) = self.doc.read(ef)? else {
            return Ok(Embeds::No);
        };
        let Some(ef) = ef.as_dict() else { return Ok(Embeds::No) };
        let mut embedded = Embeds::No;
        for key in ["F", "UF"] {
            if let Some(file) = ef.get(key) {
                if self.check.tick() {
                    return Ok(Embeds::Outside);
                }
                if let Some(Object::Stream(st)) = self.doc.read(file)?.as_deref() {
                    if EXTERNAL_DATA.iter().any(|k| st.dict.contains_key(k)) {
                        return Ok(Embeds::Outside);
                    }
                    embedded = Embeds::Yes;
                }
            }
        }
        Ok(embedded)
    }
}

/// Whether a file specification embeds its file.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Embeds {
    No,
    Yes,
    /// The embedded stream's data is itself read from another file (its `/F`).
    Outside,
}

/// What a string under a key is: no file name, any file name (reaches outside), or a file name
/// beside an embedded copy (reaches outside unless it is [a plain relative name](names_elsewhere)).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum FileName {
    No,
    Any,
    Elsewhere,
}

impl FileName {
    fn reaches(self, bytes: &[u8]) -> bool {
        match self {
            Self::No => false,
            Self::Any => true,
            Self::Elsewhere => names_elsewhere(bytes),
        }
    }
}

impl Document {
    /// Whether the file specification `spec` (a string, a dictionary or a reference to one)
    /// names a file outside the document, as an action's target file would
    /// ([`Document::action_reaches_outside`]): a file name with no embedded copy, a URL, or an
    /// embedded copy beside a name that isn't plain, or whose data is read from elsewhere.
    ///
    /// # Errors
    /// The reading errors that must propagate.
    ///
    /// Added in 0.7.0.
    pub fn file_reaches_outside(&self, spec: &Object, check: &mut TargetCheck) -> Result<bool> {
        if check.tick() {
            return Ok(true);
        }
        Target {
            doc: self,
            check,
            objects: 0,
            next: 0,
            open: BTreeMap::new(),
            back: usize::MAX,
            waiting: Vec::new(),
        }
        .value(spec, FileName::Any, 0)
    }

    /// The name at `key` of `dict`, read through a reference as a viewer would.
    pub(crate) fn name_entry(&self, dict: &Dict, key: &str) -> Result<Option<Vec<u8>>> {
        let Some(value) = dict.get(key) else { return Ok(None) };
        Ok(match self.read(value)?.as_deref() {
            Some(Object::Name(n)) => Some(n.as_bytes().to_vec()),
            _ => None,
        })
    }

    /// Whether `action`, an action dictionary whose type stays in the document (`GoTo`,
    /// `GoToE`, `Thread`, `Rendition`, `Movie`, `Sound`, `GoToDp`, `Named`), still reaches
    /// outside it: a target file (a file specification's `/F`, `/UF`, `/Unix`, `/DOS` or `/Mac`
    /// with no embedded copy, the action's own `/EF` aside; beside an embedded copy, any but a
    /// plain relative name, or an embedded stream read from elsewhere), a URL file specification
    /// (`/FS /URL`), a media clip whose data is another file or the web (a selector rendition's
    /// choices included), a rendition carrying a script (`/JS`), or a named action no standard
    /// defines (`/Print`). Other types answer false: whether they act outside the page is their
    /// type's to say. `check` keeps what was read, so actions sharing a target read it once;
    /// past a bound of objects or depth, the answer is yes.
    ///
    /// # Errors
    /// The reading errors that must propagate.
    ///
    /// Added in 0.7.0.
    pub fn action_reaches_outside(&self, action: &Dict, check: &mut TargetCheck) -> Result<bool> {
        let Some(s) = action.get("S") else {
            return Ok(false);
        };
        check.steps += 1;
        let kind = self.read(s)?;
        let Some(kind) = kind.as_deref().and_then(|k| match k {
            Object::Name(n) => Some(n.as_bytes().to_vec()),
            _ => None,
        }) else {
            return Ok(false);
        };
        if kind == b"Named" {
            let named = action.get("N").map(|n| self.read(n)).transpose()?.flatten();
            return Ok(!named
                .as_deref()
                .is_some_and(|n| matches!(n, Object::Name(n) if STANDARD_NAMES.contains(&n.as_bytes()))));
        }
        if !MAY_LEAVE.contains(&kind.as_slice()) {
            return Ok(false);
        }
        if kind == b"Rendition" && action.contains_key("JS") {
            return Ok(true);
        }
        Target {
            doc: self,
            check,
            objects: 0,
            next: 0,
            open: BTreeMap::new(),
            back: usize::MAX,
            waiting: Vec::new(),
        }
        .dict(action, true, 0)
    }
}