ferri-pdf 0.1.5

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

use crate::dom::{
    DocumentTree, HTML_NAMESPACE, MATHML_NAMESPACE, NodeData, QuirksMode, SVG_NAMESPACE, Selector,
    TreeRelation,
};
use crate::{
    Resource, ResourceBase, ResourceError, ResourceResolver, render_html, render_with_resolver,
};
use common::{assert_pt, local_options, lossy_options};
use std::cell::Cell;

fn select<'a>(tree: &'a DocumentTree, selector: &str) -> crate::dom::Element<'a> {
    tree.select(&Selector::parse(selector).unwrap())
        .next()
        .unwrap()
}

fn formatting_element<'a>(tree: &'a DocumentTree, id: &str) -> crate::dom::Element<'a> {
    tree.root_element()
        .as_node()
        .inclusive_descendants(TreeRelation::Formatting)
        .filter_map(crate::dom::Node::element)
        .find(|element| element.attr("id") == Some(id))
        .expect("the composed formatting tree contains the requested shadow element")
}

#[test]
fn declarative_shadow_slots_preserve_three_relationships() {
    let tree = DocumentTree::parse(
        "<!doctype html><div id=host><template shadowrootmode=open><section id=shadow><slot name=n id=named>Named fallback</slot><slot id=defaultslot>Default fallback</slot></section></template><p id=assigned slot=n>Named</p><p id=default>Default</p><p id=hidden slot=missing>Hidden</p></div>",
    );
    let host = select(&tree, "#host");
    let assigned = select(&tree, "#assigned");
    let named = formatting_element(&tree, "named");
    let default_slot = formatting_element(&tree, "defaultslot");
    let shadow = formatting_element(&tree, "shadow");
    assert_eq!(assigned.tree_scope(), host.tree_scope());
    assert_eq!(named.tree_scope(), shadow.tree_scope());
    assert_ne!(assigned.tree_scope(), named.tree_scope());
    assert_eq!(shadow.shadow_host().unwrap().id(), host.id());
    assert_eq!(
        assigned.parent(TreeRelation::Selector).unwrap().id(),
        host.id()
    );
    assert_eq!(
        assigned.parent(TreeRelation::Inheritance).unwrap().id(),
        named.id()
    );
    assert_eq!(
        assigned.parent(TreeRelation::Formatting).unwrap().id(),
        named.id()
    );
    assert_eq!(
        select(&tree, "#default")
            .parent(TreeRelation::Inheritance)
            .unwrap()
            .id(),
        default_slot.id()
    );
    assert!(
        shadow.parent(TreeRelation::Selector).is_none(),
        "the shadow host is not an ordinary selector ancestor"
    );
    assert_eq!(
        shadow.parent(TreeRelation::Inheritance).unwrap().id(),
        host.id()
    );
    assert!(
        tree.select(&Selector::parse("#shadow,#named,#defaultslot").unwrap())
            .next()
            .is_none(),
        "document queries cannot enter a shadow tree"
    );
    assert_eq!(
        host.children(TreeRelation::Selector)
            .map(|element| element.attr("id").unwrap().to_owned())
            .collect::<Vec<_>>(),
        ["assigned", "default", "hidden"],
        "the consumed declarative template is absent from light children"
    );
    assert_eq!(
        host.children(TreeRelation::Formatting)
            .map(crate::dom::Element::id)
            .collect::<Vec<_>>(),
        [shadow.id()]
    );
    assert_eq!(
        named
            .children(TreeRelation::Formatting)
            .map(crate::dom::Element::id)
            .collect::<Vec<_>>(),
        [assigned.id()],
        "slot projection retains original light-node identity"
    );
}

#[test]
fn slot_fallback_and_hidden_assigned_content_have_correct_presence() {
    for (light, expected) in [
        (
            "<p slot=n>Named</p><p>Default</p><p slot=missing>Undistributed</p>",
            vec!["Before", "Named", "Default", "Duplicate fallback", "After"],
        ),
        (
            "",
            vec![
                "Before",
                "Named fallback",
                "Default fallback",
                "Duplicate fallback",
                "After",
            ],
        ),
        (
            "<p slot=n style='display:none'>Hidden assigned</p>",
            vec!["Before", "Default fallback", "Duplicate fallback", "After"],
        ),
    ] {
        let html = format!(
            "<!doctype html><style>{}p{{margin:0}}</style><div><template shadowrootmode=closed><p>Before</p><slot name=n><p>Named fallback</p></slot><slot><p>Default fallback</p></slot><slot name=n><p>Duplicate fallback</p></slot><p>After</p></template>{light}</div>",
            common::PROFILE
        );
        let trace = render_html(&html, &local_options())
            .unwrap()
            .layout
            .unwrap();
        assert_eq!(
            trace
                .pages
                .iter()
                .flatten()
                .map(|line| line.text.as_str())
                .collect::<Vec<_>>(),
            expected,
            "closed roots, first matching slots and display:none assignments must preserve composition: {light}"
        );
    }
    let html = format!(
        "<!doctype html><style>{}</style><div><template shadowrootmode=open><slot>Fallback</slot></template> </div>",
        common::PROFILE
    );
    let trace = render_html(&html, &local_options())
        .unwrap()
        .layout
        .unwrap();
    assert!(
        trace
            .pages
            .iter()
            .flatten()
            .all(|line| !line.text.contains("Fallback")),
        "even whitespace-only assigned text suppresses slot fallback"
    );
}

#[test]
fn shadow_headings_use_host_ancestry_and_ignore_slot_offsets() {
    let tree = DocumentTree::parse(
        "<!doctype html><section headingoffset=2><div id=host headingoffset=1><template shadowrootmode=open><section headingoffset=1><h1 id=inner>Inner</h1><slot headingoffset=8></slot><div headingreset headingoffset=1><h1 id=reset>Reset</h1></div></section></template><h1 id=slotted>Light</h1></div></section>",
    );
    assert_eq!(
        formatting_element(&tree, "inner").heading_level(),
        Some(5),
        "heading offsets cross the shadow root through its host"
    );
    assert_eq!(
        formatting_element(&tree, "reset").heading_level(),
        Some(2),
        "inclusive headingreset stops host ancestry"
    );
    assert_eq!(
        select(&tree, "#slotted").heading_level(),
        Some(4),
        "slot assignment must not replace the light node's HTML heading ancestry"
    );
}

#[test]
fn shadow_root_host_validation_and_ascii_mode_matching() {
    for mode in ["open", "closed", "OpEn", "CLOSED"] {
        let html = format!(
            "<!doctype html><style>{}</style><div><template shadowrootmode={mode}><p>Shadow</p></template><p>Light</p></div>",
            common::PROFILE
        );
        let trace = render_html(&html, &local_options())
            .unwrap()
            .layout
            .unwrap();
        assert_eq!(
            trace
                .pages
                .iter()
                .flatten()
                .map(|line| line.text.as_str())
                .collect::<Vec<_>>(),
            ["Shadow"],
            "enumerated shadowrootmode is ASCII case insensitive: {mode}"
        );
    }
    for host in ["a", "button", "font-face", "x!invalid-name"] {
        let tree = DocumentTree::parse(&format!(
            "<!doctype html><{host} id=host><template shadowrootmode=open><p>Inert</p></template><p>Light</p></{host}>"
        ));
        let target = select(&tree, "#host");
        assert!(
            target
                .children(TreeRelation::Selector)
                .any(|child| child.name() == "template"),
            "a disallowed host retains an ordinary template: {host}"
        );
        let text = target
            .as_node()
            .inclusive_descendants(TreeRelation::Formatting)
            .filter_map(|node| node.value().as_text().map(|text| text.to_string()))
            .collect::<String>();
        assert_eq!(
            text, "Light",
            "a disallowed host cannot activate template content: {host}"
        );
    }
    let html = format!(
        "<!doctype html><style>{}</style><div><template shadowrootmode=open><p>First</p></template><template shadowrootmode=closed><p>Second</p></template><p>Light</p></div>",
        common::PROFILE
    );
    let trace = render_html(&html, &local_options())
        .unwrap()
        .layout
        .unwrap();
    assert_eq!(
        trace
            .pages
            .iter()
            .flatten()
            .map(|line| line.text.as_str())
            .collect::<Vec<_>>(),
        ["First"],
        "a duplicate root stays an ordinary inert template"
    );
}

#[test]
fn formatting_depth_limit_covers_block_inline_atomic_and_positioned_trees() {
    use crate::document::{
        ATOMIC_INLINE_DEPTH, BOX_DEPTH, BlockContent, DocumentDiagnostic,
        MAX_FORMATTING_DEPTH as FORMATTING_LIMIT, POSITIONED_DEPTH, StyledDocument,
    };
    // The body and the paragraph take a box's depth each.
    const BODY_AND_PARAGRAPH_DEPTH: usize = 2 * BOX_DEPTH;
    for (opening, closing, depth) in [
        ("<div>", "</div>", BOX_DEPTH),
        ("<span>", "</span>", BOX_DEPTH),
        (
            "<div style='display:inline-block'>",
            "</div>",
            BOX_DEPTH + ATOMIC_INLINE_DEPTH,
        ),
        (
            "<div style='position:absolute'>",
            "</div>",
            BOX_DEPTH + POSITIONED_DEPTH,
        ),
    ] {
        let deepest_levels = (FORMATTING_LIMIT - BODY_AND_PARAGRAPH_DEPTH) / depth;
        for (levels, flattened) in [
            (deepest_levels, false),
            (deepest_levels + 1, true),
            (2 * FORMATTING_LIMIT, true),
        ] {
            eprintln!("checking formatting boundary: {levels} levels of {opening}");
            let html = format!(
                "<!doctype html>{}<p>Boundary</p>{}",
                opening.repeat(levels),
                closing.repeat(levels),
            );
            let document = StyledDocument::parse(
                &html,
                &ResourceBase::default(),
                &[],
                &crate::FileResolver::default(),
            )
            .unwrap_or_else(|error| panic!("{levels} levels of {opening} must format: {error}"));
            let mut pending = vec![(document.root(), 0)];
            let (mut text, mut deepest) = (String::new(), 0);
            while let Some((block, depth)) = pending.pop() {
                deepest = deepest.max(depth);
                for content in block.children() {
                    match content {
                        BlockContent::Events(_) => {}
                        BlockContent::Block(child) | BlockContent::Positioned(child) => {
                            pending.push((child, depth + 1));
                        }
                        BlockContent::Inline(paragraph) => {
                            text.extend(
                                paragraph.text().chars().filter(|ch| {
                                    *ch != crate::document::OBJECT_REPLACEMENT_CHARACTER
                                }),
                            );
                            pending.extend(
                                paragraph
                                    .atomics()
                                    .iter()
                                    .chain(paragraph.anchors())
                                    .map(|anchor| (anchor.block(), depth + 1)),
                            );
                        }
                    }
                }
            }
            assert_eq!(
                text, "Boundary",
                "formatting {levels} levels of {opening} preserves content"
            );
            assert!(
                deepest <= FORMATTING_LIMIT,
                "{levels} levels of {opening} nest boxes {deepest} deep, past the limit"
            );
            let reported: Vec<String> = document
                .into_diagnostics()
                .iter()
                .filter(|diagnostic| {
                    matches!(diagnostic, DocumentDiagnostic::FormattingLimit { .. })
                })
                .map(ToString::to_string)
                .collect();
            let expected: &[String] = if flattened {
                &[format!(
                    "formatting nesting exceeds {FORMATTING_LIMIT}: elements nested deeper \
                     generate no boxes of their own, their contents lying in the deepest box"
                )]
            } else {
                &[]
            };
            assert_eq!(
                reported, expected,
                "{levels} levels of {opening} report whether they were flattened"
            );
        }
    }
}

#[test]
fn excessive_shadow_nesting_leaves_an_ordinary_template_and_is_reported() {
    const TOO_DEEP: usize = 65;
    let html = format!(
        "<!doctype html>{}<p>Deep</p>{}",
        "<div><template shadowrootmode=open>".repeat(TOO_DEEP),
        "</template></div>".repeat(TOO_DEEP)
    );
    for output in [
        render_html(&html, &lossy_options()),
        crate::render_bytes(html.as_bytes(), &lossy_options()),
    ] {
        let output =
            output.unwrap_or_else(|error| panic!("deep shadow roots must render: {error}"));
        assert!(
            output.diagnostics.iter().any(|diagnostic| matches!(
                diagnostic,
                crate::RenderDiagnostic::TreeLimit(crate::dom::DomError::TreeLimit {
                    resource: "shadow tree nesting",
                    limit: 64
                })
            )),
            "both HTML input paths must report the shadow-depth limit: {:?}",
            output.diagnostics
        );
        assert!(
            output
                .layout
                .unwrap()
                .pages
                .iter()
                .flatten()
                .next()
                .is_none(),
            "the template past the limit stays an ordinary, unrendered template"
        );
    }
    let html = format!(
        "<!doctype html>{}<p>Deep</p>{}",
        "<div><template shadowrootmode=open>".repeat(TOO_DEEP - 1),
        "</template></div>".repeat(TOO_DEEP - 1)
    );
    DocumentTree::parse(&html);
    let trace = render_html(&html, &local_options())
        .expect("the inclusive shadow bound remains usable")
        .layout
        .unwrap();
    assert_eq!(
        trace
            .pages
            .iter()
            .flatten()
            .map(|line| line.text.as_str())
            .collect::<Vec<_>>(),
        ["Deep"]
    );
}

#[test]
fn html_tree_recovery_preserves_namespaces_and_quirks() {
    let tree = DocumentTree::parse(
        "<!doctype html><table id=t>outside<tr><td id=cell>A<td>B</table><p id=duplicate CLASS=first class=second>C</p><svg><circle id=circle /><foreignObject><p id=foreign>HTML</p></foreignObject></svg><math><mi id=mi>x</mi><annotation-xml encoding=text/html><div id=annotation>HTML</div></annotation-xml></math>",
    );
    assert_eq!(tree.quirks_mode(), QuirksMode::NoQuirks);
    assert_eq!(
        DocumentTree::parse("<p>quirks").quirks_mode(),
        QuirksMode::Quirks
    );
    let cell = select(&tree, "#cell");
    let row = cell.parent(TreeRelation::Selector).unwrap();
    assert_eq!(row.name(), "tr");
    let group = row.parent(TreeRelation::Selector).unwrap();
    assert_eq!(group.name(), "tbody");
    assert_eq!(
        group.parent(TreeRelation::Selector).unwrap().id(),
        select(&tree, "#t").id()
    );
    let body = select(&tree, "body");
    assert_eq!(
        body.child_nodes(TreeRelation::Selector)
            .find_map(|node| node.value().as_text().map(|text| text.as_ref())),
        Some("outside")
    );
    assert_eq!(select(&tree, "#duplicate").attr("class"), Some("first"));
    assert_eq!(select(&tree, "#circle").namespace(), SVG_NAMESPACE);
    assert_eq!(select(&tree, "#foreign").namespace(), HTML_NAMESPACE);
    assert_eq!(select(&tree, "#mi").namespace(), MATHML_NAMESPACE);
    assert_eq!(select(&tree, "#annotation").namespace(), HTML_NAMESPACE);
    let malformed = DocumentTree::parse("<b><i>A</b>B</i>");
    assert_eq!(
        select(&malformed, "body > b > i")
            .text()
            .collect::<String>(),
        "A"
    );
    assert_eq!(
        select(&malformed, "body > i").text().collect::<String>(),
        "B"
    );
}

#[test]
fn scripting_disabled_noscript_and_template_parse_correctly() {
    let tree = DocumentTree::parse(
        "<head><noscript><style id=head>p{font-size:18pt}</style></noscript></head><body><noscript><p id=fallback>fallback</p></noscript><template id=t><style id=inert>p{display:none}</style><p id=inside>inert</p></template><p id=live>live</p>",
    );
    assert_eq!(
        select(&tree, "#fallback").text().collect::<String>(),
        "fallback"
    );
    assert!(
        tree.select(&Selector::parse("#head").unwrap())
            .next()
            .is_some()
    );
    assert!(
        tree.select(&Selector::parse("#inside, #inert").unwrap())
            .next()
            .is_none(),
        "inert fragment nodes are outside document queries"
    );
    let template = select(&tree, "#t");
    for relation in [
        TreeRelation::Selector,
        TreeRelation::Inheritance,
        TreeRelation::Formatting,
    ] {
        assert_eq!(
            template.children(relation).count(),
            0,
            "template contents are not template children"
        );
    }
    let contents = template.template_contents().unwrap();
    assert!(matches!(contents.value(), NodeData::Fragment));
    assert!(contents.parent(TreeRelation::Selector).is_none());
    let inside = contents
        .children(TreeRelation::Selector)
        .filter_map(crate::dom::Node::element)
        .find(|element| element.attr("id") == Some("inside"))
        .unwrap();
    assert!(inside.parent(TreeRelation::Selector).is_none());
    assert!(
        !inside.matches(&Selector::parse("#t p").unwrap()),
        "template is not a selector ancestor of its contents"
    );
}

#[test]
fn ordinary_tree_relations_preserve_existing_rendering() {
    let tree =
        DocumentTree::parse("<section id=parent><p id=child>A<em id=em>B</em>C</p></section>");
    let child = select(&tree, "#child");
    let parent = select(&tree, "#parent");
    for relation in [
        TreeRelation::Selector,
        TreeRelation::Inheritance,
        TreeRelation::Formatting,
    ] {
        assert_eq!(child.parent(relation).unwrap().id(), parent.id());
        assert_eq!(
            child
                .children(relation)
                .map(crate::dom::Element::name)
                .collect::<Vec<_>>(),
            ["em"]
        );
    }
    let output = render_html(&format!("<style>{}p{{font-size:18pt;line-height:22pt;margin:0}}</style><section><p>A<em>B</em>C</p><p>D</p></section>", common::PROFILE), &local_options()).unwrap();
    let trace = output.layout.unwrap();
    assert_eq!(
        trace.pages[0]
            .iter()
            .map(|line| line.text.as_str())
            .collect::<Vec<_>>(),
        ["ABC", "D"]
    );
    assert_pt(trace.pages[0][0].font_size, 18.0);
    assert_pt(
        trace.pages[0][1].baseline - trace.pages[0][0].baseline,
        22.0,
    );
}

#[test]
fn template_styles_and_resources_remain_inert_even_with_display_override() {
    struct DenyAll(Cell<usize>);
    impl ResourceResolver for DenyAll {
        fn resolve(&self, reference: &str, base: &ResourceBase) -> Result<Resource, ResourceError> {
            self.0.set(self.0.get() + 1);
            Err(ResourceError::Denied(base.resolve(reference)?))
        }
    }
    let resolver = DenyAll(Cell::new(0));
    let output = render_with_resolver("<style>template{display:block}p{font-size:18pt}</style><template><link rel=stylesheet href=forbidden.css><style>p{display:none}</style><p>hidden</p></template><noscript><p>fallback</p></noscript><p>visible</p>", &local_options(), &resolver).unwrap();
    let trace = output.layout.unwrap();
    assert_eq!(
        trace.pages[0]
            .iter()
            .map(|line| line.text.as_str())
            .collect::<Vec<_>>(),
        ["fallback", "visible"]
    );
    assert_eq!(
        resolver.0.get(),
        0,
        "inert sources must never reach resolver policy"
    );
    assert!(output.diagnostics.is_empty());
}

#[test]
fn quirks_mode_reaches_selector_matching_in_rendering() {
    for (doctype, expected) in [("", 18.0), ("<!doctype html>", 10.0)] {
        let output = render_html(&format!("{doctype}<style>p{{font-size:10pt}}.foo{{font-size:18pt}}</style><p class=FOO>case</p>"), &local_options()).unwrap();
        assert_pt(output.layout.unwrap().pages[0][0].font_size, expected);
    }
}

#[test]
fn language_and_direction_use_dom_parents_while_css_inherits_through_slots() {
    let tree = DocumentTree::parse(
        "<!doctype html><div id=host lang=en dir=ltr><template shadowrootmode=open><section lang=fr dir=rtl><slot></slot></section></template><span id=assigned>ABC</span></div>",
    );
    let assigned = select(&tree, "#assigned");
    assert_eq!(
        assigned.language(),
        "en",
        "HTML language must not come from the assigned slot's CSS inheritance parent"
    );
    assert_eq!(
        assigned.directionality(),
        crate::dom::Directionality::Ltr,
        "HTML directionality must retain the light-tree parent even though CSS direction inherits through the slot"
    );
    assert_eq!(
        assigned.parent(TreeRelation::Inheritance).unwrap().name(),
        "slot"
    );
}

#[test]
fn automatic_direction_scans_dom_text_and_uses_shadow_slot_host_direction() {
    let host = DocumentTree::parse(
        "<!doctype html><div id=host dir=auto><template shadowrootmode=open><p>Latin shadow text</p><slot></slot></template><span>אב</span></div>",
    );
    assert_eq!(
        select(&host, "#host").directionality(),
        crate::dom::Directionality::Rtl,
        "shadow text must not replace the host's own descendant text in dir=auto discovery"
    );
    let fallback = DocumentTree::parse(
        "<!doctype html><div dir=rtl><template shadowrootmode=open><p id=automatic dir=auto><slot>Latin fallback</slot></p></template></div>",
    );
    assert_eq!(
        formatting_element(&fallback, "automatic").directionality(),
        crate::dom::Directionality::Rtl,
        "a descendant slot in a shadow tree contributes its host direction before scanning fallback text"
    );
    let assigned = DocumentTree::parse(
        "<!doctype html><div><template shadowrootmode=open><p><slot id=automatic dir=auto></slot></p></template><span dir=ltr>Latin isolated</span><span>אב</span></div>",
    );
    assert_eq!(
        formatting_element(&assigned, "automatic").directionality(),
        crate::dom::Directionality::Rtl,
        "slot auto direction must use assigned nodes and exclude a directionally isolated assigned root"
    );
}