rpdfium-doc 7676.6.2

Document-level features for rpdfium
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
// Derived from PDFium's cpdf_bookmark.h/cpp
// Original: Copyright 2014 The PDFium Authors
// Licensed under BSD-3-Clause / Apache-2.0
// See pdfium-upstream/LICENSE for the original license.

//! Bookmark (outline) entry — `CPDF_Bookmark`.
//!
//! A single node in the document outline tree, wrapping a bookmark
//! dictionary and exposing its title, destination, action, and open state
//! (ISO 32000-2 section 12.3.3).
//!
//! Tree traversal is in [`crate::bookmark_tree`] (corresponds to
//! `CPDF_BookmarkTree`).

use std::collections::HashMap;

use rpdfium_core::{Name, PdfSource};
use rpdfium_parser::{Object, ObjectStore};

use crate::action::{Action, parse_action};
use crate::destination::{Destination, parse_destination};
use crate::error::DocResult;

/// A single bookmark entry in the document outline.
#[derive(Debug, Clone)]
pub struct Bookmark {
    /// The visible title of this bookmark.
    pub title: String,
    /// An explicit destination, if specified via `/Dest`.
    pub destination: Option<Destination>,
    /// An action, if specified via `/A`.
    pub action: Option<Action>,
    /// Child bookmarks.
    pub children: Vec<Bookmark>,
    /// Whether this bookmark's children are initially visible.
    pub is_open: bool,
}

impl Bookmark {
    /// Returns the visible title of this bookmark.
    ///
    /// Corresponds to `FPDFBookmark_GetTitle`.
    pub fn title(&self) -> &str {
        &self.title
    }

    /// ADR-019 T2 alias for [`title()`](Self::title).
    ///
    /// Corresponds to `FPDFBookmark_GetTitle`.
    #[inline]
    pub fn bookmark_get_title(&self) -> &str {
        self.title()
    }

    /// Deprecated — use [`bookmark_get_title()`](Self::bookmark_get_title).
    ///
    /// Corresponds to `FPDFBookmark_GetTitle`.
    #[deprecated(note = "use `bookmark_get_title()` — matches upstream `FPDFBookmark_GetTitle`")]
    #[inline]
    pub fn get_title(&self) -> &str {
        self.title()
    }

    /// Returns the first child bookmark, if any.
    ///
    /// Corresponds to `FPDFBookmark_GetFirstChild`.
    pub fn first_child(&self) -> Option<&Bookmark> {
        self.children.first()
    }

    /// ADR-019 T2 alias for [`first_child()`](Self::first_child).
    ///
    /// Corresponds to `FPDFBookmark_GetFirstChild`.
    #[inline]
    pub fn bookmark_get_first_child(&self) -> Option<&Bookmark> {
        self.first_child()
    }

    /// Deprecated — use [`bookmark_get_first_child()`](Self::bookmark_get_first_child).
    ///
    /// Corresponds to `FPDFBookmark_GetFirstChild`.
    #[deprecated(
        note = "use `bookmark_get_first_child()` — matches upstream `FPDFBookmark_GetFirstChild`"
    )]
    #[inline]
    pub fn get_first_child(&self) -> Option<&Bookmark> {
        self.first_child()
    }

    /// Returns the count of direct children (positive = open, negative = closed
    /// in the PDF spec; here returns signed count reflecting `is_open`).
    ///
    /// A positive value means children are shown by default (open state);
    /// a negative value (returned when `!is_open`) means hidden by default.
    ///
    /// Corresponds to `FPDFBookmark_GetCount`.
    pub fn count(&self) -> i32 {
        let n = self.children.len() as i32;
        if self.is_open { n } else { -n }
    }

    /// ADR-019 T2 alias for [`count()`](Self::count).
    ///
    /// Corresponds to `FPDFBookmark_GetCount`.
    #[inline]
    pub fn bookmark_get_count(&self) -> i32 {
        self.count()
    }

    /// Deprecated — use [`bookmark_get_count()`](Self::bookmark_get_count).
    ///
    /// Corresponds to `FPDFBookmark_GetCount`.
    #[deprecated(note = "use `bookmark_get_count()` — matches upstream `FPDFBookmark_GetCount`")]
    #[inline]
    pub fn get_count(&self) -> i32 {
        self.count()
    }

    /// Returns the destination associated with this bookmark, if any.
    ///
    /// Corresponds to `FPDFBookmark_GetDest`.
    pub fn dest(&self) -> Option<&Destination> {
        self.destination.as_ref()
    }

    /// ADR-019 T2 alias for [`dest()`](Self::dest).
    ///
    /// Corresponds to `FPDFBookmark_GetDest`.
    #[inline]
    pub fn bookmark_get_dest(&self) -> Option<&Destination> {
        self.dest()
    }

    /// Deprecated — use [`bookmark_get_dest()`](Self::bookmark_get_dest).
    ///
    /// Corresponds to `FPDFBookmark_GetDest`.
    #[deprecated(note = "use `bookmark_get_dest()` — matches upstream `FPDFBookmark_GetDest`")]
    #[inline]
    pub fn get_dest(&self) -> Option<&Destination> {
        self.dest()
    }

    /// Returns the action associated with this bookmark, if any.
    ///
    /// Corresponds to `FPDFBookmark_GetAction`.
    pub fn action(&self) -> Option<&Action> {
        self.action.as_ref()
    }

    /// ADR-019 T2 alias for [`action()`](Self::action).
    ///
    /// Corresponds to `FPDFBookmark_GetAction`.
    #[inline]
    pub fn bookmark_get_action(&self) -> Option<&Action> {
        self.action()
    }

    /// Deprecated — use [`bookmark_get_action()`](Self::bookmark_get_action).
    ///
    /// Corresponds to `FPDFBookmark_GetAction`.
    #[deprecated(note = "use `bookmark_get_action()` — matches upstream `FPDFBookmark_GetAction`")]
    #[inline]
    pub fn get_action(&self) -> Option<&Action> {
        self.action()
    }

    /// Returns the next sibling of this bookmark within `siblings`, or `None`
    /// if this bookmark is the last in the slice.
    ///
    /// The caller must pass the slice that directly contains `self` (address
    /// identity is used to locate this bookmark's position).
    ///
    /// **Architectural note**: PDFium's `FPDFBookmark_GetNextSibling` follows
    /// the `/Next` entry in the raw PDF outline dictionary.  In rpdfium the
    /// outline is eagerly parsed into an owned tree, so the caller must
    /// provide the parent's children (or root) slice explicitly.
    ///
    /// Corresponds to `FPDFBookmark_GetNextSibling`.
    pub fn next_sibling_in<'a>(&self, siblings: &'a [Bookmark]) -> Option<&'a Bookmark> {
        siblings
            .windows(2)
            .find(|w| std::ptr::eq(&w[0] as *const Bookmark, self as *const Bookmark))
            .map(|w| &w[1])
    }

    /// ADR-019 T2 alias for [`next_sibling_in()`](Self::next_sibling_in).
    ///
    /// Corresponds to `FPDFBookmark_GetNextSibling`.
    #[inline]
    pub fn bookmark_get_next_sibling<'a>(&self, siblings: &'a [Bookmark]) -> Option<&'a Bookmark> {
        self.next_sibling_in(siblings)
    }

    /// Deprecated — use [`bookmark_get_next_sibling()`](Self::bookmark_get_next_sibling).
    ///
    /// Corresponds to `FPDFBookmark_GetNextSibling`.
    #[deprecated(
        note = "use `bookmark_get_next_sibling()` — matches upstream `FPDFBookmark_GetNextSibling`"
    )]
    #[inline]
    pub fn get_next_sibling_in<'a>(&self, siblings: &'a [Bookmark]) -> Option<&'a Bookmark> {
        self.next_sibling_in(siblings)
    }
}

/// Returns the next sibling of `bookmark` within `siblings`, or `None` if
/// `bookmark` is the last in the slice.
///
/// This is a free-function wrapper around [`Bookmark::next_sibling_in`].
///
/// Corresponds to `FPDFBookmark_GetNextSibling`.
pub fn next_sibling_bookmark<'a>(
    siblings: &'a [Bookmark],
    bookmark: &Bookmark,
) -> Option<&'a Bookmark> {
    bookmark.next_sibling_in(siblings)
}

/// Search for the first bookmark with the given title using iterative DFS.
///
/// Returns a reference to the first [`Bookmark`] whose `title` exactly matches
/// `title` (Unicode-exact comparison, case-sensitive), or `None` if no match
/// is found.
///
/// Corresponds to `FPDFBookmark_Find` in PDFium.
///
/// # Example
/// ```
/// use rpdfium_doc::bookmark::{Bookmark, find_bookmark};
/// let bm = Bookmark { title: "Chapter 1".into(), children: vec![], destination: None, action: None, is_open: false };
/// let bookmarks = vec![bm];
/// assert!(find_bookmark(&bookmarks, "Chapter 1").is_some());
/// assert!(find_bookmark(&bookmarks, "chapter 1").is_none());
/// ```
pub fn find_bookmark<'a>(bookmarks: &'a [Bookmark], title: &str) -> Option<&'a Bookmark> {
    // Iterative DFS with an explicit stack.
    // `stack` holds references to bookmarks yet to be examined.
    let mut stack: Vec<&Bookmark> = bookmarks.iter().rev().collect();
    while let Some(bm) = stack.pop() {
        if bm.title == title {
            return Some(bm);
        }
        // Push children in reverse order so the first child is processed first.
        for child in bm.children.iter().rev() {
            stack.push(child);
        }
    }
    None
}

/// Non-upstream alias — use [`find_bookmark()`] instead.
#[deprecated(note = "use `find_bookmark()`")]
#[inline]
pub fn get_bookmark_by_title<'a>(bookmarks: &'a [Bookmark], title: &str) -> Option<&'a Bookmark> {
    find_bookmark(bookmarks, title)
}

/// Parse a single bookmark entry from its dictionary.
pub(crate) fn parse_single_bookmark<S: PdfSource>(
    dict: &HashMap<Name, Object>,
    store: &ObjectStore<S>,
) -> DocResult<Bookmark> {
    // /Title is required
    let title = dict
        .get(&Name::title())
        .and_then(|obj| store.deep_resolve(obj).ok())
        .and_then(|obj| obj.as_string().map(|s| s.to_string_lossy()))
        .unwrap_or_default();

    // /Dest (optional)
    let destination = dict
        .get(&Name::dest())
        .and_then(|obj| parse_destination(obj, store).ok());

    // /A (optional action)
    let action = dict
        .get(&Name::a())
        .and_then(|obj| parse_action(obj, store).ok());

    // /Count: negative means closed
    let is_open = dict
        .get(&Name::count())
        .and_then(|obj| obj.as_i64())
        .map(|c| c > 0)
        .unwrap_or(false);

    Ok(Bookmark {
        title,
        destination,
        action,
        children: Vec::new(),
        is_open,
    })
}

// ---------------------------------------------------------------------------
// Tests for find_bookmark
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    fn make_bookmark(title: &str, children: Vec<Bookmark>) -> Bookmark {
        Bookmark {
            title: title.into(),
            destination: None,
            action: None,
            children,
            is_open: false,
        }
    }

    #[test]
    fn test_find_bookmark_found_at_root() {
        let bookmarks = vec![
            make_bookmark("Chapter 1", vec![]),
            make_bookmark("Chapter 2", vec![]),
        ];
        let result = find_bookmark(&bookmarks, "Chapter 2");
        assert!(result.is_some());
        assert_eq!(result.unwrap().title, "Chapter 2");
    }

    #[test]
    fn test_find_bookmark_not_found() {
        let bookmarks = vec![make_bookmark("Chapter 1", vec![])];
        assert!(find_bookmark(&bookmarks, "Missing").is_none());
        // Case-sensitive: "chapter 1" should not match "Chapter 1"
        assert!(find_bookmark(&bookmarks, "chapter 1").is_none());
        // Empty slice
        assert!(find_bookmark(&[], "Chapter 1").is_none());
    }

    #[test]
    fn test_find_bookmark_nested() {
        let child = make_bookmark("Section 1.1", vec![]);
        let parent = make_bookmark("Chapter 1", vec![child]);
        let bookmarks = vec![parent];

        // The nested child should be found
        let result = find_bookmark(&bookmarks, "Section 1.1");
        assert!(result.is_some());
        assert_eq!(result.unwrap().title, "Section 1.1");
    }

    #[test]
    fn test_next_sibling_in_basic() {
        let bms = vec![
            make_bookmark("A", vec![]),
            make_bookmark("B", vec![]),
            make_bookmark("C", vec![]),
        ];
        // First element's next sibling is B
        let next = bms[0].next_sibling_in(&bms);
        assert!(next.is_some());
        assert_eq!(next.unwrap().title, "B");
        // Middle element's next sibling is C
        let next = bms[1].next_sibling_in(&bms);
        assert!(next.is_some());
        assert_eq!(next.unwrap().title, "C");
        // Last element has no next sibling
        assert!(bms[2].next_sibling_in(&bms).is_none());
    }

    #[test]
    fn test_next_sibling_in_single() {
        let bms = vec![make_bookmark("Only", vec![])];
        assert!(bms[0].next_sibling_in(&bms).is_none());
    }

    #[test]
    fn test_next_sibling_in_alias_matches() {
        let bms = vec![make_bookmark("X", vec![]), make_bookmark("Y", vec![])];
        assert_eq!(
            bms[0].next_sibling_in(&bms).map(|b| &b.title),
            bms[0].bookmark_get_next_sibling(&bms).map(|b| &b.title),
        );
    }

    #[test]
    fn test_next_sibling_bookmark_free_fn() {
        let bms = vec![make_bookmark("P", vec![]), make_bookmark("Q", vec![])];
        let result = next_sibling_bookmark(&bms, &bms[0]);
        assert!(result.is_some());
        assert_eq!(result.unwrap().title, "Q");
    }

    #[test]
    fn test_find_bookmark_dfs_order_returns_first_match() {
        // DFS visits Ch1 → Ch1.1 → Ch1.2 → Ch2
        // "Deep" appears at Ch1.1 and Ch2.1; DFS should return Ch1.1 first
        let ch1_1 = make_bookmark("Deep", vec![]);
        let ch1_2 = make_bookmark("Ch1.2", vec![]);
        let ch2_1 = make_bookmark("Deep", vec![]);
        let ch1 = make_bookmark("Ch1", vec![ch1_1, ch1_2]);
        let ch2 = make_bookmark("Ch2", vec![ch2_1]);
        let bookmarks = vec![ch1, ch2];

        let result = find_bookmark(&bookmarks, "Deep");
        assert!(result.is_some());
        // DFS from root: Ch1 → Ch1.1 "Deep" → found; never reaches Ch2.1
        // The parent of the first "Deep" is Ch1 which is the first bookmark
        // so result.parent would be Ch1. We verify via children' parent knowledge
        // indirectly: Ch1 has children [Deep, Ch1.2], Ch2 has children [Deep].
        // The first match returned should be Ch1's first child.
        assert_eq!(result.unwrap().title, "Deep");

        // Verify alias returns the same
        let alias_result = find_bookmark(&bookmarks, "Deep");
        assert!(alias_result.is_some());
    }
}