ferri-pdf 0.2.1

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

use crate::document::OBJECT_REPLACEMENT_CHARACTER;
use crate::graphics::ImagePaint;
use crate::images::Image;
use crate::layout::ViewportPaint;
use crate::{DisplayItem, LayoutTrace, RenderDiagnostic, RenderOptions, render_html};
use common::{assert_labelled_pt, local_options, lossy_options};

/// A 288pt-wide page area with a 12pt/18pt body font.
const PAGE: &str = "@page{size:360pt 480pt;margin:36pt}";
const PIXEL: f32 = 0.75;
const IFRAME_BORDER: f32 = 2.0 * PIXEL;
const IMAGE: &str = "../assets/image-pattern.png";
const IMAGE_PIXELS: [f32; 2] = [80.0, 40.0];

fn render(body: &str) -> crate::RenderOutput {
    render_with(body, &local_options())
}

fn render_with(body: &str, options: &RenderOptions) -> crate::RenderOutput {
    render_html(
        &format!(
            "<!doctype html><style>{}{PAGE}</style>{body}",
            common::PROFILE
        ),
        options,
    )
    .unwrap_or_else(|error| panic!("rendering `{body}`: {error}"))
}

fn trace(body: &str) -> LayoutTrace {
    render(body).layout.unwrap()
}

fn images(trace: &LayoutTrace) -> Vec<&ImagePaint> {
    trace
        .display_lists
        .iter()
        .flatten()
        .filter_map(|item| match item {
            DisplayItem::Image(paint) => Some(paint),
            _ => None,
        })
        .collect()
}

fn viewports(trace: &LayoutTrace) -> Vec<(&ImagePaint, &ViewportPaint)> {
    images(trace)
        .into_iter()
        .filter_map(|paint| match paint.image.as_ref() {
            Image::Viewport(view) => Some((paint, view.as_ref())),
            _ => None,
        })
        .collect()
}

fn texts(lines: &[crate::TextLine]) -> Vec<&str> {
    lines.iter().map(|line| line.text.trim()).collect()
}

fn outer_texts(trace: &LayoutTrace) -> Vec<&str> {
    trace.pages.iter().flat_map(|page| texts(page)).collect()
}

fn boxes(view: &ViewportPaint, rgb: [u8; 3]) -> Vec<crate::Rect> {
    view.items
        .iter()
        .filter_map(|item| match item {
            DisplayItem::Box(paint) if paint.decoration.background.rgb == rgb => Some(paint.rect),
            _ => None,
        })
        .collect()
}

#[test]
fn iframes_show_their_document_in_a_default_size_inset_bordered_viewport() {
    let trace = trace(
        "<p>before</p><iframe srcdoc=\"<style>body{margin:0;font:10pt/20pt serif}</style><p>Nested</p>\"></iframe><p>after</p>",
    );
    let [(paint, view)] = viewports(&trace)[..] else {
        panic!("one iframe viewport, got {:?}", images(&trace));
    };
    let clip = paint
        .clip
        .as_ref()
        .expect("replaced content clips to its content box")
        .rect;
    assert_labelled_pt("viewport width", paint.rect.width, 300.0 * PIXEL);
    assert_labelled_pt("viewport height", paint.rect.height, 150.0 * PIXEL);
    assert_labelled_pt("content clip width", clip.width, 300.0 * PIXEL);
    assert_labelled_pt(
        "viewport left after the 2px inset border",
        paint.rect.x,
        36.0 + IFRAME_BORDER,
    );
    assert_eq!(
        [view.area.width, view.area.height],
        [paint.rect.width, paint.rect.height],
        "the nested page area is the whole viewport"
    );
    assert_eq!(
        texts(&view.lines),
        ["Nested"],
        "the nested document lays out in the viewport"
    );
    assert_labelled_pt(
        "nested text at the viewport's left edge",
        view.lines[0].x,
        0.0,
    );
    assert_eq!(
        outer_texts(&trace).join("|"),
        format!("before|{OBJECT_REPLACEMENT_CHARACTER}|after"),
        "nested text belongs to the viewport, not the page"
    );
}

#[test]
fn iframe_viewports_fill_their_content_box_whatever_the_object_fit() {
    // CSS Images 3 §5.5: a nested navigable has no natural dimensions, so its concrete
    // object size is the content box whatever `object-fit` asks for.
    for fit in ["fill", "none", "contain", "cover", "scale-down"] {
        let trace = trace(&format!(
            "<iframe style='width:100px;height:60px;object-fit:{fit}' \
             srcdoc='<p>Nested'></iframe>"
        ));
        let [(paint, view)] = viewports(&trace)[..] else {
            panic!(
                "object-fit {fit}: one iframe viewport, got {:?}",
                images(&trace)
            );
        };
        let clip = paint.clip.as_ref().expect("content-box clip").rect;
        assert_eq!(
            [
                paint.rect.x,
                paint.rect.y,
                paint.rect.width,
                paint.rect.height
            ],
            [clip.x, clip.y, clip.width, clip.height],
            "object-fit {fit}: the viewport paints exactly over the content box"
        );
        assert_eq!(
            [view.area.width, view.area.height],
            [paint.rect.width, paint.rect.height],
            "object-fit {fit}: the nested page is drawn at its own size, unscaled"
        );
    }
}

#[test]
fn nested_documents_evaluate_media_queries_and_viewport_units_against_their_viewport() {
    let nested = "<style>@page{margin:50pt}body{margin:0}div{background:rgb(0,0,255)}\
        @media (width:144pt) and (height:90pt) and (overflow-block:none){div{background:rgb(0,128,0)}}\
        div{width:50vw;height:20vh}</style><div></div>";
    let trace = trace(&format!(
        "<iframe style='width:50%;height:90pt;border:0' srcdoc=\"{nested}\"></iframe>"
    ));
    let [(paint, view)] = viewports(&trace)[..] else {
        panic!("one viewport");
    };
    assert_labelled_pt("percentage width of the page area", paint.rect.width, 144.0);
    let [green] = boxes(view, [0, 128, 0])[..] else {
        panic!(
            "the 144pt by 90pt continuous viewport must match the media query: {:?}",
            view.items
        );
    };
    assert_eq!(
        [green.x, green.y, green.width, green.height],
        [0.0, 0.0, 72.0, 18.0],
        "viewport units resolve against the viewport and @page margins do not apply"
    );
}

#[test]
fn zoomed_frames_resolve_nested_viewport_units_in_unzoomed_coordinates() {
    let nested = "<style>body{margin:0}div{width:50vw;height:50vh;background:blue}@media(width:100pt) and (height:40pt){div{background:rgb(0,128,0)}}p{margin:0;font:10pt/12pt serif}</style><div></div><p>Nested</p>";
    let trace = trace(&format!(
        "<iframe style='display:block;border:0;zoom:2;width:100pt;height:40pt' srcdoc=\"{nested}\"></iframe>"
    ));
    let [(paint, view)] = viewports(&trace)[..] else {
        panic!("one zoomed viewport");
    };
    assert_eq!([paint.rect.width, paint.rect.height], [200.0, 80.0]);
    assert_eq!(
        [view.area.width, view.area.height],
        [100.0, 40.0],
        "nested CSS viewport excludes embedding zoom"
    );
    let [green] = boxes(view, [0, 128, 0])[..] else {
        panic!(
            "nested media query must match the unzoomed viewport: {:?}",
            view.items
        );
    };
    assert_eq!([green.width, green.height], [50.0, 20.0]);
    assert_eq!(texts(&view.lines), ["Nested"]);
    assert_eq!(
        view.lines[0].runs[0].font_size, 10.0,
        "nested font metrics are zoomed when composited"
    );
}

#[test]
fn nested_documents_are_continuous_media_clipped_to_the_viewport() {
    let nested = "<style>body{margin:0}p{margin:0;height:40pt}h1{break-before:page;margin:0;font-size:10pt}\
        </style><p>first</p><h1>second</h1><p style='height:400pt'>tall</p><p>below</p>";
    let output = render(&format!(
        "<iframe style='width:200pt;height:60pt' srcdoc=\"{nested}\"></iframe>"
    ));
    let trace = output.layout.unwrap();
    assert_eq!(
        trace.pages.len(),
        1,
        "an iframe is monolithic and never fragments the page"
    );
    let [(paint, view)] = viewports(&trace)[..] else {
        panic!("one viewport");
    };
    let second = view
        .lines
        .iter()
        .find(|line| line.text.trim() == "second")
        .expect("a forced break does not move content out of continuous media");
    assert!(
        second.baseline > 40.0 && second.baseline < 60.0,
        "the heading follows the first paragraph in the same flow, at {}",
        second.baseline
    );
    let clip = paint.clip.as_ref().unwrap().rect;
    assert_eq!(
        [clip.width, clip.height],
        [200.0, 60.0],
        "overflow beyond the viewport is clipped to the iframe's content box"
    );
}

#[test]
fn navigables_never_load_an_ancestor_document() {
    let directory = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/oracle/fixtures");
    let url = crate::Url::from_file_path(directory.join("self.html")).unwrap();
    let options = RenderOptions {
        base: url.clone().into(),
        include_layout: true,
        ..Default::default()
    };
    let trace = render_html(
        &format!("<p>outer</p><iframe src='{url}#fragment'></iframe>"),
        &options,
    )
    .expect("a self-referencing iframe keeps its initial about:blank document")
    .layout
    .unwrap();
    let [(_, view)] = viewports(&trace)[..] else {
        panic!("one viewport");
    };
    assert!(
        view.lines.is_empty(),
        "the ancestor URL must not load again, fragment aside"
    );
}

#[test]
fn srcdoc_nesting_is_bounded() {
    let nest = |depth: usize| {
        (0..depth).fold(String::from("<p>leaf</p>"), |inner, _| {
            format!(
                "<iframe srcdoc=\"{}\"></iframe>",
                inner.replace('&', "&amp;").replace('"', "&quot;")
            )
        })
    };
    let deepest = trace_depth(&render(&nest(crate::document::frames::MAX_NAVIGABLE_DEPTH)));
    assert_eq!(
        deepest,
        crate::document::frames::MAX_NAVIGABLE_DEPTH,
        "every permitted level lays out"
    );
    let output = render_with(
        &nest(crate::document::frames::MAX_NAVIGABLE_DEPTH + 1),
        &lossy_options(),
    );
    assert_eq!(
        trace_depth(&output),
        crate::document::frames::MAX_NAVIGABLE_DEPTH,
        "the iframe beyond the limit represents nothing; every permitted level still lays out"
    );
    assert!(
        output.diagnostics.iter().any(|diagnostic| matches!(
            diagnostic,
            RenderDiagnostic::NavigableDepth { limit }
                if *limit == crate::document::frames::MAX_NAVIGABLE_DEPTH
        )),
        "nesting beyond the limit is reported: {:?}",
        output.diagnostics
    );
}

/// How many viewports nest inside the first one.
fn trace_depth(output: &crate::RenderOutput) -> usize {
    let trace = output.layout.as_ref().unwrap();
    let mut depth = 0;
    let mut items: &[DisplayItem] = &trace.display_lists[0];
    while let Some(view) = items.iter().find_map(|item| match item {
        DisplayItem::Image(paint) => match paint.image.as_ref() {
            Image::Viewport(view) => Some(view),
            _ => None,
        },
        _ => None,
    }) {
        depth += 1;
        items = &view.items;
    }
    depth
}

#[test]
fn objects_fall_back_to_their_children_until_a_resource_renders() {
    let trace = trace(&format!(
        "<object data=missing.png>one <object data='data:application/octet-stream,%00%01'>two \
         <object data='{IMAGE}' type=application/x-unsupported>three \
         <object data='{IMAGE}'>hidden</object></object></object></object> <object>no data</object>"
    ));
    assert_eq!(
        outer_texts(&trace),
        [format!(
            "one two three {OBJECT_REPLACEMENT_CHARACTER} no data"
        )],
        "a missing resource, a binary type and an unsupported type attribute all show fallback"
    );
    let decoded: Vec<_> = images(&trace)
        .into_iter()
        .filter(|paint| matches!(paint.image.as_ref(), Image::Raster(_)))
        .collect();
    let [image] = decoded[..] else {
        panic!("the innermost object represents its image");
    };
    assert_eq!(
        [image.rect.width, image.rect.height],
        IMAGE_PIXELS.map(|pixels| pixels * PIXEL),
        "an object image has the image's natural size"
    );
    let output = render("<iframe src=missing.html></iframe><object data=missing.png></object>");
    let unavailable: Vec<_> = output
        .diagnostics
        .iter()
        .filter_map(|diagnostic| match diagnostic {
            RenderDiagnostic::UnavailableEmbedded { reference, .. } => Some(reference.as_str()),
            _ => None,
        })
        .collect();
    assert_eq!(
        unavailable.len(),
        2,
        "fetch failures are diagnostics: {:?}",
        output.diagnostics
    );
}

#[test]
fn objects_and_iframes_render_html_svg_text_and_image_documents() {
    let svg = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 2 1'><rect width='2' height='1'/></svg>";
    let trace = trace(&format!(
        "<object style='width:100pt;height:80pt' data=\"{svg}\"></object>\
         <iframe src='data:text/plain,a%20%3Cb%3E'></iframe>\
         <iframe src='{IMAGE}'></iframe>\
         <iframe src='data:application/pdf,%25PDF-1.7'></iframe>"
    ));
    let views = viewports(&trace);
    let [svg_view, text_view, image_view, pdf_view] = [0, 1, 2, 3].map(|index| views[index].1);
    let [DisplayItem::Image(root)] = &svg_view.items[..] else {
        panic!(
            "an SVG document paints its root element: {:?}",
            svg_view.items
        );
    };
    assert_eq!(
        [root.rect.width, root.rect.height],
        [100.0, 80.0],
        "an SVG root without width or height fills the viewport"
    );
    assert_eq!(
        texts(&text_view.lines),
        ["a <b>"],
        "text documents render their text verbatim"
    );
    assert!(
        image_view
            .items
            .iter()
            .any(|item| matches!(item, DisplayItem::Image(paint)
            if matches!(paint.image.as_ref(), Image::Raster(_)))),
        "image documents show the image"
    );
    assert!(
        pdf_view.items.is_empty() && pdf_view.lines.is_empty(),
        "types with no viewer are handed off, leaving about:blank"
    );
    let output = render("<iframe src='data:text/xml,<root/>'></iframe>");
    let trace = output.layout.as_ref().unwrap();
    let [(_, xml_view)] = viewports(trace)[..] else {
        panic!("the iframe keeps its viewport: {:?}", images(trace));
    };
    assert!(
        xml_view.items.is_empty() && xml_view.lines.is_empty(),
        "an XML document without dedicated processing shows nothing"
    );
    assert!(
        output.diagnostics.iter().any(|diagnostic| matches!(
            diagnostic,
            RenderDiagnostic::UnrenderedDocument { media_type, .. } if media_type == "text/xml"
        )),
        "the unrendered document is reported: {:?}",
        output.diagnostics
    );
}

#[test]
fn embeds_of_image_types_show_the_image_in_their_content_navigable() {
    let svg = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 2 1'><rect width='2' height='1'/></svg>";
    // HTML §4.8.6: the type attribute is consulted first, then the resource's Content-Type.
    let trace = trace(&format!(
        "<embed src='{IMAGE}'>\
         <embed src='{IMAGE}' type=application/x-plugin style='width:120pt;height:60pt'>\
         <embed src=\"{svg}\" style='width:100pt;height:80pt'>"
    ));
    let views = viewports(&trace);
    let [(default, image_view), (sized, typed_view), (_, svg_view)] = views[..] else {
        panic!(
            "three embed viewports, got {:?}",
            images(&trace)
                .iter()
                .map(|paint| paint.image.as_ref())
                .collect::<Vec<_>>()
        );
    };
    assert_eq!(
        [default.rect.width, default.rect.height],
        [300.0 * PIXEL, 150.0 * PIXEL],
        "the navigable has the default object size"
    );
    assert_eq!(
        [sized.rect.width, sized.rect.height],
        [120.0, 60.0],
        "the navigable takes the embed's dimensions"
    );
    for (view, label) in [(image_view, "untyped"), (typed_view, "unsupported type")] {
        let rasters: Vec<_> = view
            .items
            .iter()
            .filter_map(|item| match item {
                DisplayItem::Image(paint) if matches!(paint.image.as_ref(), Image::Raster(_)) => {
                    Some(paint.rect)
                }
                _ => None,
            })
            .collect();
        let [rect] = rasters[..] else {
            panic!("{label}: the image document shows the image once: {rasters:?}");
        };
        assert_eq!(
            [rect.x, rect.y, rect.width, rect.height],
            [
                8.0 * PIXEL,
                8.0 * PIXEL,
                IMAGE_PIXELS[0] * PIXEL,
                IMAGE_PIXELS[1] * PIXEL
            ],
            "{label}: the image document's body margin places the image at its natural size"
        );
    }
    let [DisplayItem::Image(root)] = &svg_view.items[..] else {
        panic!("an SVG document paints its root: {:?}", svg_view.items);
    };
    assert_eq!([root.rect.width, root.rect.height], [100.0, 80.0]);
}

#[test]
fn embeds_without_a_plugin_display_an_indication_and_represent_nothing() {
    let trace = trace(
        "<embed type=application/x-plugin style='width:40pt;height:20pt'>\
         <embed src='data:text/html,<p>page'>\
         <embed src='data:text/plain,text'>\
         <embed><embed src=''><embed src=missing.swf>",
    );
    let embeds = images(&trace);
    let kinds: Vec<_> = embeds
        .iter()
        .map(|paint| match paint.image.as_ref() {
            Image::Svg(_) => "indication",
            Image::Transparent => "nothing",
            other => panic!("an embed without a plugin shows {other:?}"),
        })
        .collect();
    assert_eq!(
        kinds,
        [
            "indication",
            "indication",
            "indication",
            "nothing",
            "nothing",
            "nothing"
        ]
    );
    assert_eq!([embeds[0].rect.width, embeds[0].rect.height], [40.0, 20.0]);
    assert_eq!(
        [embeds[1].rect.width, embeds[1].rect.height],
        [300.0 * PIXEL, 150.0 * PIXEL],
        "embedded content has the default object size"
    );
}

#[test]
fn videos_show_their_poster_and_audio_exposes_controls_one_line_high() {
    let trace = trace(&format!(
        "<video poster='{IMAGE}'></video><video poster='{IMAGE}' style='width:120pt;height:90pt'></video><video></video><audio></audio>"
    ));
    let paints = images(&trace);
    let [natural, contained, empty, controls] = paints[..] else {
        panic!("four media elements: {paints:?}");
    };
    assert_eq!(
        [natural.rect.width, natural.rect.height],
        IMAGE_PIXELS.map(|pixels| pixels * PIXEL),
        "the playback area takes the poster's natural size"
    );
    let clip = contained.clip.as_ref().unwrap().rect;
    assert_eq!(
        [contained.rect.width, contained.rect.height],
        [120.0, 60.0],
        "object-fit: contain"
    );
    assert_labelled_pt("poster centred vertically", contained.rect.y - clip.y, 15.0);
    assert!(matches!(empty.image.as_ref(), Image::Transparent));
    assert_eq!(
        [empty.rect.width, empty.rect.height],
        [300.0 * PIXEL, 150.0 * PIXEL],
        "a video without a poster has the default object size"
    );
    assert!(matches!(controls.image.as_ref(), Image::Svg(_)));
    assert_eq!(
        [controls.rect.width, controls.rect.height],
        [8.0 * 18.0, 18.0],
        "audio controls are one 18pt line high, eight control heights wide"
    );
}

#[test]
fn canvases_render_their_fallback_content_with_scripting_disabled() {
    let trace = trace("<p>a <canvas width=10 height=10>fallback <b>text</b></canvas> z</p>");
    assert_eq!(outer_texts(&trace), ["a fallback text z"]);
    assert!(
        images(&trace).is_empty(),
        "a fallback canvas is not replaced"
    );
}

#[test]
fn embedded_canvases_are_transparent_unless_the_colour_schemes_differ() {
    let surface = |iframe_scheme: &str, document_scheme: &str| {
        let trace = trace(&format!(
            "<iframe style='color-scheme:{iframe_scheme}' srcdoc=\"<style>:root{{color-scheme:{document_scheme}}}</style>\"></iframe>"
        ));
        let [(_, view)] = viewports(&trace)[..] else {
            panic!("one viewport");
        };
        view.items
            .iter()
            .filter_map(|item| match item {
                DisplayItem::Box(paint)
                    if paint.rect == view.area && paint.decoration.background.alpha == 1.0 =>
                {
                    Some(paint.decoration.background.rgb)
                }
                _ => None,
            })
            .collect::<Vec<_>>()
    };
    assert_eq!(
        surface("light", "light"),
        Vec::<[u8; 3]>::new(),
        "matching schemes stay transparent"
    );
    assert_eq!(
        surface("dark", "dark"),
        Vec::<[u8; 3]>::new(),
        "matching schemes stay transparent"
    );
    assert_eq!(
        surface("dark", "light"),
        [[255, 255, 255]],
        "a light document in a dark iframe gets an opaque light Canvas"
    );
    let [dark] = surface("light", "dark")[..] else {
        panic!("a dark document in a light iframe gets an opaque Canvas");
    };
    assert_ne!(dark, [255, 255, 255], "the dark Canvas colour");
}

#[test]
fn width_and_height_attributes_map_to_aspect_ratio_hints() {
    let trace = trace(&format!(
        "<video width=400 height=100 style='width:120pt;height:auto'></video>\
         <img src='{IMAGE}' width=40 height=40 style='width:60pt;height:auto'>\
         <img src='{IMAGE}' sizes=auto srcset='{IMAGE} 80w' loading=lazy>\
         <canvas width=200 height=50 style='display:block;width:100pt;background:blue'></canvas>"
    ));
    let paints = images(&trace);
    let [video, square, auto] = paints[..] else {
        panic!("a video and two images: {paints:?}");
    };
    assert_eq!(
        [video.rect.width, video.rect.height],
        [120.0, 30.0],
        "a video without a poster takes its attributes' 4:1 ratio"
    );
    assert_eq!(
        [
            square.clip.as_ref().unwrap().rect.width,
            square.clip.as_ref().unwrap().rect.height
        ],
        [60.0, 30.0],
        "an image's natural ratio overrides the `auto` hint ratio"
    );
    assert_eq!(
        [
            auto.clip.as_ref().unwrap().rect.width,
            auto.clip.as_ref().unwrap().rect.height
        ],
        [300.0 * PIXEL, 150.0 * PIXEL],
        "sizes=auto images are size-contained at 300 by 150 pixels"
    );
    let canvas = trace.display_lists[0]
        .iter()
        .filter_map(|item| match item {
            DisplayItem::Box(paint) if paint.rect.width == 100.0 => Some(paint.rect.height),
            _ => None,
        })
        .collect::<Vec<_>>();
    assert_eq!(
        canvas,
        [25.0],
        "a block fallback canvas takes its attributes' 4:1 ratio"
    );
}