pdfrum-doc 0.3.0

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
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
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
//! The per-subtype appearance generators that draw shapes rather than
//! text.
//!
//! Every one of these writes its coordinates through the **six-significant-
//! digit** writer, not the shortest-round-trip one that the newer form-field
//! and border code uses — these are the older generators and were never
//! converted. So a coordinate of `0.5` appears here as `0.5` and in a border
//! as `.5`, in the same stream. That is the byte parity being matched.
//!
//! Two of them also change the annotation's rectangle: a sticky note becomes
//! a fixed 20×20 box anchored at its original bottom-left, and an ink
//! annotation inflates by half its border width so wide strokes are not
//! clipped away. Neither mutates anything — both report the new rectangle to
//! the caller, which records it in the overlay.

// The midpoints below are written as `(a + b) / 2.0` on purpose: the
// standard-library midpoint is *more* accurate than that, and these numbers
// are written straight into a content stream whose bytes must match. The
// narrowing casts are equally deliberate — the arithmetic happens in double
// precision and is narrowed once, exactly where upstream narrows it.
#![allow(
    clippy::manual_midpoint,
    clippy::cast_possible_truncation,
    clippy::many_single_char_names
)]

use kurbo::Rect;
use pdfrum_common::{DiagKind, Diagnostics, Severity};
use pdfrum_object::{Array, Dict, Resolve, names as obj_names};

use crate::annot::quad;
use crate::ap::border;
use crate::ap::emit::{Content, Float, PaintOp, color_op, color_with_default, paint_operator};
use crate::color::Color;
use crate::geom;
use crate::names;

/// The prologue every one of these streams opens with.
///
/// Note the trailing **space**, not a newline — except in the pop-up
/// generator, which uses a newline. Both are reproduced.
const GS_SPACE: &str = "/GS gs ";

/// One generator's output.
#[derive(Debug, Clone, PartialEq)]
pub struct Generated {
    /// The content-stream bytes.
    pub stream: Vec<u8>,
    /// A rewritten `/Rect`, when this generator moved one.
    pub rect_override: Option<Rect>,
    /// Whether the appearance's bounding box comes from the quadrilaterals
    /// rather than from the rectangle.
    pub is_text_markup: bool,
    /// The blend mode the graphics state names.
    pub blend_multiply: bool,
    /// The `/Font` sub-dictionary the appearance stream's `/Resources` needs,
    /// as `{ resource name: font dictionary }`.
    ///
    /// Empty for every generator that writes no text — which is all of them
    /// but [`crate::ap::freetext::free_text`], since a stream with no `Tf`
    /// needs no font to resolve.
    pub font_resources: Option<Dict>,
}

impl Generated {
    fn plain(stream: Content) -> Generated {
        Generated {
            stream: stream.into_bytes(),
            rect_override: None,
            is_text_markup: false,
            blend_multiply: false,
            font_resources: None,
        }
    }

    fn markup(stream: Content) -> Generated {
        Generated {
            is_text_markup: true,
            ..Generated::plain(stream)
        }
    }
}

/// A `Highlight`: one filled quadrilateral per attachment point, composited
/// with the **Multiply** blend mode so the text below shows through.
#[must_use]
pub fn highlight<R: Resolve>(dict: &Dict, r: &R) -> Generated {
    let mut out = Content::new();
    out.raw(GS_SPACE);
    out.raw(&color_with_default(
        dict.array(names::C, r).as_ref(),
        Color::Rgb(1.0, 1.0, 0.0),
        PaintOp::Fill,
    ));
    if let Some(quads) = dict.array(names::QUAD_POINTS, r) {
        for index in 0..quad::quad_point_count(Some(&quads)) {
            let rect = geom::normalize(quad::rect_from_quad_points_array(&quads, index));
            let (l, b, right, t) = corners(rect);
            out.point(l, t, Float::G6);
            out.raw("m ");
            out.point(right, t, Float::G6);
            out.raw("l ");
            out.point(right, b, Float::G6);
            out.raw("l ");
            out.point(l, b, Float::G6);
            out.raw("l h f\n");
        }
    }
    Generated {
        blend_multiply: true,
        ..Generated::markup(out)
    }
}

/// An `Underline`: a one-unit line just above each quadrilateral's bottom.
#[must_use]
pub fn underline<R: Resolve>(dict: &Dict, r: &R) -> Generated {
    let mut out = Content::new();
    out.raw(GS_SPACE);
    out.raw(&stroke_default_black(dict, r));
    if let Some(quads) = dict.array(names::QUAD_POINTS, r) {
        // The width is written once, before the loop.
        out.raw("1 w ");
        for index in 0..quad::quad_point_count(Some(&quads)) {
            let rect = geom::normalize(quad::rect_from_quad_points_array(&quads, index));
            let (l, b, right, _) = corners(rect);
            out.point(l, b + 1.0, Float::G6);
            out.raw("m ");
            out.point(right, b + 1.0, Float::G6);
            out.raw("l S\n");
        }
    }
    Generated::markup(out)
}

/// A `StrikeOut`: a line through each quadrilateral's middle.
///
/// The width is written **inside** the loop here, unlike the underline and
/// squiggly generators — so a two-quad strikeout writes `1 w` twice.
#[must_use]
pub fn strike_out<R: Resolve>(dict: &Dict, r: &R) -> Generated {
    let mut out = Content::new();
    out.raw(GS_SPACE);
    out.raw(&stroke_default_black(dict, r));
    if let Some(quads) = dict.array(names::QUAD_POINTS, r) {
        for index in 0..quad::quad_point_count(Some(&quads)) {
            let rect = geom::normalize(quad::rect_from_quad_points_array(&quads, index));
            let (l, b, right, t) = corners(rect);
            let y = (t + b) / 2.0;
            out.raw("1 w ");
            out.point(l, y, Float::G6);
            out.raw("m ");
            out.point(right, y, Float::G6);
            out.raw("l S\n");
        }
    }
    Generated::markup(out)
}

/// A `Squiggly`: a zig-zag along each quadrilateral's bottom edge.
///
/// The zig-zag steps two units at a time and alternates between the bottom
/// and two units above it; the final segment lands wherever the remainder
/// puts it, which is why a quadrilateral narrower than one step draws only
/// its opening move and that closing segment.
#[must_use]
pub fn squiggly<R: Resolve>(dict: &Dict, r: &R) -> Generated {
    const DELTA: f32 = 2.0;
    let mut out = Content::new();
    out.raw(GS_SPACE);
    out.raw(&stroke_default_black(dict, r));
    if let Some(quads) = dict.array(names::QUAD_POINTS, r) {
        out.raw("1 w ");
        for index in 0..quad::quad_point_count(Some(&quads)) {
            let rect = geom::normalize(quad::rect_from_quad_points_array(&quads, index));
            let (l, bottom, right, _) = corners(rect);
            let top = bottom + DELTA;
            out.point(l, top, Float::G6);
            out.raw("m ");

            let mut x = l + DELTA;
            let mut upwards = false;
            while x < right {
                out.point(x, if upwards { top } else { bottom }, Float::G6);
                out.raw("l ");
                x += DELTA;
                upwards = !upwards;
            }
            let remainder = right - (x - DELTA);
            let y = if upwards {
                bottom + remainder
            } else {
                top - remainder
            };
            out.point(right, y, Float::G6);
            out.raw("l ");
            out.raw("S\n");
        }
    }
    Generated::markup(out)
}

/// An `Ink`: the freehand strokes of `/InkList`.
///
/// Returns nothing at all — not an empty appearance, no appearance — when
/// `/InkList` is missing or empty, or when the border width is not positive.
/// Each sub-array's first point is written **twice**, once as the move and
/// again as the first line, because the line loop starts at index zero.
#[must_use]
pub fn ink<R: Resolve>(dict: &Dict, r: &R, diags: &mut Diagnostics) -> Option<Generated> {
    let ink_list = dict.array(names::INK_LIST, r).filter(|a| !a.is_empty())?;
    let width = border::border_width(dict, r);
    if width <= 0.0 {
        return None;
    }

    let mut out = Content::new();
    out.raw(GS_SPACE);
    out.raw(&stroke_default_black(dict, r));
    out.num(width, Float::G6);
    out.raw("w ");
    out.raw(&border::dash_pattern_string(dict, r));

    for index in 0..ink_list.len() {
        // `CPDF_GenerateAP` skips a sub-array that is missing or holds fewer
        // than two numbers (`cpdf_generateap.cpp:1210-1213`): one stroke of
        // the drawing silently does not appear.
        let Some(points) = ink_list.array_at(index, r).filter(|a| a.len() >= 2) else {
            diags.record(Severity::Recovered, DiagKind::InkPathDropped, None);
            continue;
        };
        out.point(
            points.number_at_or_zero(0),
            points.number_at_or_zero(1),
            Float::G6,
        );
        out.raw("m ");
        // Stepping in pairs from zero, so the first point repeats and an odd
        // trailing coordinate is left out.
        let mut at = 0;
        while at + 1 < points.len() {
            out.point(
                points.number_at_or_zero(at),
                points.number_at_or_zero(at + 1),
                Float::G6,
            );
            out.raw("l ");
            at += 2;
        }
        out.raw("S\n");
    }

    // Wide strokes near the edge would be clipped away by the original
    // rectangle, so it grows by half the width.
    let rect = dict.rect(obj_names::RECT, r);
    Some(Generated {
        rect_override: Some(geom::inflate(rect, width / 2.0, width / 2.0)),
        ..Generated::plain(out)
    })
}

/// A `Square`: the rectangle, stroked and filled per its two colour keys.
#[must_use]
pub fn square<R: Resolve>(dict: &Dict, r: &R) -> Generated {
    let (mut out, rect, stroke, fill) = shape_preamble(dict, r);
    out.rect(rect, Float::G6);
    out.raw("re ");
    out.raw(paint_operator(stroke, fill));
    out.raw("\n");
    Generated::plain(out)
}

/// A `Circle`: four Bézier arcs inscribed in the rectangle.
#[must_use]
pub fn circle<R: Resolve>(dict: &Dict, r: &R) -> Generated {
    // A precalculated approximation of `4·tan(π/8)/3`, which times the radius
    // gives the control-point offset for a quarter arc.
    const K: f64 = 0.5523;

    let (mut out, rect, stroke, fill) = shape_preamble(dict, r);
    let (left, bottom, right, top) = corners(rect);
    let mid_x = (left + right) / 2.0;
    let mid_y = (top + bottom) / 2.0;
    // Computed in double precision and narrowed once, as upstream does.
    let dx = (K * f64::from(geom::width(rect)) / 2.0) as f32;
    let dy = (K * f64::from(geom::height(rect)) / 2.0) as f32;

    out.point(mid_x, top, Float::G6);
    out.raw("m\n");
    for (points, op) in [
        (
            [(mid_x + dx, top), (right, mid_y + dy), (right, mid_y)],
            "c\n",
        ),
        (
            [(right, mid_y - dy), (mid_x + dx, bottom), (mid_x, bottom)],
            "c\n",
        ),
        (
            [(mid_x - dx, bottom), (left, mid_y - dy), (left, mid_y)],
            "c\n",
        ),
        ([(left, mid_y + dy), (mid_x - dx, top), (mid_x, top)], "c\n"),
    ] {
        for (x, y) in points {
            out.point(x, y, Float::G6);
        }
        out.raw(op);
    }
    out.raw(paint_operator(stroke, fill));
    out.raw("\n");
    Generated::plain(out)
}

/// A `Text` sticky note: a fixed 20×20 icon, which **replaces** the
/// annotation's rectangle.
///
/// The new rectangle is anchored at the raw, unnormalized rectangle's
/// bottom-left corner, so an inverted `/Rect` still produces a well-formed
/// note box in a possibly surprising place.
#[must_use]
pub fn text<R: Resolve>(dict: &Dict, r: &R) -> Generated {
    const NOTE: f32 = 20.0;
    let rect = dict.rect(obj_names::RECT, r);
    let (left, bottom) = (geom::left(rect), geom::bottom(rect));
    let note = geom::rect(left, bottom, left + NOTE, bottom + NOTE);

    let mut out = Content::new();
    out.raw(GS_SPACE);
    out.raw(&text_symbol(note));
    Generated {
        rect_override: Some(note),
        ..Generated::plain(out)
    }
}

/// A `Line`: stroke between `/L` endpoints with the annotation's border width
/// and `/C` colour, plus `/LE` ending decorations when present.
///
/// Declines when `/L` is missing or shorter than four numbers.
#[must_use]
pub fn line<R: Resolve>(dict: &Dict, r: &R) -> Option<Generated> {
    let endpoints = dict.array(names::L, r)?;
    if endpoints.len() < 4 {
        return None;
    }
    let x1 = endpoints.number_at(0)?;
    let y1 = endpoints.number_at(1)?;
    let x2 = endpoints.number_at(2)?;
    let y2 = endpoints.number_at(3)?;

    let mut out = Content::new();
    out.raw(GS_SPACE);
    out.raw(&stroke_default_black(dict, r));
    // `/IC` paints filled endings; absent/empty means stroke-only chrome.
    let fill = line_ending_fill(dict, r);
    let width = border::border_width(dict, r);
    if width <= 0.0 {
        return None;
    }
    out.num(width, Float::G6);
    out.raw("w ");
    out.raw(&border::dash_pattern_string(dict, r));
    out.point(x1, y1, Float::G6);
    out.raw("m\n");
    out.point(x2, y2, Float::G6);
    out.raw("l\n");
    out.raw("S\n");

    let (start_style, end_style) = line_ending_styles(dict, r);
    // Ending length tracks stroke width (3×), with no separate absolute floor.
    let size = width * 3.0;
    draw_line_ending(&mut out, x1, y1, x2, y2, true, start_style, size, &fill);
    draw_line_ending(&mut out, x1, y1, x2, y2, false, end_style, size, &fill);

    let pad = (width / 2.0).max(size);
    let rect = dict.rect(obj_names::RECT, r);
    Some(Generated {
        rect_override: Some(geom::inflate(rect, pad, pad)),
        ..Generated::plain(out)
    })
}

/// `/LE` start and end style spellings; missing or short `/LE` is `(None, None)`.
fn line_ending_styles<R: Resolve>(dict: &Dict, r: &R) -> (LineEnd, LineEnd) {
    let Some(le) = dict.array(names::LE, r) else {
        return (LineEnd::None, LineEnd::None);
    };
    let start = le
        .name_at(0)
        .map_or(LineEnd::None, |n| LineEnd::from_bytes(n.as_bytes()));
    let end = le
        .name_at(1)
        .map_or(LineEnd::None, |n| LineEnd::from_bytes(n.as_bytes()));
    (start, end)
}

/// κ for cubic circle approximation.
const CIRCLE_K: f32 = 0.552_284_8;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LineEnd {
    None,
    Square,
    Circle,
    Diamond,
    OpenArrow,
    ClosedArrow,
    Butt,
    ROpenArrow,
    RClosedArrow,
    Slash,
}

impl LineEnd {
    fn from_bytes(bytes: &[u8]) -> Self {
        match bytes {
            b"Square" => Self::Square,
            b"Circle" => Self::Circle,
            b"Diamond" => Self::Diamond,
            b"OpenArrow" => Self::OpenArrow,
            b"ClosedArrow" => Self::ClosedArrow,
            b"Butt" => Self::Butt,
            b"ROpenArrow" => Self::ROpenArrow,
            b"RClosedArrow" => Self::RClosedArrow,
            b"Slash" => Self::Slash,
            _ => Self::None,
        }
    }
}

/// Draw one ending at the start (`at_start`) or end of the segment.
#[allow(
    clippy::too_many_arguments,
    clippy::too_many_lines,
    reason = "geometry + style + paint for one ending"
)]
fn draw_line_ending(
    out: &mut Content,
    x1: f32,
    y1: f32,
    x2: f32,
    y2: f32,
    at_start: bool,
    style: LineEnd,
    size: f32,
    fill: &str,
) {
    if matches!(style, LineEnd::None) {
        return;
    }
    let (px, py) = if at_start { (x1, y1) } else { (x2, y2) };
    let dx = x2 - x1;
    let dy = y2 - y1;
    let len = (dx * dx + dy * dy).sqrt();
    if len <= f32::EPSILON {
        return;
    }
    // Outward unit along the line at this endpoint.
    let (mut ux, mut uy) = (dx / len, dy / len);
    if at_start {
        ux = -ux;
        uy = -uy;
    }
    // Reversed styles point inward.
    if matches!(style, LineEnd::ROpenArrow | LineEnd::RClosedArrow) {
        ux = -ux;
        uy = -uy;
    }
    let (nx, ny) = (-uy, ux);
    let half = size * 0.5;

    match style {
        LineEnd::None => {}
        LineEnd::OpenArrow | LineEnd::ROpenArrow => {
            let bx = px - size * ux;
            let by = py - size * uy;
            out.point(bx + half * nx, by + half * ny, Float::G6);
            out.raw("m\n");
            out.point(px, py, Float::G6);
            out.raw("l\n");
            out.point(bx - half * nx, by - half * ny, Float::G6);
            out.raw("l\n");
            out.raw("S\n");
        }
        LineEnd::ClosedArrow | LineEnd::RClosedArrow => {
            let bx = px - size * ux;
            let by = py - size * uy;
            if !fill.is_empty() {
                out.raw(fill);
            }
            out.point(px, py, Float::G6);
            out.raw("m\n");
            out.point(bx + half * nx, by + half * ny, Float::G6);
            out.raw("l\n");
            out.point(bx - half * nx, by - half * ny, Float::G6);
            out.raw("l\n");
            out.raw("b\n");
        }
        LineEnd::Square => {
            let cx = px - half * ux;
            let cy = py - half * uy;
            if !fill.is_empty() {
                out.raw(fill);
            }
            let corners = [
                (cx + half * (-ux + nx), cy + half * (-uy + ny)),
                (cx + half * (ux + nx), cy + half * (uy + ny)),
                (cx + half * (ux - nx), cy + half * (uy - ny)),
                (cx + half * (-ux - nx), cy + half * (-uy - ny)),
            ];
            out.point(corners[0].0, corners[0].1, Float::G6);
            out.raw("m\n");
            for &(x, y) in &corners[1..] {
                out.point(x, y, Float::G6);
                out.raw("l\n");
            }
            out.raw("b\n");
        }
        LineEnd::Diamond => {
            if !fill.is_empty() {
                out.raw(fill);
            }
            let tips = [
                (px + half * ux, py + half * uy),
                (px + half * nx, py + half * ny),
                (px - half * ux, py - half * uy),
                (px - half * nx, py - half * ny),
            ];
            out.point(tips[0].0, tips[0].1, Float::G6);
            out.raw("m\n");
            for &(x, y) in &tips[1..] {
                out.point(x, y, Float::G6);
                out.raw("l\n");
            }
            out.raw("b\n");
        }
        LineEnd::Circle => {
            if !fill.is_empty() {
                out.raw(fill);
            }
            // Four-curve unit circle approx scaled to `half`.
            let (cx, cy, rad) = (px, py, half);
            out.point(cx + rad, cy, Float::G6);
            out.raw("m\n");
            out.point(cx + rad, cy + CIRCLE_K * rad, Float::G6);
            out.point(cx + CIRCLE_K * rad, cy + rad, Float::G6);
            out.point(cx, cy + rad, Float::G6);
            out.raw("c\n");
            out.point(cx - CIRCLE_K * rad, cy + rad, Float::G6);
            out.point(cx - rad, cy + CIRCLE_K * rad, Float::G6);
            out.point(cx - rad, cy, Float::G6);
            out.raw("c\n");
            out.point(cx - rad, cy - CIRCLE_K * rad, Float::G6);
            out.point(cx - CIRCLE_K * rad, cy - rad, Float::G6);
            out.point(cx, cy - rad, Float::G6);
            out.raw("c\n");
            out.point(cx + CIRCLE_K * rad, cy - rad, Float::G6);
            out.point(cx + rad, cy - CIRCLE_K * rad, Float::G6);
            out.point(cx + rad, cy, Float::G6);
            out.raw("c\n");
            out.raw("b\n");
        }
        LineEnd::Butt => {
            out.point(px + half * nx, py + half * ny, Float::G6);
            out.raw("m\n");
            out.point(px - half * nx, py - half * ny, Float::G6);
            out.raw("l\n");
            out.raw("S\n");
        }
        LineEnd::Slash => {
            // ~60° slash through the endpoint.
            let angle = core::f32::consts::FRAC_PI_3;
            let (sx, sy) = (angle.cos(), angle.sin());
            let rx = sx * ux - sy * uy;
            let ry = sy * ux + sx * uy;
            out.point(px + half * rx, py + half * ry, Float::G6);
            out.raw("m\n");
            out.point(px - half * rx, py - half * ry, Float::G6);
            out.raw("l\n");
            out.raw("S\n");
        }
    }
}

/// Interior colour for filled line endings (`/IC`).
///
/// A present non-empty array fills; missing or empty `/IC` yields no fill so
/// closed endings stroke only (ISO 32000-1 §12.5.6.7).
fn line_ending_fill<R: Resolve>(dict: &Dict, r: &R) -> String {
    match dict.array(names::IC, r) {
        Some(arr) if !arr.is_empty() => {
            color_with_default(Some(&arr), Color::Transparent, PaintOp::Fill)
        }
        _ => String::new(),
    }
}

/// A `Link`: border chrome over `/Rect`.
///
/// Honours `/BS` (and `/Border`) via [`border::border_path`] — solid, dashed,
/// underline, bevel, inset — with `/C` when present, otherwise a muted blue.
/// A missing border still draws at least a 1 pt border so the hit target is
/// visible.
#[must_use]
pub fn link<R: Resolve>(dict: &Dict, r: &R) -> Generated {
    let mut out = Content::new();
    out.raw(GS_SPACE);
    let rect = geom::normalize(dict.rect(obj_names::RECT, r));
    let bs = dict.dict(names::BS, r);
    let mut info = border::border_style_info(bs.as_ref(), r);
    if bs.is_none() && dict.array(obj_names::BORDER, r).is_none() {
        info.width = info.width.max(1.0);
    }
    // `/C` as RGB when present; else muted blue.
    let color = match dict.array(names::C, r) {
        Some(arr) if arr.len() >= 3 => Color::Rgb(
            arr.number_at_or_zero(0),
            arr.number_at_or_zero(1),
            arr.number_at_or_zero(2),
        ),
        _ => Color::Rgb(0.0, 0.0, 1.0),
    };
    let path = border::border_path(rect, info, color);
    if path.is_empty() {
        let stroke = color_op(color, PaintOp::Stroke);
        out.raw(&stroke);
        let width = info.width.max(1.0);
        out.num(width, Float::G6);
        out.raw("w ");
        let inset = geom::deflate(rect, width / 2.0, width / 2.0);
        out.rect(inset, Float::G6);
        out.raw(
            "re s
",
        );
    } else {
        out.raw(&path);
    }
    Generated::plain(out)
}

/// A `Caret`: a simple inverted-V glyph centered in `/Rect`.
#[must_use]
pub fn caret<R: Resolve>(dict: &Dict, r: &R) -> Generated {
    let mut out = Content::new();
    out.raw(GS_SPACE);
    out.raw(&stroke_default_black(dict, r));
    let width = border::border_width(dict, r).max(1.0);
    out.num(width, Float::G6);
    out.raw("w\n");

    let rect = geom::normalize(dict.rect(obj_names::RECT, r));
    let (left, bottom, right, top) = corners(rect);
    let mid_x = (left + right) / 2.0;
    // Tip near the top, legs toward the bottom corners — a caret mark.
    out.point(left, bottom, Float::G6);
    out.raw("m\n");
    out.point(mid_x, top, Float::G6);
    out.raw("l\n");
    out.point(right, bottom, Float::G6);
    out.raw("l\n");
    out.raw("S\n");
    Generated::plain(out)
}

/// The sticky-note icon: a page outline with a folded corner and three
/// ruled lines.
#[must_use]
pub fn text_symbol(rect: Rect) -> String {
    const TIP: f32 = 4.0;
    let mut out = Content::new();
    out.raw(&color_op(Color::Rgb(1.0, 1.0, 0.0), PaintOp::Fill));
    out.raw(&color_op(Color::Rgb(0.0, 0.0, 0.0), PaintOp::Stroke));
    out.raw("1 w\n");

    let outer = geom::translate(geom::deflate(rect, 0.5, 0.5), 0.0, 0.0);
    let (ol, ob, or_, ot) = (
        geom::left(outer),
        geom::bottom(outer) + TIP,
        geom::right(outer),
        geom::top(outer),
    );
    // The fold: a small square whose "top" sits *below* its "bottom". These
    // are read out as coordinates, never normalized.
    let (fl, fb) = (ol + TIP, ob);
    let (fr, ft) = (fl + TIP, fb - TIP);
    let fold_mid = (fl + fr) / 2.0;

    for (x, y, op) in [
        (ol, ob, "m\n"),
        (ol, ot, "l\n"),
        (or_, ot, "l\n"),
        (or_, ob, "l\n"),
        (fr, fb, "l\n"),
        (fold_mid, ft, "l\n"),
        (fl, fb, "l\n"),
        (ol, ob, "l\n"),
    ] {
        out.point(x, y, Float::Shortest);
        out.raw(op);
    }

    let (line_left, line_right) = (ol + 2.0, or_ - 2.0);
    let step = (ot - ob) / 4.0;
    let mut y = ot;
    for _ in 0..3 {
        y -= step;
        out.point(line_left, y, Float::Shortest);
        out.raw("m\n");
        out.point(line_right, y, Float::Shortest);
        out.raw("l\n");
    }
    out.raw("B*\n");
    out.as_str().to_owned()
}

/// The shared opening of the square and circle generators: the two colours,
/// the border width and dash pattern, and the rectangle they draw into.
fn shape_preamble<R: Resolve>(dict: &Dict, r: &R) -> (Content, Rect, bool, bool) {
    let mut out = Content::new();
    out.raw(GS_SPACE);

    let interior = dict.array(names::IC, r);
    out.raw(&color_with_default(
        interior.as_ref(),
        Color::Transparent,
        PaintOp::Fill,
    ));
    out.raw(&stroke_default_black(dict, r));

    let width = border::border_width(dict, r);
    let stroke = width > 0.0;
    if stroke {
        out.num(width, Float::G6);
        out.raw("w ");
        out.raw(&border::dash_pattern_string(dict, r));
    }

    let mut rect = geom::normalize(dict.rect(obj_names::RECT, r));
    if stroke {
        // A stroke paints half a width either side of the path, so the path
        // moves inward to keep the ink inside the rectangle.
        rect = geom::deflate(rect, width / 2.0, width / 2.0);
    }
    // A present-but-empty `/IC` says "do not fill"; an absent one says the
    // same, and only a usable array fills.
    let fill = interior.is_some_and(|array: Array| !array.is_empty());
    (out, rect, stroke, fill)
}

/// The stroke colour from `/C`, defaulting to black.
fn stroke_default_black<R: Resolve>(dict: &Dict, r: &R) -> String {
    color_with_default(
        dict.array(names::C, r).as_ref(),
        Color::Rgb(0.0, 0.0, 0.0),
        PaintOp::Stroke,
    )
}

/// A rectangle's four edges, in the order the emitters read them.
fn corners(rect: Rect) -> (f32, f32, f32, f32) {
    (
        geom::left(rect),
        geom::bottom(rect),
        geom::right(rect),
        geom::top(rect),
    )
}

#[cfg(test)]
mod tests {
    use super::{
        caret, circle, highlight, ink, line, link, square, squiggly, strike_out, text, text_symbol,
        underline,
    };
    use crate::geom;
    use pdfrum_common::{DiagKind, Diagnostics};
    use pdfrum_object::{Array, Dict, Name, NoResolve, Object};

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

    fn numbers(values: &[f32]) -> Object {
        Object::Array(Array::of(values.iter().copied().map(Object::from)))
    }

    /// One quadrilateral spanning (10, 10) to (30, 20), written in the
    /// canonical corner order.
    fn one_quad() -> Object {
        numbers(&[10.0, 20.0, 30.0, 20.0, 10.0, 10.0, 30.0, 10.0])
    }

    fn stream(generated: &super::Generated) -> String {
        String::from_utf8_lossy(&generated.stream).into_owned()
    }

    #[test]
    fn a_highlight_fills_each_quadrilateral_and_asks_for_multiply() {
        let annot = dict(&[("QuadPoints", one_quad())]);
        let got = highlight(&annot, &NoResolve);
        assert!(got.blend_multiply);
        assert!(got.is_text_markup);
        assert_eq!(
            stream(&got),
            "/GS gs 1 1 0 rg\n10 20 m 30 20 l 30 10 l 10 10 l h f\n"
        );
    }

    #[test]
    fn a_highlights_default_colour_is_yellow_and_an_empty_array_beats_it() {
        let with_empty = dict(&[
            ("C", Object::Array(Array::new())),
            ("QuadPoints", one_quad()),
        ]);
        let got = stream(&highlight(&with_empty, &NoResolve));
        assert!(got.starts_with("/GS gs 10 20 m"), "{got}");
    }

    #[test]
    fn an_underline_writes_its_width_once_and_a_strikeout_writes_it_per_quad() {
        let two_quads = numbers(&[
            10.0, 20.0, 30.0, 20.0, 10.0, 10.0, 30.0, 10.0, 10.0, 40.0, 30.0, 40.0, 10.0, 30.0,
            30.0, 30.0,
        ]);
        let annot = dict(&[("QuadPoints", two_quads)]);
        assert_eq!(
            stream(&underline(&annot, &NoResolve))
                .matches("1 w ")
                .count(),
            1
        );
        assert_eq!(
            stream(&strike_out(&annot, &NoResolve))
                .matches("1 w ")
                .count(),
            2
        );
    }

    #[test]
    fn an_underline_sits_one_unit_above_the_bottom_edge() {
        let annot = dict(&[("QuadPoints", one_quad())]);
        assert_eq!(
            stream(&underline(&annot, &NoResolve)),
            "/GS gs 0 0 0 RG\n1 w 10 11 m 30 11 l S\n"
        );
    }

    #[test]
    fn a_strikeout_runs_through_the_vertical_middle() {
        let annot = dict(&[("QuadPoints", one_quad())]);
        assert_eq!(
            stream(&strike_out(&annot, &NoResolve)),
            "/GS gs 0 0 0 RG\n1 w 10 15 m 30 15 l S\n"
        );
    }

    #[test]
    fn a_squiggly_alternates_every_two_units() {
        let annot = dict(&[(
            "QuadPoints",
            numbers(&[10.0, 20.0, 16.0, 20.0, 10.0, 10.0, 16.0, 10.0]),
        )]);
        assert_eq!(
            stream(&squiggly(&annot, &NoResolve)),
            "/GS gs 0 0 0 RG\n1 w 10 12 m 12 10 l 14 12 l 16 10 l S\n"
        );
    }

    #[test]
    fn a_quadrilateral_narrower_than_one_step_draws_only_its_ends() {
        // Width 1, so the zig-zag loop never runs.
        let annot = dict(&[(
            "QuadPoints",
            numbers(&[10.0, 20.0, 11.0, 20.0, 10.0, 10.0, 11.0, 10.0]),
        )]);
        // The closing segment lands at `top - remainder`, and the remainder
        // is the full width because the loop never advanced past the start.
        let got = stream(&squiggly(&annot, &NoResolve));
        assert_eq!(got, "/GS gs 0 0 0 RG\n1 w 10 12 m 11 11 l S\n");
    }

    #[test]
    fn ink_repeats_its_first_point_and_drops_an_odd_trailing_coordinate() {
        let annot = dict(&[
            (
                "InkList",
                Object::Array(Array::of([numbers(&[1.0, 2.0, 3.0, 4.0, 5.0])])),
            ),
            ("Rect", numbers(&[0.0, 0.0, 10.0, 10.0])),
        ]);
        let mut diags = Diagnostics::default();
        let got = ink(&annot, &NoResolve, &mut diags).expect("has an ink list");
        assert_eq!(stream(&got), "/GS gs 0 0 0 RG\n1 w 1 2 m 1 2 l 3 4 l S\n");
        // The rectangle grew by half the border width.
        assert_eq!(got.rect_override, Some(geom::rect(-0.5, -0.5, 10.5, 10.5)));
    }

    #[test]
    fn ink_declines_entirely_without_a_usable_list_or_a_positive_width() {
        let mut diags = Diagnostics::default();
        assert!(ink(&Dict::new(), &NoResolve, &mut diags).is_none());
        assert!(
            ink(
                &dict(&[("InkList", Object::Array(Array::new()))]),
                &NoResolve,
                &mut diags
            )
            .is_none()
        );
        let zero_width = dict(&[
            (
                "InkList",
                Object::Array(Array::of([numbers(&[1.0, 2.0, 3.0, 4.0])])),
            ),
            ("Border", numbers(&[0.0, 0.0, 0.0])),
        ]);
        assert!(ink(&zero_width, &NoResolve, &mut diags).is_none());
    }

    #[test]
    fn a_too_short_ink_sub_array_is_dropped_and_recorded() {
        // Three strokes: a good one, one with a single coordinate, and one
        // that is not an array at all. PDFium `continue`s past the last two
        // (`cpdf_generateap.cpp:1210-1213`) and so do we — the difference is
        // that the caller can now find out a stroke went missing.
        let annot = dict(&[
            (
                "InkList",
                Object::Array(Array::of([
                    numbers(&[1.0, 2.0, 3.0, 4.0]),
                    numbers(&[9.0]),
                    Object::Int(7),
                ])),
            ),
            ("Rect", numbers(&[0.0, 0.0, 10.0, 10.0])),
        ]);
        let mut diags = Diagnostics::default();
        let got = ink(&annot, &NoResolve, &mut diags).expect("has an ink list");
        // Only the usable stroke is drawn.
        assert_eq!(stream(&got), "/GS gs 0 0 0 RG\n1 w 1 2 m 1 2 l 3 4 l S\n");
        assert!(diags.contains(&DiagKind::InkPathDropped));
        assert_eq!(diags.recorded(), 2, "one per dropped sub-array");
    }

    #[test]
    fn a_square_deflates_by_half_its_border_and_names_its_paint_operator() {
        let annot = dict(&[("Rect", numbers(&[0.0, 0.0, 10.0, 10.0]))]);
        // No interior colour: stroke only.
        assert_eq!(
            stream(&square(&annot, &NoResolve)),
            "/GS gs 0 0 0 RG\n1 w 0.5 0.5 9 9 re s\n"
        );

        let filled = dict(&[
            ("Rect", numbers(&[0.0, 0.0, 10.0, 10.0])),
            ("IC", numbers(&[0.0, 0.0, 1.0])),
        ]);
        let got = stream(&square(&filled, &NoResolve));
        assert!(got.contains("0 0 1 rg\n"), "{got}");
        assert!(got.ends_with("re b\n"), "{got}");
    }

    #[test]
    fn a_present_but_empty_interior_colour_leaves_the_square_unfilled() {
        let annot = dict(&[
            ("Rect", numbers(&[0.0, 0.0, 10.0, 10.0])),
            ("IC", Object::Array(Array::new())),
        ]);
        assert!(stream(&square(&annot, &NoResolve)).ends_with("re s\n"));
    }

    #[test]
    fn a_circle_draws_four_bezier_arcs() {
        let annot = dict(&[("Rect", numbers(&[0.0, 0.0, 10.0, 10.0]))]);
        let got = stream(&circle(&annot, &NoResolve));
        assert_eq!(got.matches(" c\n").count(), 4);
        assert!(got.contains("5 9.5 m\n"), "{got}");
        assert!(got.ends_with("s\n"), "{got}");
    }

    #[test]
    fn a_sticky_note_replaces_its_rectangle_with_a_twenty_unit_box() {
        let annot = dict(&[("Rect", numbers(&[234.372, 340.046, 400.0, 500.0]))]);
        let got = text(&annot, &NoResolve);
        assert_eq!(
            got.rect_override,
            Some(geom::rect(234.372, 340.046, 254.372, 360.046))
        );
        assert!(stream(&got).starts_with("/GS gs 1 1 0 rg\n0 0 0 RG\n1 w\n"));
    }

    #[test]
    fn the_note_icon_folds_a_corner_and_rules_three_lines() {
        let got = text_symbol(geom::rect(0.0, 0.0, 20.0, 20.0));
        // Eight outline points, then three ruled pairs, then the paint op.
        assert_eq!(got.matches(" m\n").count(), 4);
        assert_eq!(got.matches(" l\n").count(), 10);
        assert!(got.ends_with("B*\n"), "{got}");
    }

    #[test]
    fn a_line_strokes_between_its_endpoints() {
        let annot = dict(&[
            ("Rect", numbers(&[0.0, 0.0, 100.0, 100.0])),
            ("L", numbers(&[10.0, 10.0, 90.0, 90.0])),
            (
                "BS",
                Object::Dict(Dict::from_pairs([(Name::from("W"), Object::from(2.0_f32))])),
            ),
        ]);
        let got = line(&annot, &NoResolve).expect("line");
        let s = stream(&got);
        assert!(s.contains("10 10 m\n"), "{s}");
        assert!(s.contains("90 90 l\n"), "{s}");
        assert!(s.ends_with("S\n"), "{s}");
    }

    #[test]
    fn a_line_declines_without_endpoints() {
        let annot = dict(&[("Rect", numbers(&[0.0, 0.0, 10.0, 10.0]))]);
        assert!(line(&annot, &NoResolve).is_none());
    }

    #[test]
    fn a_link_draws_a_solid_border_donut() {
        // Default solid border paints an even-odd fill donut (outer − inset)
        // rather than a stroked rectangle, matching Square/Widget borders.
        let annot = dict(&[("Rect", numbers(&[0.0, 0.0, 50.0, 12.0]))]);
        let s = stream(&link(&annot, &NoResolve));
        assert!(s.contains("0 0 1 rg"), "{s}");
        assert!(s.contains("re f*"), "{s}");
        assert!(s.contains("0 0 50 12 re"), "{s}");
        assert!(s.contains("1 1 48 10 re"), "{s}");
    }

    #[test]
    fn a_link_with_underline_bs_strokes_the_bottom_edge() {
        let annot = dict(&[
            ("Rect", numbers(&[0.0, 0.0, 50.0, 12.0])),
            (
                "BS",
                Object::Dict(Dict::from_pairs([
                    (Name::from("W"), Object::from(1.0_f32)),
                    (Name::from("S"), Object::Name(Name::from("U"))),
                ])),
            ),
        ]);
        let s = stream(&link(&annot, &NoResolve));
        assert!(
            s.contains("0 0 1 RG") || s.contains("0 0 1 RG\n") || s.contains("0 0 1 RG "),
            "{s}"
        );
        assert!(
            s.contains(" S\n") || s.ends_with("S\n") || s.contains("S\n"),
            "{s}"
        );
    }

    #[test]
    fn a_caret_draws_an_inverted_vee() {
        let annot = dict(&[("Rect", numbers(&[0.0, 0.0, 10.0, 20.0]))]);
        let s = stream(&caret(&annot, &NoResolve));
        assert_eq!(s.matches(" m\n").count(), 1);
        assert_eq!(s.matches(" l\n").count(), 2);
        assert!(s.ends_with("S\n"), "{s}");
    }
}

#[cfg(test)]
mod line_ending_tests {
    use super::line;
    use crate::names as doc_names;
    use pdfrum_object::{Array, Dict, Name, NoResolve, Object, names};

    fn line_dict(le: Option<[&str; 2]>) -> Dict {
        let mut dict = Dict::from_pairs([
            (
                names::L.clone(),
                Object::Array(Array::of([
                    Object::Real(0.0),
                    Object::Real(0.0),
                    Object::Real(100.0),
                    Object::Real(0.0),
                ])),
            ),
            (
                names::RECT.clone(),
                Object::Array(Array::of([
                    Object::Real(0.0),
                    Object::Real(-10.0),
                    Object::Real(100.0),
                    Object::Real(10.0),
                ])),
            ),
            (
                names::C.clone(),
                Object::Array(Array::of([
                    Object::Real(0.0),
                    Object::Real(0.0),
                    Object::Real(0.0),
                ])),
            ),
            (
                doc_names::BS.clone(),
                Object::Dict(Dict::from_pairs([(names::W.clone(), Object::Real(2.0))])),
            ),
        ]);
        if let Some([a, b]) = le {
            dict.insert(
                doc_names::LE.clone(),
                Object::Array(Array::of([
                    Object::Name(Name::from(a)),
                    Object::Name(Name::from(b)),
                ])),
            );
        }
        dict
    }

    #[test]
    fn line_without_le_is_stroke_only() {
        let generated = line(&line_dict(None), &NoResolve).expect("line");
        let s = String::from_utf8(generated.stream).expect("utf8");
        assert!(s.contains("S\n"), "{s}");
        assert!(
            !s.contains("\nb\n") && !s.contains(" b\n"),
            "no fill close without LE: {s}"
        );
    }

    #[test]
    fn line_draws_closed_arrow_ops() {
        let generated = line(&line_dict(Some(["None", "ClosedArrow"])), &NoResolve).expect("line");
        let s = String::from_utf8(generated.stream).expect("utf8");
        assert!(
            s.contains('b') || s.contains("b\n"),
            "closed arrow close: {s}"
        );
        assert!(s.matches("m\n").count() >= 2 || s.contains("m\n"), "{s}");
        // No `/IC` → no fill colour operator before the ending.
        assert!(!s.contains(" rg") && !s.contains("rg\n"), "no IC fill: {s}");
    }

    #[test]
    fn line_closed_arrow_uses_ic_fill() {
        let mut d = line_dict(Some(["None", "ClosedArrow"]));
        d.insert(
            names::IC.clone(),
            Object::Array(Array::of([
                Object::Real(1.0),
                Object::Real(0.0),
                Object::Real(0.0),
            ])),
        );
        let generated = line(&d, &NoResolve).expect("line");
        let s = String::from_utf8(generated.stream).expect("utf8");
        assert!(s.contains("1 0 0 rg") || s.contains("1 0 0 rg\n"), "{s}");
        assert!(s.contains('b') || s.contains("b\n"), "{s}");
    }

    #[test]
    fn line_ending_size_tracks_stroke_width() {
        // line_dict uses `/BS /W 2` → ending size 6 (3× width), no absolute floor.
        let generated = line(&line_dict(Some(["OpenArrow", "None"])), &NoResolve).expect("line");
        let s = String::from_utf8(generated.stream).expect("utf8");
        // Start tip (0,0); open-arrow wings at x=6.
        assert!(s.contains("6 -3 m\n") || s.contains("6 -3 m"), "{s}");
        assert!(s.contains("6 3 l\n") || s.contains("6 3 l"), "{s}");
    }

    #[test]
    fn line_draws_open_arrow_stroke() {
        let generated = line(&line_dict(Some(["OpenArrow", "None"])), &NoResolve).expect("line");
        let s = String::from_utf8(generated.stream).expect("utf8");
        // Open arrow adds two extra stroke segments after the main line.
        assert!(s.matches("S\n").count() >= 2, "open arrow strokes: {s}");
    }
}