pdfrum-doc 0.5.2

Bookmarks, annotations, AcroForm data model, structure tree
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
//! Finding an annotation's appearance stream, and placing it on the page.
//!
//! The lookup is a ladder every rung of which has a trap, so it is written
//! once and called from everywhere:
//!
//! 1. `/AP` must be a dictionary.
//! 2. The mode's entry (`/N`, `/R`, `/D`); when the caller allows it, a
//!    **missing key** — not an unusable value — falls back to `/N`.
//! 3. A stream there is the answer.
//! 4. Otherwise it must be a dictionary of states, chosen by `/AS`.
//! 5. With no `/AS`, `/V` on the annotation, then `/V` on its immediate
//!    `/Parent` — one level, not the full inherited-attribute walk — and the
//!    chosen name must actually be a key of the state dictionary or the state
//!    is `Off`.

use kurbo::Affine;
use pdfrum_object::{Dict, Name, Object, Resolve, Stream};

use crate::annot::{Annotation, Subtype};
use crate::geom;
use crate::names;

/// Which appearance a lookup wants.
///
/// ```
/// use pdfrum_doc::annot::{ApMode, annot_ap, has_appearance};
/// use pdfrum_object::{ByteSpan, Dict, Name, NoResolve, Object, Stream};
///
/// let normal = Stream::new(Dict::default(), ByteSpan::whole(b"0 0 10 10 re f".as_slice().into()));
/// let annot = Dict::from_pairs([(
///     Name::from("AP"),
///     Object::Dict(Dict::from_pairs([(
///         Name::from("N"),
///         Object::Stream(Box::new(normal)),
///     )])),
/// )]);
///
/// // A missing `/R` falls back to `/N` when the caller allows it.
/// assert!(annot_ap(&annot, ApMode::Rollover, true, &NoResolve).is_some());
/// assert!(annot_ap(&annot, ApMode::Rollover, false, &NoResolve).is_none());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ApMode {
    /// The normal appearance (`/N`).
    #[default]
    Normal,
    /// The rollover appearance (`/R`).
    Rollover,
    /// The pressed appearance (`/D`).
    Down,
}

impl ApMode {
    /// The `/AP` sub-key this mode reads.
    fn key(self) -> &'static Name {
        match self {
            ApMode::Normal => names::N,
            ApMode::Rollover => names::R,
            ApMode::Down => names::D,
        }
    }
}

/// Resolves an annotation's appearance stream.
///
/// `fallback_to_normal` decides what a missing rollover or down entry means.
/// With it set, a **missing key** falls back to `/N`; a key that is present
/// but holds nothing usable does **not** — it suppresses the fallback and the
/// lookup comes back empty.
///
/// ```
/// use pdfrum_doc::annot::{ApMode, annot_ap, has_appearance};
/// use pdfrum_object::{ByteSpan, Dict, Name, NoResolve, Object, Stream};
///
/// let normal = Stream::new(Dict::default(), ByteSpan::whole(b"0 0 10 10 re f".as_slice().into()));
/// let annot = Dict::from_pairs([(
///     Name::from("AP"),
///     Object::Dict(Dict::from_pairs([(
///         Name::from("N"),
///         Object::Stream(Box::new(normal)),
///     )])),
/// )]);
///
/// assert!(annot_ap(&annot, ApMode::Normal, false, &NoResolve).is_some());
/// // No `/AP` at all: nothing.
/// assert!(annot_ap(&Dict::default(), ApMode::Normal, true, &NoResolve).is_none());
/// ```
#[must_use]
pub fn annot_ap<R: Resolve>(
    dict: &Dict,
    mode: ApMode,
    fallback_to_normal: bool,
    r: &R,
) -> Option<Stream> {
    let ap = dict.dict(names::AP, r)?;
    let mut entry = mode.key();
    if fallback_to_normal && !ap.contains_key(entry) {
        entry = names::N;
    }
    let sub = ap.get(entry, r)?.get().clone();
    if let Object::Stream(stream) = sub {
        return Some(*stream);
    }
    let states = sub.as_dict()?;

    let mut state = dict.byte_string(names::AS, r).unwrap_or_default();
    if state.is_empty() {
        // Both `/AS` and `/V` are read coercively, so a name `/V /Yes` and a
        // string `/V (Yes)` choose the same state.
        let mut value = dict.byte_string(names::V, r).unwrap_or_default();
        if value.is_empty() {
            value = dict
                .dict(names::PARENT, r)
                .and_then(|parent| parent.byte_string(names::V, r))
                .unwrap_or_default();
        }
        // A value naming a state the dictionary lacks falls back to `Off`,
        // not to whichever single on-state exists.
        state = if !value.is_empty() && states.contains_key(&Name::new(value.clone())) {
            value
        } else {
            names::OFF.as_bytes().to_vec()
        };
    }
    states.stream(&Name::new(state), r)
}

/// Whether an annotation already carries a usable normal appearance.
///
/// The test is that `/AP /N` reads as a **dictionary** — and a stream answers
/// with its own dictionary, so the overwhelmingly common "a stream is there"
/// case suppresses generation just as a multi-state dictionary does. Only a
/// missing `/AP`, a missing `/N`, or a scalar `/N` leaves the door open.
///
/// ```
/// use pdfrum_doc::annot::{ApMode, annot_ap, has_appearance};
/// use pdfrum_object::{ByteSpan, Dict, Name, NoResolve, Object, Stream};
///
/// let normal = Stream::new(Dict::default(), ByteSpan::whole(b"0 0 10 10 re f".as_slice().into()));
/// let annot = Dict::from_pairs([(
///     Name::from("AP"),
///     Object::Dict(Dict::from_pairs([(
///         Name::from("N"),
///         Object::Stream(Box::new(normal)),
///     )])),
/// )]);
///
/// assert!(has_appearance(&annot, &NoResolve));
/// assert!(!has_appearance(&Dict::default(), &NoResolve));
/// ```
#[must_use]
pub fn has_appearance<R: Resolve>(dict: &Dict, r: &R) -> bool {
    dict.dict(names::AP, r)
        .and_then(|ap| ap.dict(names::N, r))
        .is_some()
}

/// Whether an annotation stays upright on a rotated page.
///
/// `NoRotate` says so, and a text note (`/Text`, the sticky-note icon) does
/// whatever its flags say: pdf.js sets `noRotate` for every `TextAnnotation`,
/// and poppler and Acrobat keep the icon upright too. Upstream rotates a note
/// without the flag along with the page; three readers out of four do not,
/// so the note follows them.
fn keeps_upright(annot: &Annotation) -> bool {
    annot.flags.no_rotate() || annot.subtype == Subtype::Text
}

/// The transform placing an annotation's appearance form on the page.
///
/// The form's `/BBox`, mapped through its own `/Matrix`, is fitted into the
/// annotation's **normalized** rectangle. A `NoRotate` annotation on a
/// rotated page then counter-rotates about the rectangle's **top-left**
/// corner, which is where the anchor comes from.
///
/// `page_quarter_turns` is the page's `/Rotate` in quarter turns clockwise
/// (`Rotation::quarters`), which is `GetPageRotation` upstream
/// (`cpdf_annot.cpp`, `AnnotGetMatrix`). The sign needs no flip: the matrix
/// built here is in unrotated page space, where `Affine::rotate` with a
/// positive angle turns **counter**-clockwise (y points up), and the page's
/// display matrix then turns everything clockwise by `/Rotate`. The two
/// cancel, so the annotation ends upright on screen, which is also what
/// pdf.js's viewer does for `NoRotate`.
///
/// The composition order is the inverse of the C++'s row-vector `Concat`
/// chain: `kurbo`'s `a * b` applies `b` first, so the fit comes last in the
/// product and `user_to_device` first.
#[must_use]
pub(crate) fn annot_matrix(
    annot: &Annotation,
    form_dict: &Dict,
    page_quarter_turns: u8,
    user_to_device: Affine,
    r: &impl Resolve,
) -> Affine {
    let form_matrix = form_dict.matrix(names::MATRIX, r);
    let form_bbox = geom::transform_rect(form_matrix, form_dict.rect(names::BBOX, r));
    let rect = geom::normalize(annot.rect);
    let mut matrix = geom::match_rect(rect, form_bbox);

    if keeps_upright(annot) && page_quarter_turns != 0 {
        let (ox, oy) = (rect.x0, rect.y1);
        let angle = std::f64::consts::FRAC_PI_2 * f64::from(page_quarter_turns);
        matrix = Affine::translate((ox, oy))
            * Affine::rotate(angle)
            * Affine::translate((-ox, -oy))
            * matrix;
    }
    user_to_device * matrix
}

#[cfg(test)]
mod tests {
    use super::{ApMode, annot_ap, has_appearance};
    use pdfrum_object::{ByteSpan, Dict, Name, NoResolve, Object, PdfString, Stream};

    fn dict(pairs: &[(&str, Object)]) -> Dict {
        Dict::from_pairs(
            pairs
                .iter()
                .map(|(k, v)| (Name::from(*k), v.clone()))
                .collect::<Vec<_>>(),
        )
    }

    fn stream(marker: &[u8]) -> Object {
        Object::Stream(Box::new(Stream::new(
            Dict::new(),
            ByteSpan::from(marker.to_vec()),
        )))
    }

    fn found(annot: &Dict, mode: ApMode, fallback: bool) -> Option<Vec<u8>> {
        annot_ap(annot, mode, fallback, &NoResolve).map(|s| s.data.as_bytes().to_vec())
    }

    #[test]
    fn no_appearance_dictionary_finds_nothing() {
        assert_eq!(found(&Dict::new(), ApMode::Normal, true), None);
        assert_eq!(
            found(&dict(&[("AP", Object::Int(4))]), ApMode::Normal, true),
            None
        );
    }

    #[test]
    fn a_direct_stream_is_the_answer() {
        let annot = dict(&[("AP", Object::Dict(dict(&[("N", stream(b"body"))])))]);
        assert_eq!(found(&annot, ApMode::Normal, true), Some(b"body".to_vec()));
    }

    #[test]
    fn the_mode_fallback_tests_presence_not_usability() {
        let ap_missing_r = dict(&[("AP", Object::Dict(dict(&[("N", stream(b"n"))])))]);
        assert_eq!(
            found(&ap_missing_r, ApMode::Rollover, true),
            Some(b"n".to_vec())
        );
        assert_eq!(found(&ap_missing_r, ApMode::Rollover, false), None);

        // A present-but-null `/R` suppresses the fallback and yields nothing.
        let ap_null_r = dict(&[(
            "AP",
            Object::Dict(dict(&[("N", stream(b"n")), ("R", Object::Null)])),
        )]);
        assert_eq!(found(&ap_null_r, ApMode::Rollover, true), None);
    }

    #[test]
    fn a_state_dictionary_is_chosen_by_the_appearance_state() {
        let states = dict(&[("Yes", stream(b"on")), ("Off", stream(b"off"))]);
        let with_as = dict(&[
            (
                "AP",
                Object::Dict(dict(&[("N", Object::Dict(states.clone()))])),
            ),
            ("AS", Object::Name(Name::from("Yes"))),
        ]);
        assert_eq!(found(&with_as, ApMode::Normal, true), Some(b"on".to_vec()));

        // With no `/AS`, `/V` on the annotation decides — coercively, so a
        // string works as well as a name.
        let with_v = dict(&[
            (
                "AP",
                Object::Dict(dict(&[("N", Object::Dict(states.clone()))])),
            ),
            ("V", Object::Str(PdfString::literal(b"Yes"))),
        ]);
        assert_eq!(found(&with_v, ApMode::Normal, true), Some(b"on".to_vec()));

        // A `/V` naming a state the dictionary lacks falls back to `Off`,
        // not to the only on-state.
        let wrong_v = dict(&[
            (
                "AP",
                Object::Dict(dict(&[("N", Object::Dict(states.clone()))])),
            ),
            ("V", Object::Name(Name::from("Nope"))),
        ]);
        assert_eq!(found(&wrong_v, ApMode::Normal, true), Some(b"off".to_vec()));

        // With neither, `Off` again.
        let bare = dict(&[("AP", Object::Dict(dict(&[("N", Object::Dict(states))])))]);
        assert_eq!(found(&bare, ApMode::Normal, true), Some(b"off".to_vec()));
    }

    #[test]
    fn the_parent_is_consulted_one_level_only() {
        let states = dict(&[("Yes", stream(b"on")), ("Off", stream(b"off"))]);
        let grandparent = dict(&[("V", Object::Name(Name::from("Yes")))]);
        let parent = dict(&[("Parent", Object::Dict(grandparent))]);
        let annot = dict(&[
            (
                "AP",
                Object::Dict(dict(&[("N", Object::Dict(states.clone()))])),
            ),
            ("Parent", Object::Dict(parent)),
        ]);
        // The grandparent's `/V` is invisible to this ladder.
        assert_eq!(found(&annot, ApMode::Normal, true), Some(b"off".to_vec()));

        let direct_parent = dict(&[("V", Object::Name(Name::from("Yes")))]);
        let annot = dict(&[
            ("AP", Object::Dict(dict(&[("N", Object::Dict(states))]))),
            ("Parent", Object::Dict(direct_parent)),
        ]);
        assert_eq!(found(&annot, ApMode::Normal, true), Some(b"on".to_vec()));
    }

    #[test]
    fn a_non_stream_state_value_yields_nothing() {
        let states = dict(&[("Yes", Object::Int(5))]);
        let annot = dict(&[
            ("AP", Object::Dict(dict(&[("N", Object::Dict(states))]))),
            ("AS", Object::Name(Name::from("Yes"))),
        ]);
        assert_eq!(found(&annot, ApMode::Normal, true), None);
    }

    #[test]
    fn a_stream_normal_appearance_counts_as_having_one() {
        let with_stream = dict(&[("AP", Object::Dict(dict(&[("N", stream(b"x"))])))]);
        assert!(has_appearance(&with_stream, &NoResolve));

        let with_states = dict(&[(
            "AP",
            Object::Dict(dict(&[("N", Object::Dict(dict(&[("Yes", stream(b"x"))])))])),
        )]);
        assert!(has_appearance(&with_states, &NoResolve));

        // A scalar `/N` leaves generation open, as does a missing `/AP`.
        let scalar = dict(&[("AP", Object::Dict(dict(&[("N", Object::Int(5))])))]);
        assert!(!has_appearance(&scalar, &NoResolve));
        assert!(!has_appearance(&Dict::new(), &NoResolve));
    }

    /// A `NoRotate` annotation on a rotated page counter-rotates about the
    /// rectangle's top-left corner: that corner stays where it was and the
    /// opposite one moves.
    #[test]
    fn no_rotate_counter_rotates_about_the_top_left_corner() {
        use super::annot_matrix;
        use crate::annot::Annotation;
        use kurbo::{Affine, Point};

        let ints = |values: &[i64]| {
            Object::Array(pdfrum_object::Array::of(
                values.iter().copied().map(Object::Int),
            ))
        };
        let annot = Annotation::read(
            &dict(&[
                ("Subtype", Object::Name(Name::from("Stamp"))),
                ("Rect", ints(&[100, 200, 140, 260])),
                ("F", Object::Int(16)),
            ]),
            &NoResolve,
        );
        let form = dict(&[("BBox", ints(&[0, 0, 40, 60]))]);

        let upright = annot_matrix(&annot, &form, 0, Affine::IDENTITY, &NoResolve);
        let turned = annot_matrix(&annot, &form, 1, Affine::IDENTITY, &NoResolve);

        // The form's top-left corner is the rectangle's top-left, in both.
        let corner = Point::new(100.0, 260.0);
        let top_left = Point::new(0.0, 60.0);
        for matrix in [upright, turned] {
            let got = matrix * top_left;
            assert!(got.distance(corner) < 1e-9, "{got:?}");
        }
        // The opposite corner swings a quarter turn about it.
        let far = turned * Point::new(40.0, 0.0);
        assert!(
            far.distance(Point::new(100.0 + 60.0, 260.0 + 40.0)) < 1e-9,
            "{far:?}"
        );

        // Without the flag the page's rotation changes nothing.
        let plain = Annotation::read(&dict(&[("Rect", ints(&[100, 200, 140, 260]))]), &NoResolve);
        let plain = annot_matrix(&plain, &form, 1, Affine::IDENTITY, &NoResolve);
        let unturned = upright * Point::new(40.0, 0.0);
        assert!((plain * Point::new(40.0, 0.0)).distance(unturned) < 1e-9);
        assert!(
            far.distance(unturned) > 1.0,
            "the turn moved the far corner"
        );
    }
}