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
//! Link annotation hit testing and link object introspection.
//!
//! Provides point-in-annotation testing for link annotations, supporting
//! both simple rectangle-based and QuadPoints-based hit detection.
//!
//! Also provides `LinkObject`, a typed view of a link annotation that
//! exposes quad-points, destination, and action — corresponding to
//! `FPDFLink_*` functions in PDFium's `fpdf_doc.h`.

use crate::action::Action;
use crate::annotation::{Annotation, AnnotationType};
use crate::destination::Destination;

/// A typed view of a link annotation for introspection.
///
/// Wraps a reference to an `Annotation` of subtype `Link` and provides
/// the upstream `FPDFLink_*` API surface: quad-point access, destination,
/// and action retrieval.
///
/// Obtain via [`find_link_at_position`] or [`collect_links`].
#[derive(Debug, Clone)]
pub struct LinkObject {
    /// Annotation rectangle `[x1, y1, x2, y2]`.
    pub rect: [f32; 4],
    /// QuadPoints (flat array of 8-float groups), if present.
    pub quad_points: Option<Vec<f32>>,
    /// The destination, if specified via `/Dest`.
    pub destination: Option<Destination>,
    /// The action, if specified via `/A`.
    pub action: Option<Action>,
    /// Index of this annotation in the page's annotation list.
    pub annotation_index: usize,
}

impl LinkObject {
    /// Build a `LinkObject` from a link `Annotation` at the given index.
    fn from_annotation(annot: &Annotation, index: usize) -> Self {
        Self {
            rect: annot.rect,
            quad_points: annot.subtype_data.quad_points.clone(),
            destination: annot.destination.clone(),
            action: annot.action.clone(),
            annotation_index: index,
        }
    }

    /// Returns the number of quad-point groups (quadrilaterals) on this link.
    ///
    /// Each group is 8 floats `[x1,y1, x2,y2, x3,y3, x4,y4]`.
    ///
    /// Corresponds to `FPDFLink_CountQuadPoints`.
    pub fn quad_point_count(&self) -> usize {
        self.quad_points.as_ref().map_or(0, |v| v.len() / 8)
    }

    /// ADR-019 alias for `quad_point_count()`.
    ///
    /// Corresponds to `FPDFLink_CountQuadPoints`.
    #[inline]
    pub fn link_count_quad_points(&self) -> usize {
        self.quad_point_count()
    }

    /// Deprecated: use [`link_count_quad_points()`](Self::link_count_quad_points)
    /// or [`quad_point_count()`](Self::quad_point_count) instead.
    #[deprecated(
        since = "0.1.0",
        note = "use link_count_quad_points() or quad_point_count() instead"
    )]
    #[inline]
    pub fn count_quad_points(&self) -> usize {
        self.quad_point_count()
    }

    /// Returns the `index`-th quad-point group as 8 floats, or `None` if
    /// the index is out of bounds.
    ///
    /// Corresponds to `FPDFLink_GetQuadPoints`.
    pub fn quad_points_at(&self, index: usize) -> Option<[f32; 8]> {
        let flat = self.quad_points.as_ref()?;
        let start = index * 8;
        if start + 8 > flat.len() {
            return None;
        }
        let s = &flat[start..start + 8];
        Some([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]])
    }

    /// Upstream-aligned alias for [`quad_points_at()`](Self::quad_points_at).
    ///
    /// Corresponds to `FPDFLink_GetQuadPoints`.
    #[inline]
    pub fn link_get_quad_points(&self, index: usize) -> Option<[f32; 8]> {
        self.quad_points_at(index)
    }

    /// Deprecated: use [`link_get_quad_points()`](Self::link_get_quad_points)
    /// or [`quad_points_at()`](Self::quad_points_at) instead.
    #[deprecated(
        since = "0.1.0",
        note = "use link_get_quad_points() or quad_points_at() instead"
    )]
    #[inline]
    pub fn get_quad_points(&self, index: usize) -> Option<[f32; 8]> {
        self.quad_points_at(index)
    }

    /// Deprecated: use [`link_get_quad_points()`](Self::link_get_quad_points)
    /// or [`quad_points_at()`](Self::quad_points_at) instead.
    #[deprecated(
        since = "0.1.0",
        note = "use link_get_quad_points() or quad_points_at() instead"
    )]
    #[inline]
    pub fn get_quad_points_at(&self, index: usize) -> Option<[f32; 8]> {
        self.quad_points_at(index)
    }

    /// Returns the link's destination, if any.
    ///
    /// Corresponds to `FPDFLink_GetDest`.
    pub fn dest(&self) -> Option<&Destination> {
        self.destination.as_ref()
    }

    /// ADR-019 alias for `dest()`.
    ///
    /// Corresponds to `FPDFLink_GetDest`.
    #[inline]
    pub fn link_get_dest(&self) -> Option<&Destination> {
        self.dest()
    }

    /// Deprecated: use [`link_get_dest()`](Self::link_get_dest)
    /// or [`dest()`](Self::dest) instead.
    #[deprecated(since = "0.1.0", note = "use link_get_dest() or dest() instead")]
    #[inline]
    pub fn get_dest(&self) -> Option<&Destination> {
        self.dest()
    }

    /// Returns the link's action, if any.
    ///
    /// Corresponds to `FPDFLink_GetAction`.
    pub fn action(&self) -> Option<&Action> {
        self.action.as_ref()
    }

    /// ADR-019 alias for `action()`.
    ///
    /// Corresponds to `FPDFLink_GetAction`.
    #[inline]
    pub fn link_get_action(&self) -> Option<&Action> {
        self.action()
    }

    /// Deprecated: use [`link_get_action()`](Self::link_get_action)
    /// or [`action()`](Self::action) instead.
    #[deprecated(since = "0.1.0", note = "use link_get_action() or action() instead")]
    #[inline]
    pub fn get_action(&self) -> Option<&Action> {
        self.action()
    }

    /// Returns the link's annotation rectangle.
    ///
    /// Corresponds to `FPDFLink_GetAnnotRect`.
    pub fn rect(&self) -> [f32; 4] {
        self.rect
    }

    /// ADR-019 alias for [`rect()`](Self::rect).
    ///
    /// Corresponds to `FPDFLink_GetAnnotRect`.
    #[inline]
    pub fn link_get_annot_rect(&self) -> [f32; 4] {
        self.rect()
    }

    /// Deprecated: use [`link_get_annot_rect()`](Self::link_get_annot_rect)
    /// or [`rect()`](Self::rect) instead.
    #[deprecated(since = "0.1.0", note = "use link_get_annot_rect() or rect() instead")]
    #[inline]
    pub fn get_annot_rect(&self) -> [f32; 4] {
        self.rect()
    }

    /// Returns the index of this link annotation in the page's annotation list.
    ///
    /// The caller can use this index to retrieve the full `Annotation` via
    /// `page.annotations()[link.annotation_index()]`.
    ///
    /// Corresponds to `FPDFLink_GetAnnot` — in PDFium this returns the
    /// annotation handle for a link; in rpdfium the equivalent is to look up
    /// the annotation by this index in the page's annotation slice.
    pub fn annotation_index(&self) -> usize {
        self.annotation_index
    }

    /// Upstream-aligned alias for [`annotation_index()`](Self::annotation_index).
    ///
    /// Corresponds to `FPDFLink_GetAnnot`.
    #[inline]
    pub fn link_get_annot(&self) -> usize {
        self.annotation_index()
    }

    /// Deprecated: use [`link_get_annot()`](Self::link_get_annot)
    /// or [`annotation_index()`](Self::annotation_index) instead.
    #[deprecated(
        since = "0.1.0",
        note = "use link_get_annot() or annotation_index() instead"
    )]
    #[inline]
    pub fn get_annot(&self) -> usize {
        self.annotation_index()
    }

    /// Deprecated: use [`link_get_annot()`](Self::link_get_annot)
    /// or [`annotation_index()`](Self::annotation_index) instead.
    #[deprecated(
        since = "0.1.0",
        note = "use link_get_annot() or annotation_index() instead"
    )]
    #[inline]
    pub fn get_annotation_index(&self) -> usize {
        self.annotation_index()
    }
}

/// Collect all link annotations from a page's annotation list.
///
/// Returns a `Vec<LinkObject>` containing only link-type annotations.
///
/// Corresponds to iterating links for `FPDFLink_Enumerate` usage.
pub fn collect_links(annotations: &[Annotation]) -> Vec<LinkObject> {
    annotations
        .iter()
        .enumerate()
        .filter(|(_, a)| a.subtype == AnnotationType::Link)
        .map(|(idx, a)| LinkObject::from_annotation(a, idx))
        .collect()
}

/// ADR-019 alias for [`collect_links`].
///
/// Corresponds to `FPDFLink_Enumerate`.
#[inline]
pub fn link_enumerate(annotations: &[Annotation]) -> Vec<LinkObject> {
    collect_links(annotations)
}

/// Deprecated: use [`link_enumerate()`] or [`collect_links()`] instead.
///
/// Corresponds to `FPDFLink_Enumerate`.
#[deprecated(
    since = "0.1.0",
    note = "use link_enumerate() or collect_links() instead"
)]
#[inline]
pub fn enumerate(annotations: &[Annotation]) -> Vec<LinkObject> {
    collect_links(annotations)
}

/// Deprecated: use [`link_enumerate()`] or [`collect_links()`] instead.
///
/// Corresponds to `FPDFLink_Enumerate`.
#[deprecated(
    since = "0.1.0",
    note = "use link_enumerate() or collect_links() instead"
)]
#[inline]
pub fn enumerate_links(annotations: &[Annotation]) -> Vec<LinkObject> {
    collect_links(annotations)
}

/// Find a link annotation at the given point and return it as a `LinkObject`.
///
/// Corresponds to `FPDFLink_GetLinkAtPoint`.
pub fn link_at_point(annotations: &[Annotation], x: f32, y: f32) -> Option<LinkObject> {
    for (idx, annot) in annotations.iter().enumerate() {
        if annot.subtype != AnnotationType::Link {
            continue;
        }

        let hit = if let Some(ref qp) = annot.subtype_data.quad_points {
            point_in_quad_points(qp, x, y)
        } else {
            point_in_rect(&annot.rect, x, y)
        };

        if hit {
            return Some(LinkObject::from_annotation(annot, idx));
        }
    }
    None
}

/// ADR-019 alias for [`link_at_point()`].
///
/// Corresponds to `FPDFLink_GetLinkAtPoint`.
#[inline]
pub fn link_get_link_at_point(annotations: &[Annotation], x: f32, y: f32) -> Option<LinkObject> {
    link_at_point(annotations, x, y)
}

/// Deprecated: use [`link_get_link_at_point()`] or [`link_at_point()`] instead.
///
/// Corresponds to `FPDFLink_GetLinkAtPoint`.
#[deprecated(
    since = "0.1.0",
    note = "use link_get_link_at_point() or link_at_point() instead"
)]
#[inline]
pub fn get_link_at_point(annotations: &[Annotation], x: f32, y: f32) -> Option<LinkObject> {
    link_at_point(annotations, x, y)
}

/// Result of a link hit test.
#[derive(Debug, Clone)]
pub struct HitTestResult {
    /// Index of the matching annotation in the annotations list.
    pub annotation_index: usize,
    /// The action associated with the link, if any.
    pub action: Option<Action>,
    /// The destination associated with the link, if any.
    pub destination: Option<Destination>,
    /// The URI if the action is a URI action.
    pub uri: Option<String>,
}

/// Find a link annotation at the given point.
///
/// Iterates over annotations, testing only those with `AnnotationType::Link`.
/// If the annotation has `/QuadPoints`, uses point-in-quadrilateral testing;
/// otherwise falls back to simple rectangle containment.
///
/// Returns the first matching link annotation.
pub fn find_link_at_position(annotations: &[Annotation], x: f32, y: f32) -> Option<HitTestResult> {
    for (idx, annot) in annotations.iter().enumerate() {
        if annot.subtype != AnnotationType::Link {
            continue;
        }

        let hit = if let Some(ref quad_points) = annot.subtype_data.quad_points {
            point_in_quad_points(quad_points, x, y)
        } else {
            point_in_rect(&annot.rect, x, y)
        };

        if hit {
            let uri = annot.action.as_ref().and_then(|a| {
                if let Action::Uri(u) = a {
                    Some(u.clone())
                } else {
                    None
                }
            });

            return Some(HitTestResult {
                annotation_index: idx,
                action: annot.action.clone(),
                destination: annot.destination.clone(),
                uri,
            });
        }
    }
    None
}

/// Test if a point is inside a rectangle `[x1, y1, x2, y2]`.
fn point_in_rect(rect: &[f32; 4], x: f32, y: f32) -> bool {
    let (x_min, x_max) = if rect[0] <= rect[2] {
        (rect[0], rect[2])
    } else {
        (rect[2], rect[0])
    };
    let (y_min, y_max) = if rect[1] <= rect[3] {
        (rect[1], rect[3])
    } else {
        (rect[3], rect[1])
    };
    x >= x_min && x <= x_max && y >= y_min && y <= y_max
}

/// Test if a point is inside any quadrilateral defined by QuadPoints.
///
/// QuadPoints are groups of 8 floats: `[x1,y1, x2,y2, x3,y3, x4,y4]`.
/// Each group defines one quadrilateral.
fn point_in_quad_points(quad_points: &[f32], x: f32, y: f32) -> bool {
    // Each quad is 8 floats (4 points)
    let mut offset = 0;
    while offset + 7 < quad_points.len() {
        let p0 = (quad_points[offset], quad_points[offset + 1]);
        let p1 = (quad_points[offset + 2], quad_points[offset + 3]);
        let p2 = (quad_points[offset + 4], quad_points[offset + 5]);
        let p3 = (quad_points[offset + 6], quad_points[offset + 7]);

        if point_in_quad(p0, p1, p2, p3, x, y) {
            return true;
        }
        offset += 8;
    }
    false
}

/// Test if a point is inside a convex quadrilateral using cross products.
///
/// For a convex quad (p0, p1, p2, p3), the point is inside if it is on the
/// same side of all four edges.
fn point_in_quad(
    p0: (f32, f32),
    p1: (f32, f32),
    p2: (f32, f32),
    p3: (f32, f32),
    x: f32,
    y: f32,
) -> bool {
    let edges = [(p0, p1), (p1, p2), (p2, p3), (p3, p0)];

    let mut pos = 0i32;
    let mut neg = 0i32;

    for &(a, b) in &edges {
        let cross = (b.0 - a.0) * (y - a.1) - (b.1 - a.1) * (x - a.0);
        if cross > 0.0 {
            pos += 1;
        } else if cross < 0.0 {
            neg += 1;
        }
    }

    // Point is inside if all cross products have the same sign (or are zero)
    pos == 0 || neg == 0
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::annotation::{AnnotationFlags, AnnotationSubtypeData};

    fn make_link(
        rect: [f32; 4],
        action: Option<Action>,
        quad_points: Option<Vec<f32>>,
    ) -> Annotation {
        Annotation {
            subtype: AnnotationType::Link,
            rect,
            contents: None,
            flags: AnnotationFlags::from_bits(0),
            name: None,
            appearance: None,
            color: None,
            border: None,
            action,
            destination: None,
            subtype_data: AnnotationSubtypeData {
                quad_points,
                ..Default::default()
            },
            mk: None,
            file_spec: None,
            parent_ref: None,
            object_id: None,
            open: None,
            ap_n_bytes: None,
            ap_r_bytes: None,
            ap_d_bytes: None,
            irt_ref: None,
            field_name: None,
            alternate_name: None,
            field_value: None,
            form_field_flags: None,
            additional_actions: None,
            form_field_type: None,
            options: None,
        }
    }

    fn make_text(rect: [f32; 4]) -> Annotation {
        Annotation {
            subtype: AnnotationType::Text,
            rect,
            contents: None,
            flags: AnnotationFlags::from_bits(0),
            name: None,
            appearance: None,
            color: None,
            border: None,
            action: None,
            destination: None,
            subtype_data: AnnotationSubtypeData::default(),
            mk: None,
            file_spec: None,
            parent_ref: None,
            object_id: None,
            open: None,
            ap_n_bytes: None,
            ap_r_bytes: None,
            ap_d_bytes: None,
            irt_ref: None,
            field_name: None,
            alternate_name: None,
            field_value: None,
            form_field_flags: None,
            additional_actions: None,
            form_field_type: None,
            options: None,
        }
    }

    #[test]
    fn test_hit_test_rect_inside() {
        let annotations = vec![make_link(
            [10.0, 10.0, 100.0, 30.0],
            Some(Action::Uri("https://example.com".into())),
            None,
        )];

        let result = find_link_at_position(&annotations, 50.0, 20.0).unwrap();
        assert_eq!(result.annotation_index, 0);
        assert_eq!(result.uri.as_deref(), Some("https://example.com"));
    }

    #[test]
    fn test_hit_test_rect_outside() {
        let annotations = vec![make_link(
            [10.0, 10.0, 100.0, 30.0],
            Some(Action::Uri("https://example.com".into())),
            None,
        )];

        assert!(find_link_at_position(&annotations, 5.0, 5.0).is_none());
    }

    #[test]
    fn test_hit_test_skips_non_link() {
        let annotations = vec![
            make_text([0.0, 0.0, 200.0, 200.0]),
            make_link(
                [10.0, 10.0, 100.0, 30.0],
                Some(Action::Uri("https://example.com".into())),
                None,
            ),
        ];

        let result = find_link_at_position(&annotations, 50.0, 20.0).unwrap();
        assert_eq!(result.annotation_index, 1);
    }

    #[test]
    fn test_hit_test_quad_points() {
        // A simple axis-aligned quad: (0,0) (100,0) (100,20) (0,20)
        let quad_points = vec![0.0, 0.0, 100.0, 0.0, 100.0, 20.0, 0.0, 20.0];
        let annotations = vec![make_link(
            [0.0, 0.0, 100.0, 20.0],
            Some(Action::Uri("https://example.com".into())),
            Some(quad_points),
        )];

        assert!(find_link_at_position(&annotations, 50.0, 10.0).is_some());
        assert!(find_link_at_position(&annotations, 150.0, 10.0).is_none());
    }

    #[test]
    fn test_hit_test_no_links_returns_none() {
        let annotations: Vec<Annotation> = Vec::new();
        assert!(find_link_at_position(&annotations, 50.0, 20.0).is_none());
    }

    #[test]
    fn test_hit_test_returns_first_match() {
        let annotations = vec![
            make_link(
                [0.0, 0.0, 100.0, 100.0],
                Some(Action::Uri("https://first.com".into())),
                None,
            ),
            make_link(
                [0.0, 0.0, 200.0, 200.0],
                Some(Action::Uri("https://second.com".into())),
                None,
            ),
        ];

        let result = find_link_at_position(&annotations, 50.0, 50.0).unwrap();
        assert_eq!(result.annotation_index, 0);
        assert_eq!(result.uri.as_deref(), Some("https://first.com"));
    }

    // -----------------------------------------------------------------------
    // LinkObject API tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_link_at_point_returns_link_object() {
        let annotations = vec![make_link(
            [10.0, 10.0, 100.0, 30.0],
            Some(Action::Uri("https://example.com".into())),
            None,
        )];

        let link = link_at_point(&annotations, 50.0, 20.0).unwrap();
        assert_eq!(link.annotation_index, 0);
        assert_eq!(link.rect(), [10.0, 10.0, 100.0, 30.0]);
        match link.action() {
            Some(Action::Uri(u)) => assert_eq!(u, "https://example.com"),
            _ => panic!("expected URI action"),
        }
        assert!(link.dest().is_none());
    }

    #[test]
    fn test_link_at_point_miss_returns_none() {
        let annotations = vec![make_link(
            [10.0, 10.0, 100.0, 30.0],
            Some(Action::Uri("https://example.com".into())),
            None,
        )];

        assert!(link_at_point(&annotations, 200.0, 200.0).is_none());
    }

    #[test]
    fn test_link_at_point_with_quad_points() {
        let qp = vec![0.0, 0.0, 100.0, 0.0, 100.0, 20.0, 0.0, 20.0];
        let annotations = vec![make_link(
            [0.0, 0.0, 100.0, 20.0],
            Some(Action::Uri("https://example.com".into())),
            Some(qp),
        )];

        let link = link_at_point(&annotations, 50.0, 10.0).unwrap();
        assert_eq!(link.quad_point_count(), 1);
        assert_eq!(link.link_count_quad_points(), 1);
        let qp = link.quad_points_at(0).unwrap();
        assert_eq!(qp[0], 0.0);
        assert_eq!(qp[2], 100.0);
        assert!(link.quad_points_at(1).is_none());
    }

    #[test]
    fn test_link_object_quad_points_multiple_groups() {
        let qp = vec![
            0.0, 0.0, 10.0, 0.0, 10.0, 10.0, 0.0, 10.0, // group 0
            20.0, 20.0, 30.0, 20.0, 30.0, 30.0, 20.0, 30.0, // group 1
        ];
        let link = LinkObject {
            rect: [0.0, 0.0, 30.0, 30.0],
            quad_points: Some(qp),
            destination: None,
            action: None,
            annotation_index: 0,
        };
        assert_eq!(link.quad_point_count(), 2);
        let g0 = link.link_get_quad_points(0).unwrap();
        assert_eq!(g0[0], 0.0);
        let g1 = link.link_get_quad_points(1).unwrap();
        assert_eq!(g1[0], 20.0);
        assert!(link.link_get_quad_points(2).is_none());
    }

    #[test]
    fn test_link_object_no_quad_points() {
        let link = LinkObject {
            rect: [0.0, 0.0, 100.0, 50.0],
            quad_points: None,
            destination: None,
            action: None,
            annotation_index: 0,
        };
        assert_eq!(link.quad_point_count(), 0);
        assert!(link.quad_points_at(0).is_none());
    }

    #[test]
    fn test_collect_links_filters_link_annotations() {
        let annotations = vec![
            make_text([0.0, 0.0, 100.0, 100.0]),
            make_link(
                [10.0, 10.0, 50.0, 20.0],
                Some(Action::Uri("https://a.com".into())),
                None,
            ),
            make_text([200.0, 200.0, 300.0, 300.0]),
            make_link(
                [60.0, 60.0, 90.0, 80.0],
                Some(Action::Uri("https://b.com".into())),
                None,
            ),
        ];

        let links = collect_links(&annotations);
        assert_eq!(links.len(), 2);
        assert_eq!(links[0].annotation_index, 1);
        assert_eq!(links[1].annotation_index, 3);
    }

    #[test]
    fn test_link_get_link_at_point_alias_works() {
        let annotations = vec![make_link(
            [0.0, 0.0, 100.0, 100.0],
            Some(Action::Uri("https://example.com".into())),
            None,
        )];

        let link = link_get_link_at_point(&annotations, 50.0, 50.0).unwrap();
        assert_eq!(link.annotation_index, 0);
    }

    #[test]
    fn test_link_object_dest_accessor() {
        use crate::destination::{Destination, PageFit};
        let link = LinkObject {
            rect: [0.0, 0.0, 100.0, 50.0],
            quad_points: None,
            destination: Some(Destination::Page {
                page_index: 3,
                page_ref: None,
                fit: PageFit::Fit,
            }),
            action: None,
            annotation_index: 0,
        };
        assert!(link.dest().is_some());
        assert!(link.link_get_dest().is_some());
        assert!(link.action().is_none());
        assert!(link.link_get_action().is_none());
    }

    // -----------------------------------------------------------------------
    // annotation_index / get_annot — FPDFLink_GetAnnot equivalent
    // -----------------------------------------------------------------------

    #[test]
    fn test_annotation_index_returns_correct_index() {
        // Build a page with two annotations: one Text (idx 0) and one Link (idx 1).
        let annotations = vec![
            make_text([0.0, 0.0, 100.0, 100.0]),
            make_link(
                [10.0, 10.0, 90.0, 30.0],
                Some(Action::Uri("https://example.com".into())),
                None,
            ),
        ];

        let links = collect_links(&annotations);
        assert_eq!(links.len(), 1);

        let link = &links[0];
        // The link is the second annotation (index 1).
        assert_eq!(link.annotation_index(), 1);
        assert_eq!(link.link_get_annot(), 1);
    }

    #[test]
    fn test_annotation_index_matches_link_at_point() {
        // Two links at different positions.
        let annotations = vec![
            make_link(
                [0.0, 0.0, 50.0, 50.0],
                Some(Action::Uri("https://first.com".into())),
                None,
            ),
            make_link(
                [100.0, 100.0, 200.0, 150.0],
                Some(Action::Uri("https://second.com".into())),
                None,
            ),
        ];

        let link0 = link_at_point(&annotations, 25.0, 25.0).unwrap();
        let link1 = link_at_point(&annotations, 150.0, 125.0).unwrap();

        assert_eq!(link0.annotation_index(), 0);
        assert_eq!(link0.link_get_annot(), 0);
        assert_eq!(link1.annotation_index(), 1);
        assert_eq!(link1.link_get_annot(), 1);
    }
}