spindrift 0.1.0

A HTML/CSS to PDF renderer, targeting spec compliance and efficiency
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
use super::*;

/// Prepare CSS text-decoration strokes for one rendered inline line.
///
/// CSS Text Decoration paints decoration lines relative to the decorated text's
/// inline axis. Preparing strokes in an axis-aware form before emitting PDF
/// primitives lets horizontal and vertical writing share the same skip and
/// style pipeline:
/// <https://www.w3.org/TR/css-text-decor-3/#line-decoration> and
/// <https://www.w3.org/TR/css-writing-modes-4/#line-directions>.
pub(in crate::layout) fn prepare_text_decoration_strokes(
    input: TextDecorationPreparationInput<'_>,
) -> Vec<PreparedTextDecorationStroke> {
    let TextDecorationPreparationInput {
        baseline,
        inline_span,
        inset_start,
        inset_end,
        style,
        inset_style,
        inset_inline_axis,
        decoration,
        phase,
        color,
        color_override,
        geometry,
    } = input;
    if inline_span.length() <= 0.0 {
        return Vec::new();
    }

    let axis = if style.writing_mode == WritingMode::HorizontalTb {
        TextDecorationStrokeAxis::Horizontal
    } else {
        TextDecorationStrokeAxis::Vertical
    };
    let Some(inline_span) = text_decoration_inline_span(
        axis,
        inline_span,
        inset_start,
        inset_end,
        inset_style,
        inset_inline_axis,
    ) else {
        return Vec::new();
    };

    let underline_thickness = used_text_decoration_thickness(
        decoration.thickness.clone(),
        decoration_thickness_font_size(&decoration.thickness, geometry),
        &geometry.considered_metrics,
        false,
    );
    let strikeout_thickness = used_text_decoration_thickness(
        decoration.thickness.clone(),
        decoration_thickness_font_size(&decoration.thickness, geometry),
        &geometry.considered_metrics,
        true,
    );
    let mut strokes = Vec::new();

    if phase.paints_underlines()
        && decoration.underline
        && !text_decoration_skip_self_suppresses(style, TextDecorationLineKind::Underline)
    {
        strokes.push(PreparedTextDecorationStroke {
            axis,
            baseline,
            inline_span,
            block_position: text_decoration_block_position(
                axis,
                baseline.x,
                baseline.y,
                geometry.considered_font_size,
                style.writing_mode,
                decoration.underline_position,
                decoration.underline_offset.clone(),
                &geometry.considered_metrics,
                underline_thickness,
                TextDecorationPreparedLineKind::Underline,
            ),
            thickness: underline_thickness,
            color,
            style: decoration.style,
            skip_ink: decoration.skip_ink,
            skip_spaces: decoration.skip_spaces,
        });
    }

    if phase.paints_overlines()
        && decoration.overline
        && !text_decoration_skip_self_suppresses(style, TextDecorationLineKind::Overline)
    {
        strokes.push(PreparedTextDecorationStroke {
            axis,
            baseline,
            inline_span,
            block_position: text_decoration_block_position(
                axis,
                baseline.x,
                baseline.y,
                geometry.considered_font_size,
                style.writing_mode,
                decoration.underline_position,
                decoration.underline_offset.clone(),
                &geometry.considered_metrics,
                underline_thickness,
                TextDecorationPreparedLineKind::Overline,
            ),
            thickness: underline_thickness,
            color,
            style: decoration.style,
            skip_ink: decoration.skip_ink,
            skip_spaces: decoration.skip_spaces,
        });
    }

    if phase.paints_after_text()
        && decoration.line_through
        && !text_decoration_skip_self_suppresses(style, TextDecorationLineKind::LineThrough)
    {
        strokes.push(PreparedTextDecorationStroke {
            axis,
            baseline,
            inline_span,
            block_position: text_decoration_block_position(
                axis,
                baseline.x,
                baseline.y,
                geometry.considered_font_size,
                style.writing_mode,
                decoration.underline_position,
                decoration.underline_offset.clone(),
                &geometry.considered_metrics,
                strikeout_thickness,
                TextDecorationPreparedLineKind::LineThrough,
            ),
            thickness: strikeout_thickness,
            color,
            style: decoration.style,
            skip_ink: decoration.skip_ink,
            skip_spaces: decoration.skip_spaces,
        });
    }

    if phase.paints_underlines() && decoration.spelling_error {
        strokes.push(PreparedTextDecorationStroke {
            axis,
            baseline,
            inline_span,
            block_position: text_decoration_block_position(
                axis,
                baseline.x,
                baseline.y,
                geometry.considered_font_size,
                style.writing_mode,
                decoration.underline_position,
                decoration.underline_offset.clone(),
                &geometry.considered_metrics,
                underline_thickness,
                TextDecorationPreparedLineKind::Underline,
            ),
            thickness: underline_thickness,
            color: color_override.unwrap_or(CssColor::new(255, 0, 0)),
            style: TextDecorationStyle::Wavy,
            skip_ink: TextDecorationSkipInk::None,
            skip_spaces: TextDecorationSkipSpaces::NONE,
        });
    }

    if phase.paints_underlines() && decoration.grammar_error {
        strokes.push(PreparedTextDecorationStroke {
            axis,
            baseline,
            inline_span,
            block_position: text_decoration_block_position(
                axis,
                baseline.x,
                baseline.y,
                geometry.considered_font_size,
                style.writing_mode,
                decoration.underline_position,
                decoration.underline_offset,
                &geometry.considered_metrics,
                underline_thickness,
                TextDecorationPreparedLineKind::Underline,
            ),
            thickness: underline_thickness,
            color: color_override.unwrap_or(CssColor::new(0, 128, 0)),
            style: TextDecorationStyle::Wavy,
            skip_ink: TextDecorationSkipInk::None,
            skip_spaces: TextDecorationSkipSpaces::NONE,
        });
    }

    strokes
}

/// Select the percentage basis for a decoration thickness.
///
/// Explicit lengths and percentages are values of the decorating origin;
/// automatic and font-derived thickness are selected from the considered text
/// on this line.
fn decoration_thickness_font_size(
    thickness: &TextDecorationThickness,
    geometry: TextDecorationLineGeometry,
) -> f32 {
    match thickness {
        TextDecorationThickness::Auto | TextDecorationThickness::FromFont => {
            geometry.considered_font_size
        }
        TextDecorationThickness::LengthPercentage(_) => geometry.origin_font_size,
    }
}

pub(in crate::layout) fn text_decoration_inline_span(
    axis: TextDecorationStrokeAxis,
    span: TextInlineSpan,
    inset_start: f32,
    inset_end: f32,
    _inset_style: &ComputedStyle,
    inset_inline_axis: TextDecorationInlineAxis,
) -> Option<TextInlineSpan> {
    debug_assert_eq!(axis, inset_inline_axis.stroke_axis());
    inset_inline_axis.inset_span(span, inset_start, inset_end)
}

#[allow(clippy::too_many_arguments)]
pub(in crate::layout) fn text_decoration_block_position(
    axis: TextDecorationStrokeAxis,
    x: f32,
    baseline_y: f32,
    considered_font_size: f32,
    writing_mode: WritingMode,
    underline_position: TextUnderlinePosition,
    underline_offset: TextUnderlineOffset,
    metrics: &TextDecorationFontMetrics,
    thickness: f32,
    kind: TextDecorationPreparedLineKind,
) -> f32 {
    match axis {
        TextDecorationStrokeAxis::Horizontal => match kind {
            // The CSS zero position is the inner edge of an underline. In
            // page coordinates text-under points toward decreasing y, so the
            // painted stroke extends its full thickness outward from that
            // edge rather than back through the glyph ink.
            // <https://drafts.csswg.org/css-text-decor-4/#text-underline-offset-property>
            TextDecorationPreparedLineKind::Underline => {
                used_underline_y(
                    baseline_y,
                    underline_position,
                    underline_offset,
                    considered_font_size,
                    metrics,
                ) - thickness
            }
            TextDecorationPreparedLineKind::Overline => baseline_y + considered_font_size,
            TextDecorationPreparedLineKind::LineThrough => baseline_y + metrics.strikeout_position,
        },
        TextDecorationStrokeAxis::Vertical => {
            match kind {
                TextDecorationPreparedLineKind::Underline => {
                    // `text-underline-offset` applies only to the underline;
                    // it must not move an overline or a line-through.  Keep
                    // the signed used value: a negative offset intentionally
                    // moves an underline back toward the text.
                    // <https://www.w3.org/TR/css-text-decor-4/#text-underline-offset-property>
                    let offset = used_text_underline_offset(underline_offset, considered_font_size);
                    vertical_text_decoration_side_position(
                        x,
                        considered_font_size,
                        resolve_vertical_underline_side(underline_position, writing_mode),
                        thickness,
                        offset,
                    )
                }
                TextDecorationPreparedLineKind::Overline => vertical_text_decoration_side_position(
                    x,
                    considered_font_size,
                    opposite_text_decoration_side(resolve_vertical_underline_side(
                        underline_position,
                        writing_mode,
                    )),
                    thickness,
                    0.0,
                ),
                TextDecorationPreparedLineKind::LineThrough => x + considered_font_size * 0.5,
            }
        }
    }
}

pub(in crate::layout) fn resolve_vertical_underline_side(
    position: TextUnderlinePosition,
    writing_mode: WritingMode,
) -> TextDecorationSide {
    if position.left {
        return TextDecorationSide::Left;
    }
    if position.right {
        return TextDecorationSide::Right;
    }
    match css::line_under_side(writing_mode) {
        PhysicalSide::Left => TextDecorationSide::Left,
        PhysicalSide::Right => TextDecorationSide::Right,
        PhysicalSide::Top | PhysicalSide::Bottom => TextDecorationSide::Right,
    }
}

pub(in crate::layout) fn opposite_text_decoration_side(
    side: TextDecorationSide,
) -> TextDecorationSide {
    match side {
        TextDecorationSide::Left => TextDecorationSide::Right,
        TextDecorationSide::Right => TextDecorationSide::Left,
    }
}

pub(in crate::layout) fn vertical_text_decoration_side_position(
    x: f32,
    font_size: f32,
    side: TextDecorationSide,
    thickness: f32,
    offset: f32,
) -> f32 {
    match side {
        TextDecorationSide::Left => x - thickness - offset,
        TextDecorationSide::Right => x + font_size + offset,
    }
}

/// Adjust inline fragment background/border painting for sliced inline boxes.
///
/// CSS Fragmentation defines `box-decoration-break: slice` as the initial
/// behavior: inline-start decorations are painted only on the first fragment,
/// inline-end decorations only on the last fragment, while top/bottom
/// decorations continue on every line fragment. CSS 2.2 positions non-replaced
/// inline padding and borders from the content-area edges, not from the
/// line-height box:
/// <https://www.w3.org/TR/CSS22/visuren.html#inline-formatting>,
/// <https://www.w3.org/TR/CSS22/visudet.html#line-height>, and
/// <https://www.w3.org/TR/css-backgrounds-3/#box-decoration-break>.
pub(in crate::layout) fn apply_inline_fragment_edge_painting(
    style: &mut ComputedStyle,
    edges: InlineHangingEdges,
    x: &mut f32,
    y: &mut f32,
    width: &mut f32,
    height: &mut f32,
) {
    let borders = used_border_widths(style);
    let top_extra = borders.top + style.padding.top;
    let bottom_extra = borders.bottom + style.padding.bottom;
    *y -= bottom_extra;
    *height += top_extra + bottom_extra;
    let start_extra = match style.direction {
        Direction::Ltr => borders.left + style.padding.left,
        Direction::Rtl => borders.right + style.padding.right,
    };
    let end_extra = match style.direction {
        Direction::Ltr => borders.right + style.padding.right,
        Direction::Rtl => borders.left + style.padding.left,
    };
    if edges.blocks_start {
        match style.direction {
            Direction::Ltr => *x -= start_extra,
            Direction::Rtl => {}
        }
        *width += start_extra;
    } else {
        match style.direction {
            Direction::Ltr => {
                style.border_widths.left = 0.0;
                style.border_styles.left = BorderStyle::None;
                style.padding.left = 0.0;
            }
            Direction::Rtl => {
                style.border_widths.right = 0.0;
                style.border_styles.right = BorderStyle::None;
                style.padding.right = 0.0;
            }
        }
    }
    if edges.blocks_end {
        match style.direction {
            Direction::Ltr => {}
            Direction::Rtl => *x -= end_extra,
        }
        *width += end_extra;
    } else {
        match style.direction {
            Direction::Ltr => {
                style.border_widths.right = 0.0;
                style.border_styles.right = BorderStyle::None;
                style.padding.right = 0.0;
            }
            Direction::Rtl => {
                style.border_widths.left = 0.0;
                style.border_styles.left = BorderStyle::None;
                style.padding.left = 0.0;
            }
        }
    }
}

/// Build the debug/extraction summary for a painted inline-fragment group.
///
/// CSS Text collapses document white space at inline box boundaries before
/// paint groups are prepared, while Parley-shaped glyph runs preserve the
/// actual Unicode clusters emitted to PDF. `RenderedLine::text` is a line
/// summary used by layout tests and diagnostics, so it keeps internal
/// collapsed spaces even when style or bidi boundaries split one line into
/// several PDF text objects:
/// <https://www.w3.org/TR/css-text-3/#white-space-processing> and
/// <https://www.w3.org/TR/css-inline-3/#line-box>.
pub(in crate::layout) fn inline_fragment_text_summary<F: InlineFragmentAccess>(
    fragments: &[F],
    preserve_leading_summary_space: bool,
    synthesize_leading_summary_space: bool,
) -> String {
    let mut summary = String::new();
    for (index, fragment) in fragments.iter().enumerate() {
        if index == 0 && synthesize_leading_summary_space {
            summary.push(' ');
            summary.push_str(fragment.text());
        } else if index == 0
            && !preserve_leading_summary_space
            && fragment.style().white_space.collapses_spaces()
        {
            summary.push_str(trim_start_css_collapsible_whitespace(fragment.text()));
        } else {
            summary.push_str(fragment.text());
        }
    }
    summary
}