rpdfium-doc 7676.6.4

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
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
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
//! PDF destination types (ISO 32000-2 section 12.3.2).
//!
//! Destinations define a particular view of a page, typically used by
//! bookmarks, links, and GoTo actions.

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

use crate::error::{DocError, DocResult};
use crate::name_tree::NameTree;

/// A destination within a PDF document.
#[derive(Debug, Clone)]
pub enum Destination {
    /// An explicit page destination with a fit type.
    Page {
        /// Zero-based page index (derived from the page object reference).
        /// Deprecated: use `resolve_page_index` for accurate page lookup.
        page_index: u32,
        /// The page object reference, if available.
        page_ref: Option<ObjectId>,
        /// How the page should be displayed.
        fit: PageFit,
    },
    /// A named destination (resolved via the document's name tree).
    Named(String),
}

impl Destination {
    /// Resolve the page index by finding the page reference in the given
    /// page ID list (from page tree traversal).
    ///
    /// Returns `None` if this is a named destination or if the page reference
    /// is not found in `page_ids`.
    pub fn resolve_page_index(&self, page_ids: &[ObjectId]) -> Option<usize> {
        match self {
            Destination::Page {
                page_ref: Some(id), ..
            } => page_ids.iter().position(|pid| pid == id),
            Destination::Page {
                page_ref: None,
                page_index,
                ..
            } => Some(*page_index as usize),
            Destination::Named(_) => None,
        }
    }

    /// Returns the 0-based page index of this destination.
    ///
    /// Returns `None` if this is a named destination (index unknown without
    /// resolving against the actual page tree).
    ///
    /// Corresponds to `CPDF_Dest::GetDestPageIndex()` / `FPDFDest_GetDestPageIndex`.
    pub fn dest_page_index(&self) -> Option<u32> {
        match self {
            Destination::Page { page_index, .. } => Some(*page_index),
            Destination::Named(_) => None,
        }
    }

    /// ADR-019 Tier 2 alias for [`dest_page_index()`](Self::dest_page_index).
    ///
    /// Corresponds to `FPDFDest_GetDestPageIndex`.
    #[inline]
    pub fn dest_get_dest_page_index(&self) -> Option<u32> {
        self.dest_page_index()
    }

    /// Older short alias — prefer [`dest_get_dest_page_index()`](Self::dest_get_dest_page_index).
    #[deprecated(
        note = "use `dest_get_dest_page_index()` — matches upstream `FPDFDest_GetDestPageIndex`"
    )]
    #[inline]
    pub fn get_dest_page_index(&self) -> Option<u32> {
        self.dest_page_index()
    }

    /// Returns the page index stored in the destination.
    ///
    /// Deprecated: prefer [`dest_page_index()`](Self::dest_page_index) which is the
    /// upstream-aligned primary.
    #[deprecated(since = "0.1.0", note = "use dest_page_index() instead")]
    #[inline]
    pub fn page_index(&self) -> Option<u32> {
        self.dest_page_index()
    }

    /// Returns the view (fit type) specified by this destination.
    ///
    /// Returns `None` if this is a named destination (no fit type is known
    /// without resolving it).  For explicit page destinations, returns
    /// a reference to the [`PageFit`] variant.
    ///
    /// Corresponds to `FPDFDest_GetView`.
    pub fn view(&self) -> Option<&PageFit> {
        match self {
            Destination::Page { fit, .. } => Some(fit),
            Destination::Named(_) => None,
        }
    }

    /// ADR-019 Tier 2 alias for [`view()`](Self::view).
    ///
    /// Corresponds to `FPDFDest_GetView`.
    #[inline]
    pub fn dest_get_view(&self) -> Option<&PageFit> {
        self.view()
    }

    /// Older short alias — prefer [`dest_get_view()`](Self::dest_get_view).
    #[deprecated(note = "use `dest_get_view()` — matches upstream `FPDFDest_GetView`")]
    #[inline]
    pub fn get_view(&self) -> Option<&PageFit> {
        self.view()
    }

    /// Returns the `(left, top, zoom)` XYZ location parameters of this
    /// destination, if the view is [`PageFit::XYZ`].
    ///
    /// Each component is `Some(value)` only if the corresponding field is
    /// non-null in the PDF destination array.  Returns `None` if this
    /// destination is not an XYZ view or is a named destination.
    ///
    /// Corresponds to `FPDFDest_GetLocationInPage`.
    pub fn location_in_page(&self) -> Option<(Option<f32>, Option<f32>, Option<f32>)> {
        match self {
            Destination::Page {
                fit: PageFit::XYZ { left, top, zoom },
                ..
            } => Some((*left, *top, *zoom)),
            _ => None,
        }
    }

    /// ADR-019 Tier 2 alias for [`location_in_page()`](Self::location_in_page).
    ///
    /// Corresponds to `FPDFDest_GetLocationInPage`.
    #[inline]
    pub fn dest_get_location_in_page(&self) -> Option<(Option<f32>, Option<f32>, Option<f32>)> {
        self.location_in_page()
    }

    /// Older short alias — prefer [`dest_get_location_in_page()`](Self::dest_get_location_in_page).
    #[deprecated(
        note = "use `dest_get_location_in_page()` — matches upstream `FPDFDest_GetLocationInPage`"
    )]
    #[inline]
    pub fn get_location_in_page(&self) -> Option<(Option<f32>, Option<f32>, Option<f32>)> {
        self.location_in_page()
    }

    /// Returns the zoom mode as a `PDFDEST_VIEW_*`-like integer.
    ///
    /// Maps the `PageFit` variant to the integer constants defined by PDFium:
    /// 1=`XYZ`, 2=`Fit`, 3=`FitH`, 4=`FitV`, 5=`FitR`, 6=`FitB`, 7=`FitBH`,
    /// 8=`FitBV`, 0=unknown/named.
    ///
    /// Corresponds to `CPDF_Dest::GetZoomMode()` in PDFium.
    pub fn zoom_mode(&self) -> u32 {
        match self {
            Destination::Page { fit, .. } => match fit {
                PageFit::XYZ { .. } => 1,
                PageFit::Fit => 2,
                PageFit::FitH { .. } => 3,
                PageFit::FitV { .. } => 4,
                PageFit::FitR { .. } => 5,
                PageFit::FitB => 6,
                PageFit::FitBH { .. } => 7,
                PageFit::FitBV { .. } => 8,
            },
            Destination::Named(_) => 0,
        }
    }

    /// Non-upstream alias — use [`zoom_mode()`](Self::zoom_mode).
    #[deprecated(note = "use `zoom_mode()` — there is no public `FPDFDest_GetZoomMode` API")]
    #[inline]
    pub fn get_zoom_mode(&self) -> u32 {
        self.zoom_mode()
    }

    /// Returns the number of numeric parameters for this destination.
    ///
    /// The parameter count depends on the fit type:
    /// - `XYZ`: up to 3 (left, top, zoom)
    /// - `FitH`/`FitBH`: up to 1 (top)
    /// - `FitV`/`FitBV`: up to 1 (left)
    /// - `FitR`: 4 (left, bottom, right, top)
    /// - `Fit`/`FitB`: 0
    /// - Named or unknown: 0
    ///
    /// Corresponds to `CPDF_Dest::GetNumParams()` in PDFium.
    pub fn param_count(&self) -> usize {
        match self {
            Destination::Page { fit, .. } => match fit {
                PageFit::XYZ { .. } => 3,
                PageFit::FitH { .. } | PageFit::FitBH { .. } => 1,
                PageFit::FitV { .. } | PageFit::FitBV { .. } => 1,
                PageFit::FitR { .. } => 4,
                PageFit::Fit | PageFit::FitB => 0,
            },
            Destination::Named(_) => 0,
        }
    }

    /// ADR-019 alias for [`param_count()`](Self::param_count).
    ///
    /// Corresponds to `CPDF_Dest::GetNumParams()` in PDFium.
    #[inline]
    pub fn get_num_params(&self) -> usize {
        self.param_count()
    }

    /// Returns the numeric parameter at the given zero-based `index`.
    ///
    /// Parameters are ordered as they appear in the destination array
    /// (after the page reference and fit-type name).  Returns `None` if
    /// the index is out of range or the destination is named.
    ///
    /// Corresponds to `CPDF_Dest::GetParam(size_t index)` in PDFium.
    pub fn param(&self, index: usize) -> Option<f32> {
        match self {
            Destination::Page { fit, .. } => match fit {
                PageFit::XYZ { left, top, zoom } => match index {
                    0 => *left,
                    1 => *top,
                    2 => *zoom,
                    _ => None,
                },
                PageFit::FitH { top } | PageFit::FitBH { top } => {
                    if index == 0 {
                        *top
                    } else {
                        None
                    }
                }
                PageFit::FitV { left } | PageFit::FitBV { left } => {
                    if index == 0 {
                        *left
                    } else {
                        None
                    }
                }
                PageFit::FitR {
                    left,
                    bottom,
                    right,
                    top,
                } => match index {
                    0 => Some(*left),
                    1 => Some(*bottom),
                    2 => Some(*right),
                    3 => Some(*top),
                    _ => None,
                },
                PageFit::Fit | PageFit::FitB => None,
            },
            Destination::Named(_) => None,
        }
    }

    /// ADR-019 alias for [`param()`](Self::param).
    ///
    /// Corresponds to `CPDF_Dest::GetParam(size_t index)` in PDFium.
    #[inline]
    pub fn get_param(&self, index: usize) -> Option<f32> {
        self.param(index)
    }

    /// Returns the scroll position parameters as a `Vec<f32>`.
    ///
    /// For `XYZ` destinations this is `[left, top, zoom]` (omitting nulls);
    /// for other explicit page destinations the fit-type parameters are
    /// collected in order.  Returns an empty `Vec` for named destinations.
    ///
    /// Corresponds to `CPDF_Dest::GetScrollPositionArray()` in PDFium.
    pub fn scroll_position_array(&self) -> Vec<f32> {
        let count = self.param_count();
        (0..count).filter_map(|i| self.param(i)).collect()
    }

    /// ADR-019 alias for [`scroll_position_array()`](Self::scroll_position_array).
    ///
    /// Corresponds to `CPDF_Dest::GetScrollPositionArray()` in PDFium.
    #[inline]
    pub fn get_scroll_position_array(&self) -> Vec<f32> {
        self.scroll_position_array()
    }

    /// Returns the XYZ location parameters of this destination.
    ///
    /// Each of `x`, `y`, `zoom` is `Some(value)` only when the corresponding
    /// field is non-null in the PDF destination array.  Returns `(None, None,
    /// None)` for non-XYZ destinations or named destinations.
    ///
    /// This is the low-level equivalent of [`Self::location_in_page()`].
    ///
    /// Corresponds to `CPDF_Dest::GetXYZ()` in PDFium.
    pub fn xyz(&self) -> (Option<f32>, Option<f32>, Option<f32>) {
        match self.location_in_page() {
            Some((x, y, zoom)) => (x, y, zoom),
            None => (None, None, None),
        }
    }

    /// ADR-019 alias for [`xyz()`](Self::xyz).
    ///
    /// Corresponds to `CPDF_Dest::GetXYZ()` in PDFium.
    #[inline]
    pub fn get_xyz(&self) -> (Option<f32>, Option<f32>, Option<f32>) {
        self.xyz()
    }
}

/// How a page should be displayed when navigating to a destination.
#[derive(Debug, Clone)]
pub enum PageFit {
    /// Display the page at a scale that fits the entire page in the window.
    Fit,
    /// Display the page with the vertical coordinate `top` at the top of the window.
    FitH { top: Option<f32> },
    /// Display the page with the horizontal coordinate `left` at the left of the window.
    FitV { left: Option<f32> },
    /// Display the specified rectangle on the page.
    FitR {
        left: f32,
        bottom: f32,
        right: f32,
        top: f32,
    },
    /// Fit the bounding box of the page contents in the window.
    FitB,
    /// Fit the bounding box width, with `top` at the top of the window.
    FitBH { top: Option<f32> },
    /// Fit the bounding box height, with `left` at the left of the window.
    FitBV { left: Option<f32> },
    /// Display at a specific position and zoom level.
    XYZ {
        left: Option<f32>,
        top: Option<f32>,
        zoom: Option<f32>,
    },
}

/// Parse a destination from a PDF object.
///
/// The object can be:
/// - An array: `[page_ref /FitType params...]`
/// - A string: a named destination
/// - A name: a named destination
pub fn parse_destination<S: PdfSource>(
    obj: &Object,
    store: &ObjectStore<S>,
) -> DocResult<Destination> {
    let resolved = store
        .deep_resolve(obj)
        .map_err(|e| DocError::Parser(e.to_string()))?;

    // Named destination (string)
    if let Some(s) = resolved.as_string() {
        return Ok(Destination::Named(s.to_string_lossy()));
    }

    // Named destination (name)
    if let Some(n) = resolved.as_name() {
        return Ok(Destination::Named(n.as_str().into_owned()));
    }

    // Explicit destination (array)
    let arr = resolved.as_array().ok_or(DocError::UnexpectedType)?;
    if arr.is_empty() {
        return Err(DocError::MissingKey("destination array is empty".into()));
    }

    // First element is the page reference.
    let (page_index, page_ref) = match &arr[0] {
        Object::Reference(id) => (id.number.saturating_sub(1), Some(*id)),
        Object::Integer(n) => ((*n).max(0) as u32, None),
        _ => (0, None),
    };

    // Second element is the fit type name
    let fit = if arr.len() < 2 {
        PageFit::Fit
    } else {
        let fit_name = store
            .deep_resolve(&arr[1])
            .map_err(|e| DocError::Parser(e.to_string()))?;
        let fit_str = fit_name
            .as_name()
            .map(|n| n.as_str().into_owned())
            .unwrap_or_default();

        match fit_str.as_str() {
            "Fit" => PageFit::Fit,
            "FitB" => PageFit::FitB,
            "FitH" => PageFit::FitH {
                top: get_optional_f32(arr, 2),
            },
            "FitV" => PageFit::FitV {
                left: get_optional_f32(arr, 2),
            },
            "FitBH" => PageFit::FitBH {
                top: get_optional_f32(arr, 2),
            },
            "FitBV" => PageFit::FitBV {
                left: get_optional_f32(arr, 2),
            },
            "FitR" => PageFit::FitR {
                left: get_f32(arr, 2),
                bottom: get_f32(arr, 3),
                right: get_f32(arr, 4),
                top: get_f32(arr, 5),
            },
            "XYZ" => PageFit::XYZ {
                left: get_optional_f32(arr, 2),
                top: get_optional_f32(arr, 3),
                zoom: get_optional_f32(arr, 4),
            },
            _ => PageFit::Fit,
        }
    };

    Ok(Destination::Page {
        page_index,
        page_ref,
        fit,
    })
}

/// Maximum number of named destinations to collect (safety limit).
const MAX_NAMED_DESTS: usize = 10_000;

/// Collects all named destinations from the document catalog.
///
/// Looks for `/Names/Dests` (name tree, preferred) and falls back to
/// `/Dests` (old-style dictionary) in the catalog.
/// Returns a `Vec` of `(name, Destination)` pairs.
///
/// Corresponds to `FPDF_CountNamedDests` / `FPDF_GetNamedDest` in PDFium.
pub fn collect_named_destinations<S: PdfSource>(
    catalog: &Object,
    store: &ObjectStore<S>,
) -> DocResult<Vec<(String, Destination)>> {
    let catalog_dict = catalog.as_dict().ok_or(DocError::UnexpectedType)?;

    // Try /Names/Dests (name tree — modern PDFs)
    if let Some(names_obj) = catalog_dict.get(&Name::names()) {
        if let Ok(names_resolved) = store.deep_resolve(names_obj) {
            if let Some(names_dict) = names_resolved.as_dict() {
                if let Some(dests_obj) = names_dict.get(&Name::dests()) {
                    let tree = NameTree::<Object>::parse(dests_obj, store, |obj| Ok(obj.clone()))?;
                    let mut results = Vec::new();
                    for (name, obj) in tree.entries() {
                        if results.len() >= MAX_NAMED_DESTS {
                            break;
                        }
                        if let Ok(dest) = parse_destination(obj, store) {
                            results.push((name.clone(), dest));
                        }
                    }
                    return Ok(results);
                }
            }
        }
    }

    // Fall back to /Dests dictionary (old-style, pre-1.2 PDFs)
    if let Some(dests_obj) = catalog_dict.get(&Name::dests()) {
        if let Ok(dests_resolved) = store.deep_resolve(dests_obj) {
            if let Some(dests_dict) = dests_resolved.as_dict() {
                let mut results = Vec::new();
                for (name, val) in dests_dict {
                    if results.len() >= MAX_NAMED_DESTS {
                        break;
                    }
                    if let Ok(dest) = parse_destination(val, store) {
                        results.push((name.as_str().into_owned(), dest));
                    }
                }
                return Ok(results);
            }
        }
    }

    Ok(Vec::new())
}

/// Get a required f32 from an array at the given index, defaulting to 0.0.
fn get_f32(arr: &[Object], idx: usize) -> f32 {
    arr.get(idx)
        .and_then(|o| o.as_f64())
        .map(|f| f as f32)
        .unwrap_or(0.0)
}

/// Get an optional f32 from an array at the given index.
/// Returns None if the element is null or missing.
fn get_optional_f32(arr: &[Object], idx: usize) -> Option<f32> {
    arr.get(idx).and_then(|o| {
        if o.is_null() {
            None
        } else {
            o.as_f64().map(|f| f as f32)
        }
    })
}

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

    fn build_store() -> ObjectStore<Vec<u8>> {
        let pdf = build_minimal_pdf();
        ObjectStore::open(pdf, rpdfium_core::ParsingMode::Lenient).unwrap()
    }

    fn build_minimal_pdf() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");
        let obj1_offset = pdf.len();
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
        let obj2_offset = pdf.len();
        pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [] /Count 0 >>\nendobj\n");
        let xref_offset = pdf.len();
        pdf.extend_from_slice(b"xref\n0 3\n");
        pdf.extend_from_slice(b"0000000000 65535 f \r\n");
        pdf.extend_from_slice(format!("{:010} 00000 n \r\n", obj1_offset).as_bytes());
        pdf.extend_from_slice(format!("{:010} 00000 n \r\n", obj2_offset).as_bytes());
        pdf.extend_from_slice(b"trailer\n<< /Size 3 /Root 1 0 R >>\n");
        pdf.extend_from_slice(format!("startxref\n{}\n%%EOF", xref_offset).as_bytes());
        pdf
    }

    #[test]
    fn test_fit_destination() {
        let store = build_store();
        use rpdfium_core::error::ObjectId;
        let dest = Object::Array(vec![
            Object::Reference(ObjectId::new(1, 0)),
            Object::Name(Name::from("Fit")),
        ]);
        let result = parse_destination(&dest, &store).unwrap();
        match result {
            Destination::Page { fit, .. } => assert!(matches!(fit, PageFit::Fit)),
            _ => panic!("expected Page destination"),
        }
    }

    #[test]
    fn test_xyz_destination() {
        let store = build_store();
        use rpdfium_core::error::ObjectId;
        let dest = Object::Array(vec![
            Object::Reference(ObjectId::new(1, 0)),
            Object::Name(Name::from("XYZ")),
            Object::Real(72.0),
            Object::Real(720.0),
            Object::Real(1.5),
        ]);
        let result = parse_destination(&dest, &store).unwrap();
        match result {
            Destination::Page { fit, .. } => match fit {
                PageFit::XYZ { left, top, zoom } => {
                    assert_eq!(left, Some(72.0));
                    assert_eq!(top, Some(720.0));
                    assert_eq!(zoom, Some(1.5));
                }
                _ => panic!("expected XYZ"),
            },
            _ => panic!("expected Page destination"),
        }
    }

    #[test]
    fn test_fit_h_with_null_top() {
        let store = build_store();
        use rpdfium_core::error::ObjectId;
        let dest = Object::Array(vec![
            Object::Reference(ObjectId::new(1, 0)),
            Object::Name(Name::from("FitH")),
            Object::Null,
        ]);
        let result = parse_destination(&dest, &store).unwrap();
        match result {
            Destination::Page { fit, .. } => match fit {
                PageFit::FitH { top } => assert_eq!(top, None),
                _ => panic!("expected FitH"),
            },
            _ => panic!("expected Page destination"),
        }
    }

    #[test]
    fn test_named_destination_string() {
        let store = build_store();
        let dest = Object::String(rpdfium_core::PdfString::from_bytes(b"chapter1".to_vec()));
        let result = parse_destination(&dest, &store).unwrap();
        match result {
            Destination::Named(name) => assert_eq!(name, "chapter1"),
            _ => panic!("expected Named destination"),
        }
    }

    #[test]
    fn test_named_destination_name() {
        let store = build_store();
        let dest = Object::Name(Name::from("section2"));
        let result = parse_destination(&dest, &store).unwrap();
        match result {
            Destination::Named(name) => assert_eq!(name, "section2"),
            _ => panic!("expected Named destination"),
        }
    }

    #[test]
    fn test_resolve_page_index_found() {
        let store = build_store();
        use rpdfium_core::error::ObjectId;
        let dest = Object::Array(vec![
            Object::Reference(ObjectId::new(5, 0)),
            Object::Name(Name::from("Fit")),
        ]);
        let result = parse_destination(&dest, &store).unwrap();
        let page_ids = vec![
            ObjectId::new(3, 0),
            ObjectId::new(5, 0),
            ObjectId::new(7, 0),
        ];
        assert_eq!(result.resolve_page_index(&page_ids), Some(1));
    }

    #[test]
    fn test_resolve_page_index_not_found() {
        let store = build_store();
        use rpdfium_core::error::ObjectId;
        let dest = Object::Array(vec![
            Object::Reference(ObjectId::new(99, 0)),
            Object::Name(Name::from("Fit")),
        ]);
        let result = parse_destination(&dest, &store).unwrap();
        let page_ids = vec![ObjectId::new(3, 0), ObjectId::new(5, 0)];
        assert_eq!(result.resolve_page_index(&page_ids), None);
    }

    #[test]
    fn test_resolve_page_index_named_returns_none() {
        let store = build_store();
        let dest = Object::Name(Name::from("chapter1"));
        let result = parse_destination(&dest, &store).unwrap();
        let page_ids = vec![ObjectId::new(1, 0)];
        assert_eq!(result.resolve_page_index(&page_ids), None);
    }

    #[test]
    fn test_page_index_deprecation_accessor() {
        let store = build_store();
        use rpdfium_core::error::ObjectId;
        let dest = Object::Array(vec![
            Object::Reference(ObjectId::new(5, 0)),
            Object::Name(Name::from("Fit")),
        ]);
        let result = parse_destination(&dest, &store).unwrap();
        // dest_page_index uses saturating_sub(1): 5-1 = 4
        assert_eq!(result.dest_page_index(), Some(4));
    }

    #[test]
    fn test_page_ref_stored_for_reference() {
        let store = build_store();
        use rpdfium_core::error::ObjectId;
        let dest = Object::Array(vec![
            Object::Reference(ObjectId::new(10, 0)),
            Object::Name(Name::from("XYZ")),
            Object::Null,
            Object::Null,
            Object::Null,
        ]);
        let result = parse_destination(&dest, &store).unwrap();
        match result {
            Destination::Page { page_ref, .. } => {
                assert_eq!(page_ref, Some(ObjectId::new(10, 0)));
            }
            _ => panic!("expected Page destination"),
        }
    }

    #[test]
    fn test_collect_named_destinations_from_names_tree() {
        use rpdfium_core::PdfString;
        let store = build_store();

        // Build a catalog with /Names/Dests name tree containing one destination
        let mut dests_leaf = std::collections::HashMap::new();
        dests_leaf.insert(
            Name::names(),
            Object::Array(vec![
                Object::String(PdfString::from_bytes(b"chapter1".to_vec())),
                Object::Array(vec![Object::Integer(0), Object::Name(Name::from("Fit"))]),
                Object::String(PdfString::from_bytes(b"chapter2".to_vec())),
                Object::Array(vec![Object::Integer(1), Object::Name(Name::from("FitH"))]),
            ]),
        );

        let mut names_dict = std::collections::HashMap::new();
        names_dict.insert(Name::dests(), Object::Dictionary(dests_leaf));

        let mut catalog = std::collections::HashMap::new();
        catalog.insert(Name::names(), Object::Dictionary(names_dict));

        let catalog_obj = Object::Dictionary(catalog);
        let results = collect_named_destinations(&catalog_obj, &store).unwrap();
        assert_eq!(results.len(), 2);
        assert_eq!(results[0].0, "chapter1");
        assert_eq!(results[1].0, "chapter2");
    }

    #[test]
    fn test_collect_named_destinations_old_style_dests_dict() {
        let store = build_store();

        let mut dests_dict = std::collections::HashMap::new();
        dests_dict.insert(
            Name::from("intro"),
            Object::Array(vec![Object::Integer(0), Object::Name(Name::from("Fit"))]),
        );

        let mut catalog = std::collections::HashMap::new();
        catalog.insert(Name::dests(), Object::Dictionary(dests_dict));

        let catalog_obj = Object::Dictionary(catalog);
        let results = collect_named_destinations(&catalog_obj, &store).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].0, "intro");
    }

    #[test]
    fn test_collect_named_destinations_empty_catalog() {
        let store = build_store();
        let catalog_obj = Object::Dictionary(std::collections::HashMap::new());
        let results = collect_named_destinations(&catalog_obj, &store).unwrap();
        assert!(results.is_empty());
    }

    #[test]
    fn test_integer_page_has_no_page_ref() {
        let store = build_store();
        let dest = Object::Array(vec![Object::Integer(3), Object::Name(Name::from("Fit"))]);
        let result = parse_destination(&dest, &store).unwrap();
        match result {
            Destination::Page {
                page_index,
                page_ref,
                ..
            } => {
                assert_eq!(page_index, 3);
                assert!(page_ref.is_none());
            }
            _ => panic!("expected Page destination"),
        }
    }

    // -----------------------------------------------------------------------
    // named_dest_by_name equivalent — collect then search (FPDF_GetNamedDestByName)
    // -----------------------------------------------------------------------

    /// Helper that wraps the collect-then-find pattern used by
    /// `Document::named_dest_by_name`.
    fn lookup_named_dest(
        catalog: &Object,
        store: &ObjectStore<Vec<u8>>,
        name: &str,
    ) -> Option<Destination> {
        collect_named_destinations(catalog, store)
            .ok()?
            .into_iter()
            .find(|(n, _)| n == name)
            .map(|(_, d)| d)
    }

    #[test]
    fn test_named_dest_by_name_found_in_names_tree() {
        use rpdfium_core::PdfString;
        let store = build_store();

        // Build catalog with /Names/Dests containing "chapter1" → page 0 Fit.
        let mut dests_leaf = std::collections::HashMap::new();
        dests_leaf.insert(
            Name::names(),
            Object::Array(vec![
                Object::String(PdfString::from_bytes(b"chapter1".to_vec())),
                Object::Array(vec![Object::Integer(0), Object::Name(Name::from("Fit"))]),
                Object::String(PdfString::from_bytes(b"chapter2".to_vec())),
                Object::Array(vec![Object::Integer(1), Object::Name(Name::from("FitH"))]),
            ]),
        );
        let mut names_dict = std::collections::HashMap::new();
        names_dict.insert(Name::dests(), Object::Dictionary(dests_leaf));
        let mut catalog = std::collections::HashMap::new();
        catalog.insert(Name::names(), Object::Dictionary(names_dict));
        let catalog_obj = Object::Dictionary(catalog);

        // "chapter1" should be found and match Fit.
        let dest = lookup_named_dest(&catalog_obj, &store, "chapter1");
        assert!(dest.is_some(), "expected to find chapter1");
        match dest.unwrap() {
            Destination::Page { fit, .. } => assert!(matches!(fit, PageFit::Fit)),
            _ => panic!("expected Page destination"),
        }
    }

    #[test]
    fn test_named_dest_by_name_not_found_returns_none() {
        use rpdfium_core::PdfString;
        let store = build_store();

        let mut dests_leaf = std::collections::HashMap::new();
        dests_leaf.insert(
            Name::names(),
            Object::Array(vec![
                Object::String(PdfString::from_bytes(b"intro".to_vec())),
                Object::Array(vec![Object::Integer(0), Object::Name(Name::from("Fit"))]),
            ]),
        );
        let mut names_dict = std::collections::HashMap::new();
        names_dict.insert(Name::dests(), Object::Dictionary(dests_leaf));
        let mut catalog = std::collections::HashMap::new();
        catalog.insert(Name::names(), Object::Dictionary(names_dict));
        let catalog_obj = Object::Dictionary(catalog);

        // "nonexistent" should not be found.
        let dest = lookup_named_dest(&catalog_obj, &store, "nonexistent");
        assert!(dest.is_none(), "expected None for unknown name");
    }

    #[test]
    fn test_named_dest_by_name_found_in_old_style_dests_dict() {
        let store = build_store();

        let mut dests_dict = std::collections::HashMap::new();
        dests_dict.insert(
            Name::from("section3"),
            Object::Array(vec![Object::Integer(2), Object::Name(Name::from("XYZ"))]),
        );
        let mut catalog = std::collections::HashMap::new();
        catalog.insert(Name::dests(), Object::Dictionary(dests_dict));
        let catalog_obj = Object::Dictionary(catalog);

        let dest = lookup_named_dest(&catalog_obj, &store, "section3");
        assert!(dest.is_some(), "expected to find section3");
        match dest.unwrap() {
            Destination::Page { fit, .. } => assert!(matches!(fit, PageFit::XYZ { .. })),
            _ => panic!("expected Page destination"),
        }
    }

    /// Upstream: TEST_F(PDFDocTest, GetLocationInPage)
    #[test]
    fn test_pdf_doc_get_location_in_page() {
        // XYZ with all values present.
        let dest = Destination::Page {
            page_index: 0,
            page_ref: None,
            fit: PageFit::XYZ {
                left: Some(4.0),
                top: Some(5.0),
                zoom: Some(6.0),
            },
        };
        let loc = dest.location_in_page();
        assert!(loc.is_some());
        let (x, y, zoom) = loc.unwrap();
        assert_eq!(x, Some(4.0));
        assert_eq!(y, Some(5.0));
        assert_eq!(zoom, Some(6.0));

        // XYZ with all null values.
        let dest_nulls = Destination::Page {
            page_index: 0,
            page_ref: None,
            fit: PageFit::XYZ {
                left: None,
                top: None,
                zoom: None,
            },
        };
        let loc2 = dest_nulls.location_in_page();
        assert!(loc2.is_some());
        let (x2, y2, zoom2) = loc2.unwrap();
        assert_eq!(x2, None);
        assert_eq!(y2, None);
        assert_eq!(zoom2, None);

        // Non-XYZ destination returns None (empty array equivalent).
        let dest_fit = Destination::Page {
            page_index: 0,
            page_ref: None,
            fit: PageFit::Fit,
        };
        assert!(dest_fit.location_in_page().is_none());

        // Named destination also returns None.
        let dest_named = Destination::Named("test".into());
        assert!(dest_named.location_in_page().is_none());
    }
}