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
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
use super::*;
use crate::css::{FontSizeAdjust, FontSizeAdjustValue, FontVariationSettings};
use crate::text::system::api::{font_feature_family, font_size_adjust_metric_ratio};

/// The font-family selection made for a styled `unicode-range` fragment.
///
/// It is deliberately limited to face selection at the shaping boundary.
/// CSS metrics, provenance, and every property other than `font-family`
/// remain on the authored computed style.
#[derive(Debug)]
pub(in crate::text) struct SelectedFaceStyleView<'a> {
    authored: &'a ComputedStyle,
    selected_family: Option<FontFamily>,
}

impl<'a> SelectedFaceStyleView<'a> {
    pub(in crate::text) fn new(
        authored: &'a ComputedStyle,
        selected_family: Option<FontFamily>,
    ) -> Self {
        Self {
            authored,
            selected_family,
        }
    }

    pub(in crate::text) fn authored(&self) -> &'a ComputedStyle {
        self.authored
    }

    pub(in crate::text) fn font_family(&self) -> &FontFamily {
        self.selected_family
            .as_ref()
            .unwrap_or(&self.authored.font_family)
    }

    pub(in crate::text) fn has_same_effective_style(&self, other: &Self) -> bool {
        self.authored == other.authored && self.font_family() == other.font_family()
    }

    /// Return the CSS boundary effect relevant to glyph shaping.
    ///
    /// Paint properties such as color, text decoration, and font palette must
    /// remain separate for painting but must not force a new shaping context.
    /// Font selection and OpenType inputs do affect shaping and may require
    /// synthetic join context when the backend cannot carry context across
    /// the boundary:
    /// <https://drafts.csswg.org/css-text-3/#boundary-shaping>.
    pub(in crate::text) fn boundary_effect(&self, other: &Self) -> InlineBoundaryEffect {
        if self.has_same_shaping_inputs(other) {
            InlineBoundaryEffect::PaintOnly
        } else {
            InlineBoundaryEffect::ShapingInputChange
        }
    }

    fn has_same_shaping_inputs(&self, other: &Self) -> bool {
        let left = self.authored;
        let right = other.authored;
        self.font_family() == other.font_family()
            && left.font_size == right.font_size
            && left.font_size_adjust == right.font_size_adjust
            && left.line_height == right.line_height
            && left.font_weight == right.font_weight
            && left.font_style == right.font_style
            && left.font_width == right.font_width
            && left.font_synthesis == right.font_synthesis
            && left.font_feature_settings == right.font_feature_settings
            && left.text_spacing_trim == right.text_spacing_trim
            && left.font_variation_settings == right.font_variation_settings
            && left.font_kerning == right.font_kerning
            && left.font_variant_ligatures == right.font_variant_ligatures
            && left.font_variant_position == right.font_variant_position
            && left.font_variant_caps == right.font_variant_caps
            && left.font_variant_numeric == right.font_variant_numeric
            && left.font_variant_alternates == right.font_variant_alternates
            && left.font_variant_east_asian == right.font_variant_east_asian
            && left.font_variant_emoji == right.font_variant_emoji
            && left.overflow_wrap == right.overflow_wrap
            && left.text_wrap_mode == right.text_wrap_mode
            && left.word_spacing == right.word_spacing
            && left.letter_spacing == right.letter_spacing
            && left.language == right.language
            && left.writing_mode == right.writing_mode
            && left.text_orientation == right.text_orientation
    }
}

impl FontSystem {
    /// Run one Parley shaping pass with layout storage retained for the next
    /// pass in this document.
    ///
    /// Parley lines borrow their layout, while Spindrift converts them into owned
    /// glyph runs before this closure returns. Taking the scratch out of
    /// [`FontSystem`] keeps those borrows separate from the mutable font
    /// system needed during conversion and guarantees restoration on every
    /// normal closure return, including its early returns.
    pub(in crate::text) fn with_reusable_parley_layout<T>(
        &mut self,
        shape: impl FnOnce(&mut Self, &mut ParleyLayout<FontPalette>) -> T,
    ) -> T {
        let mut layout = std::mem::take(&mut self.parley_layout_scratch);
        let result = shape(self, &mut layout);
        self.parley_layout_scratch = layout;
        result
    }

    #[cfg(test)]
    pub(crate) fn new() -> Self {
        Self::from_seed(Self::sync_seed())
    }

    pub(crate) fn into_fonts(self) -> Vec<DocumentFont> {
        self.document_fonts.into_fonts()
    }

    pub(in crate::text) fn font_feature_context_for_style(
        &mut self,
        style: &ComputedStyle,
    ) -> Option<FontFeatureContext> {
        self.font_feature_context_for_family(style, &style.font_family)
    }

    pub(in crate::text) fn font_feature_context_for_selected_face(
        &mut self,
        style: &SelectedFaceStyleView<'_>,
    ) -> Option<FontFeatureContext> {
        self.font_feature_context_for_family(style.authored(), style.font_family())
    }

    fn font_feature_context_for_family(
        &mut self,
        style: &ComputedStyle,
        family: &FontFamily,
    ) -> Option<FontFeatureContext> {
        // `font-feature-settings` defaults in an @font-face rule belong to
        // the selected face, rather than its family. Resolve the authored
        // face directly: a descriptor applies while shaping the face's own
        // supported characters, even when the face cannot render U+0020 and
        // is therefore unsuitable for a metric-only probe.
        // <https://www.w3.org/TR/css-fonts-4/#font-face-font-feature-settings>
        let selected_face = self
            .resolve_font_family(
                family,
                style.font_weight,
                style.font_style,
                style.font_width,
            )
            .and_then(|font_id| self.document_fonts.selected_face_features(font_id));
        let (family, face_defaults) = selected_face
            .map(|(family, defaults)| (Some(family), Some(defaults)))
            .unwrap_or_else(|| (font_feature_family(family), None));
        if face_defaults.is_none() && self.font_feature_values.values.is_empty() {
            return None;
        }
        Some(FontFeatureContext {
            family,
            face_defaults,
            font_feature_values: self.font_feature_values.clone(),
        })
    }

    /// Merge selected-face descriptor coordinates into the style's explicit
    /// variation map. The element property remains later in the map and thus
    /// wins duplicate tags, while descriptor coordinates override registered
    /// CSS-axis defaults during shaping.
    fn selected_face_variation_settings(
        &mut self,
        style: &ComputedStyle,
        family: &FontFamily,
    ) -> Option<FontVariationSettings> {
        // Descriptor defaults belong to the authored face selected from the
        // CSS family, not to the font used for U+0020 line metrics. A
        // selected face may not contain U+0020 while still rendering its
        // supported glyphs with these variation coordinates.
        // <https://www.w3.org/TR/css-fonts-4/#font-feature-variation-resolution>
        let font_id = self.resolve_font_family(
            family,
            style.font_weight,
            style.font_style,
            style.font_width,
        )?;
        let descriptor = self.document_fonts.selected_face_variations(font_id)?;
        if descriptor.0.is_empty() {
            return None;
        }
        let mut variations = descriptor.0;
        for setting in &style.font_variation_settings.0 {
            if let Some(existing) = variations
                .iter_mut()
                .find(|existing| existing.tag == setting.tag)
            {
                *existing = *setting;
            } else {
                variations.push(*setting);
            }
        }
        variations.sort_by_key(|setting| setting.tag);
        Some(FontVariationSettings(variations))
    }

    /// Prepare the style passed to the shaping backend after CSS face
    /// selection. A fixed selected face cannot receive faux bold or italic
    /// when the corresponding `font-synthesis` gate is disabled. Keeping the
    /// gate at this boundary preserves the backend's complete glyph stream
    /// (including GPOS kerning), instead of replacing it with a simplified
    /// post-shaping fallback.
    /// <https://www.w3.org/TR/css-fonts-4/#font-synthesis-intro>
    pub(in crate::text) fn shaping_style_for_selected_face<'a>(
        &mut self,
        style: &'a ComputedStyle,
    ) -> ParleyStyleView<'a> {
        let selected_style = SelectedFaceStyleView::new(style, None);
        self.shaping_style_for_selected_face_view(&selected_style)
    }

    pub(in crate::text) fn shaping_style_for_selected_face_view<'a>(
        &mut self,
        style: &SelectedFaceStyleView<'a>,
    ) -> ParleyStyleView<'a> {
        let authored = style.authored();
        let mut shaping_style = ParleyStyleView::new(authored);
        if let Some(variations) =
            self.selected_face_variation_settings(authored, style.font_family())
        {
            shaping_style.set_font_variation_settings(variations);
        }
        let Some(font_id) = self.resolve_metric_font_for_family(authored, style.font_family())
        else {
            return shaping_style;
        };
        let selected_attributes = self.document_fonts.selected_face_fixed_attributes(font_id);
        let is_registered_css_family = named_font_families(style.font_family())
            .iter()
            .any(|family| self.document_fonts.has_registered_css_family(family));
        let intrinsic_attributes = is_registered_css_family
            .then(|| {
                self.document_fonts.get(font_id).and_then(|font| {
                    let face = ttf_parser::Face::parse(&font.data, font.face_index).ok()?;
                    Some((
                        FontWeight::from_number(face.weight().to_number() as f32)?,
                        if face.is_italic() {
                            FontStyle::Italic
                        } else {
                            FontStyle::Normal
                        },
                    ))
                })
            })
            .flatten();
        let (weight, face_style) = match (selected_attributes, intrinsic_attributes) {
            (Some((weight, style)), _) => (weight, style),
            (None, Some((weight, style))) => (Some(weight), style),
            (None, None) => return shaping_style,
        };
        if !authored.font_synthesis.weight
            && let Some(weight) = weight
            && weight != authored.font_weight
        {
            shaping_style.set_font_weight(weight);
        }
        if !authored.font_synthesis.style && face_style != authored.font_style {
            shaping_style.set_font_style(face_style);
        }
        shaping_style
    }

    pub(crate) fn resolve_style(&mut self, style: &ComputedStyle) -> Option<usize> {
        if let Some(id) = self.resolve_font_family(
            &style.font_family,
            style.font_weight,
            style.font_style,
            style.font_width,
        ) {
            return Some(id);
        }
        self.resolve_system_fallback_for_character(
            'M',
            style.font_weight,
            style.font_style,
            style.font_width,
        )
    }

    /// Return whether the selected face advertises a caps substitution feature.
    ///
    /// CSS may synthesize small caps only when the selected face cannot provide
    /// the relevant OpenType feature itself.
    /// <https://drafts.csswg.org/css-fonts-4/#font-variant-caps-prop>
    pub(crate) fn selected_font_supports_caps_feature(&mut self, style: &ComputedStyle) -> bool {
        let Some(font_id) = self.resolve_metric_font_for_style(style) else {
            return false;
        };
        let Some(font) = self.document_fonts.get(font_id) else {
            return false;
        };
        let Ok(face) = ttf_parser::Face::parse(&font.data, font.face_index) else {
            return false;
        };
        let Some(gsub) = face.tables().gsub else {
            return false;
        };
        [b"smcp", b"c2sc", b"pcap", b"c2pc"]
            .into_iter()
            .any(|wanted| {
                let wanted = ttf_parser::Tag::from_bytes(wanted);
                gsub.features
                    .into_iter()
                    .any(|feature| feature.tag == wanted)
            })
    }

    /// Resolve the face's used shaping size. An element-level
    /// `font-size-adjust` takes precedence over the `@font-face size-adjust`
    /// descriptor; otherwise the descriptor scales this face alone.
    /// <https://www.w3.org/TR/css-fonts-5/#font-size-adjust-prop>
    /// <https://www.w3.org/TR/css-fonts-5/#descdef-font-face-size-adjust>
    pub(in crate::text) fn used_font_size_for_font(
        &mut self,
        style: &ComputedStyle,
        font_id: usize,
    ) -> Option<f32> {
        self.font_size_adjusted_size_for_font_id(style, font_id)
    }

    pub(in crate::text) fn font_size_adjusted_size_for_font_id(
        &mut self,
        style: &ComputedStyle,
        font_id: usize,
    ) -> Option<f32> {
        let adjusted = match style.font_size_adjust {
            FontSizeAdjust::None => self
                .document_fonts
                .font_size_adjust(font_id)
                .map_or(style.font_size, |factor| style.font_size * factor),
            FontSizeAdjust::Value { metric, value } => {
                let target_ratio = match value {
                    FontSizeAdjustValue::Number(value) => value,
                    FontSizeAdjustValue::FromFont => {
                        // `from-font` resolves the requested aspect value
                        // from the element's first available face, not from
                        // each fallback run. The selected run's own metric
                        // is the denominator below, so fallback glyphs keep
                        // the primary face's intended apparent size.
                        // <https://www.w3.org/TR/css-fonts-5/#font-size-adjust-prop>
                        let primary_font_id = self.resolve_metric_font_for_style(style)?;
                        let font = self.document_fonts.get(primary_font_id)?;
                        font_size_adjust_metric_ratio(font, metric)?
                    }
                };
                let font = self.document_fonts.get(font_id)?;
                let selected_ratio = font_size_adjust_metric_ratio(font, metric)?;
                if selected_ratio <= 0.0 {
                    return None;
                }
                style.font_size * target_ratio / selected_ratio
            }
        };
        adjusted.is_finite().then_some(adjusted)
    }

    pub(in crate::text) fn character_font_match(
        &mut self,
        style: &ComputedStyle,
        character: char,
    ) -> Option<CharacterFontMatch> {
        let families = match &style.font_family {
            FontFamily::List(families) => families.as_slice(),
            family => std::slice::from_ref(family),
        };
        for family in families {
            let matched = match family {
                FontFamily::Named(name) => self
                    .resolve_single_family(
                        name.as_str(),
                        style.font_weight,
                        style.font_style,
                        style.font_width,
                    )
                    .and_then(|font_id| {
                        self.document_fonts.character_font_match(font_id, character)
                    }),
                _ => self
                    .resolve_font_family(
                        family,
                        style.font_weight,
                        style.font_style,
                        style.font_width,
                    )
                    .and_then(|font_id| {
                        self.document_fonts.character_font_match(font_id, character)
                    }),
            };
            if matched.is_some() {
                return matched;
            }
        }
        self.resolve_system_fallback_for_character(
            character,
            style.font_weight,
            style.font_style,
            style.font_width,
        )
        .and_then(|font_id| self.document_fonts.character_font_match(font_id, character))
    }

    /// Finds the first CSS font-stack face that is eligible to render one
    /// character, including `unicode-range` restrictions.
    #[cfg(test)]
    pub(in crate::text) fn font_for_character(
        &mut self,
        style: &ComputedStyle,
        character: char,
    ) -> Option<usize> {
        self.character_font_match(style, character)
            .map(|matched| matched.font_id)
    }

    pub(in crate::text) fn font_for_character_in_family(
        &mut self,
        style: &ComputedStyle,
        family: &FontFamily,
        character: char,
    ) -> Option<usize> {
        self.resolve_family_fallback_for_character_in_family(style, family, character)
    }

    pub(in crate::text) fn vertical_upright_ch_advance(
        &mut self,
        style: &ComputedStyle,
    ) -> Option<f32> {
        self.vertical_glyph_advance_for_style(style, '0')
    }

    /// Returns a metric glyph's vertical advance for vertical CSS layout.
    /// `ic` uses U+6C34 and `ch` uses upright U+0030. The face is selected
    /// for that character, including font-stack fallback and `unicode-range`.
    /// <https://www.w3.org/TR/css-values-4/#ch>
    /// <https://www.w3.org/TR/css-values-4/#ic>
    pub(super) fn vertical_glyph_advance_for_style(
        &mut self,
        style: &ComputedStyle,
        character: char,
    ) -> Option<f32> {
        let matched = self.metric_glyph_match_for_style(style, character)?;
        let used_font_size = self
            .font_size_adjusted_size_for_font_id(style, matched.font_id)
            .unwrap_or(style.font_size);
        let font = self.document_fonts.get(matched.font_id)?;
        let face = ttf_parser::Face::parse(&font.data, font.face_index).ok()?;
        let units_per_em = font.units_per_em.max(1) as f32;
        let advance = face
            .glyph_ver_advance(matched.glyph_id.raw())
            .map(|advance| advance as f32)
            .unwrap_or(units_per_em);
        Some(advance * used_font_size / units_per_em)
    }
}

pub(super) fn named_font_families(family: &FontFamily) -> Vec<String> {
    match family {
        FontFamily::Named(name) => vec![name.as_str().to_owned()],
        FontFamily::List(families) => families.iter().flat_map(named_font_families).collect(),
        _ => Vec::new(),
    }
}

pub(super) fn parley_run_fallback_character(text: &str, range: Range<usize>) -> char {
    text.get(range)
        .and_then(|text| text.chars().find(|character| !character.is_control()))
        .unwrap_or(' ')
}