ferri-pdf 0.1.10

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

use crate::style::{Degradation, StyleDiagnosticKind};
use crate::{
    RenderDiagnostic, Resource, ResourceBase, ResourceError, ResourceResolver, Url, render_html,
    render_with_resolver,
};
use common::{assert_pt, local_options};

fn render_css(css: &str) -> crate::RenderOutput {
    render_html(
        &format!("<style>{css}</style><p>survives</p>"),
        &local_options(),
    )
    .unwrap()
}

#[test]
fn malformed_rule_recovers_at_correct_css_boundary() {
    let output = render_css("p, ] { color:red; font-size:99pt } p { font-size:18pt }");
    let line = &output.layout.as_ref().unwrap().pages[0][0];
    assert_eq!(line.text, "survives");
    assert_pt(line.font_size, 18.0);
    assert!(output.diagnostics.iter().any(
        |d| matches!(d, RenderDiagnostic::Css(d) if d.kind == StyleDiagnosticKind::InvalidRule)
    ));
}

#[test]
fn unknown_rule_does_not_consume_following_rule() {
    let output = render_css(
        "@future f([one; two]) { p { font-size:99pt } @inner { p{color:red} } } @future-statement x(y); p{font-size:18pt}",
    );
    assert_eq!(output.layout.as_ref().unwrap().pages[0][0].text, "survives");
    assert_pt(output.layout.unwrap().pages[0][0].font_size, 18.0);
    assert_eq!(output.diagnostics.iter().filter(|d| matches!(d, RenderDiagnostic::Css(d) if d.kind == StyleDiagnosticKind::InvalidRule)).count(), 2);
}

#[test]
fn invalid_declaration_preserves_valid_siblings() {
    for css in [
        "p{broken f(one; two[three]);font-size:18pt;color:navy}",
        "p{color:url(bad\"quote);font-size:18pt;color:navy}",
        "p{color:\"bad\n; font-size:18pt;color:navy}",
        "p{font-size:calc(12pt + [bad]);font-size:18pt;color:navy}",
        "p{color:rgb(0,bad,0);font-size:18pt;color:navy}",
        "p{--bad:url(bad\"quote);font-size:18pt;color:navy}",
        "p{color:red !oops; font-size:18pt;color:navy}",
        "p{--keep:{x;y}; broken; font-size:18pt;color:navy}",
    ] {
        let output = render_css(css);
        let line = &output.layout.unwrap().pages[0][0];
        assert_pt(line.font_size, 18.0);
        assert_eq!(line.color.rgb, [0, 0, 128], "valid sibling after {css:?}");
        assert!(output.diagnostics.iter().any(|d| matches!(d, RenderDiagnostic::Css(d) if d.kind == StyleDiagnosticKind::InvalidDeclaration)), "missing source diagnostic for {css:?}");
    }
}

#[test]
fn nesting_diagnostics_distinguish_rules_from_declarations() {
    let output = render_css(
        "p{\n broken f(a;b);\n broken @not-an-at-rule;\n &bad{color:red}\n @unknown future;\n font-size:18pt}",
    );
    assert_pt(output.layout.as_ref().unwrap().pages[0][0].font_size, 18.0);
    let diagnostics: Vec<_> = output
        .diagnostics
        .iter()
        .filter_map(|diagnostic| match diagnostic {
            RenderDiagnostic::Css(diagnostic) => Some((diagnostic.location.line, diagnostic.kind)),
            _ => None,
        })
        .collect();
    assert_eq!(
        diagnostics,
        [
            (2, StyleDiagnosticKind::InvalidDeclaration),
            (3, StyleDiagnosticKind::InvalidDeclaration),
            (4, StyleDiagnosticKind::InvalidRule),
            (5, StyleDiagnosticKind::InvalidRule)
        ],
        "mixed block contents must preserve both diagnostic categories and their original CSS lines"
    );
}

#[test]
fn inline_declaration_recovery_uses_the_same_parser() {
    let output = render_html(
        "<p style='font-size:18pt; broken f(a;b); color:navy; font-size:20pt'>survives</p>",
        &local_options(),
    )
    .unwrap();
    assert_pt(output.layout.unwrap().pages[0][0].font_size, 20.0);
    assert!(output.diagnostics.iter().any(|d| matches!(d, RenderDiagnostic::Css(d) if d.kind == StyleDiagnosticKind::InvalidDeclaration)));
}

#[test]
fn eof_closes_valid_constructs_and_at_rule_names_are_case_insensitive() {
    let output = render_html(&format!("<style>{}</style><style>@PAGE{{size:300pt 400pt; margin:20pt}}p{{font-size:18pt;color:navy</style><p>survives</p>", common::PROFILE), &local_options()).unwrap();
    let trace = output.layout.unwrap();
    assert_pt(trace.page_width, 300.0);
    assert_pt(trace.page_height, 400.0);
    assert_pt(trace.pages[0][0].font_size, 18.0);
}

/// Whether `output` reports `declaration` as invalid at computed-value time.
fn discarded(output: &crate::RenderOutput, declaration: &str) -> bool {
    output.diagnostics.iter().any(|diagnostic| {
        matches!(
            diagnostic,
            RenderDiagnostic::Degraded(Degradation::InvalidAtComputedValueTime {
                declaration: discarded,
                ..
            }) if discarded == declaration
        )
    })
}

#[test]
fn unsupported_active_winner_is_invalid_at_computed_value_time() {
    let output =
        render_css("p{scroll-initial-target:none;scroll-initial-target:nearest;font-size:18pt}");
    assert!(
        discarded(&output, "scroll-initial-target: nearest"),
        "the active unsupported winner is reported: {:?}",
        output.diagnostics
    );
    assert_pt(output.layout.unwrap().pages[0][0].font_size, 18.0);
    let output =
        render_css("p{scroll-initial-target:nearest;scroll-initial-target:none;font-size:18pt}");
    assert!(
        !discarded(&output, "scroll-initial-target: nearest"),
        "an unsupported value the cascade discards is never computed: {:?}",
        output.diagnostics
    );
    assert_pt(output.layout.unwrap().pages[0][0].font_size, 18.0);
}

struct Sheet;
impl ResourceResolver for Sheet {
    fn resolve(&self, reference: &str, _: &ResourceBase) -> Result<Resource, ResourceError> {
        assert_eq!(reference, "sheet.css");
        Ok(Resource {
            bytes: b"p {\n  color:red;\n  broken;\n  font-size:18pt;\n}".to_vec(),
            base: Url::parse("https://example.test/styles/final.css")
                .unwrap()
                .into(),
        })
    }
}

#[test]
fn stylesheet_diagnostic_keeps_final_base_and_css_line() {
    let output = render_with_resolver(
        "<link rel=stylesheet href=sheet.css><p>survives</p>",
        &local_options(),
        &Sheet,
    )
    .unwrap();
    let diagnostic = output
        .diagnostics
        .iter()
        .find_map(|d| match d {
            RenderDiagnostic::Css(d) if d.kind == StyleDiagnosticKind::InvalidDeclaration => {
                Some(d)
            }
            _ => None,
        })
        .unwrap();
    assert_eq!(
        diagnostic.location.base,
        Url::parse("https://example.test/styles/final.css")
            .unwrap()
            .into()
    );
    assert_eq!(diagnostic.location.line, 3);
    assert!(diagnostic.location.column > 0);
    assert!(diagnostic.context.contains("broken"));
}

#[test]
fn syntax_recovery_drops_declarations_past_parse_limits() {
    const OVERSIZED_NESTING: usize = 300;
    let output = render_css(&format!(
        "p{{--deep:{}0{};font-size:18pt}}",
        "f(".repeat(OVERSIZED_NESTING),
        ")".repeat(OVERSIZED_NESTING)
    ));
    assert!(
        output.diagnostics.iter().any(|diagnostic| matches!(
            diagnostic,
            RenderDiagnostic::Css(diagnostic)
                if diagnostic.kind == StyleDiagnosticKind::LimitExceeded
                    && diagnostic.context.starts_with("--deep:")
        )),
        "the declaration past the component bound is reported: {:?}",
        output.diagnostics
    );
    assert_pt(output.layout.unwrap().pages[0][0].font_size, 18.0);
}

#[test]
fn syntax_recovery_keeps_the_declaration_whose_font_is_denied() {
    struct Denied;
    impl ResourceResolver for Denied {
        fn resolve(&self, reference: &str, base: &ResourceBase) -> Result<Resource, ResourceError> {
            assert_eq!(reference, "blocked.ttf");
            Err(ResourceError::Denied(base.resolve(reference)?))
        }
    }
    let output = render_with_resolver(
        "<style>@font-face{font-family:Denied;src:url(blocked.ttf)}p{broken; font-family:Denied}</style><p>denied</p>",
        &local_options(),
        &Denied,
    )
    .expect("a denied font is unavailable, not fatal");
    let denied = output
        .diagnostics
        .iter()
        .filter(|diagnostic| {
            matches!(
                diagnostic,
                RenderDiagnostic::UnavailableFont(failure)
                    if failure.reference == "blocked.ttf"
                        && matches!(failure.error, crate::fonts::FontError::Resource(ResourceError::Denied(_)))
            )
        })
        .count();
    assert_eq!(
        denied, 1,
        "the font-family after the recovered declaration requests the denied face: {:?}",
        output.diagnostics
    );
}

#[test]
fn curly_block_mixed_with_other_value_is_rejected_before_substitution() {
    let output = render_css("p{font-size:18pt;--n:20pt;font-size:var(--n) {};color:navy}");
    assert_pt(output.layout.unwrap().pages[0][0].font_size, 18.0);
}

#[test]
fn unknown_property_url_does_not_require_resource_resolution() {
    let output = render_css("p{unknown-feature:url(http://[bad);font-size:18pt}");
    assert_pt(output.layout.unwrap().pages[0][0].font_size, 18.0);
}

#[test]
fn implicit_eof_closes_a_valid_calculation() {
    let output = render_css("p{font-size:calc(6pt + 12pt");
    assert_pt(output.layout.unwrap().pages[0][0].font_size, 18.0);
}

#[test]
fn invalid_page_rule_and_font_face_do_not_remove_valid_siblings() {
    let output = render_css(
        "@page :unknown {size:999pt} @font-face{font-family:MissingSource} p{font-size:18pt}",
    );
    assert_pt(output.layout.unwrap().pages[0][0].font_size, 18.0);
    assert!(output.diagnostics.iter().filter(|d| matches!(d, RenderDiagnostic::Css(d) if d.kind == StyleDiagnosticKind::InvalidRule)).count() >= 2);
}

#[test]
fn unsupported_generated_winner_is_invalid_at_computed_value_time() {
    let output = render_css("p::before{content:'grid';scroll-initial-target:nearest}");
    assert!(
        discarded(&output, "scroll-initial-target: nearest"),
        "the generated box's unsupported winner is reported: {:?}",
        output.diagnostics
    );
    assert_eq!(
        output.layout.unwrap().pages[0][0].text,
        "gridsurvives",
        "the pseudo-element still generates its content"
    );
}

#[test]
fn inline_diagnostics_use_document_base_after_an_external_sheet_redirect() {
    let document_base: ResourceBase = Url::parse("https://example.test/documents/report.html")
        .unwrap()
        .into();
    let mut options = local_options();
    options.base = document_base.clone();
    let output = render_with_resolver(
        "<link rel=stylesheet href=sheet.css><p style='broken; font-size:18pt'>survives</p>",
        &options,
        &Sheet,
    )
    .unwrap();
    let locations: Vec<_> = output
        .diagnostics
        .iter()
        .filter_map(|d| match d {
            RenderDiagnostic::Css(d) if d.kind == StyleDiagnosticKind::InvalidDeclaration => {
                Some(&d.location)
            }
            _ => None,
        })
        .collect();
    assert!(
        locations
            .iter()
            .any(|location| location.base == document_base && location.line == 1),
        "inline CSS must retain the document base: {locations:?}"
    );
    assert!(
        locations.iter().any(|location| location.base
            == Url::parse("https://example.test/styles/final.css")
                .unwrap()
                .into()
            && location.line == 3),
        "external CSS must retain its final resource base: {locations:?}"
    );
}

#[test]
fn valid_page_selection_resolves_without_invalid_syntax_diagnostics() {
    for prelude in [
        ":first",
        " :first",
        "named:first",
        " named:first",
        "named, :right",
    ] {
        let output = render_html(
            &format!(
                "<style>@page {prelude} {{size:300pt 400pt}}p{{page:named}}</style><p>page</p>"
            ),
            &local_options(),
        )
        .unwrap_or_else(|error| panic!("valid page selector {prelude:?}: {error}"));
        let trace = output.layout.unwrap();
        assert_eq!(
            [trace.page_width, trace.page_height],
            [300.0, 400.0],
            "selected geometry for {prelude:?}"
        );
        assert!(
            !output.diagnostics.iter().any(|d| matches!(d, RenderDiagnostic::Css(d) if d.kind == StyleDiagnosticKind::InvalidRule)),
            "valid page selector {prelude:?} must not be discarded"
        );
    }
    let output = render_css("@page named :first {size:999pt} p{font-size:18pt}");
    assert_pt(output.layout.unwrap().pages[0][0].font_size, 18.0);
    assert!(output.diagnostics.iter().any(
        |d| matches!(d, RenderDiagnostic::Css(d) if d.kind == StyleDiagnosticKind::InvalidRule)
    ));
}

#[test]
fn running_strings_are_active_in_assignment_and_page_margin_contexts() {
    let output =
        render_css("p{string-set:chapter content()}@page{@top-left{content:'H:' string(chapter)}}");
    let lines = &output.layout.as_ref().unwrap().pages[0];
    assert!(
        lines.iter().any(|line| line.text == "H:survives"),
        "the margin must use the captured assignment, not silently discard valid syntax"
    );
    assert!(!output.diagnostics.iter().any(|diagnostic| matches!(diagnostic, RenderDiagnostic::Css(diagnostic) if matches!(diagnostic.kind, StyleDiagnosticKind::InvalidDeclaration | StyleDiagnosticKind::InvalidRule))));
}

#[test]
fn valid_leader_content_is_not_discarded_as_invalid_syntax() {
    let declaration = "p::after{content:leader('.')}";
    let html = format!("<style>{declaration}</style><p id=chapter>Chapter</p>");
    let output = render_html(&html, &local_options()).expect("valid leader content must render");
    assert!(
        output
            .layout
            .unwrap()
            .pages
            .iter()
            .flatten()
            .any(|line| line.text.contains("..."))
    );
}

#[test]
fn book_content_grammar_preserves_cascade_and_invalid_value_recovery() {
    for value in [
        "string(chapter)",
        "string(chapter,first)",
        "string(chapter,start)",
        "string(chapter,last)",
        "string(chapter,first-except)",
        "leader(dotted)",
        "leader(solid)",
        "leader(space)",
        "leader('..')",
        "target-counter('#chapter',page)",
        "target-counter('#chapter',page,lower-roman)",
        "target-counters('#chapter',section,'.')",
        "target-counters('#chapter',section,'.',decimal)",
        "target-text('#chapter')",
        "target-text('#chapter',before)",
        "target-text('#chapter',after)",
        "target-text('#chapter',first-letter)",
        "contents",
        "content()",
    ] {
        let html = format!("<style>p::after{{content:{value};content:' tail'}}</style><p>Body</p>");
        let output = render_html(&html, &local_options()).unwrap();
        assert!(
            !output
                .diagnostics
                .iter()
                .any(|d| matches!(d, RenderDiagnostic::Css(d)
            if d.kind == StyleDiagnosticKind::InvalidDeclaration)),
            "valid overridden content: {value}"
        );
    }
    for value in [
        "chapter content()",
        "chapter content(before) ':' content(after), title attr(title)",
        "chapter counter(section) '.' counters(subsection,'.')",
        "none",
    ] {
        let html = format!("<style>p{{string-set:{value};string-set:none}}</style><p>Body</p>");
        let output = render_html(&html, &local_options()).unwrap();
        assert!(
            !output
                .diagnostics
                .iter()
                .any(|d| matches!(d, RenderDiagnostic::Css(d)
            if d.kind == StyleDiagnosticKind::InvalidDeclaration)),
            "valid overridden string assignment: {value}"
        );
    }
    for value in [
        "string()",
        "string(chapter,)",
        "string(chapter,middle)",
        "target-counter('#chapter',page,)",
        "target-text('#chapter',)",
        "leader()",
    ] {
        let html = format!("<style>p::after{{content:' tail';content:{value}}}</style><p>Body</p>");
        let output = render_html(&html, &local_options()).unwrap();
        assert!(
            output
                .diagnostics
                .iter()
                .any(|d| matches!(d, RenderDiagnostic::Css(d)
            if d.kind == StyleDiagnosticKind::InvalidDeclaration)),
            "malformed content needs recovery: {value}"
        );
        assert!(
            output.layout.unwrap().pages[0]
                .iter()
                .any(|line| line.text.contains("tail")),
            "invalid content must preserve the earlier declaration: {value}"
        );
    }
}