ferri-pdf 0.1.3

HTML and CSS to PDF renderer for print, in pure Rust
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
mod dimensions;
use crate::document::{BlockBox, CounterSnapshot, PageBox, Paragraph, RunningStringAssignment};
use crate::graphics::{BoxDecoration, BoxPaint, DisplayItem, FlowPaint, ImagePaint, Rect};
use crate::layout::measure::{MeasuredBlock, Measurer};
use crate::layout::{LayoutError, TextLine};
use crate::style::{BoxSizing, MarginLocation, PageMargin, Size, VerticalAlign};
use crate::text::Line;
use dimensions::{Variable, variable};

const HORIZONTAL: usize = 0;
const VERTICAL: usize = 1;
const START: usize = 0;
const CENTER: usize = 1;
const END: usize = 2;
const GROUPS: [[MarginLocation; 3]; 4] = [
    [
        MarginLocation::TopLeft,
        MarginLocation::TopCenter,
        MarginLocation::TopRight,
    ],
    [
        MarginLocation::BottomLeft,
        MarginLocation::BottomCenter,
        MarginLocation::BottomRight,
    ],
    [
        MarginLocation::LeftTop,
        MarginLocation::LeftMiddle,
        MarginLocation::LeftBottom,
    ],
    [
        MarginLocation::RightTop,
        MarginLocation::RightMiddle,
        MarginLocation::RightBottom,
    ],
];
struct Prepared<'a, 't> {
    margin: &'a PageMargin,
    decoration: &'a BoxDecoration,
    paragraph: Option<Paragraph>,
    /// The sizes and line metrics of the paragraph's `content` images.
    images: (Vec<[f32; 2]>, Vec<crate::text::AtomicMetrics>),
    /// The image a `<content-replacement>` replaces the box with (CSS Content 3 §1).
    replacement: Option<std::sync::Arc<crate::images::Image>>,
    /// The running element `element()` places (CSS GCPM 3 §1.2.2), laid out as the box's
    /// only child.
    element: Option<&'t BlockBox>,
    measured: Option<MeasuredBlock<'t>>,
    padding: [f32; 4],
    borders: [f32; 4],
    margins: [Option<f32>; 4],
    specified: [Option<f32>; 2],
    start: [f32; 2],
    content: [f32; 2],
    lines: Vec<Line>,
}
impl<'t> Prepared<'_, 't> {
    fn inline_axis(&self) -> usize {
        if self.margin.style.used_writing_mode().vertical() {
            VERTICAL
        } else {
            HORIZONTAL
        }
    }
    fn block_axis(&self) -> usize {
        1 - self.inline_axis()
    }
    fn sides(axis: usize) -> [usize; 2] {
        if axis == HORIZONTAL { [3, 1] } else { [0, 2] }
    }
    fn edges(&self, axis: usize) -> f32 {
        Self::sides(axis)
            .iter()
            .map(|&i| self.padding[i] + self.borders[i])
            .sum()
    }
    fn outer_edges(&self, axis: usize) -> f32 {
        self.edges(axis)
            + Self::sides(axis)
                .iter()
                .map(|&i| self.margins[i].unwrap_or(0.0))
                .sum::<f32>()
    }
    fn fixed(&mut self, axis: usize, available: f32) {
        let [start, end] = Self::sides(axis).map(|i| self.margins[i].unwrap_or(0.0));
        self.start[axis] = start;
        // The fixed dimension fills the margin area regardless of width/height declarations.
        self.content[axis] = available - self.edges(axis) - start - end;
    }
    fn variable(&mut self, axis: usize, available: f32, outer: f32, position: usize) {
        self.content[axis] = (outer - self.outer_edges(axis)).max(0.0);
        let style = &self.margin.style;
        if axis == HORIZONTAL && *style.width.basis() == Size::Auto {
            // CSS Values 5 §10.2: a `calc-size()` adjusts the automatic width once resolved.
            self.content[axis] = crate::style::SizeConstraints::new(
                [&style.width, &Size::Auto, &Size::Auto],
                Some(available),
                style.box_sizing,
                self.edges(axis),
            )
            .preferred(self.content[axis]);
        }
        let offset = match position {
            START => 0.0,
            CENTER => (available - outer) / 2.0,
            END => available - outer,
            _ => unreachable!(),
        };
        self.start[axis] = offset + self.margins[Self::sides(axis)[0]].unwrap_or(0.0);
    }
    fn validate(&self) -> Result<(), LayoutError> {
        let values = self
            .padding
            .iter()
            .chain(self.borders.iter())
            .chain(self.margins.iter().flatten())
            .chain(self.specified.iter().flatten())
            .chain(self.start.iter())
            .chain(self.content.iter());
        if values.into_iter().any(|value| !value.is_finite())
            || [HORIZONTAL, VERTICAL]
                .iter()
                .any(|&axis| !self.outer_edges(axis).is_finite())
        {
            return Err(LayoutError::NonFinitePageMarginGeometry {
                location: self.margin.location,
            });
        }
        Ok(())
    }
    fn layout(&mut self, measurer: &mut Measurer<'t>) -> Result<(), LayoutError> {
        self.validate()?;
        let inline = self.content[self.inline_axis()];
        if let Some(element) = self.element {
            self.measured = Some(measurer.block(
                element,
                0.0,
                inline,
                self.margin.style.used_rtl(),
                false,
                None,
            )?);
            return Ok(());
        }
        self.lines = self
            .paragraph
            .as_ref()
            .map(|p| measurer.text_lines(p, inline, &self.images.1))
            .transpose()?
            .unwrap_or_default();
        Ok(())
    }
    /// The content's min-content and max-content contributions in the inline axis.
    fn intrinsic(
        &self,
        measurer: &mut Measurer<'t>,
        available: f32,
    ) -> Result<[f32; 2], LayoutError> {
        if let Some(element) = self.element {
            let widths = measurer
                .run(|measurer| crate::layout::intrinsic::measure(element, measurer, available))?;
            return Ok([widths.min, widths.max]);
        }
        if self.replacement.is_some() {
            let inline = self.inline_axis();
            let width = self.replaced_extent(inline, self.content[1 - inline]);
            return Ok([width; 2]);
        }
        let atomics: Vec<_> = self
            .images
            .0
            .iter()
            .map(|&[width, _]| crate::text::IntrinsicWidths {
                min: width,
                max: width,
            })
            .collect();
        let intrinsic = self
            .paragraph
            .as_ref()
            .map(|p| measurer.intrinsic_widths(p, &atomics))
            .transpose()?
            .unwrap_or_default();
        Ok([intrinsic.min, intrinsic.max])
    }
    fn block_extent(&self) -> f32 {
        if let Some(measured) = &self.measured {
            // The margin box is a block formatting context root, so the element's margins
            // stay inside it.
            return if measured.through {
                let mut margins = measured.before.clone();
                margins.merge(measured.after.clone());
                margins.value()
            } else {
                measured.before.value() + measured.height + measured.after.value()
            };
        }
        if self.replacement.is_some() {
            let inline = self.inline_axis();
            return self.replaced_extent(1 - inline, self.content[inline]);
        }
        self.lines.iter().map(|line| line.height).sum()
    }
    /// The replaced content's extent along physical `axis` when the other axis spans `other`:
    /// its natural size, or the size its natural ratio transfers, as for a replaced element
    /// whose other dimension is specified (CSS 2.1 §10.3.2, §10.6.2).
    fn replaced_extent(&self, axis: usize, other: f32) -> f32 {
        let image = self
            .replacement
            .as_ref()
            .expect("only a replaced margin box has replaced content");
        let natural = crate::paint::natural_points(
            image,
            crate::paint::INITIAL_IMAGE_SCALE,
            self.margin.style.effective_zoom,
        );
        let mut size = [
            crate::paint::SizeComponent::Auto,
            crate::paint::SizeComponent::Auto,
        ];
        size[1 - axis] =
            crate::paint::SizeComponent::Value(crate::paint::LengthPercentage::Length(other));
        crate::paint::image_size(
            &crate::paint::BackgroundSize::Explicit(size),
            natural,
            crate::images::DEFAULT_OBJECT_SIZE
                .map(|extent| extent * crate::style::POINTS_PER_PIXEL),
        )[axis]
    }
    /// The decoration, then the content laid out at its vertical alignment, then the outline.
    fn paint(
        mut self,
        origin: [f32; 2],
        index: usize,
        output: &mut MarginOutput<'_>,
        measurer: &mut Measurer<'t>,
        destinations: usize,
    ) -> Result<(), LayoutError> {
        self.validate()?;
        let block_axis = self.block_axis();
        let mut used = 0.0;
        let mut retained = 0;
        for line in &self.lines {
            if self.content[block_axis] < 0.0
                || (retained > 0 && used + line.height > self.content[block_axis])
            {
                break;
            }
            used += line.height;
            retained += 1;
        }
        self.lines.truncate(retained);
        let rect = Rect {
            x: origin[0] + self.start[0],
            y: origin[1] + self.start[1],
            width: self.content[0] + self.edges(0),
            height: self.content[1] + self.edges(1),
        };
        if [
            rect.x,
            rect.y,
            rect.width,
            rect.height,
            rect.x + rect.width,
            rect.y + rect.height,
        ]
        .iter()
        .any(|value| !value.is_finite())
        {
            return Err(LayoutError::NonFinitePageMarginGeometry {
                location: self.margin.location,
            });
        }
        let paint = BoxPaint {
            padding: self.padding,
            ..BoxPaint::whole(rect, self.decoration.clone())
        };
        let outline = paint.outline();
        let replaced = self
            .replacement
            .take()
            .map(|image| self.replaced(image, &paint));
        // CSS Backgrounds 4 §2.8: `background-clip: text` layers paint within the text of
        // the box's content, which a page box's text holds too.
        let clips_to_text = self.decoration.backgrounds.clips_to_text();
        let text = clips_to_text || output.page_text.is_some();
        let painted = self.decoration.is_visible().then(|| {
            output.display.push(DisplayItem::Box(paint));
            output.display.len() - 1
        });
        let content = output.display.len();
        let extent = self.block_extent();
        let text_area = if let Some(measured) = self.measured.take() {
            self.paint_element(
                measured,
                extent,
                rect,
                output,
                measurer,
                (destinations, text),
            )?
        } else if let Some(image) = replaced {
            output.display.push(DisplayItem::Image(image));
            text.then(|| text_flow(&[], &[], rect))
        } else {
            self.paint_lines(rect, index, output.lines, output.display);
            text.then(|| text_flow(&output.display[content..], output.lines, rect))
        };
        if let (Some(page_text), Some(area)) = (&mut output.page_text, &text_area) {
            page_text
                .items
                .push(DisplayItem::Frame(Box::new(area.clone())));
        }
        if clips_to_text
            && let (Some(slot), Some(area)) = (painted, text_area)
            && let DisplayItem::Box(paint) = &mut output.display[slot]
        {
            paint.text_area = Some(std::sync::Arc::new(area));
        }
        // The outline paints over the margin box's content (CSS UI 4 §3.1).
        output.display.extend(outline.map(DisplayItem::Box));
        Ok(())
    }
    /// The replaced content fitted into the content box by `object-fit` and
    /// `object-position`, clipped to the content edge (CSS Images 3 §4.5); content without
    /// natural dimensions fills it.
    fn replaced(
        &self,
        image: std::sync::Arc<crate::images::Image>,
        paint: &BoxPaint,
    ) -> ImagePaint {
        let style = &self.margin.style;
        let clip = paint.inner_clip(self.padding, [true; 2]);
        let content = clip.rect;
        let box_size = [content.width, content.height];
        let [width, height] = if image.natural_size() == Default::default() {
            box_size
        } else {
            let scale = crate::style::POINTS_PER_PIXEL * style.effective_zoom;
            let natural = image
                .pixel_size(content.width / scale)
                .map(|extent| extent * scale);
            style.object_fit.size(natural, box_size)
        };
        ImagePaint {
            image,
            rect: Rect {
                x: content.x + style.object_position[0].resolve(content.width - width),
                y: content.y + style.object_position[1].resolve(content.height - height),
                width,
                height,
            },
            clip: Some(clip),
            source_scale: style.effective_zoom,
        }
    }
    fn vertical_offset(&self, physical_height: f32) -> f32 {
        let extra = self.content[VERTICAL] - physical_height;
        match self.margin.style.table.vertical_align {
            VerticalAlign::Middle => extra / 2.0,
            VerticalAlign::Bottom => extra,
            VerticalAlign::Top
            | VerticalAlign::Baseline
            | VerticalAlign::BaselineMiddle
            | VerticalAlign::Sub
            | VerticalAlign::Super
            | VerticalAlign::TextTop
            | VerticalAlign::TextBottom
            | VerticalAlign::Length(_) => 0.0,
        }
    }
    fn content_origin(&self, rect: Rect, physical_height: f32) -> [f32; 2] {
        [
            rect.x + self.padding[3] + self.borders[3],
            rect.y + self.padding[0] + self.borders[0] + self.vertical_offset(physical_height),
        ]
    }
    /// A running element lays out unbroken in the content box, in the margin box's flow.
    fn paint_element(
        &self,
        measured: MeasuredBlock<'t>,
        extent: f32,
        rect: Rect,
        output: &mut MarginOutput<'_>,
        measurer: &mut Measurer<'t>,
        (destinations, text_area): (usize, bool),
    ) -> Result<Option<FlowPaint>, LayoutError> {
        let vertical = self.inline_axis() == VERTICAL;
        let logical = [self.content[self.inline_axis()], extent];
        let size = if vertical {
            [logical[1], logical[0]]
        } else {
            logical
        };
        let flow = crate::layout::pagination::Paginator::standalone(
            measurer,
            measured,
            Rect {
                x: 0.0,
                y: 0.0,
                width: logical[0],
                height: logical[1],
            },
            destinations,
            text_area,
        )?;
        let margin_flow = crate::style::logical::Flow::used(&self.margin.style);
        let frame = crate::layout::writing::Frame::physical(margin_flow, size);
        // CSS Images 4 §2.7: a running element is copied into each page that places it
        // (CSS GCPM 3 §1.2.2); `element()` images the copy on the first page showing it.
        measurer
            .element_targets
            .displayed
            .borrow_mut()
            .adopt(flow.renderings.physical(margin_flow));
        let mut items = flow.items;
        let mut text_area = flow.text_area;
        let mut navigation = flow.navigation.into_links();
        if vertical {
            frame.items(&mut items);
            if let Some(area) = &mut text_area {
                frame.items(&mut area.items);
            }
            for area in &mut navigation {
                match &mut area.shape {
                    crate::layout::LinkShape::Rect(rect) => *rect = frame.rect(*rect),
                    crate::layout::LinkShape::Quads(quads) => {
                        for point in quads.iter_mut().flatten() {
                            *point = frame.point(*point);
                        }
                    }
                }
            }
        }
        let origin = self.content_origin(rect, size[1]);
        for mut area in navigation {
            match &mut area.shape {
                crate::layout::LinkShape::Rect(rect) => {
                    rect.x += origin[0];
                    rect.y += origin[1];
                }
                crate::layout::LinkShape::Quads(quads) => {
                    for point in quads.iter_mut().flatten() {
                        point[0] += origin[0];
                        point[1] += origin[1];
                    }
                }
            }
            output.links.push(area);
        }
        let matrix = [1.0, 0.0, 0.0, 1.0, origin[0], origin[1]];
        let area = Rect {
            x: 0.0,
            y: 0.0,
            width: size[0],
            height: size[1],
        };
        output.display.push(DisplayItem::Frame(Box::new(FlowPaint {
            matrix,
            area,
            items,
            lines: flow.lines,
        })));
        Ok(text_area.map(|text| FlowPaint {
            matrix,
            area,
            ..text
        }))
    }
    fn paint_lines(
        self,
        rect: Rect,
        index: usize,
        page: &mut Vec<TextLine>,
        display: &mut Vec<DisplayItem>,
    ) {
        let style = &self.margin.style;
        let vertical = self.inline_axis() == VERTICAL;
        let inline_extent = if vertical {
            self.lines.iter().map(|line| line.width).fold(0.0, f32::max)
        } else {
            self.content[HORIZONTAL]
        };
        let physical_height = if vertical {
            inline_extent
        } else {
            self.block_extent()
        };
        let content_origin = self.content_origin(rect, physical_height);
        let mut frame_lines = Vec::new();
        let mut frame_items = Vec::new();
        let (text_lines, text_items) = if vertical {
            (&mut frame_lines, &mut frame_items)
        } else {
            (&mut *page, &mut *display)
        };
        let mut y = if vertical { 0.0 } else { content_origin[1] };
        for line in self.lines {
            let x = if vertical { 0.0 } else { content_origin[0] }
                + line.alignment_offset(inline_extent, style.used_rtl());
            let baseline = y + line.ascent;
            let [below, above] =
                crate::layout::inline::decoration_items(&line.decorations, x, baseline);
            text_items.extend(below);
            text_items.push(DisplayItem::Text {
                line: text_lines.len(),
            });
            text_items.extend(above);
            let paragraph = self
                .paragraph
                .as_ref()
                .expect("a margin box's lines lay out its paragraph");
            text_items.extend(
                crate::layout::markers::content_image_paints(paragraph, &line, &self.images.0)
                    .into_iter()
                    .map(|mut image| {
                        image.rect.x += x;
                        image.rect.y += baseline;
                        DisplayItem::Image(image)
                    }),
            );
            text_lines.push(TextLine {
                paragraph: index,
                text: line.text,
                x,
                baseline,
                width: line.width,
                height: line.height,
                runs: line.runs,
                font_size: style.size,
                color: style.color,
            });
            y += line.height;
        }
        if vertical {
            let size = [self.content[HORIZONTAL], inline_extent];
            crate::layout::writing::Frame::physical(crate::style::logical::Flow::used(style), size)
                .items(&mut frame_items);
            display.push(DisplayItem::Frame(Box::new(FlowPaint {
                matrix: [1.0, 0.0, 0.0, 1.0, content_origin[0], content_origin[1]],
                area: Rect {
                    x: 0.0,
                    y: 0.0,
                    width: size[0],
                    height: size[1],
                },
                items: frame_items,
                lines: frame_lines,
            })));
        }
    }
}
/// The text and decorations among `items`, whose text lines are `lines`, drawn opaquely in a
/// flow of their own over `area`: the text a margin box's lines paint.
fn text_flow(items: &[DisplayItem], lines: &[TextLine], area: Rect) -> FlowPaint {
    let mut flow = FlowPaint {
        matrix: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
        area,
        items: Vec::new(),
        lines: Vec::new(),
    };
    for item in items {
        match item {
            DisplayItem::Text { line } => {
                flow.lines.push(lines[*line].clone().opaque());
                flow.items.push(DisplayItem::Text {
                    line: flow.lines.len() - 1,
                });
            }
            DisplayItem::Decoration(decoration) => {
                flow.items
                    .push(DisplayItem::Decoration(decoration.opaque()));
            }
            DisplayItem::Frame(frame) => {
                flow.items.push(DisplayItem::Frame(Box::new(FlowPaint {
                    matrix: frame.matrix,
                    ..text_flow(&frame.items, &frame.lines, frame.area)
                })));
            }
            DisplayItem::PushTransform(_) | DisplayItem::Pop => flow.items.push(item.clone()),
            DisplayItem::Image(_) => {}
            DisplayItem::Box(_)
            | DisplayItem::TextShadow(_)
            | DisplayItem::PushClip(_)
            | DisplayItem::PushOpacity(_)
            | DisplayItem::PushBlend(_)
            | DisplayItem::PushFilter(_)
            | DisplayItem::PushMask(_)
            | DisplayItem::PushBackdropRoot
            | DisplayItem::Backdrop(_) => {
                unreachable!("margin lines paint text, decorations, images and their transforms")
            }
        }
    }
    flow
}
/// What one page's margin boxes paint, and the page's text area when its page box's
/// backgrounds clip to text, which holds their text.
struct MarginOutput<'p> {
    lines: &'p mut Vec<TextLine>,
    display: &'p mut Vec<DisplayItem>,
    links: &'p mut Vec<crate::layout::LinkArea>,
    page_text: Option<&'p mut FlowPaint>,
}
/// The page-margin boxes' shared inputs: the selected strings and running elements, the
/// document's destination count, the page-based counters and the document's counters where
/// pages start.
pub(super) struct MarginContext<'s, 't> {
    pub resolver: &'s dyn crate::resources::ResourceResolver,
    pub strings: &'s crate::layout::strings::PageStrings,
    pub running: &'t [RunningStringAssignment],
    pub destinations: usize,
    pub counters: &'s crate::layout::page_counters::PageCounters,
    pub document: &'s crate::document::StyledDocument,
}
/// The running element each page-margin box places, with the `page` counter it shows.
pub(super) fn running(
    page_boxes: &[std::sync::Arc<PageBox>],
    running: &[RunningStringAssignment],
    strings: &crate::layout::strings::PageStrings,
    counters: &crate::layout::page_counters::PageCounters,
) -> Vec<(crate::style::PageStyleTarget, i128)> {
    page_boxes
        .iter()
        .enumerate()
        .flat_map(|(page, page_box)| {
            page_box.margins.iter().filter_map(move |margin| {
                let request = margin.margin.content.running_element()?;
                let element = running[strings.element(page, request)?].element.as_ref()?;
                Some((
                    element.target,
                    counters.page(page, Some(margin.margin.location)),
                ))
            })
        })
        .collect()
}
/// Prepares a page-margin box of the page at index `page` of `pages`.
fn prepare<'a, 't>(
    margin: &'a PageMargin,
    decoration: &'a BoxDecoration,
    containing: [f32; 2],
    page: usize,
    pages: usize,
    context: &MarginContext<'_, 't>,
) -> Result<Prepared<'a, 't>, LayoutError> {
    let style = &margin.style;
    let bases = [containing[1], containing[0], containing[1], containing[0]];
    let padding = std::array::from_fn(|i| style.padding[i].resolve(bases[i]));
    let borders = style
        .decoration
        .borders
        .map(crate::graphics::Border::used_width);
    let margins = std::array::from_fn(|i| style.margin[i].resolve(bases[i]));
    let mut specified = [style.width.resolve(containing[0]), None];
    if style.box_sizing == BoxSizing::BorderBox {
        for axis in [HORIZONTAL, VERTICAL] {
            let edges = Prepared::sides(axis)
                .iter()
                .map(|&i| padding[i] + borders[i])
                .sum::<f32>();
            specified[axis] = specified[axis].map(|size| (size - edges).max(0.0));
        }
    }
    let mut replacement = None;
    let (paragraph, element) = if let Some(request) = margin.content.running_element() {
        (
            None,
            context
                .strings
                .element(page, request)
                .and_then(|owner| context.running[owner].element.as_ref())
                .map(|element| {
                    element.block(context.counters.page(page, Some(margin.location)), pages)
                }),
        )
    } else if let Some(image) = margin.content.replacement() {
        replacement = Some(
            context
                .document
                .margin_replacement(image, style, context.resolver),
        );
        (None, None)
    } else {
        let output = margin.content.page_output(
            context.counters.page(page, Some(margin.location)),
            pages,
            crate::document::MAX_INLINE_TEXT_BYTES,
            &style.quotes,
            &mut |request| Ok(context.strings.text(page, request)),
            &mut |request| {
                context.counters.text(
                    page,
                    margin.location,
                    request,
                    context
                        .document
                        .page_counters(page)
                        .unwrap_or(&CounterSnapshot::default()),
                )
            },
        )?;
        let images = context
            .document
            .margin_images(&output, style, context.resolver);
        (Paragraph::generated_output(&output, &images, style)?, None)
    };
    let images = paragraph
        .as_ref()
        .map(crate::layout::markers::content_image_atomics)
        .unwrap_or_default();
    Ok(Prepared {
        margin,
        decoration,
        paragraph,
        images,
        replacement,
        element,
        measured: None,
        padding,
        borders,
        margins,
        specified,
        start: [0.0; 2],
        content: [0.0; 2],
        lines: Vec::new(),
    })
}

pub(super) fn render<'t>(
    page_boxes: &[std::sync::Arc<PageBox>],
    context: &MarginContext<'_, 't>,
    measurer: &mut Measurer<'t>,
    first_index: usize,
    (pages, display, links, text_areas): crate::layout::PageOutputs<'_>,
) -> Result<(), LayoutError> {
    let total = pages.len();
    for (number, (((page_lines, display), links), page_text)) in pages
        .iter_mut()
        .zip(display)
        .zip(links.iter_mut())
        .zip(text_areas.iter_mut())
        .enumerate()
    {
        let page = &page_boxes[number];
        let margins: Vec<_> = page
            .margins
            .iter()
            .map(|margin| (&margin.margin, &margin.decoration))
            .collect();
        if margins.is_empty() {
            continue;
        }
        let page_box = page.geometry.margin_box();
        let [width, height] = [page_box.width, page_box.height];
        let [top, right, bottom, left] = page.geometry.margin;
        let groups = [
            ([left, 0.0], [width - left - right, top], HORIZONTAL),
            (
                [left, height - bottom],
                [width - left - right, bottom],
                HORIZONTAL,
            ),
            ([0.0, top], [left, height - top - bottom], VERTICAL),
            (
                [width - right, top],
                [right, height - top - bottom],
                VERTICAL,
            ),
        ];
        let page = page_lines;
        for (locations, (origin, containing, axis)) in GROUPS.iter().zip(groups) {
            let mut boxes: [Option<Prepared<'_, '_>>; 3] = [None, None, None];
            let mut dimensions = [Variable::default(); 3];
            for (position, location) in locations.iter().enumerate() {
                let Some((margin, decoration)) = margins
                    .iter()
                    .find(|(margin, _)| margin.location == *location)
                else {
                    continue;
                };
                let mut prepared = prepare(margin, decoration, containing, number, total, context)?;
                prepared.validate()?;
                let fixed_axis = 1 - axis;
                prepared.fixed(fixed_axis, containing[fixed_axis]);
                let bounds = if axis == prepared.inline_axis() {
                    prepared.intrinsic(measurer, containing[axis])?
                } else {
                    prepared.layout(measurer)?;
                    [prepared.block_extent(); 2]
                };
                if axis == HORIZONTAL && prepared.margin.style.width.intrinsic().is_some() {
                    let available = containing[axis] - prepared.outer_edges(axis);
                    let style = &prepared.margin.style;
                    let sizes = [&style.width, &Size::Auto, &Size::Auto];
                    prepared.specified[axis] = crate::style::SizeConstraints::new(
                        sizes,
                        Some(containing[axis]),
                        style.box_sizing,
                        prepared.edges(axis),
                    )
                    .with_intrinsic(
                        sizes,
                        crate::style::IntrinsicWidths {
                            min: bounds[0],
                            max: bounds[1],
                        },
                        Some(available.max(0.0)),
                    )
                    .specified;
                }
                let edges = prepared.outer_edges(axis);
                dimensions[position] = Variable {
                    min: bounds[0] + edges,
                    max: bounds[1] + edges,
                    specified: prepared.specified[axis].map(|size| size + edges),
                    generated: true,
                };
                boxes[position] = Some(prepared);
            }
            let sizes = variable(dimensions, containing[axis]);
            for (position, prepared) in boxes.into_iter().enumerate() {
                if let Some(mut prepared) = prepared {
                    prepared.variable(axis, containing[axis], sizes[position], position);
                    prepared.layout(measurer)?;
                    let index = first_index + prepared.margin.location as usize;
                    prepared.paint(
                        origin,
                        index,
                        &mut MarginOutput {
                            lines: page,
                            display,
                            links,
                            page_text: page_text.as_mut(),
                        },
                        measurer,
                        context.destinations,
                    )?;
                }
            }
        }
        for (location, origin, containing) in [
            (MarginLocation::TopLeftCorner, [0.0, 0.0], [left, top]),
            (
                MarginLocation::TopRightCorner,
                [width - right, 0.0],
                [right, top],
            ),
            (
                MarginLocation::BottomLeftCorner,
                [0.0, height - bottom],
                [left, bottom],
            ),
            (
                MarginLocation::BottomRightCorner,
                [width - right, height - bottom],
                [right, bottom],
            ),
        ] {
            if let Some((margin, decoration)) = margins
                .iter()
                .find(|(margin, _)| margin.location == location)
            {
                let mut prepared = prepare(margin, decoration, containing, number, total, context)?;
                prepared.validate()?;
                for axis in [HORIZONTAL, VERTICAL] {
                    prepared.fixed(axis, containing[axis]);
                }
                prepared.layout(measurer)?;
                prepared.paint(
                    origin,
                    first_index + location as usize,
                    &mut MarginOutput {
                        lines: page,
                        display,
                        links,
                        page_text: page_text.as_mut(),
                    },
                    measurer,
                    context.destinations,
                )?;
            }
        }
    }
    Ok(())
}