ferri-pdf 0.1.9

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
//! CSS Writing Modes 4: vertical glyph selection and metrics from independent `HarfBuzz` samples.
use super::common;
use crate::layout::LayoutTrace;
use crate::text::GlyphOrientation;
use std::fmt::Write as _;

const SIZE_PT: f32 = 20.0;
const TOLERANCE: f32 = 1e-6;
const UNITS: f32 = 1000.0;

fn render(mode: &str, declarations: &str, body: &str) -> LayoutTrace {
    let mut options = common::local_options();
    options.base = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures/fonts")
        .into();
    let html = format!(
        "<style>@font-face{{font-family:CJK;src:url(CJKWritingTest.otf)}}\
        @page{{size:240pt 180pt;margin:20pt}}html{{writing-mode:{mode}}}\
        body{{margin:0;font:{SIZE_PT}pt/1 CJK;{declarations}}}p{{margin:0}}</style>{body}"
    );
    crate::render_html(&html, &options)
        .unwrap_or_else(|error| panic!("{mode}/{declarations}: {error}"))
        .layout
        .unwrap()
}

#[test]
fn vertical_substitutions_origins_and_advances_match_the_pinned_font_samples() {
    let reference: serde_json::Value = serde_json::from_str(include_str!(
        "../../tests/fixtures/fonts/CJKWritingTest-source.json"
    ))
    .unwrap();
    for mode in ["vertical-rl", "vertical-lr"] {
        for ch in "漢字水あア「」()〔〕、。A".chars() {
            let trace = render(mode, "", &format!("<p>{ch}</p>"));
            let run = &trace.pages[0][0].runs[0];
            let actual = &run.glyphs()[0];
            let expected = &reference["samples"]["ttb"][ch.to_string()][0];
            assert_eq!(
                actual.id,
                expected["g"].as_u64().unwrap() as u32,
                "{mode}/{ch}: vertical glyph"
            );
            for (name, actual, expected) in [
                (
                    "inline advance",
                    actual.x_advance,
                    -(expected["ay"].as_f64().unwrap() as f32) / UNITS,
                ),
                (
                    "vertical origin",
                    actual.x_offset,
                    -(expected["dy"].as_f64().unwrap() as f32) / UNITS,
                ),
                (
                    "cross-axis origin",
                    actual.y_offset,
                    expected["dx"].as_f64().unwrap() as f32 / UNITS
                        * if mode == "vertical-rl" { -1.0 } else { 1.0 },
                ),
            ] {
                assert!(
                    (actual - expected).abs() <= TOLERANCE,
                    "{mode}/{ch}: {name}: expected {expected}, got {actual}"
                );
            }
            assert!(
                matches!(
                    run.orientation,
                    GlyphOrientation::UprightRl | GlyphOrientation::UprightLr
                ),
                "{mode}/{ch}: {:?}",
                run.orientation
            );
        }
    }
    let sample = &reference["samples"];
    assert_ne!(
        sample["ltr"]["「"][0]["g"], sample["ttb"]["「"][0]["g"],
        "the fixture must distinguish horizontal and vertical punctuation glyphs"
    );
}

#[test]
fn mixed_orientation_keeps_cjk_upright_and_turns_latin_clockwise_in_both_column_orders() {
    for mode in ["vertical-rl", "vertical-lr"] {
        let trace = render(mode, "", "<p>漢A字</p>");
        let runs = &trace.pages[0][0].runs;
        let expected = if mode == "vertical-rl" {
            [
                GlyphOrientation::UprightRl,
                GlyphOrientation::Horizontal,
                GlyphOrientation::UprightRl,
            ]
        } else {
            [
                GlyphOrientation::UprightLr,
                GlyphOrientation::ReflectedSideways,
                GlyphOrientation::UprightLr,
            ]
        };
        assert_eq!(
            runs.iter().map(|run| run.orientation).collect::<Vec<_>>(),
            expected,
            "{mode}: mixed text orientation"
        );
    }
}

#[test]
fn orthogonal_frames_keep_their_links_and_destinations_in_physical_page_coordinates() {
    let trace = render(
        "vertical-rl",
        "",
        "<p>漢<span style='writing-mode:horizontal-tb'><a id=target href='#target'>A</a></span>字</p>",
    );
    assert_eq!(
        trace.links[0].len(),
        1,
        "the orthogonal hyperlink must survive frame pagination"
    );
    let destination = trace
        .destinations
        .iter()
        .flatten()
        .next()
        .expect("the orthogonal id has a destination");
    assert_eq!(destination.page, 0);
    assert!(
        destination.top >= 20.0 && destination.top < 160.0,
        "physical destination: {destination:?}"
    );
}

#[test]
fn combined_fullwidth_characters_select_native_width_forms_before_geometric_compression() {
    let reference: serde_json::Value = serde_json::from_str(include_str!(
        "../../tests/fixtures/fonts/CJKWritingTest-source.json"
    ))
    .unwrap();
    for (count, feature) in [(2, "hwid"), (3, "twid"), (4, "qwid")] {
        let trace = render(
            "vertical-rl",
            "text-combine-upright:all",
            &format!("<p>{}</p>", "A".repeat(count)),
        );
        let run = &trace.pages[0][0].runs[0];
        let expected = reference["samples"]["widths"][feature][0]["g"]
            .as_u64()
            .unwrap() as u32;
        if count == 2 {
            assert_ne!(
                expected,
                reference["samples"]["ltr"]["A"][0]["g"].as_u64().unwrap() as u32,
                "fixture must retain hwid substitution"
            );
        }
        assert!(
            run.glyphs().iter().all(|glyph| glyph.id == expected),
            "{count} characters must select the font's {feature} forms: {:?}",
            run.glyphs()
        );
        let advance = reference["samples"]["widths"][feature][0]["ax"]
            .as_f64()
            .unwrap() as f32
            / UNITS;
        let expected_scale = (1.0 / (count as f32 * advance)).min(1.0);
        assert!(
            (run.inline_scale - expected_scale).abs() <= TOLERANCE,
            "{feature}: native half-width forms precede compression; unavailable third/quarter forms need it: {}",
            run.inline_scale
        );
    }
}

#[test]
fn deep_native_flows_render_once_with_stacking_contexts_and_dynamic_positioned_jobs() {
    for (label, positioned, stacking) in [
        ("flow", false, false),
        ("stacking", false, true),
        ("positioned", true, false),
    ] {
        deep_native_flow(label, positioned, stacking, false);
    }
}

#[test]
fn deep_native_flows_inside_columns_render_once_on_the_default_stack() {
    deep_native_flow("columns", false, false, true);
}

fn deep_native_flow(label: &str, positioned: bool, stacking: bool, columns: bool) {
    const DEPTH: usize = 254;
    let mut body = String::new();
    for index in 0..DEPTH {
        let mode = if index % 2 == 0 {
            "vertical-rl"
        } else {
            "horizontal-tb"
        };
        let position = if positioned && index > 0 {
            "position:absolute;left:0;top:0;"
        } else if stacking {
            "position:relative;z-index:0;"
        } else {
            ""
        };
        let column_style = if columns { "column-count:1;" } else { "" };
        write!(
            body,
            "<section style='writing-mode:{mode};width:40pt;height:40pt;{position}{column_style}'>"
        )
        .unwrap();
        if positioned {
            body.push_str("<div style='position:relative;width:40pt;height:40pt'>");
        }
    }
    body.push_str("<p>A</p>");
    for _ in 0..DEPTH {
        if positioned {
            body.push_str("</div>");
        }
        body.push_str("</section>");
    }
    eprintln!("rendering {label}: {DEPTH} native boundaries");
    let trace = render(
        "horizontal-tb",
        "position:relative;width:100pt;height:100pt",
        &body,
    );
    let text: String = trace
        .pages
        .iter()
        .flatten()
        .map(|line| line.text.as_str())
        .collect();
    assert_eq!(
        text, "A",
        "{label}: complete native jobs must preserve the leaf once; provisional frame passes must never publish paint or text"
    );
    assert_eq!(
        trace.pages.len(),
        1,
        "{label}: nested fixed-size frames stay on one page"
    );
}

#[test]
fn implicit_columns_keep_their_content_and_trim_only_the_box_edges() {
    let lines = |declaration: &str| {
        let html = format!(
            "<style>section{{writing-mode:vertical-rl;width:30pt;{declaration}}}</style>\
             <section>A<br>B<br>C<br>D</section>"
        );
        crate::render_html(&html, &common::local_options())
            .unwrap_or_else(|error| panic!("{declaration}: {error}"))
            .layout
            .unwrap()
            .pages
            .concat()
            .into_iter()
            .map(|line| (line.text, line.x, line.baseline))
            .collect::<Vec<_>>()
    };
    let plain = lines("");
    assert_eq!(
        plain.len(),
        4,
        "two implicit columns of two lines: {plain:?}"
    );
    assert!(
        plain[2].1 > plain[0].1,
        "the third line starts a second column"
    );
    assert_eq!(
        lines("continue:discard"),
        plain,
        "an orthogonal flow's implicit columns are not overflow columns to discard"
    );
    let trimmed = lines("text-box-trim:trim-start");
    assert!(
        trimmed[0].2 < plain[0].2,
        "the box's first formatted line trims: {trimmed:?}"
    );
    assert_eq!(
        trimmed[2..],
        plain[2..],
        "implicit columns are not a multi-column container's columns to trim"
    );
}

#[test]
fn combined_emphasis_uses_one_object_replacement_character_for_skip_rules() {
    for mode in ["vertical-rl", "vertical-lr", "sideways-rl", "sideways-lr"] {
        for text in ["12", "AA"] {
            let body = format!("<p>{text}</p>");
            let plain = render(mode, "text-combine-upright:all", &body);
            let plain = &plain.pages[0][0];
            for (skip, expected) in [("spaces punctuation", 1), ("symbols", 0), ("narrow", 0)] {
                let trace = render(
                    mode,
                    &format!(
                        "text-combine-upright:all;text-emphasis:dot;text-emphasis-skip:{skip}"
                    ),
                    &body,
                );
                let line = &trace.pages[0][0];
                assert!(
                    line.runs.iter().any(|run| run.combined),
                    "{mode}/{text}: fixture must combine its characters"
                );
                let marks: usize = line
                    .runs
                    .iter()
                    .map(|run| run.marks.len() + run.mark_shapes.len())
                    .sum();
                assert_eq!(
                    marks, expected,
                    "{mode}/{text}/{skip}: one combined unit represents U+FFFC for emphasis eligibility"
                );
                assert!(
                    (line.width - plain.width).abs() <= TOLERANCE,
                    "{mode}/{text}/{skip}: emphasis leaves base advances unchanged"
                );
                if expected == 0 {
                    assert!(
                        (line.height - plain.height).abs() <= TOLERANCE,
                        "{mode}/{text}/{skip}: skipped marks must not grow line leading: {} vs {}",
                        line.height,
                        plain.height
                    );
                }
            }
        }
    }
}

#[test]
fn underline_left_and_right_choose_the_side_in_vertical_typographic_modes() {
    use crate::graphics::{DecorationLine, DisplayItem};
    for (mode, position, underline_under, overline_under) in [
        ("vertical-rl", "under left", true, false),
        ("vertical-rl", "right", false, true),
        ("vertical-lr", "under right", false, true),
        ("vertical-lr", "left", true, false),
        ("horizontal-tb", "under right", true, false),
    ] {
        let trace = render(
            mode,
            &format!("text-decoration:underline overline;text-underline-position:{position}"),
            "<p>AA</p>",
        );
        let baseline = trace.pages[0][0].baseline;
        let side = |line: DecorationLine| {
            let tops: Vec<f32> = trace.display_lists[0]
                .iter()
                .filter_map(|item| match item {
                    DisplayItem::Decoration(paint) if paint.line == line => Some(paint.rect.y),
                    _ => None,
                })
                .collect();
            assert!(!tops.is_empty(), "{mode}/{position}: {line:?} must paint");
            tops.iter().all(|top| *top > baseline)
        };
        assert_eq!(
            [
                side(DecorationLine::Underline),
                side(DecorationLine::Overline)
            ],
            [underline_under, overline_under],
            "{mode}/{position}: [underline, overline] below the baseline (line-under side)"
        );
    }
}

#[test]
fn emphasis_marks_take_their_side_from_left_and_right_in_vertical_typographic_modes() {
    for (mode, orientation, position, under) in [
        ("vertical-rl", "mixed", "over right", false),
        ("vertical-rl", "mixed", "over left", true),
        ("vertical-lr", "upright", "under right", false),
        ("vertical-lr", "upright", "under left", true),
        ("vertical-rl", "sideways", "under left", true),
        ("vertical-rl", "sideways", "over left", false),
        ("sideways-rl", "mixed", "under right", true),
        ("horizontal-tb", "mixed", "under right", true),
    ] {
        let trace = render(
            mode,
            &format!(
                "text-orientation:{orientation};text-emphasis:'A';\
                 text-emphasis-position:{position}"
            ),
            "<p>AA</p>",
        );
        let shifts: Vec<f32> = trace.pages[0][0]
            .runs
            .iter()
            .flat_map(|run| &run.marks)
            .map(|mark| mark.baseline_shift)
            .collect();
        assert!(
            !shifts.is_empty() && shifts.iter().all(|shift| (*shift > 0.0) == under),
            "{mode}/{orientation}/{position}: marks must sit on the line-{} side, shifts {shifts:?}",
            if under { "under" } else { "over" }
        );
    }
}