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
use super::*;
use crate::css::{ModeledLonghandSet, copy_modeled_longhand, modeled_longhand_has_same_source};
pub(in crate::layout) fn apply_first_line_pseudos_to_line_items(
    items: &mut Vec<InlineLineItem>,
    block_style: &ComputedStyle,
    apply_first_letter: bool,
    font_system: &mut FontSystem,
) {
    if let Some(first_line_style) = block_style.first_line_style.as_deref() {
        for item in items.iter_mut() {
            match item {
                InlineLineItem::Fragment(fragment) => {
                    // CSS Overflow inserts a block ellipsis *after* the
                    // clamp container's first formatted line is determined.
                    // It is an anonymous inline of the terminal root inline
                    // box, not source content participating in `::first-line`.
                    // <https://drafts.csswg.org/css-overflow-4/#block-ellipsis>
                    if matches!(fragment.source(), InlineTextSource::BlockEllipsis) {
                        continue;
                    }
                    if apply_first_line_style_delta(
                        fragment.style_mut(),
                        block_style,
                        first_line_style,
                        &block_style.first_line_overrides,
                    ) {
                        fragment.set_force_inline_background_paint(true);
                    }
                    fragment.apply_to_ancestor_inline_decoration_styles(|style| {
                        apply_first_line_style_delta(
                            style,
                            block_style,
                            first_line_style,
                            &block_style.first_line_overrides,
                        );
                    });
                }
                InlineLineItem::Atom(atom) => {
                    if matches!(
                        atom.content(),
                        InlineAtomContent::InlineEdge(InlineEdgeRole::BoxEdge(_))
                    ) {
                        if first_line_style.color != block_style.color
                            && atom.style().color == block_style.color
                        {
                            atom.set_current_color_override(first_line_style.color);
                        }
                        continue;
                    }
                    if matches!(
                        atom.content(),
                        InlineAtomContent::InlineEdge(InlineEdgeRole::TextAutospace(_))
                    ) {
                        let mut style = atom.style().clone();
                        apply_first_line_style_delta(
                            &mut style,
                            block_style,
                            first_line_style,
                            &block_style.first_line_overrides,
                        );
                        let advance = font_system.ic_advance_for_style(&style) / 8.0;
                        atom.set_text_autospace_advance(&style, advance);
                        continue;
                    }
                    let content = Rc::make_mut(&mut atom.data);
                    let InlineAtomContent::Ruby {
                        base,
                        annotations,
                        annotation_sides,
                        ..
                    } = &mut content.content
                    else {
                        continue;
                    };
                    apply_first_line_style_to_ruby_level(
                        base,
                        block_style,
                        first_line_style,
                        &block_style.first_line_overrides,
                    );
                    for (annotation, side) in annotations.iter_mut().zip(annotation_sides) {
                        apply_first_line_style_to_ruby_level(
                            annotation,
                            block_style,
                            first_line_style,
                            &block_style.first_line_overrides,
                        );
                        *side = annotation.style.ruby_position.interlinear_side();
                    }
                }
                InlineLineItem::Float(_) => {}
            }
        }
    }
    if apply_first_letter
        && let Some(first_letter_style) = block_style.first_letter_style.as_deref()
    {
        apply_first_letter_pseudo_to_line_items(items, first_letter_style);
    }
}

/// Replay the originating block's first-line inheritance into a ruby level's
/// already-selected inner line records. Ruby collection captures these records
/// before the parent line has been selected, so changing only the level style
/// would leave its text fragments with stale inherited values at paint time.
///
/// CSS Pseudo specifies that inherited first-line values apply to the first
/// line's descendants, rather than creating a new `ruby::first-line` scope.
/// <https://drafts.csswg.org/css-pseudo-4/#first-line-pseudo>
fn apply_first_line_style_to_ruby_level(
    level: &mut RubyInlineLevel,
    originating_style: &ComputedStyle,
    first_line_style: &ComputedStyle,
    overrides: &ModeledLonghandSet,
) {
    apply_first_line_style_delta(
        &mut level.style,
        originating_style,
        first_line_style,
        overrides,
    );
    for record in &mut level.sequence.records {
        let Some(fragment) = &mut record.fragment else {
            continue;
        };
        for measured in Rc::make_mut(&mut fragment.items).iter_mut() {
            match &mut measured.item {
                InlineLineItem::Fragment(fragment) => {
                    apply_first_line_style_delta(
                        fragment.style_mut(),
                        originating_style,
                        first_line_style,
                        overrides,
                    );
                }
                InlineLineItem::Atom(_) | InlineLineItem::Float(_) => {}
            }
        }
    }
}

/// Materialize the canonical properties established by `::first-line`
/// without discarding a nested inline fragment's own cascade.
///
/// The cascade records both the pseudo's affected longhands and the source
/// owner of every computed value. A descendant receives a generated-box value
/// only while its source still traces to the originating block; an explicit
/// descendant declaration therefore wins even when its computed value happens
/// to equal the block's value.
/// <https://drafts.csswg.org/css-pseudo-4/#first-line-pseudo>
pub(in crate::layout) fn apply_first_line_style_delta(
    fragment_style: &mut ComputedStyle,
    originating_style: &ComputedStyle,
    first_line_style: &ComputedStyle,
    overrides: &ModeledLonghandSet,
) -> bool {
    let mut background_changed = false;
    for longhand in overrides.iter() {
        let is_background = longhand.css_name().starts_with("background");
        // Non-inherited effects belong to the generated first-line box and
        // are consumed by its dedicated paint scope. Only background geometry
        // and vertical alignment need fragment-local materialization.
        if !longhand.is_inherited() && !is_background && longhand.css_name() != "vertical-align" {
            continue;
        }
        if !modeled_longhand_has_same_source(fragment_style, originating_style, longhand) {
            continue;
        }
        if is_background {
            background_changed = true;
        }
        copy_modeled_longhand(fragment_style, first_line_style, longhand);
    }
    background_changed
}

pub(in crate::layout) fn apply_first_letter_pseudo_to_line_items(
    items: &mut Vec<InlineLineItem>,
    first_letter_style: &ComputedStyle,
) {
    for index in 0..items.len() {
        let InlineLineItem::Fragment(fragment) = &items[index] else {
            continue;
        };
        let Some(range) = first_letter_byte_range(fragment.text()) else {
            continue;
        };
        let pieces = split_fragment_for_first_letter(fragment, range, first_letter_style)
            .into_iter()
            .map(InlineLineItem::Fragment)
            .collect::<Vec<_>>();
        items.splice(index..=index, pieces);
        break;
    }
}

pub(in crate::layout) fn split_fragment_for_first_letter(
    fragment: &InlineFragment,
    range: std::ops::Range<usize>,
    first_letter_style: &ComputedStyle,
) -> Vec<InlineFragment> {
    let mut pieces = Vec::new();
    if range.start > 0 {
        let mut before = fragment.clone();
        before.set_text(Rc::<str>::from(&fragment.text()[..range.start]));
        pieces.push(before);
    }
    let mut letter = fragment.clone();
    letter.set_text(Rc::<str>::from(&fragment.text()[range.clone()]));
    *letter.style_mut() = first_letter_style.clone();
    letter.set_mergeable(false);
    pieces.push(letter);
    if range.end < fragment.text().len() {
        let mut after = fragment.clone();
        after.set_text(Rc::<str>::from(&fragment.text()[range.end..]));
        pieces.push(after);
    }
    pieces
}

pub(in crate::layout) fn first_letter_byte_range(text: &str) -> Option<std::ops::Range<usize>> {
    /// Classify a complete CSS typographic character unit by its visible base
    /// character. Combining marks and default-ignorable controls remain in
    /// the selected unit rather than creating their own first-letter choice.
    fn unit_base(unit: &str) -> Option<char> {
        unit.chars().find(|character| {
            !character_is_unicode_mark(*character)
                && !character_is_default_ignorable_code_point(*character)
        })
    }

    let units = CursiveProtectedUnitRanges::new(text);
    let mut prefix_start = None;
    let mut selected_start = None;
    let mut selected_end = None;
    let mut pending_suffix_space_start = None;

    for range in units {
        let unit = &text[range.clone()];
        let Some(base) = unit_base(unit) else {
            continue;
        };

        let selected = selected_start.is_some();
        if !selected {
            if character_is_first_letter_associated_space(base) && prefix_start.is_some() {
                continue;
            }
            if base.is_whitespace() && prefix_start.is_none() {
                // Leading white space is selected separately when preserved;
                // ordinary collapsed space cannot create first-letter text.
                continue;
            }
            if character_is_unicode_punctuation(base) {
                prefix_start.get_or_insert(range.start);
                continue;
            }
            if character_is_unicode_first_letter_base(base) {
                selected_start = Some(prefix_start.unwrap_or(range.start));
                selected_end = Some(range.end);
                continue;
            }
            // A non-punctuation, non-base unit between an associated prefix
            // and a prospective initial prevents that prefix from attaching.
            if prefix_start.is_some() {
                return None;
            }
            continue;
        }

        if character_is_first_letter_associated_space(base) {
            pending_suffix_space_start.get_or_insert(range.start);
            continue;
        }
        if character_is_first_letter_suffix_punctuation(base) {
            if let Some(space_start) = pending_suffix_space_start.take() {
                selected_end = Some(range.end.max(space_start));
            } else {
                selected_end = Some(range.end);
            }
            continue;
        }
        break;
    }

    selected_start
        .zip(selected_end)
        .map(|(start, end)| start..end)
}

#[cfg(test)]
mod first_letter_tests {
    use super::first_letter_byte_range;

    #[test]
    fn selects_symbol_first_letters_and_associated_punctuation() {
        for (text, expected) in [
            ("$1,234.56", "$"),
            ("(£)78.90", "(£)"),
            ("₹10,000", "₹"),
            ("©2021", "©"),
        ] {
            let range = first_letter_byte_range(text).expect("expected first-letter text");
            assert_eq!(&text[range], expected, "{text}");
        }
    }

    #[test]
    fn preserves_complete_typographic_units_and_associated_spaces() {
        let text = "“\u{00a0}e\u{301}”x";
        let range = first_letter_byte_range(text).expect("expected first-letter text");
        assert_eq!(&text[range], "“\u{00a0}e\u{301}”");
    }

    #[test]
    fn rejects_unassociated_prefix_punctuation() {
        assert_eq!(first_letter_byte_range("(\u{3000}A"), None);
    }
}

#[cfg(test)]
mod inter_character_unit_tests {
    use super::*;

    fn fragment(text: &str, generated_leader: bool) -> InlineFragment {
        InlineFragment::new(
            text,
            ComputedStyle::initial(),
            0.0,
            None,
            true,
            InlineTextSource::Normal,
            generated_leader,
            InlineHangingEdges::default(),
            Vec::new(),
        )
    }

    #[test]
    fn inter_character_unit_eligibility_requires_nonempty_non_leader_text() {
        assert!(!inline_fragment_is_inter_character_unit(&fragment(
            "", false
        )));
        assert!(!inline_fragment_is_inter_character_unit(&fragment(
            "text", true
        )));
        assert!(inline_fragment_is_inter_character_unit(&fragment(
            "text", false
        )));
        assert!(inline_fragment_is_inter_character_unit(&fragment(
            "\u{200e}", false
        )));
    }
}

#[cfg(test)]
mod first_line_autospace_tests {
    use super::*;

    #[test]
    fn first_line_materializes_font_synthesis_subproperties() {
        let originating = ComputedStyle::initial();
        let mut pseudo = originating.clone();
        pseudo.font_synthesis.weight = false;
        pseudo.font_synthesis.style = false;
        let mut overrides = ModeledLonghandSet::empty();
        overrides.insert_css_name("font-synthesis-weight");
        overrides.insert_css_name("font-synthesis-style");
        let mut fragment = originating.clone();

        apply_first_line_style_delta(&mut fragment, &originating, &pseudo, &overrides);

        assert!(!fragment.font_synthesis.weight);
        assert!(!fragment.font_synthesis.style);
    }

    #[test]
    fn first_line_remeasures_an_autospace_marker_with_its_font_style() {
        let mut block_style = ComputedStyle::initial();
        block_style.font_size = 12.0;
        let mut first_line_style = block_style.clone();
        first_line_style.font_size = 48.0;
        block_style
            .first_line_overrides
            .insert_css_name("font-size");
        block_style.first_line_style = Some(Box::new(first_line_style));
        let mut font_system = FontSystem::new();
        let initial_advance = font_system.ic_advance_for_style(&block_style) / 8.0;
        let mut items = vec![InlineLineItem::Atom(InlineAtom::new(
            InlineAtomContent::InlineEdge(InlineEdgeRole::TextAutospace(
                InlineTextBoundarySpacing::new(initial_advance),
            )),
            block_style.clone(),
            None,
            InlineSize::new(initial_advance.points(), 0.0),
            0.0,
            0.0,
            None,
            None,
        ))];

        apply_first_line_pseudos_to_line_items(&mut items, &block_style, false, &mut font_system);

        let InlineLineItem::Atom(atom) = &items[0] else {
            panic!("test setup creates an autospace atom");
        };
        let InlineAtomContent::InlineEdge(InlineEdgeRole::TextAutospace(spacing)) = atom.content()
        else {
            panic!("expected an autospace atom");
        };
        assert_eq!(atom.style().font_size, 48.0);
        assert_eq!(
            spacing.advance().points(),
            (font_system.ic_advance_for_style(atom.style()) / 8.0).points()
        );
        assert_ne!(spacing.advance().points(), initial_advance.points());
    }
}