ferri-pdf 0.1.12

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
use super::common;

use crate::document::{BlockContent, Paragraph, StyledDocument};
use crate::resources::FileResolver;
use crate::style::TextAlign;
use crate::text::{AtomicMetrics, Line, TextContext, TextError};
use common::{assert_pt, local_options};

const PROFILE: &str = "@font-face{font-family:Fixed;src:url('../assets/DejaVuSans.ttf')}html,body,p{margin:0;padding:0;font:10pt/10pt Fixed}";

fn document(css: &str, body: &str) -> StyledDocument {
    StyledDocument::parse(
        &format!(
            "<!doctype html><style>{}{PROFILE}{css}</style>{body}",
            common::PROFILE
        ),
        &local_options().base,
        &[],
        &FileResolver::default(),
    )
    .unwrap()
}

fn paragraphs(document: &StyledDocument) -> Vec<&Paragraph> {
    let mut pending = document.root().children().iter().rev().collect::<Vec<_>>();
    let mut paragraphs = Vec::new();
    while let Some(child) = pending.pop() {
        match child {
            BlockContent::Events(_) => {}
            BlockContent::Inline(paragraph) => paragraphs.push(paragraph),
            BlockContent::Block(block) | BlockContent::Positioned(block) => {
                pending.extend(block.children().iter().rev());
            }
        }
    }
    paragraphs
}

fn glyphs_from(lines: &[Line], start: usize) -> Vec<(usize, u32)> {
    let mut glyphs = lines
        .iter()
        .flat_map(|line| &line.runs)
        .filter(|run| run.source_range.start >= start)
        .flat_map(|run| {
            run.glyphs()
                .iter()
                .map(|glyph| (run.source_range.start + glyph.text_range.start, glyph.id))
        })
        .collect::<Vec<_>>();
    glyphs.sort_unstable();
    glyphs
}

#[test]
fn resumed_lines_use_new_widths_and_absolute_source_checkpoints() {
    let words = (0..12)
        .map(|index| format!("A{index:03}"))
        .collect::<Vec<_>>();
    let document = document("", &format!("<p>{}</p>", words.join(" ")));
    let paragraphs = paragraphs(&document);
    let source = paragraphs[0];
    let resolver = FileResolver::default();
    let context = TextContext::new(&document.styles().fonts, &resolver);
    let prepared = context.prepare_paragraph(source);
    let mut cursor = prepared.start();
    for (width, range, expected) in [
        (100.0, 0..15, words[..3].join(" ")),
        (200.0, 15..45, words[3..9].join(" ")),
        (100.0, 45..59, words[9..].join(" ")),
    ] {
        let mut lines = prepared.lines(cursor, width, &[]).unwrap();
        let line = lines.next().unwrap().unwrap();
        assert_eq!(
            line.range, range,
            "width {width} consumes original source bytes including trimmed spaces"
        );
        assert_eq!(line.text, expected);
        assert_pt(line.height, 10.0);
        cursor = lines.checkpoint();
    }
    assert!(prepared.lines(cursor, 300.0, &[]).unwrap().next().is_none());
}

#[test]
fn resumed_arabic_keeps_full_word_shaping_absolute_spans_and_unboxed_link_identity() {
    let document = document(
        "p{overflow-wrap:anywhere}a{display:contents}",
        "<p dir=rtl>A000 A001 A002 <a href='https://example.com/'><span>سسسس</span></a></p>",
    );
    let paragraphs = paragraphs(&document);
    let source = paragraphs[0];
    assert_eq!(
        source.links().len(),
        1,
        "display:contents links use source text ranges"
    );
    let resolver = FileResolver::default();
    let context = TextContext::new(&document.styles().fonts, &resolver);
    let prepared = context.prepare_paragraph(source);
    let arabic_start = source.text().find('س').unwrap();
    let reference = context.layout_paragraph(source, 300.0, &[]).unwrap();
    let mut prefix = prepared.lines(prepared.start(), 100.0, &[]).unwrap();
    let line = prefix.next().unwrap().unwrap();
    assert_eq!(line.range.end, arabic_start);
    let mut cursor = prefix.checkpoint();
    let mut resumed = Vec::new();
    for width in [6.0, 12.0, 6.0, 30.0] {
        let mut lines = prepared.lines(cursor, width, &[]).unwrap();
        if let Some(line) = lines.next() {
            let line = line.unwrap();
            assert!(
                !line.links.is_empty(),
                "each resumed Arabic fragment retains its link: text {:?}, range {:?}, runs {:?}, source links {:?}",
                line.text,
                line.range,
                line.runs
                    .iter()
                    .map(|run| (&run.text, run.source_range.clone(), run.x, run.width))
                    .collect::<Vec<_>>(),
                source
                    .links()
                    .iter()
                    .map(|link| (link.link, link.range.clone()))
                    .collect::<Vec<_>>()
            );
            assert!(
                line.links
                    .iter()
                    .all(|link| link.link == source.links()[0].link)
            );
            assert!(
                line.runs
                    .iter()
                    .all(|run| run.source_range.start >= arabic_start
                        && run.source_span < source.spans().len())
            );
            resumed.push(line);
            cursor = lines.checkpoint();
        }
    }
    assert!(prepared.lines(cursor, 30.0, &[]).unwrap().next().is_none());
    assert_eq!(
        resumed
            .iter()
            .map(|line| line.text.as_str())
            .collect::<String>(),
        "سسسس"
    );
    assert_eq!(
        glyphs_from(&resumed, arabic_start),
        glyphs_from(&reference, arabic_start),
        "resuming inside a word must preserve original joining forms, not reshape a sliced paragraph"
    );
}

#[test]
fn a_resumed_numeric_line_keeps_bidi_embedding_from_preceding_source() {
    let document = document("", "<p>A000 A001 A002 \u{202b}אבג 12 34 56 78\u{202c}</p>");
    let paragraphs = paragraphs(&document);
    let source = paragraphs[0];
    let resolver = FileResolver::default();
    let context = TextContext::new(&document.styles().fonts, &resolver);
    let prepared = context.prepare_paragraph(source);
    let numbers = source.text().find("12").unwrap();
    let mut prefix = prepared.lines(prepared.start(), 20.0, &[]).unwrap();
    let mut consumed = 0;
    while consumed < numbers {
        let line = prefix.next().unwrap().unwrap();
        consumed = line.range.end;
    }
    assert_eq!(consumed, numbers);
    let mut next = prepared.lines(prefix.checkpoint(), 60.0, &[]).unwrap();
    let line = next.next().unwrap().unwrap();
    assert_eq!(line.range, numbers..source.text().find("78").unwrap());
    assert_eq!(line.text, "12 34 56");
    let visual = line
        .runs
        .iter()
        .flat_map(|run| run.text.split_ascii_whitespace())
        .filter_map(|text| text.parse::<u32>().ok())
        .collect::<Vec<_>>();
    assert_eq!(
        visual,
        [56, 34, 12],
        "the earlier RLE is still active; a sliced LTR paragraph would reorder these as 12,34,56"
    );
}

#[test]
fn soft_hyphens_and_emergency_graphemes_resume_at_consumed_source_boundaries() {
    let document = document(
        "p{hyphens:manual}#comb{overflow-wrap:anywhere}",
        "<p>A000 A001 A002 ab\u{ad}cd A003</p><p id=comb>e\u{301}e\u{301}e\u{301}e\u{301}</p>",
    );
    let paragraphs = paragraphs(&document);
    let resolver = FileResolver::default();
    let context = TextContext::new(&document.styles().fonts, &resolver);
    let prepared = context.prepare_paragraph(paragraphs[0]);
    let mut first = prepared.lines(prepared.start(), 100.0, &[]).unwrap();
    assert_eq!(first.next().unwrap().unwrap().text, "A000 A001 A002");
    let mut hyphen = prepared.lines(first.checkpoint(), 18.0, &[]).unwrap();
    let line = hyphen.next().unwrap().unwrap();
    assert_eq!(line.text, "ab\u{2010}");
    assert_eq!(line.range, 15..19);
    let mut end = prepared.lines(hyphen.checkpoint(), 100.0, &[]).unwrap();
    assert_eq!(end.next().unwrap().unwrap().text, "cd A003");
    assert!(end.next().is_none());
    let prepared = context.prepare_paragraph(paragraphs[1]);
    let mut first = prepared.lines(prepared.start(), 1.0, &[]).unwrap();
    let line = first.next().unwrap().unwrap();
    assert_eq!((line.text.as_str(), line.range), ("e\u{301}", 0..3));
    let mut rest = prepared.lines(first.checkpoint(), 30.0, &[]).unwrap();
    let line = rest.next().unwrap().unwrap();
    assert_eq!(
        (line.text.as_str(), line.range),
        ("e\u{301}e\u{301}e\u{301}", 3..12)
    );
    assert!(rest.next().is_none());
}

#[test]
fn page_local_iteration_does_not_turn_a_wrapped_line_into_a_paragraph_last_line() {
    let document = document(
        "p{text-align:justify;text-align-last:right}",
        "<p>A000 A001 A002 A003<br>A004 A005</p>",
    );
    let paragraphs = paragraphs(&document);
    let resolver = FileResolver::default();
    let context = TextContext::new(&document.styles().fonts, &resolver);
    let prepared = context.prepare_paragraph(paragraphs[0]);
    let mut first = prepared.lines(prepared.start(), 100.0, &[]).unwrap();
    assert_eq!(first.next().unwrap().unwrap().align, TextAlign::Justify);
    let mut second = prepared.lines(first.checkpoint(), 200.0, &[]).unwrap();
    let line = second.next().unwrap().unwrap();
    assert_eq!((line.text.as_str(), line.align), ("A003", TextAlign::Right));
    let mut last = prepared.lines(second.checkpoint(), 100.0, &[]).unwrap();
    let line = last.next().unwrap().unwrap();
    assert_eq!(
        (line.text.as_str(), line.align),
        ("A004 A005", TextAlign::Right)
    );
    assert!(last.next().is_none());
}

#[test]
fn empty_inline_edges_are_consumed_once_even_when_the_next_page_changes_width() {
    let document = document("span{padding:2pt;border:1pt solid}", "<p><span></span></p>");
    let paragraphs = paragraphs(&document);
    assert_eq!(paragraphs.len(), 1);
    assert_eq!(paragraphs[0].text(), "");
    assert!(!paragraphs[0].boxes().is_empty());
    let resolver = FileResolver::default();
    let context = TextContext::new(&document.styles().fonts, &resolver);
    let prepared = context.prepare_paragraph(paragraphs[0]);
    let mut first = prepared.lines(prepared.start(), 20.0, &[]).unwrap();
    let line = first.next().unwrap().unwrap();
    assert_eq!(line.range, 0..0);
    assert!(line.height > 0.0);
    assert!(
        prepared
            .lines(first.checkpoint(), 200.0, &[])
            .unwrap()
            .next()
            .is_none()
    );
}

#[test]
fn resumed_atomic_metrics_keep_original_indices_and_ignore_consumed_objects() {
    let document = document(
        "span{display:inline-block}",
        "<p><span>First</span> <span>Second</span></p>",
    );
    let paragraphs = paragraphs(&document);
    assert_eq!(paragraphs[0].atomics().len(), 2);
    let resolver = FileResolver::default();
    let context = TextContext::new(&document.styles().fonts, &resolver);
    let prepared = context.prepare_paragraph(paragraphs[0]);
    let initial = [
        AtomicMetrics {
            width: 30.0,
            height: 10.0,
            baseline: 8.0,
            synthesized_baseline: false,
        },
        AtomicMetrics {
            width: 40.0,
            height: 10.0,
            baseline: 8.0,
            synthesized_baseline: false,
        },
    ];
    let changed = [
        AtomicMetrics {
            width: 99.0,
            ..initial[0]
        },
        AtomicMetrics {
            width: 20.0,
            ..initial[1]
        },
    ];
    let mut first = prepared.lines(prepared.start(), 35.0, &initial).unwrap();
    let line = first.next().unwrap().unwrap();
    assert_eq!(line.atomics.len(), 1);
    assert_eq!(line.atomics[0].index, 0);
    let mut rest = prepared.lines(first.checkpoint(), 25.0, &changed).unwrap();
    let line = rest.next().unwrap().unwrap();
    assert_eq!(line.atomics.len(), 1);
    assert_eq!((line.atomics[0].index, line.atomics[0].width), (1, 20.0));
    assert!(rest.next().is_none());
}

#[test]
fn a_checkpoint_from_another_paragraph_is_rejected_before_layout() {
    let document = document("", "<p>Same text</p><p>Same text</p>");
    let paragraphs = paragraphs(&document);
    let resolver = FileResolver::default();
    let context = TextContext::new(&document.styles().fonts, &resolver);
    let first = context.prepare_paragraph(paragraphs[0]);
    let second = context.prepare_paragraph(paragraphs[1]);
    assert!(matches!(
        second.lines(first.start(), 100.0, &[]),
        Err(TextError::ParagraphMismatch)
    ));
}

#[test]
fn producing_one_line_does_not_shape_an_unrequested_suffix_or_retry_a_denied_fallback() {
    let words = (0..30)
        .map(|index| format!("A{index:03}"))
        .collect::<Vec<_>>()
        .join(" ");
    let document = document(
        "@font-face{font-family:Blocked;src:url(blocked.ttf)}p{font-family:Fixed,Blocked}",
        &format!("<p>{words} 漢</p>"),
    );
    let paragraphs = paragraphs(&document);
    struct DeniedFallback(std::cell::Cell<usize>);
    impl crate::resources::ResourceResolver for DeniedFallback {
        fn resolve(
            &self,
            reference: &str,
            base: &crate::resources::ResourceBase,
        ) -> Result<crate::resources::Resource, crate::resources::ResourceError> {
            if reference.ends_with("blocked.ttf") {
                self.0.set(self.0.get() + 1);
                return Err(crate::resources::ResourceError::Denied(
                    base.resolve(reference)?,
                ));
            }
            crate::resources::ResourceResolver::resolve(&FileResolver::default(), reference, base)
        }
    }
    let resolver = DeniedFallback(std::cell::Cell::new(0));
    let context = TextContext::new(&document.styles().fonts, &resolver);
    let prepared = context.prepare_paragraph(paragraphs[0]);
    let mut lines = prepared.lines(prepared.start(), 100.0, &[]).unwrap();
    assert_eq!(lines.next().unwrap().unwrap().text, "A000 A001 A002");
    assert_eq!(
        resolver.0.get(),
        0,
        "the unrequested suffix must not load its fallback"
    );
    let rest: Vec<_> = lines
        .map(|line| line.expect("a denied fallback face is unavailable, not fatal"))
        .collect();
    assert!(
        rest.last().is_some_and(|line| line.text.ends_with('漢')),
        "the final character falls back past the denied face: {:?}",
        rest.iter().map(|line| &line.text).collect::<Vec<_>>()
    );
    assert_eq!(
        resolver.0.get(),
        1,
        "a denied fallback is requested once, when a character first needs it"
    );
    assert!(
        matches!(
            document.styles().fonts.take_failures().as_slice(),
            [failure] if matches!(
                failure.error,
                crate::fonts::FontError::Resource(crate::resources::ResourceError::Denied(_))
            )
        ),
        "the denial is recorded for the document's diagnostics"
    );
}

#[test]
fn pathological_missing_combining_sequences_cannot_trigger_unbounded_matching() {
    const COMBINING_MARKS: usize = 65_536;
    let text = format!("\u{ef00}{}", "\u{1ab0}".repeat(COMBINING_MARKS));
    let document = document("", &format!("<p>{text}</p>"));
    let paragraphs = paragraphs(&document);
    let resolver = FileResolver::default();
    let context = TextContext::new(&document.styles().fonts, &resolver);
    let result = context.layout_paragraph(paragraphs[0], 100.0, &[]);
    assert!(
        matches!(
            result,
            Err(TextError::GlyphMatchingLimit {
                limit: crate::text::MAX_GLYPH_MATCH_WORK
            })
        ),
        "a pathological unsupported combining tail must hit the typed matching work bound"
    );
    assert!(
        matches!(
            context.layout_paragraph(paragraphs[0], 100.0, &[]),
            Err(TextError::GlyphMatchingLimit { .. })
        ),
        "the work failure is sticky across the same context"
    );
}

#[test]
fn resumed_css_bidi_overrides_preserve_visual_order_and_original_source_positions() {
    let words = (0..30)
        .map(|index| format!("A{index:02}"))
        .collect::<Vec<_>>()
        .join(" ");
    let document = document(
        "",
        &format!("<p><span style='direction:rtl;unicode-bidi:isolate-override'>{words}</span></p>"),
    );
    let paragraphs = paragraphs(&document);
    let resolver = FileResolver::default();
    let context = TextContext::new(&document.styles().fonts, &resolver);
    let prepared = context.prepare_paragraph(paragraphs[0]);
    let mut first = prepared.lines(prepared.start(), 100.0, &[]).unwrap();
    let head = first.next().unwrap().unwrap();
    let checkpoint = first.checkpoint();
    let mut lines = vec![head];
    lines.extend(
        prepared
            .lines(checkpoint, 60.0, &[])
            .unwrap()
            .collect::<Result<Vec<_>, _>>()
            .unwrap(),
    );
    assert!(
        lines.len() > 3,
        "the override must continue across several differently sized fragmentainers"
    );
    for line in &lines {
        let visual: String = line
            .runs
            .iter()
            .flat_map(|run| {
                run.glyphs()
                    .iter()
                    .map(|glyph| &run.text[glyph.text_range.clone()])
            })
            .collect();
        assert_eq!(
            visual,
            line.text.chars().rev().collect::<String>(),
            "each continued line must retain its RTL override: {:?}",
            line.range
        );
    }
    assert_eq!(
        lines
            .iter()
            .flat_map(|line| line.text.split_whitespace())
            .collect::<Vec<_>>(),
        words.split_whitespace().collect::<Vec<_>>()
    );
    let source_glyphs = glyphs_from(&lines, 0);
    let offsets = source_glyphs
        .iter()
        .filter(|(offset, _)| paragraphs[0].text().as_bytes()[*offset] != b' ')
        .map(|(offset, _)| *offset)
        .collect::<Vec<_>>();
    let expected = paragraphs[0]
        .text()
        .char_indices()
        .filter(|(_, ch)| *ch != ' ')
        .map(|(offset, _)| offset)
        .collect::<Vec<_>>();
    assert_eq!(
        offsets, expected,
        "source glyph positions must have neither injected controls nor omissions across the checkpoint"
    );
}

#[test]
fn pathological_css_bidi_expansion_hits_a_sticky_typed_limit() {
    const SCOPES: usize = 128;
    const BREAKS: usize = 90_000;
    let body = format!(
        "<p style='white-space:pre'>{}{}{}</p><p>Ordinary</p>",
        "<span style='unicode-bidi:embed'>".repeat(SCOPES),
        "a\n".repeat(BREAKS),
        "</span>".repeat(SCOPES)
    );
    let document = document("", &body);
    let paragraphs = paragraphs(&document);
    let resolver = FileResolver::default();
    let context = TextContext::new(&document.styles().fonts, &resolver);
    let ready = context.prepare_paragraph(paragraphs[1]);
    let mut live = ready.lines(ready.start(), 100.0, &[]).unwrap();
    let prepared = context.prepare_paragraph(paragraphs[0]);
    assert!(
        matches!(
            prepared.lines(prepared.start(), 100.0, &[]),
            Err(TextError::BidiExpansionLimit {
                limit: crate::document::MAX_INLINE_TEXT_BYTES
            })
        ),
        "reopening deep CSS scopes must hit the typed expansion bound before running UBA on an unbounded stream"
    );
    let next = context.prepare_paragraph(paragraphs[1]);
    assert!(
        matches!(
            next.lines(next.start(), 100.0, &[]),
            Err(TextError::BidiExpansionLimit { .. })
        ),
        "exhausted bidi work must remain terminal for the shared text context"
    );
    assert!(
        matches!(
            ready.lines(ready.start(), 100.0, &[]),
            Err(TextError::BidiExpansionLimit { .. })
        ),
        "a previously prepared paragraph must not bypass the context's terminal work bound"
    );
    assert!(
        matches!(live.next(), Some(Err(TextError::BidiExpansionLimit { .. }))),
        "an already-created iterator must observe shared exhaustion before emitting another line"
    );
    assert!(
        live.next().is_none(),
        "the failed iterator must remain terminated"
    );
}

#[test]
fn leader_intrinsic_widths_keep_one_pattern_and_do_not_mutate_after_expansion() {
    let document = document("p::after{content:leader('.') 'Z'}", "<p>A</p>");
    let source = paragraphs(&document)[0];
    let resolver = FileResolver::default();
    let context = TextContext::new(&document.styles().fonts, &resolver);
    let minimum = Paragraph::generated(".Z", source.style()).unwrap().unwrap();
    let maximum = Paragraph::generated("A", source.style()).unwrap().unwrap();
    let expected_min = context.intrinsic_widths(&minimum, &[], &[]).unwrap().max;
    let expected_max = expected_min + context.intrinsic_widths(&maximum, &[], &[]).unwrap().max;
    let before = context.intrinsic_widths(source, &[], &[]).unwrap();
    assert_pt(before.min, expected_min);
    assert_pt(before.max, expected_max);
    let prepared = context.prepare_paragraph(source);
    let wide = prepared
        .lines(prepared.start(), 200.0, &[])
        .unwrap()
        .next()
        .unwrap()
        .unwrap();
    assert!(wide.text.matches('.').count() > 20);
    let narrow: Vec<_> = prepared
        .lines(prepared.start(), before.min, &[])
        .unwrap()
        .map(Result::unwrap)
        .collect();
    assert_eq!(
        narrow
            .iter()
            .map(|line| line.text.as_str())
            .collect::<Vec<_>>(),
        ["A", ".Z"]
    );
    let after = context.intrinsic_widths(source, &[], &[]).unwrap();
    assert_pt(after.min, before.min);
    assert_pt(after.max, before.max);
    assert_eq!(source.text(), "A.Z");
}

#[test]
fn indentation_keeps_first_and_forced_line_state_across_resumed_widths() {
    for (keywords, indents) in [
        ("", [20.0, 0.0, 0.0, 0.0]),
        ("each-line", [20.0, 0.0, 40.0, 0.0]),
        ("each-line hanging", [0.0, 30.0, 0.0, 10.0]),
    ] {
        let document = document(
            &format!("p{{text-indent:20% {keywords}}}"),
            "<p>MMMM MMMM<br>MMMM MMMM</p>",
        );
        let resolver = FileResolver::default();
        let context = TextContext::new(&document.styles().fonts, &resolver);
        let prepared = context.prepare_paragraph(paragraphs(&document)[0]);
        let mut cursor = prepared.start();
        for (basis, expected) in [100.0, 150.0, 200.0, 50.0].into_iter().zip(indents) {
            let mut stream = prepared
                .lines_in_block(cursor, 60.0, basis, [0.0; 2], &[])
                .unwrap();
            let line = stream.next().unwrap().unwrap();
            assert_eq!(line.text, "MMMM", "each checkpoint must consume one word");
            assert_pt(line.indent, expected);
            cursor = stream.checkpoint();
        }
        assert!(prepared.lines(cursor, 100.0, &[]).unwrap().next().is_none());
    }
}

#[test]
fn intrinsic_indentation_uses_zero_percentage_and_the_selected_line() {
    let document = document("", "<p>MMMM MMMM</p>");
    let resolver = FileResolver::default();
    let context = TextContext::new(&document.styles().fonts, &resolver);
    let source = paragraphs(&document)[0];
    let baseline = context.intrinsic_widths(source, &[], &[]).unwrap();
    for (amount, hanging, each_line, min_extra, max_extra) in [
        (
            crate::style::LengthPercentage::Length(20.0),
            false,
            false,
            20.0,
            20.0,
        ),
        (
            crate::style::LengthPercentage::Percentage(0.2),
            false,
            false,
            0.0,
            0.0,
        ),
        (
            crate::style::LengthPercentage::Length(20.0),
            true,
            false,
            20.0,
            0.0,
        ),
        (
            crate::style::LengthPercentage::Length(-10.0),
            false,
            false,
            0.0,
            -10.0,
        ),
    ] {
        let mut style = crate::style::Style::clone(source.style());
        style.text_indent = crate::style::TextIndent {
            amount,
            hanging,
            each_line,
        };
        let paragraph = Paragraph::generated(source.text(), &style)
            .unwrap()
            .unwrap();
        let widths = context.intrinsic_widths(&paragraph, &[], &[]).unwrap();
        assert_pt(widths.min, baseline.min + min_extra);
        assert_pt(widths.max, baseline.max + max_extra);
    }
}

/// A paragraph of `words` words, every other one bold, so each line holds many spans.
fn alternating_spans(words: usize) -> StyledDocument {
    let body = (0..words)
        .map(|index| {
            if index % 2 == 0 {
                format!("w{index:03}")
            } else {
                format!("<b>w{index:03}</b>")
            }
        })
        .collect::<Vec<_>>()
        .join(" ");
    document("", &format!("<p>{body}</p>"))
}

/// The runs the shaper shapes to lay `prepared`'s paragraph out at `width`, and its lines.
fn shaped_runs(
    prepared: &crate::text::PreparedParagraph<'_, '_, '_>,
    width: f32,
) -> (usize, usize) {
    let (lines, runs) = crate::work::measured(crate::work::Work::ShapedRun, || {
        prepared
            .lines(prepared.start(), width, &[])
            .unwrap()
            .collect::<Result<Vec<_>, _>>()
            .unwrap()
    });
    (runs, lines.len())
}

#[test]
fn line_candidates_shape_each_whole_span_once() {
    // Every candidate end of a line reshapes the line from its start; the spans before the
    // candidate end shape alike in each, so shaping must grow with the spans, not with the
    // spans times the candidates.
    crate::work::assert_linear(
        "runs shaped for one line of alternating spans",
        64,
        |words| {
            let document = alternating_spans(words);
            let resolver = FileResolver::default();
            let context = TextContext::new(&document.styles().fonts, &resolver);
            let prepared = context.prepare_paragraph(paragraphs(&document)[0]);
            let (runs, lines) = shaped_runs(&prepared, 1.0e5);
            assert_eq!(lines, 1, "{words} words fit one line");
            runs
        },
    );
}

#[test]
fn relaying_a_paragraph_reshapes_only_the_pieces_line_ends_clip() {
    const WORDS: usize = 120;
    let document = alternating_spans(WORDS);
    let resolver = FileResolver::default();
    let context = TextContext::new(&document.styles().fonts, &resolver);
    let prepared = context.prepare_paragraph(paragraphs(&document)[0]);
    let (first, lines) = shaped_runs(&prepared, 200.0);
    let (second, relaid) = shaped_runs(&prepared, 200.0);
    assert_eq!(relaid, lines, "the same width lays out the same lines");
    // Each candidate end tried, one per word and the overflowing one per line, clips the
    // piece it ends in; every other piece was shaped by the first layout.
    let clipped = WORDS + lines;
    assert!(
        second <= clipped,
        "relaying {WORDS} words on {lines} lines shaped {second} runs after the first layout \
         shaped {first}; at most {clipped} candidate ends clip a piece"
    );
}

#[test]
fn runs_with_the_same_settings_share_their_shape_plan() {
    // Making a plan costs more than shaping a word with it, so the plans a paragraph makes
    // follow its faces and settings, not its runs.
    let shaped = |words| {
        let document = alternating_spans(words);
        let resolver = FileResolver::default();
        let context = TextContext::new(&document.styles().fonts, &resolver);
        let prepared = context.prepare_paragraph(paragraphs(&document)[0]);
        let ((runs, lines), plans) = crate::work::measured(crate::work::Work::ShapePlan, || {
            shaped_runs(&prepared, 60.0)
        });
        assert!(lines > words / 4, "{words} words take {lines} lines");
        (runs, plans)
    };
    let (few_runs, few_plans) = shaped(32);
    let (many_runs, many_plans) = shaped(128);
    assert!(
        many_runs > 2 * few_runs,
        "128 words shaped {many_runs} runs, 32 words {few_runs}"
    );
    assert!(
        few_plans > 0 && many_plans == few_plans,
        "32 words in {few_runs} runs made {few_plans} plans; 128 words in {many_runs} runs \
         made {many_plans}"
    );
}