f-office-pdf 0.2.1

Writes a display list as PDF.
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
//! Per-page PDF content stream builder and immediate streaming emission.

use std::collections::HashMap;
use std::io::Write;

use f_office_paint::{
    self as paint, GlyphRun, GradientItem, GradientStop, GroupClip, ImageItem, Page, Painted,
    PathItem, Rect as PaintRect, Rgb,
};
use f_office_units::Length;
use pdf_writer::types::{ColorSpaceOperand, FunctionShadingType, LineJoinStyle, TextRenderingMode};
use pdf_writer::{Chunk, Content, Filter, Finish, Name, Rect, Ref, Str};

use crate::fonts::UsedFonts;
use crate::images::EmittedImages;
use crate::stream::{StreamPdf, deflate};
use crate::{
    Anchor, Error, FillAnchor, SideStart, Warning, Warnings, clip_commands, decimal, exact_points,
    points, printed, side_scale, stop_offset, text, to_f32, turn_entries, upright_run,
    upright_start,
};

/// Shared cross-page registries for streaming a PDF document.
pub(crate) struct DocState<'f, 'w, W: Write> {
    pub(crate) pdf: StreamPdf<'w, W>,
    pub(crate) fonts: UsedFonts<'f>,
    pub(crate) images: EmittedImages,
    pub(crate) ext_gstates: HashMap<i64, Ref>,
    pub(crate) warnings: Warnings,
}

impl<W: Write> DocState<'_, '_, W> {
    /// Returns the `ExtGState` object `Ref` for an opacity share in `0..=100_000`, streaming it
    /// once on first use.
    fn opacity_gstate(&mut self, share: i64) -> Result<Ref, Error> {
        if let Some(&id) = self.ext_gstates.get(&share) {
            return Ok(id);
        }
        #[expect(
            clippy::cast_precision_loss,
            reason = "opacity share is at most 100,000"
        )]
        let alpha = share as f32 / f_office_units::scale::DRAWING_WHOLE as f32;
        let id = self.pdf.alloc();
        let mut chunk = Chunk::new();
        chunk
            .ext_graphics(id)
            .non_stroking_alpha(alpha)
            .stroking_alpha(alpha)
            .alpha_source(false);
        self.pdf.emit(id, &chunk)?;
        self.ext_gstates.insert(share, id);
        Ok(id)
    }
}

/// Deterministic resource tables accumulated for a single page form.
#[derive(Default)]
struct PageResources {
    fonts: ResourceMap,
    xobjects: ResourceMap,
    patterns: ResourceMap,
    gstates: ResourceMap,
}

#[derive(Default)]
struct ResourceMap {
    by_ref: HashMap<Ref, String>,
    order: Vec<(String, Ref)>,
}

impl ResourceMap {
    fn intern(&mut self, prefix: &str, id: Ref) -> String {
        if let Some(name) = self.by_ref.get(&id) {
            return name.clone();
        }
        let name = format!("{prefix}{}", self.order.len());
        self.by_ref.insert(id, name.clone());
        self.order.push((name.clone(), id));
        name
    }
}

/// Tracks the conservative bounding box of a page's Form `XObject` in PDF bottom-left coordinates.
struct PageBounds {
    min_x: f32,
    min_y: f32,
    max_x: f32,
    max_y: f32,
}

impl PageBounds {
    fn new(width: f32, height: f32) -> Self {
        Self {
            min_x: 0.0,
            min_y: 0.0,
            max_x: width,
            max_y: height,
        }
    }

    fn include(&mut self, x: f32, y: f32) {
        self.min_x = self.min_x.min(x);
        self.min_y = self.min_y.min(y);
        self.max_x = self.max_x.max(x);
        self.max_y = self.max_y.max(y);
    }

    fn include_dl_rect(&mut self, page_h: Length, x: Length, y: Length, w: Length, h: Length) {
        let x0 = points(x.min(x + w));
        let x1 = points(x.max(x + w));
        let y_top = points(page_h - y.min(y + h));
        let y_bot = points(page_h - y.max(y + h));
        self.include(x0, y_bot);
        self.include(x1, y_top);
    }

    fn to_rect(&self) -> Rect {
        Rect::new(self.min_x, self.min_y, self.max_x, self.max_y)
    }
}

/// Streams one [`Page`] straight to `state.pdf` and returns its allocated PDF page `Ref`.
pub(crate) fn write_page<W: Write>(
    page: &Page,
    pages_ref: Ref,
    state: &mut DocState<'_, '_, W>,
) -> Result<Ref, Error> {
    let width = points(page.width());
    let height = points(page.height());
    if !(width > 0.0 && height > 0.0 && width.is_finite() && height.is_finite()) {
        return Err(Error::PageSize);
    }
    let mut ctx = PageCtx {
        height: page.height(),
        content: Content::new(),
        resources: PageResources::default(),
        bounds: PageBounds::new(width, height),
    };
    let mut painted = page.painted().into_iter();
    write_items(&mut ctx, &mut painted, state)?;

    // Emit the page Form XObject immediately.
    let form_bytes = deflate(&ctx.content.finish())?;
    let form_ref = state.pdf.alloc();
    let mut form_chunk = Chunk::new();
    let mut form = form_chunk.form_xobject(form_ref, &form_bytes);
    form.filter(Filter::FlateDecode);
    form.bbox(ctx.bounds.to_rect());
    write_resources(form.resources(), &ctx.resources);
    form.finish();
    state.pdf.emit(form_ref, &form_chunk)?;
    drop(form_bytes);

    // Emit the tiny page content stream invoking the form.
    let mut page_content = Content::new();
    page_content.x_object(Name(b"Fm0"));
    let page_stream_bytes = page_content.finish();
    let content_ref = state.pdf.alloc();
    let mut stream_chunk = Chunk::new();
    stream_chunk.stream(content_ref, &page_stream_bytes);
    state.pdf.emit(content_ref, &stream_chunk)?;

    // Emit the Page dictionary immediately.
    let leaf_ref = state.pdf.alloc();
    let mut dict_chunk = Chunk::new();
    let mut entry = dict_chunk.page(leaf_ref);
    entry
        .parent(pages_ref)
        .media_box(Rect::new(0.0, 0.0, width, height))
        .contents(content_ref);
    entry.resources().x_objects().pair(Name(b"Fm0"), form_ref);
    entry.finish();
    state.pdf.emit(leaf_ref, &dict_chunk)?;
    Ok(leaf_ref)
}

fn write_resources(mut res: pdf_writer::writers::Resources<'_>, table: &PageResources) {
    write_resource_group(&table.fonts, || res.fonts());
    write_resource_group(&table.xobjects, || res.x_objects());
    write_resource_group(&table.patterns, || res.patterns());
    write_resource_group(&table.gstates, || res.ext_g_states());
}

fn write_resource_group<'a>(map: &ResourceMap, open: impl FnOnce() -> pdf_writer::Dict<'a>) {
    if map.order.is_empty() {
        return;
    }
    let mut dict = open();
    for (name, id) in &map.order {
        dict.pair(Name(name.as_bytes()), *id);
    }
}

/// Mutable state for writing a single page's Form `XObject` content stream.
struct PageCtx {
    height: Length,
    content: Content,
    resources: PageResources,
    bounds: PageBounds,
}

fn write_items<W: Write>(
    ctx: &mut PageCtx,
    painted: &mut std::vec::IntoIter<Painted<'_>>,
    state: &mut DocState<'_, '_, W>,
) -> Result<(), Error> {
    while let Some(item) = painted.next() {
        match item {
            Painted::Glyphs(run) => draw_run(ctx, run, state)?,
            Painted::Rect(rect) => fill_rect(ctx, rect),
            Painted::Path(path) => fill_path(ctx, path),
            Painted::Gradient(gradient) => fill_gradient(ctx, gradient, state)?,
            Painted::Image(image) => draw_image(ctx, image, state)?,
            Painted::ClipStart(clip) => draw_clipped(ctx, clip, painted, state)?,
            Painted::ClipEnd => return Ok(()),
        }
    }
    Ok(())
}

fn draw_clipped<W: Write>(
    ctx: &mut PageCtx,
    clip: &GroupClip,
    painted: &mut std::vec::IntoIter<Painted<'_>>,
    state: &mut DocState<'_, '_, W>,
) -> Result<(), Error> {
    let anchor = crate::path_anchor(ctx.height, &clip.commands);
    let commands = clip_commands(&clip.commands);
    let filled = paint::fill_commands(&commands);
    if filled.is_empty() {
        return Err(Error::Clip);
    }
    ctx.content.save_state();
    ctx.content.transform(anchor.matrix());
    emit_path_commands(&mut ctx.content, &filled, |p| anchor.local(p.x, p.y));
    match clip.fill_rule {
        paint::FillRule::NonZero => ctx.content.clip_nonzero().end_path(),
        paint::FillRule::EvenOdd => ctx.content.clip_even_odd().end_path(),
    };
    ctx.content.transform(anchor.undone_matrix());
    let res = write_items(ctx, painted, state);
    ctx.content.restore_state();
    res
}

fn fill_rect(ctx: &mut PageCtx, rect: &PaintRect) {
    if !paint::fill_shows(rect.width, rect.height) {
        return;
    }
    ctx.bounds
        .include_dl_rect(ctx.height, rect.x, rect.y, rect.width, rect.height);
    let corner = (rect.x, rect.y);
    let far = (rect.x + rect.width, rect.y + rect.height);
    let anchor = FillAnchor::middle(ctx.height, corner, far);
    let (left, right) = anchor.span(rect.x - anchor.anchor.x, rect.width);
    let (top, bottom) = anchor.span(rect.y - anchor.anchor.y, rect.height);
    if !(right > left && bottom > top) {
        return;
    }
    let [r, g, b] = rgb_f32(rect.color);
    ctx.content.save_state();
    ctx.content.transform(anchor.matrix());
    ctx.content.set_fill_rgb(r, g, b);
    ctx.content
        .move_to(left, top)
        .line_to(right, top)
        .line_to(right, bottom)
        .line_to(left, bottom)
        .close_path();
    ctx.content.fill_nonzero();
    ctx.content.restore_state();
}

fn path_fill_anchor(ctx: &mut PageCtx, commands: &[paint::PathCommand]) -> FillAnchor {
    let bounds = crate::path_bounds(commands);
    if let Some((low, high)) = bounds {
        ctx.bounds
            .include_dl_rect(ctx.height, low.x, low.y, high.x - low.x, high.y - low.y);
    }
    bounds.map_or(
        FillAnchor::middle(
            ctx.height,
            (Length::ZERO, Length::ZERO),
            (Length::ZERO, Length::ZERO),
        ),
        |(low, high)| FillAnchor::middle(ctx.height, (low.x, low.y), (high.x, high.y)),
    )
}

fn fill_path(ctx: &mut PageCtx, item: &PathItem) {
    if !paint::path_shows(&item.commands) {
        return;
    }
    let anchor = path_fill_anchor(ctx, &item.commands);
    let filled = paint::fill_commands(&item.commands);
    if filled.is_empty() {
        return;
    }
    let [r, g, b] = rgb_f32(item.color);
    ctx.content.save_state();
    ctx.content.transform(anchor.matrix());
    ctx.content.set_fill_rgb(r, g, b);
    emit_path_commands(&mut ctx.content, &filled, |p| anchor.local(p.x, p.y));
    match item.fill_rule {
        paint::FillRule::NonZero => ctx.content.fill_nonzero(),
        paint::FillRule::EvenOdd => ctx.content.fill_even_odd(),
    };
    ctx.content.restore_state();
}

fn fill_gradient<W: Write>(
    ctx: &mut PageCtx,
    item: &GradientItem,
    state: &mut DocState<'_, '_, W>,
) -> Result<(), Error> {
    if !paint::path_shows(&item.commands) {
        return Ok(());
    }
    if item.stops.len() < 2 || item.start == item.end {
        let path = PathItem {
            commands: item.commands.clone(),
            color: item.color_at(i64::from(GradientStop::START)),
            fill_rule: item.fill_rule,
        };
        fill_path(ctx, &path);
        return Ok(());
    }
    let mut with_axis = item.commands.clone();
    with_axis.push(paint::PathCommand::MoveTo(item.start));
    with_axis.push(paint::PathCommand::LineTo(item.end));
    let anchor = path_fill_anchor(ctx, &with_axis);
    let filled = paint::fill_commands(&item.commands);
    if filled.is_empty() {
        return Ok(());
    }
    let ((x1, y1), (x2, y2)) = (
        anchor.local(item.start.x, item.start.y),
        anchor.local(item.end.x, item.end.y),
    );
    let shading_ref = emit_axial_shading([x1, y1, x2, y2], &item.stops, &mut state.pdf)?;
    let pattern_ref = state.pdf.alloc();
    let mut pattern_chunk = Chunk::new();
    pattern_chunk
        .shading_pattern(pattern_ref)
        .shading_ref(shading_ref)
        .matrix(anchor.matrix());
    state.pdf.emit(pattern_ref, &pattern_chunk)?;
    let pattern_name = ctx.resources.patterns.intern("P", pattern_ref);
    ctx.content.save_state();
    ctx.content.transform(anchor.matrix());
    ctx.content.set_fill_color_space(ColorSpaceOperand::Pattern);
    ctx.content
        .set_fill_pattern([], Name(pattern_name.as_bytes()));
    emit_path_commands(&mut ctx.content, &filled, |p| anchor.local(p.x, p.y));
    match item.fill_rule {
        paint::FillRule::NonZero => ctx.content.fill_nonzero(),
        paint::FillRule::EvenOdd => ctx.content.fill_even_odd(),
    };
    ctx.content.restore_state();
    Ok(())
}

/// Emits a Type 2 axial shading object and its color interpolation function(s) straight to `pdf`.
fn emit_axial_shading<W: Write>(
    coords: [f32; 4],
    stops: &[GradientStop],
    pdf: &mut StreamPdf<'_, W>,
) -> Result<Ref, Error> {
    let mut normalized: Vec<(f32, [f32; 3])> = stops
        .iter()
        .map(|s| (stop_offset(s.place), rgb_f32(s.color)))
        .collect();
    normalized.sort_by(|a, b| a.0.total_cmp(&b.0));

    let mut segments: Vec<(f32, f32, [f32; 3], [f32; 3])> = Vec::new();
    if let Some(&(first_t, first_c)) = normalized.first()
        && first_t > 0.0
    {
        segments.push((0.0, first_t, first_c, first_c));
    }
    for pair in normalized.windows(2) {
        if let [(t0, c0), (t1, c1)] = *pair
            && t1 > t0
        {
            segments.push((t0, t1, c0, c1));
        }
    }
    if let Some(&(last_t, last_c)) = normalized.last()
        && last_t < 1.0
    {
        segments.push((last_t, 1.0, last_c, last_c));
    }
    if segments.is_empty() {
        let color = normalized.first().map_or([0.0, 0.0, 0.0], |s| s.1);
        segments.push((0.0, 1.0, color, color));
    }

    let fn_ref = emit_gradient_function(&segments, pdf)?;
    let shading_ref = pdf.alloc();
    let mut chunk = Chunk::new();
    let mut shading = chunk.function_shading(shading_ref);
    shading
        .shading_type(FunctionShadingType::Axial)
        .coords(coords)
        .function(fn_ref)
        .extend([true, true]);
    shading.color_space().device_rgb();
    shading.finish();
    pdf.emit(shading_ref, &chunk)?;
    Ok(shading_ref)
}

fn emit_gradient_function<W: Write>(
    segments: &[(f32, f32, [f32; 3], [f32; 3])],
    pdf: &mut StreamPdf<'_, W>,
) -> Result<Ref, Error> {
    let mut sub_refs = Vec::with_capacity(segments.len());
    for &(_, _, c0, c1) in segments {
        let id = pdf.alloc();
        let mut chunk = Chunk::new();
        chunk
            .exponential_function(id)
            .domain([0.0, 1.0])
            .c0(c0)
            .c1(c1)
            .n(1.0);
        pdf.emit(id, &chunk)?;
        sub_refs.push(id);
    }
    if sub_refs.len() == 1
        && let Some(&only) = sub_refs.first()
    {
        return Ok(only);
    }
    let bounds: Vec<f32> = segments
        .iter()
        .take(segments.len().saturating_sub(1))
        .map(|s| s.1)
        .collect();
    let encode: Vec<f32> = segments.iter().flat_map(|_| [0.0_f32, 1.0_f32]).collect();
    let stitch_ref = pdf.alloc();
    let mut chunk = Chunk::new();
    chunk
        .stitching_function(stitch_ref)
        .domain([0.0, 1.0])
        .functions(sub_refs)
        .bounds(bounds)
        .encode(encode);
    pdf.emit(stitch_ref, &chunk)?;
    Ok(stitch_ref)
}

fn draw_image<W: Write>(
    ctx: &mut PageCtx,
    item: &ImageItem,
    state: &mut DocState<'_, '_, W>,
) -> Result<(), Error> {
    let w = points(item.width);
    let h = points(item.height);
    if !(w > 0.0 && h > 0.0 && w.is_finite() && h.is_finite()) {
        return Ok(());
    }
    let xobj_ref = match state.images.get_or_emit(&item.image, &mut state.pdf)? {
        Ok(id) => id,
        Err(fault) => {
            state.warnings.push(Warning::ImageSkipped {
                format: item.image.format,
                fault,
            });
            return Ok(());
        }
    };
    let name = ctx.resources.xobjects.intern("Im", xobj_ref);
    let gstate_name = if item.image.opacity.share() < f_office_units::scale::DRAWING_WHOLE {
        let gs_ref = state.opacity_gstate(item.image.opacity.share())?;
        Some(ctx.resources.gstates.intern("Gs", gs_ref))
    } else {
        None
    };
    ctx.bounds
        .include_dl_rect(ctx.height, item.x, item.y, item.width, item.height);
    if let Some(clip) = item.clip {
        ctx.bounds
            .include_dl_rect(ctx.height, clip.x, clip.y, clip.width, clip.height);
        draw_image_clipped(ctx, clip, |ctx| {
            emit_image_draw(ctx, item, &name, gstate_name.as_deref());
        });
    } else {
        emit_image_draw(ctx, item, &name, gstate_name.as_deref());
    }
    Ok(())
}

fn draw_image_clipped(ctx: &mut PageCtx, clip: paint::Clip, draw: impl FnOnce(&mut PageCtx)) {
    let width_pt = exact_points(clip.width).abs();
    let height_pt = exact_points(clip.height).abs();
    if width_pt < 127.0 && height_pt < 127.0 {
        let anchor = Anchor::at(ctx.height, clip.x, clip.y);
        let Some((l, t, r, b)) =
            clip_rect_ltrb(anchor, (clip.x, clip.y), (clip.width, clip.height))
        else {
            return;
        };
        ctx.content.save_state();
        ctx.content.transform(anchor.matrix());
        emit_clip_rect_with_return(&mut ctx.content, l, t, r, b);
        ctx.content.transform(anchor.undone_matrix());
        draw(ctx);
        ctx.content.restore_state();
        return;
    }
    let (left, right) = (
        clip.x.min(clip.x + clip.width),
        clip.x.max(clip.x + clip.width),
    );
    let (top, bottom) = (
        clip.y.min(clip.y + clip.height),
        clip.y.max(clip.y + clip.height),
    );
    let top_left = Anchor::at(ctx.height, left, top);
    let bottom_right = Anchor::at(ctx.height, right, bottom);
    let pad_x = to_f32(width_pt.ceil() + 16.0);
    let pad_y = to_f32(height_pt.ceil() + 16.0);
    let (left_x, top_y) = top_left.local(left, top);
    let (right_x, bottom_y) = bottom_right.local(right, bottom);
    if !(pad_x > left_x && pad_y > top_y && right_x > -pad_x && bottom_y > -pad_y) {
        return;
    }
    ctx.content.save_state();
    ctx.content.transform(top_left.matrix());
    emit_clip_rect_with_return(&mut ctx.content, left_x, top_y, pad_x, pad_y);
    ctx.content.transform(top_left.undone_matrix());
    ctx.content.save_state();
    ctx.content.transform(bottom_right.matrix());
    emit_clip_rect_with_return(&mut ctx.content, -pad_x, -pad_y, right_x, bottom_y);
    ctx.content.transform(bottom_right.undone_matrix());
    draw(ctx);
    ctx.content.restore_state();
    ctx.content.restore_state();
}

fn clip_rect_ltrb(
    anchor: Anchor,
    (x, y): (Length, Length),
    (across, down): (Length, Length),
) -> Option<(f32, f32, f32, f32)> {
    let span = |start: Length, length: Length| {
        let from = exact_points(start);
        let to = from + exact_points(length);
        (decimal(from.min(to)), decimal(from.max(to)))
    };
    let (left, right) = span(x - anchor.x, across);
    let (top, bottom) = span(y - anchor.y, down);
    (right >= left && bottom >= top).then_some((left, top, right, bottom))
}

fn emit_clip_rect_with_return(content: &mut Content, l: f32, t: f32, r: f32, b: f32) {
    content
        .move_to(l, t)
        .line_to(r, t)
        .line_to(r, b)
        .line_to(l, b)
        .line_to(l, t)
        .close_path()
        .clip_nonzero()
        .end_path();
}

fn emit_image_draw(ctx: &mut PageCtx, item: &ImageItem, name: &str, gstate: Option<&str>) {
    match item.turn {
        Some(turn) => draw_turned_image(ctx, item, name, gstate, turn),
        None => draw_upright_image(ctx, item, name, gstate),
    }
}

fn emit_image_xobject(
    content: &mut Content,
    (name, gstate): (&str, Option<&str>),
    anchor: Anchor,
    placement: [f32; 6],
    scale: (f32, f32),
    box_matrix: [f32; 6],
) {
    content.save_state();
    if let Some(gs) = gstate {
        content.set_parameters(Name(gs.as_bytes()));
    }
    content.transform(anchor.matrix());
    content.transform(placement);
    if scale != (1.0, 1.0) {
        content.transform([scale.0, 0.0, 0.0, scale.1, 0.0, 0.0]);
    }
    content.transform(box_matrix);
    content.rect(0.0, 0.0, 1.0, 1.0).clip_nonzero().end_path();
    content.x_object(Name(name.as_bytes()));
    content.restore_state();
}

fn draw_upright_image(ctx: &mut PageCtx, item: &ImageItem, name: &str, gstate: Option<&str>) {
    let bottom = item.y + item.height;
    let anchor = Anchor::at(ctx.height, item.x, bottom);
    let (scale_across, across) = side_scale(exact_points(item.width), SideStart::Corner, 1.0);
    let (scale_down, down) = side_scale(exact_points(item.height), SideStart::Corner, 1.0);
    if !(across > 0.0 && down > 0.0) {
        return;
    }
    let (x, y) = anchor.local(item.x, bottom);
    emit_image_xobject(
        &mut ctx.content,
        (name, gstate),
        anchor,
        [1.0, 0.0, 0.0, 1.0, x, y],
        (scale_across, scale_down),
        [across, 0.0, 0.0, -down, 0.0, 0.0],
    );
}

fn draw_turned_image(
    ctx: &mut PageCtx,
    item: &ImageItem,
    name: &str,
    gstate: Option<&str>,
    turn: paint::Turn,
) {
    let [xx, yx, xy, yy] = turn_entries(turn);
    let length = |a: f32, b: f32| printed(a).hypot(printed(b));
    let (scale_across, across) =
        side_scale(exact_points(item.width), SideStart::Centre, length(xx, yx));
    let (scale_down, down) =
        side_scale(exact_points(item.height), SideStart::Centre, length(xy, yy));
    if !(across > 0.0 && down > 0.0) {
        return;
    }
    let half = |side: Length| Length::from_units(side.units().div_euclid(2));
    let anchor = Anchor::at(
        ctx.height,
        item.x + half(item.width),
        item.y + half(item.height),
    );
    let centre = |from: Length, side: Length| decimal(exact_points(from + from + side) / 2.0);
    let (centre_x, centre_y) = (
        centre(item.x - anchor.x, item.width),
        centre(item.y - anchor.y, item.height),
    );
    emit_image_xobject(
        &mut ctx.content,
        (name, gstate),
        anchor,
        [xx, yx, xy, yy, centre_x, centre_y],
        (scale_across, scale_down),
        [across, 0.0, 0.0, -down, -across / 2.0, down / 2.0],
    );
}

/// Resolved glyph data ready for streaming into a PDF text object.
struct PreparedGlyph {
    cid: u16,
    width_1000: f32,
    x: Length,
    y: Length,
}

/// Prepared glyph group (either a single glyph or a multi-glyph cluster sharing one text range).
struct PreparedGroup<'a> {
    glyphs: Vec<PreparedGlyph>,
    text: &'a str,
    use_actual_text: bool,
}

/// Paint mode for a glyph run pass (filled, invisible searchable text, or stroked outline).
#[derive(Clone, Copy)]
enum TextPaint {
    Fill(Rgb),
    Invisible,
    Stroke(paint::Outline),
}

fn draw_run<W: Write>(
    ctx: &mut PageCtx,
    run: &GlyphRun,
    state: &mut DocState<'_, '_, W>,
) -> Result<(), Error> {
    state.fonts.validate(run.font)?;
    if run.glyphs.is_empty() || run.size == Length::ZERO {
        return Ok(());
    }
    let used = state.fonts.get_or_register(run.font, &mut state.pdf)?;
    let font_ref = used.type0_ref();
    let units = used.units_per_em();
    let right_edge = used.right_edge();
    let font_name = ctx.resources.fonts.intern("F", font_ref);
    let size = points(run.size);
    let reach = right_edge
        .filter(|&e| e > 0)
        .map_or(size, |e| f32::from(e) / units * size);
    let upright = run.turn.map(|turn| upright_run(run, turn));
    let shown = upright.as_ref().unwrap_or(run);
    let groups = prepare_groups(run, shown, state)?;
    for group in &groups {
        for glyph in &group.glyphs {
            let x_pt = points(glyph.x);
            let y_pt = points(ctx.height - glyph.y);
            ctx.bounds.include(x_pt, y_pt - size);
            ctx.bounds.include(x_pt + reach, y_pt + size);
        }
    }
    let line = run.outline.filter(|o| o.width > Length::ZERO);
    if run.filled {
        emit_run_pass(
            ctx,
            run,
            &groups,
            (&font_name, size),
            TextPaint::Fill(run.color),
            state,
        )?;
    } else if line.is_none() {
        emit_run_pass(
            ctx,
            run,
            &groups,
            (&font_name, size),
            TextPaint::Invisible,
            state,
        )?;
    }
    if let Some(outline) = line {
        emit_run_pass(
            ctx,
            run,
            &groups,
            (&font_name, size),
            TextPaint::Stroke(outline),
            state,
        )?;
    }
    Ok(())
}

fn prepare_groups<'a, W: Write>(
    run: &'a GlyphRun,
    shown: &GlyphRun,
    state: &mut DocState<'_, '_, W>,
) -> Result<Vec<PreparedGroup<'a>>, Error> {
    let raw_groups = text::positioned_groups(run);
    let mut out = Vec::with_capacity(raw_groups.len());
    for range in raw_groups {
        let places = run.glyphs.get(range.clone()).unwrap_or_default();
        let shown_slice = shown.glyphs.get(range).unwrap_or_default();
        let mut group_start = usize::MAX;
        let mut group_end = 0_usize;
        for g in places {
            let r = run.glyph_range(g).ok_or(Error::TextRange)?;
            group_start = group_start.min(r.start);
            group_end = group_end.max(r.end);
        }
        let group_text = if group_start <= group_end {
            run.text
                .get(group_start..group_end)
                .ok_or(Error::TextRange)?
        } else {
            ""
        };
        let mut glyphs = Vec::with_capacity(places.len());
        let mut any_actual = false;
        let multi = places.len() > 1;
        for (idx, (orig, upright_g)) in places.iter().zip(shown_slice).enumerate() {
            let adv = state
                .fonts
                .db()
                .advance(run.font, orig.id)
                .ok_or(Error::UnknownGlyph {
                    font: run.font,
                    glyph: orig.id,
                })?;
            let used = state.fonts.get_or_register(run.font, &mut state.pdf)?;
            let width_1000 = f32::from(adv) / used.units_per_em() * 1000.0;
            let glyph_text = if multi {
                if idx == 0 { group_text } else { "" }
            } else {
                group_text
            };
            let mapped = used.record_glyph(orig.id, glyph_text)?;
            if mapped.needs_actual_text {
                any_actual = true;
            }
            glyphs.push(PreparedGlyph {
                cid: mapped.cid,
                width_1000,
                x: upright_g.x,
                y: upright_g.y,
            });
        }
        let use_actual_text = any_actual && !group_text.is_empty();
        out.push(PreparedGroup {
            glyphs,
            text: group_text,
            use_actual_text,
        });
    }
    Ok(out)
}

fn emit_run_pass<W: Write>(
    ctx: &mut PageCtx,
    run: &GlyphRun,
    groups: &[PreparedGroup<'_>],
    (font_name, size): (&str, f32),
    paint_mode: TextPaint,
    state: &mut DocState<'_, '_, W>,
) -> Result<(), Error> {
    let invisible_gs = if matches!(paint_mode, TextPaint::Invisible) {
        let gs = state.opacity_gstate(0)?;
        Some(ctx.resources.gstates.intern("Gs", gs))
    } else {
        None
    };
    if let Some(turn) = run.turn {
        emit_turned_groups(
            ctx,
            run,
            groups,
            (font_name, size),
            (paint_mode, invisible_gs.as_deref()),
            turn,
        );
        return Ok(());
    }
    let mut rest = groups;
    while let Some(first_group) = rest.first() {
        let Some(origin) = first_group.glyphs.first() else {
            rest = rest.get(1..).unwrap_or_default();
            continue;
        };
        let anchor = Anchor::of_line(ctx.height, origin.x, origin.y);
        let count = rest
            .iter()
            .take_while(|g| g.glyphs.iter().all(|gl| anchor.reaches(gl.x, gl.y)))
            .count()
            .max(1);
        let slice = rest.get(..count).unwrap_or_default();
        emit_anchored_text_object(
            &mut ctx.content,
            anchor,
            slice,
            (font_name, size),
            (paint_mode, invisible_gs.as_deref()),
        );
        rest = rest.get(count..).unwrap_or_default();
    }
    Ok(())
}

fn emit_turned_groups(
    ctx: &mut PageCtx,
    run: &GlyphRun,
    groups: &[PreparedGroup<'_>],
    (font_name, size): (&str, f32),
    (paint_mode, invisible_gs): (TextPaint, Option<&str>),
    turn: paint::Turn,
) {
    let mut glyph_idx = 0_usize;
    for group in groups {
        let Some(orig_place) = run.glyphs.get(glyph_idx) else {
            break;
        };
        glyph_idx += group.glyphs.len();
        let Some(first_upright) = group.glyphs.first() else {
            continue;
        };
        let anchor = Anchor::at(ctx.height, orig_place.x, orig_place.y);
        let (ux, uy) = upright_start(turn, anchor, orig_place);
        ctx.content.save_state();
        apply_text_paint(&mut ctx.content, paint_mode, invisible_gs);
        ctx.content.transform(anchor.turned_matrix(turn));
        ctx.content.begin_text();
        ctx.content.set_font(Name(font_name.as_bytes()), size);
        if group.use_actual_text {
            begin_actual_text(&mut ctx.content, group.text);
        }
        let mut cursor_x = f64::from(ux);
        let mut cursor_y = f64::from(uy);
        let mut has_tm = false;
        let mut items: Vec<TjItem> = Vec::new();
        for gl in &group.glyphs {
            let target_x = f64::from(ux) + exact_points(gl.x - first_upright.x);
            let target_y = f64::from(uy) + exact_points(gl.y - first_upright.y);
            push_glyph_tj(
                &mut ctx.content,
                &mut items,
                (&mut has_tm, &mut cursor_x, &mut cursor_y),
                (target_x, target_y, size),
                gl,
            );
        }
        flush_tj(&mut ctx.content, &mut items);
        if group.use_actual_text {
            ctx.content.end_marked_content();
        }
        ctx.content.end_text();
        ctx.content.restore_state();
    }
}

/// Emits one `BT ... ET` text object for all groups within one `Anchor`'s reach.
fn emit_anchored_text_object(
    content: &mut Content,
    anchor: Anchor,
    groups: &[PreparedGroup<'_>],
    (font_name, size): (&str, f32),
    (paint_mode, invisible_gs): (TextPaint, Option<&str>),
) {
    content.save_state();
    apply_text_paint(content, paint_mode, invisible_gs);
    content.transform(anchor.matrix());
    content.begin_text();
    content.set_font(Name(font_name.as_bytes()), size);
    let mut cursor_x = 0.0_f64;
    let mut cursor_y = 0.0_f64;
    let mut has_tm = false;
    let mut items: Vec<TjItem> = Vec::new();
    for group in groups {
        if group.use_actual_text {
            flush_tj(content, &mut items);
            begin_actual_text(content, group.text);
            has_tm = false;
        }
        for gl in &group.glyphs {
            let target_x = exact_points(gl.x - anchor.x);
            let target_y = exact_points(gl.y - anchor.y);
            push_glyph_tj(
                content,
                &mut items,
                (&mut has_tm, &mut cursor_x, &mut cursor_y),
                (target_x, target_y, size),
                gl,
            );
        }
        if group.use_actual_text {
            flush_tj(content, &mut items);
            content.end_marked_content();
            has_tm = false;
        }
    }
    flush_tj(content, &mut items);
    content.end_text();
    content.restore_state();
}

enum TjItem {
    Bytes(Vec<u8>),
    Adjust(f32),
}

/// Tolerance below which a glyph follows the previous glyph at its natural advance without an
/// explicit `TJ` adjustment: 0.2 half-EMUs in points.
#[expect(
    clippy::cast_precision_loss,
    reason = "UNITS_PER_POINT is exact in double precision"
)]
const WIDTH_TOLERANCE_PT: f64 = 0.2 / Length::UNITS_PER_POINT as f64;

fn push_glyph_tj(
    content: &mut Content,
    items: &mut Vec<TjItem>,
    (has_tm, cursor_x, cursor_y): (&mut bool, &mut f64, &mut f64),
    (target_x, target_y, size): (f64, f64, f32),
    gl: &PreparedGlyph,
) {
    let same_line = *has_tm && (target_y - *cursor_y).abs() <= 1e-6;
    if same_line {
        let delta_pt = target_x - *cursor_x;
        if delta_pt.abs() > WIDTH_TOLERANCE_PT {
            let adj = to_f32(-delta_pt * 1000.0 / f64::from(size));
            if adj != 0.0 {
                items.push(TjItem::Adjust(adj));
                *cursor_x -= printed(adj) * f64::from(size) / 1000.0;
            }
        }
    } else {
        flush_tj(content, items);
        let lx = decimal(target_x);
        let ly = decimal(target_y);
        content.set_text_matrix([1.0, 0.0, 0.0, -1.0, lx, ly]);
        *cursor_x = printed(lx);
        *cursor_y = target_y;
        *has_tm = true;
    }
    let cid_bytes = gl.cid.to_be_bytes();
    if let Some(TjItem::Bytes(buf)) = items.last_mut() {
        buf.extend_from_slice(&cid_bytes);
    } else {
        items.push(TjItem::Bytes(cid_bytes.to_vec()));
    }
    *cursor_x += f64::from(gl.width_1000) * f64::from(size) / 1000.0;
}

fn flush_tj(content: &mut Content, items: &mut Vec<TjItem>) {
    if items.is_empty() {
        return;
    }
    let mut positioned = content.show_positioned();
    let mut array = positioned.items();
    for item in items.drain(..) {
        match item {
            TjItem::Bytes(bytes) => {
                array.show(Str(&bytes));
            }
            TjItem::Adjust(adj) => {
                array.adjust(adj);
            }
        }
    }
}

fn apply_text_paint(content: &mut Content, mode: TextPaint, invisible_gs: Option<&str>) {
    match mode {
        TextPaint::Fill(color) => {
            let [r, g, b] = rgb_f32(color);
            content.set_text_rendering_mode(TextRenderingMode::Fill);
            content.set_fill_rgb(r, g, b);
        }
        TextPaint::Invisible => {
            content.set_text_rendering_mode(TextRenderingMode::Fill);
            content.set_fill_rgb(0.0, 0.0, 0.0);
            if let Some(gs) = invisible_gs {
                content.set_parameters(Name(gs.as_bytes()));
            }
        }
        TextPaint::Stroke(outline) => {
            let [r, g, b] = rgb_f32(outline.color);
            content.set_text_rendering_mode(TextRenderingMode::Stroke);
            content.set_stroke_rgb(r, g, b);
            content.set_line_width(points(outline.width));
            content.set_miter_limit(10.0);
            content.set_line_join(match outline.join {
                paint::Join::Round => LineJoinStyle::RoundJoin,
                paint::Join::Miter => LineJoinStyle::MiterJoin,
            });
        }
    }
}

fn begin_actual_text(content: &mut Content, text: &str) {
    let mut encoded = Vec::with_capacity(2 + text.len() * 2);
    encoded.extend_from_slice(&[0xFE, 0xFF]);
    for unit in text.encode_utf16() {
        encoded.extend_from_slice(&unit.to_be_bytes());
    }
    content
        .begin_marked_content_with_properties(Name(b"Span"))
        .properties()
        .pair(Name(b"ActualText"), Str(&encoded));
}

fn emit_path_commands(
    content: &mut Content,
    commands: &[paint::PathCommand],
    at: impl Fn(paint::Point) -> (f32, f32),
) {
    use paint::PathCommand::{Close, CubicTo, LineTo, MoveTo, QuadTo};
    let mut current = (0.0_f32, 0.0_f32);
    for command in commands {
        match *command {
            MoveTo(p) => {
                let (x, y) = at(p);
                content.move_to(x, y);
                current = (x, y);
            }
            LineTo(p) => {
                let (x, y) = at(p);
                content.line_to(x, y);
                current = (x, y);
            }
            QuadTo(c, p) => {
                let (cx, cy) = at(c);
                let (x, y) = at(p);
                let c1x = current.0 + (2.0 / 3.0) * (cx - current.0);
                let c1y = current.1 + (2.0 / 3.0) * (cy - current.1);
                let c2x = x + (2.0 / 3.0) * (cx - x);
                let c2y = y + (2.0 / 3.0) * (cy - y);
                content.cubic_to(c1x, c1y, c2x, c2y, x, y);
                current = (x, y);
            }
            CubicTo(c0, c1, p) => {
                let (x0, y0) = at(c0);
                let (x1, y1) = at(c1);
                let (x, y) = at(p);
                content.cubic_to(x0, y0, x1, y1, x, y);
                current = (x, y);
            }
            Close => {
                content.close_path();
            }
        }
    }
}

fn rgb_f32(color: Rgb) -> [f32; 3] {
    [
        f32::from(color.r) / 255.0,
        f32::from(color.g) / 255.0,
        f32::from(color.b) / 255.0,
    ]
}