ferri-pdf 0.1.4

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
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
//! Initial letters (CSS Inline 3 §7), checked against the profile font's own metrics.
use super::common;
use crate::render_html;
use common::{PROFILE, assert_labelled_pt, local_options, painted_box};

const PROFILE_FONT: &[u8] = include_bytes!("../../tests/oracle/assets/DejaVuSans.ttf");
/// The profile's `body` font size and line height, and its page content box origin.
const FONT_SIZE: f32 = 12.0;
const LINE_HEIGHT: f32 = 18.0;
const CONTENT_LEFT: f32 = 36.0;
const CONTENT_TOP: f32 = 36.0;
const CONTENT_WIDTH: f32 = 288.0;
const TEXT: &str = "Lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor \
                    incididunt ut labore et dolore magna aliqua ut enim ad minim veniam quis \
                    nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo";
const LIME: [u8; 3] = [0, 255, 0];
const RED: [u8; 3] = [255, 0, 0];

fn render(css: &str, body: &str) -> crate::LayoutTrace {
    render_html(
        &format!("<style>{PROFILE}{css}</style>{body}"),
        &local_options(),
    )
    .unwrap_or_else(|error| panic!("render failed: {error}\ncss: {css}\nbody: {body}"))
    .layout
    .expect("layout requested")
}

/// The profile face's metrics in em: cap height (the top of `H`, as it has no OS/2 cap
/// height), ascent and descent.
struct Font {
    cap: f32,
    ascent: f32,
    descent: f32,
}
impl Font {
    fn profile() -> Self {
        let face = ttf_parser::Face::parse(PROFILE_FONT, 0).expect("profile font parses");
        let em = f32::from(face.units_per_em());
        let cap = face
            .glyph_index('H')
            .and_then(|glyph| face.glyph_bounding_box(glyph))
            .expect("the profile font has an H");
        Self {
            cap: f32::from(cap.y_max) / em,
            ascent: f32::from(face.ascender()) / em,
            descent: -f32::from(face.descender()) / em,
        }
    }
    /// The used size of a letter whose cap height spans `lines` lines of profile text from
    /// its cap height to its baseline (§7.5.3).
    fn letter_size(&self, lines: f32) -> f32 {
        ((lines - 1.0) * LINE_HEIGHT + self.cap * FONT_SIZE) / self.cap
    }
    /// The first profile line's baseline below its line box top.
    fn baseline(&self) -> f32 {
        let content = (self.ascent + self.descent) * FONT_SIZE;
        self.ascent * FONT_SIZE + (LINE_HEIGHT - content) / 2.0
    }
    /// The left side bearing of `ch` at `size`.
    fn bearing(ch: char, size: f32) -> f32 {
        let face = ttf_parser::Face::parse(PROFILE_FONT, 0).expect("profile font parses");
        let bounds = face
            .glyph_index(ch)
            .and_then(|glyph| face.glyph_bounding_box(glyph))
            .expect("the profile font has the glyph");
        f32::from(bounds.x_min) / f32::from(face.units_per_em()) * size
    }
}

/// The first page's line holding `text` alone, and the other lines in order.
fn split<'a>(
    trace: &'a crate::LayoutTrace,
    text: &str,
) -> (&'a crate::TextLine, Vec<&'a crate::TextLine>) {
    let lines = &trace.pages[0];
    let letter = lines
        .iter()
        .find(|line| line.text == text)
        .unwrap_or_else(|| panic!("no line {text:?} among {:#?}", texts(lines)));
    let rest = lines
        .iter()
        .filter(|line| !std::ptr::eq(*line, letter))
        .collect();
    (letter, rest)
}

/// Where a line's text starts: its first run, after any initial letter the line holds.
fn start(line: &crate::TextLine) -> f32 {
    line.x + line.runs.first().map_or(0.0, |run| run.x)
}

fn texts(lines: &[crate::TextLine]) -> Vec<(String, f32, f32)> {
    lines
        .iter()
        .map(|line| (line.text.clone(), start(line), line.baseline))
        .collect()
}

fn describe(lines: &[&crate::TextLine]) -> Vec<(String, f32, f32)> {
    lines
        .iter()
        .map(|line| (line.text.clone(), start(line), line.baseline))
        .collect()
}

#[test]
fn drop_cap_spans_three_lines_and_excludes_their_start() {
    let font = Font::profile();
    let trace = render(
        "p::first-letter{initial-letter:3}",
        &format!("<p>{TEXT}</p>"),
    );
    let (letter, lines) = split(&trace, "L");
    let size = font.letter_size(3.0);
    assert_labelled_pt("drop cap font size", letter.runs[0].font_size, size);
    assert_labelled_pt(
        "the drop cap's baseline is the third line's",
        letter.baseline,
        lines[2].baseline,
    );
    assert_labelled_pt(
        "the drop cap's cap height is the first line's",
        letter.baseline - font.cap * size,
        lines[0].baseline - font.cap * FONT_SIZE,
    );
    assert_labelled_pt(
        "the first line keeps its place",
        lines[0].baseline,
        CONTENT_TOP + font.baseline(),
    );
    assert_labelled_pt(
        "zero padding and borders kern the glyph to the line start (§7.6.2)",
        letter.x + Font::bearing('L', size),
        CONTENT_LEFT,
    );
    for (index, line) in lines.iter().enumerate().take(3) {
        assert_labelled_pt(
            &format!(
                "line {index} starts after the letter: {:#?}",
                describe(&lines)
            ),
            start(line),
            letter.x + letter.width,
        );
    }
    assert_labelled_pt(
        &format!(
            "the fourth line is below the letter: {:#?}",
            describe(&lines)
        ),
        start(lines[3]),
        CONTENT_LEFT,
    );
}

#[test]
fn letter_size_follows_its_lines_and_sink_follows_drop_and_raise() {
    let font = Font::profile();
    for (value, lines, sink) in [
        ("2", 2.0, 2),
        ("2.5", 2.5, 2),
        ("drop 3", 3.0, 3),
        ("3 3", 3.0, 3),
        ("raise 3", 3.0, 1),
        ("3 1", 3.0, 1),
        ("2.51 3", 2.51, 3),
    ] {
        let trace = render(
            &format!("p::first-letter{{initial-letter:{value}}}"),
            &format!("<p>{TEXT}</p>"),
        );
        let (letter, rest) = split(&trace, "L");
        let size = font.letter_size(lines);
        assert_labelled_pt(
            &format!("initial-letter: {value} font size"),
            letter.runs[0].font_size,
            size,
        );
        if lines >= sink as f32 {
            assert_labelled_pt(
                &format!(
                    "initial-letter: {value} sits on line {sink}: {:#?}",
                    describe(&rest)
                ),
                letter.baseline,
                rest[sink - 1].baseline,
            );
        } else {
            assert_labelled_pt(
                &format!("initial-letter: {value} hangs from the first line's cap height"),
                letter.baseline - font.cap * size,
                rest[0].baseline - font.cap * FONT_SIZE,
            );
            for (index, line) in rest.iter().enumerate().take(sink) {
                assert_labelled_pt(
                    &format!("initial-letter: {value} excludes line {index} of its sink"),
                    start(line),
                    letter.x + letter.width,
                );
            }
            assert_labelled_pt(
                &format!("initial-letter: {value} leaves the line after its sink"),
                start(rest[sink]),
                CONTENT_LEFT,
            );
        }
    }
}

#[test]
fn raised_letters_move_their_line_down_to_stay_inside_the_content_box() {
    let font = Font::profile();
    for (value, sink) in [("3 1", 1), ("3 2", 2)] {
        let trace = render(
            &format!("p::first-letter{{initial-letter:{value}}}"),
            &format!("<p>{TEXT}</p>"),
        );
        let (letter, rest) = split(&trace, "L");
        let size = font.letter_size(3.0);
        assert_labelled_pt(
            &format!("initial-letter: {value} keeps its cap height at the content top (§7.6.1)"),
            letter.baseline - font.cap * size,
            CONTENT_TOP,
        );
        assert_labelled_pt(
            &format!("initial-letter: {value} aligns to line {sink}"),
            letter.baseline,
            rest[sink - 1].baseline,
        );
        assert_labelled_pt(
            &format!("initial-letter: {value} excludes only the lines of its sink"),
            start(rest[sink]),
            CONTENT_LEFT,
        );
    }
}

#[test]
fn space_after_a_sunken_letter_collapses_but_a_raised_one_keeps_it() {
    let first_line = |value: &str| {
        let trace = render(
            &format!("span{{initial-letter:{value}}}"),
            "<p><span>Words</span> follow the letter</p>",
        );
        let (_, rest) = split(&trace, "Words");
        rest[0].text.clone()
    };
    let placeholder = crate::document::OBJECT_REPLACEMENT_CHARACTER;
    assert_eq!(
        first_line("2"),
        format!("{placeholder}follow the letter"),
        "collapsible space after a sunken letter is collapsed away (§7.8.1)"
    );
    assert_eq!(
        first_line("2 1"),
        format!("{placeholder} follow the letter"),
        "a raised letter's line keeps the word space after it"
    );
}

#[test]
fn atomic_initial_letters_take_the_block_size_of_their_lines() {
    let font = Font::profile();
    let span = LINE_HEIGHT + font.cap * FONT_SIZE;
    let trace = render(
        "span{display:inline-block;initial-letter:2;background:lime;width:20pt}",
        &format!("<p><span></span>{TEXT}</p>"),
    );
    let lime = painted_box(&trace, LIME);
    assert_labelled_pt(
        "an automatic block size spans the letter's lines (§7.5.5)",
        lime.height,
        span,
    );
    let lines = &trace.pages[0];
    assert_labelled_pt(
        "its content box bottom is the second line's baseline",
        lime.y + lime.height,
        lines[1].baseline,
    );
    assert_labelled_pt(
        "its content box top is the first line's cap height",
        lime.y,
        lines[0].baseline - font.cap * FONT_SIZE,
    );
    for line in &lines[..2] {
        assert_labelled_pt(
            "lines beside the box start after it",
            start(line),
            lime.x + 20.0,
        );
    }
    assert_labelled_pt("the third line is below it", start(&lines[2]), CONTENT_LEFT);
}

#[test]
fn inside_markers_and_the_first_inline_box_become_initial_letters() {
    let font = Font::profile();
    let size = font.letter_size(2.0);
    let trace = render(
        "ol{margin:0;padding:0;list-style-position:inside}li::marker{initial-letter:2}",
        &format!("<ol><li>{TEXT}</li></ol>"),
    );
    let (marker, lines) = split(&trace, "1. ");
    assert_labelled_pt("inside marker letter size", marker.runs[0].font_size, size);
    assert_labelled_pt(
        "the marker letter sits on the second line",
        marker.baseline,
        lines[1].baseline,
    );
    let trace = render(
        "em{initial-letter:2}b{initial-letter:3}",
        &format!("<p><span><em><b>T</b>wo</em> words</span> {TEXT}</p>"),
    );
    let (letter, _) = split(&trace, "Two");
    for run in &letter.runs {
        assert_labelled_pt(
            &format!(
                "the first-most inline box is the letter, and its descendants' own \
                 initial-letter is ignored (§7.3.1): {:?}",
                run.text
            ),
            run.font_size,
            size,
        );
    }
}

#[test]
fn initial_letter_is_normal_after_other_inline_content() {
    for (css, body) in [
        ("span{initial-letter:2}", "<p>A <span>late</span> span</p>"),
        ("b{initial-letter:2}", "<p><i></i><b>second</b> child</p>"),
        (
            "ol{list-style-position:inside}li::first-letter{initial-letter:2}",
            "<ol><li>After the marker</li></ol>",
        ),
    ] {
        let trace = render(css, body);
        for line in &trace.pages[0] {
            for run in &line.runs {
                assert_labelled_pt(
                    &format!("{body}: {:?} keeps the computed font size", run.text),
                    run.font_size,
                    FONT_SIZE,
                );
            }
        }
    }
}

#[test]
fn first_line_styles_reach_the_initial_letter() {
    let trace = render(
        "p::first-line{color:red}p::first-letter{initial-letter:2}",
        &format!("<p>{TEXT}</p>"),
    );
    let (letter, lines) = split(&trace, "L");
    assert_eq!(
        letter.runs[0].color.rgb, RED,
        "::first-letter inherits from ::first-line"
    );
    assert_eq!(lines[0].runs[0].color.rgb, RED);
    assert_ne!(lines[1].runs[0].color.rgb, RED);
}

#[test]
fn short_paragraph_letters_exclude_the_next_block_until_it_clears_them() {
    let font = Font::profile();
    let size = font.letter_size(3.0);
    let following = |css: &str| {
        let trace = render(
            &format!("p{{margin:0}}p.short::first-letter{{initial-letter:3}}{css}"),
            &format!("<p class=short>Short.</p><p class=next>{TEXT}</p>"),
        );
        let (letter, lines) = split(&trace, "S");
        let next: Vec<_> = lines.into_iter().skip(1).collect();
        (
            letter.x + letter.width,
            letter.baseline,
            start(next[0]),
            next[0].baseline,
            describe(&next),
        )
    };
    let (right, _, x, baseline, lines) = following("");
    assert_labelled_pt(
        &format!("the next paragraph wraps around the letter (§7.9.2): {lines:#?}"),
        x,
        right,
    );
    assert_labelled_pt(
        "the next paragraph follows the short one",
        baseline,
        CONTENT_TOP + LINE_HEIGHT + font.baseline(),
    );
    for css in [
        "p.next::first-letter{initial-letter:2}",
        "p.next{overflow:hidden}",
        "p.next{clear:left}",
    ] {
        let (_, letter_baseline, x, baseline, lines) = following(css);
        let line_top = baseline - font.baseline();
        assert!(
            line_top >= letter_baseline - 0.001,
            "{css}: the next block clears the letter, whose bottom is its baseline \
             {letter_baseline}, but its first line box starts at {line_top}: {lines:#?}"
        );
        if css.contains("first-letter") {
            continue;
        }
        assert_labelled_pt(
            &format!("{css}: the cleared line starts at the edge"),
            x,
            CONTENT_LEFT,
        );
    }
    let _ = size;
}

#[test]
fn floats_beside_a_letter_follow_its_line_or_clear_it() {
    let font = Font::profile();
    let trace = render(
        "p::first-letter{initial-letter:3}i{float:left;width:20pt;height:10pt;background:lime}",
        &format!("<p>Lorem <i></i>{TEXT}</p>"),
    );
    let lime = painted_box(&trace, LIME);
    let (letter, lines) = split(&trace, "L");
    assert_labelled_pt(
        "a float of the first line moves past the letter to the edge (§7.9.3)",
        lime.x,
        CONTENT_LEFT,
    );
    assert_labelled_pt(
        "the letter follows the float",
        letter.x + Font::bearing('L', font.letter_size(3.0)),
        CONTENT_LEFT + 20.0,
    );
    assert_labelled_pt(
        "the first line follows the letter",
        start(lines[0]),
        letter.x + letter.width,
    );
    let trace = render(
        "p::first-letter{initial-letter:3}i{float:left;width:20pt;height:10pt;background:lime}",
        &format!("<p>{TEXT} <i></i>{TEXT}</p>"),
    );
    let lime = painted_box(&trace, LIME);
    let (letter, _) = split(&trace, "L");
    assert!(
        lime.y >= letter.baseline - 0.001,
        "an inline-start float after the first line clears the letter: float top {}, \
         letter bottom {}",
        lime.y,
        letter.baseline
    );
}

#[test]
fn letters_lean_on_the_start_side_and_its_indent() {
    let font = Font::profile();
    let size = font.letter_size(2.0);
    let trace = render(
        "p{text-indent:20pt}p::first-letter{initial-letter:2}",
        &format!("<p>{TEXT}</p>"),
    );
    let (letter, lines) = split(&trace, "L");
    assert_labelled_pt(
        "text-indent shifts the letter (§7.8.2)",
        letter.x + Font::bearing('L', size),
        CONTENT_LEFT + 20.0,
    );
    assert_labelled_pt(
        "the second line is shortened by the shifted letter",
        start(lines[1]),
        letter.x + letter.width,
    );
    let trace = render(
        "p{direction:rtl;text-align:start}p::first-letter{initial-letter:2}",
        &format!("<p>{TEXT}</p>"),
    );
    let (letter, lines) = split(&trace, "L");
    assert!(
        letter.x + letter.width > CONTENT_LEFT + CONTENT_WIDTH - 1.0,
        "a right-to-left letter sits at the right edge: {} + {}",
        letter.x,
        letter.width
    );
    for line in &lines[..2] {
        let end = line
            .runs
            .iter()
            .map(|run| line.x + run.x + run.width)
            .fold(f32::NEG_INFINITY, f32::max);
        assert!(
            end <= letter.x + 0.001,
            "right-to-left text beside the letter ends before it at {}: {:#?}",
            letter.x,
            describe(&lines)
        );
    }
}

#[test]
fn letter_paragraphs_move_whole_to_the_next_page_rather_than_break_beside_the_letter() {
    // Two of the three lines beside the letter fit below the filler.
    let filler = "<div style=height:366pt></div>";
    let trace = render(
        "p::first-letter{initial-letter:3}",
        &format!("{filler}<p>{TEXT}</p>"),
    );
    assert!(
        trace.pages[0].is_empty(),
        "two lines fit at the page end, but breaking beside the letter is avoided \
         (§7.9.4): {:#?}",
        texts(&trace.pages[0])
    );
    assert!(
        trace.pages[1].iter().any(|line| line.text == "L"),
        "the letter moves with its paragraph"
    );
    let control = render("", &format!("{filler}<p>{TEXT}</p>"));
    assert!(
        !control.pages[0].is_empty(),
        "without the letter the paragraph splits there"
    );
}

#[test]
fn block_level_content_ends_the_letter_and_its_box_continues_after() {
    let font = Font::profile();
    let trace = render(
        "span{initial-letter:2}div{margin:0}",
        &format!("<div><span>W<div>{TEXT}</div>c</span> tail</div>"),
    );
    let (letter, lines) = split(&trace, "W");
    assert_labelled_pt(
        "the letter keeps its size",
        letter.runs[0].font_size,
        font.letter_size(2.0),
    );
    assert_eq!(
        lines[0].text,
        "\u{fffc}",
        "the letter alone takes the line before the block: {:#?}",
        describe(&lines)
    );
    assert_labelled_pt(
        "the letter's baseline is the block's first line's (§7.9.2)",
        letter.baseline,
        lines[1].baseline,
    );
    assert!(
        start(lines[1]) >= letter.x + letter.width,
        "the block's first line starts after the letter: {:#?}",
        describe(&lines)
    );
    assert_labelled_pt(
        "the block's next line clears the letter",
        start(lines[2]),
        CONTENT_LEFT,
    );
    let rest = lines.last().expect("the box continues after the block");
    assert_eq!(rest.text, "c tail", "{:#?}", describe(&lines));
    assert!(
        rest.runs.iter().all(|run| run.font_size == FONT_SIZE),
        "the box's fragments after the block are ordinary text: {:#?}",
        rest.runs
    );
}

#[test]
fn letters_too_long_for_a_line_wrap_each_line_as_a_letter() {
    let font = Font::profile();
    let trace = render(
        "span{initial-letter:3}",
        &format!("<p><span>Once more</span> {TEXT}</p>"),
    );
    let (first, rest) = split(&trace, "Once");
    let last = rest[0];
    let lines = &rest[1..];
    let size = font.letter_size(3.0);
    assert_eq!(last.text, "more", "{:#?}", describe(&rest));
    for row in [first, last] {
        assert_labelled_pt("each letter line's size", row.runs[0].font_size, size);
    }
    assert_labelled_pt(
        "the first letter line drops from the paragraph's first line",
        first.baseline - font.cap * size,
        CONTENT_TOP + font.baseline() - font.cap * FONT_SIZE,
    );
    let top = lines[0].baseline - font.baseline();
    assert!(
        top >= first.baseline && top <= first.baseline + font.descent * size,
        "the last letter line originates on the first line box below the first letter \
         line's glyphs, at {top}: {:#?}",
        describe(&rest)
    );
    assert_labelled_pt(
        "the last letter line sinks three lines from there",
        last.baseline,
        lines[2].baseline,
    );
    assert_labelled_pt(
        "the last letter line starts at the line's start",
        last.x,
        CONTENT_LEFT,
    );
    for line in &lines[..3] {
        assert_labelled_pt(
            "normal text follows the last letter line",
            start(line),
            last.x + last.width,
        );
    }
    assert_labelled_pt(
        "the line after the sink clears the letter",
        start(lines[3]),
        CONTENT_LEFT,
    );
    let rtl = render(
        "p{direction:rtl}span{initial-letter:3}",
        &format!("<p><span>Once more</span> {TEXT}</p>"),
    );
    let (_, rest) = split(&rtl, "Once");
    let last = rest[0];
    assert_labelled_pt(
        "a right-to-left letter's last line ends at the line's right start",
        last.x + last.width,
        CONTENT_LEFT + CONTENT_WIDTH,
    );
    let text_end = rest[1].x
        + rest[1]
            .runs
            .iter()
            .map(|run| run.x + run.width)
            .fold(0.0, f32::max);
    assert!(
        text_end <= last.x + 0.001,
        "right-to-left text ends before the last letter line at {}: {:#?}",
        last.x,
        describe(&rest)
    );
}

#[test]
fn percentage_padding_sizes_letters_against_their_containing_block() {
    const PARAGRAPH_WIDTH: f32 = 200.0;
    const PERCENT: f32 = 5.0;
    let padding = PARAGRAPH_WIDTH * PERCENT / 100.0;
    let body = format!("<p><span></span>{TEXT}</p>");
    // Border-box alignment fits the font inside the letter's padding (CSS Inline 3 §7.4).
    let inline = |padding: &str| {
        let trace = render(
            &format!(
                "p{{width:{PARAGRAPH_WIDTH}pt}}p::first-letter{{initial-letter:2;\
                 initial-letter-align:border-box;padding:{padding}}}"
            ),
            &format!("<p>{TEXT}</p>"),
        );
        split(&trace, "L").0.runs[0].font_size
    };
    let percentage = inline(&format!("{PERCENT}%"));
    assert_labelled_pt(
        "a percentage of the paragraph's width sizes an inline letter like that length",
        percentage,
        inline(&format!("{padding}pt")),
    );
    assert!(
        percentage < inline("0pt") - 1.0,
        "the padding shrinks the letter: {percentage} pt"
    );
    // An atomic letter's automatic block size spans its lines with its border box (§7.5.5).
    let atomic = |padding: &str| {
        let trace = render(
            &format!(
                "p{{width:{PARAGRAPH_WIDTH}pt}}span{{display:inline-block;initial-letter:2;\
                 background:lime;width:20pt;padding:{padding}}}"
            ),
            &body,
        );
        painted_box(&trace, LIME).height
    };
    let height = atomic(&format!("{PERCENT}%"));
    assert_labelled_pt(
        "a percentage of the paragraph's width sizes an atomic letter like that length",
        height,
        atomic(&format!("{padding}pt")),
    );
    assert_labelled_pt(
        "its border box spans the letter's lines",
        height,
        LINE_HEIGHT + Font::profile().cap * FONT_SIZE,
    );
}

/// The lime box paints of a trace, in painting order.
fn lime_boxes(trace: &crate::LayoutTrace) -> Vec<&crate::graphics::BoxPaint> {
    trace
        .display_lists
        .iter()
        .flatten()
        .filter_map(|item| match item {
            crate::DisplayItem::Box(paint) if paint.decoration.background.rgb == LIME => {
                Some(paint)
            }
            _ => None,
        })
        .collect()
}

/// The `[left, right]` extent of a letter line's text.
fn text_extent(line: &crate::TextLine) -> [f32; 2] {
    [start(line), start(line) + line.width]
}

#[test]
fn wrapped_letters_paint_a_box_fragment_per_line() {
    const PADDING: f32 = 2.0;
    let body = format!("<p><span>Once more</span> {TEXT}</p>");
    let sliced = render(
        &format!("span{{initial-letter:3;background:lime;padding:{PADDING}pt}}"),
        &body,
    );
    let (first, rest) = split(&sliced, "Once");
    let last = rest[0];
    let boxes = lime_boxes(&sliced);
    assert_eq!(boxes.len(), 2, "one fragment per letter line: {boxes:#?}");
    let [head, tail] = [boxes[0], boxes[1]];
    let describe_boxes = || format!("{:#?}\n{:#?}", boxes, describe(&rest));
    assert_eq!(
        head.inline_edges,
        [true, false],
        "the first fragment keeps only its start edge: {}",
        describe_boxes()
    );
    assert_eq!(
        tail.inline_edges,
        [false, true],
        "the last fragment keeps only its end edge: {}",
        describe_boxes()
    );
    let [first_left, first_right] = text_extent(first);
    assert_labelled_pt(
        "the first fragment starts at the line start",
        head.rect.x,
        CONTENT_LEFT,
    );
    assert_labelled_pt(
        "the first fragment's start padding precedes its text",
        head.rect.x + PADDING,
        first_left,
    );
    assert_labelled_pt(
        "the first fragment ends with its text",
        head.rect.x + head.rect.width,
        first_right,
    );
    let [last_left, last_right] = text_extent(last);
    assert_labelled_pt(
        "the last fragment starts with its text",
        tail.rect.x,
        last_left,
    );
    assert_labelled_pt(
        "a sliced last fragment starts at the line start",
        tail.rect.x,
        CONTENT_LEFT,
    );
    assert_labelled_pt(
        "the last fragment's end padding follows its text",
        tail.rect.x + tail.rect.width,
        last_right + PADDING,
    );
    assert_labelled_pt(
        "normal text follows the last fragment",
        start(rest[1]),
        tail.rect.x + tail.rect.width,
    );
    assert!(
        head.rect.y + head.rect.height <= tail.rect.y + 0.001,
        "the fragments stack without overlapping: {}",
        describe_boxes()
    );
    for (fragment, line) in [(head, first), (tail, last)] {
        assert!(
            fragment.rect.y + PADDING <= line.baseline - Font::profile().cap * line.font_size
                && line.baseline <= fragment.rect.y + fragment.rect.height,
            "each fragment's box holds its line's glyphs, from its cap height to its \
             baseline: {fragment:#?} {:?}",
            (&line.text, line.baseline)
        );
    }
    // CSS Fragmentation 3 §5.4: a sliced box's background is drawn as if unbroken.
    let total = head.rect.width + tail.rect.width;
    for (fragment, before) in [(head, 0.0), (tail, head.rect.width)] {
        let assembled = fragment
            .background_box
            .unwrap_or_else(|| panic!("a sliced fragment has its assembled box: {fragment:#?}"));
        assert_labelled_pt(
            "the assembled box spans both fragments",
            assembled.width,
            total,
        );
        assert_labelled_pt(
            "each fragment takes its share of the assembled box",
            fragment.rect.x - assembled.x,
            before,
        );
    }

    let cloned = render(
        &format!(
            "span{{initial-letter:3;background:lime;padding:{PADDING}pt;\
             box-decoration-break:clone}}"
        ),
        &body,
    );
    let (_, rest) = split(&cloned, "Once");
    let last = rest[0];
    let boxes = lime_boxes(&cloned);
    assert_eq!(
        boxes.len(),
        2,
        "one cloned fragment per letter line: {boxes:#?}"
    );
    for fragment in &boxes {
        assert_eq!(
            fragment.inline_edges,
            [true, true],
            "cloned fragments keep both edges: {boxes:#?}"
        );
    }
    let tail = boxes[1];
    assert_labelled_pt(
        "a cloned last fragment starts at the line start",
        tail.rect.x,
        CONTENT_LEFT,
    );
    let [last_left, last_right] = text_extent(last);
    assert_labelled_pt(
        "its start padding precedes its text",
        tail.rect.x + PADDING,
        last_left,
    );
    assert_labelled_pt(
        "normal text follows its end padding",
        start(rest[1]),
        last_right + PADDING,
    );

    let rtl = render(
        &format!("p{{direction:rtl}}span{{initial-letter:3;background:lime;padding:{PADDING}pt}}"),
        &body,
    );
    let boxes = lime_boxes(&rtl);
    assert_eq!(boxes.len(), 2, "{boxes:#?}");
    assert_eq!(
        [boxes[0].inline_edges, boxes[1].inline_edges],
        [[false, true], [true, false]],
        "right-to-left fragments keep their start edge on the right: {boxes:#?}"
    );
    for fragment in &boxes {
        assert_labelled_pt(
            "right-to-left fragments start at the line's right start",
            fragment.rect.x + fragment.rect.width,
            CONTENT_LEFT + CONTENT_WIDTH,
        );
    }
}

#[test]
fn inline_box_ancestors_start_after_the_letter() {
    let trace = render(
        "p::first-letter{initial-letter:2}span{background:lime}",
        "<p><span>Lorem ipsum</span> dolor</p>",
    );
    let (letter, _) = split(&trace, "L");
    let lime = painted_box(&trace, LIME);
    assert_labelled_pt(
        "the ancestor inline box is drawn outside the letter (§7.8.3)",
        lime.x,
        letter.x + letter.width,
    );
}

#[test]
fn leading_alignment_spans_the_lines_half_leading_edges() {
    let font = Font::profile();
    let trace = render(
        "p::first-letter{initial-letter:3;initial-letter-align:leading}",
        &format!("<p>{TEXT}</p>"),
    );
    let (letter, _) = split(&trace, "L");
    assert_labelled_pt(
        "the cap height meets the first line box's top",
        letter.baseline - font.cap * letter.runs[0].font_size,
        CONTENT_TOP,
    );
    assert_labelled_pt(
        "the baseline meets the third line box's bottom",
        letter.baseline,
        CONTENT_TOP + 3.0 * LINE_HEIGHT,
    );
}

#[test]
fn content_languages_choose_the_alignment_by_the_ua_style_sheet() {
    let size = |lang: &str| {
        let trace = render(
            "p::first-letter{initial-letter:2}",
            &format!("<p lang={lang}>{TEXT}</p>"),
        );
        split(&trace, "L").0.runs[0].font_size
    };
    let alphabetic = size("en");
    assert_labelled_pt(
        "alphabetic alignment for English",
        alphabetic,
        Font::profile().letter_size(2.0),
    );
    let ideographic = size("ja");
    assert!(
        (ideographic - alphabetic).abs() > 0.1,
        "Japanese aligns to the ideographic ink box: {ideographic} vs {alphabetic} (§7.4.1)"
    );
    assert_labelled_pt(
        "a Latin script tag restores alphabetic alignment",
        size("ja-Latn"),
        alphabetic,
    );
    assert!(
        (size("hi") - alphabetic).abs() > 0.1,
        "Hindi aligns to the hanging baseline"
    );
}