Skip to main content

fonts/
font.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::borrow::ToOwned;
6use std::collections::HashMap;
7use std::hash::Hash;
8use std::ops::Deref;
9use std::sync::{Arc, OnceLock};
10use std::{iter, str};
11
12use app_units::Au;
13use atomic_refcell::AtomicRef;
14use bitflags::bitflags;
15use euclid::default::{Point2D, Rect};
16use euclid::num::Zero;
17use font_types::NameId;
18use fonts_traits::FontDescriptor;
19use icu_locale_core::subtags::Language;
20use icu_properties::props::{EnumeratedProperty, GeneralCategory};
21use log::debug;
22use malloc_size_of_derive::MallocSizeOf;
23use parking_lot::RwLock;
24use read_fonts::collections::int_set::Domain;
25use read_fonts::tables::fvar::Fvar;
26use read_fonts::tables::name::Name as NameTable;
27use read_fonts::tables::os2::{Os2, SelectionFlags};
28use read_fonts::types::Tag;
29use read_fonts::{FontRead, ReadError};
30use rustc_hash::FxHashMap;
31use serde::{Deserialize, Serialize};
32use servo_base::id::PainterId;
33use servo_base::text::{UnicodeBlock, UnicodeBlockMethod};
34use skrifa::string::LocalizedString;
35use smallvec::SmallVec;
36use style::Atom;
37use style::computed_values::font_optical_sizing::T as FontOpticalSizing;
38use style::computed_values::font_variant_caps;
39use style::computed_values::font_variant_position::T as FontVariantPosition;
40use style::properties::style_structs::Font as FontStyleStruct;
41use style::values::computed::font::{
42    FamilyName, FontFamilyNameSyntax, GenericFontFamily, SingleFontFamily,
43};
44use style::values::computed::{
45    FontFeatureSettings, FontStyle, FontSynthesis, FontVariantEastAsian, FontVariantLigatures,
46    FontVariantNumeric, FontWeight, FontWidth,
47};
48use unicode_script::Script;
49use webrender_api::{
50    FontInstanceFlags, FontInstanceKey, FontInstancePlatformOptions, FontVariation,
51};
52
53use crate::font_feature_values::ResolvedFontVariantAlternates;
54use crate::platform::font::{FontTable, PlatformFont};
55use crate::platform::font_list::fallback_font_families;
56use crate::{
57    EmojiPresentationPreference, FallbackFontSelectionOptions, FontContext, FontData,
58    FontDataAndIndex, FontDataError, FontIdentifier, FontTemplateDescriptor, FontTemplateRef,
59    FontTemplateRefMethods, GlyphId, LocalFontIdentifier, ShapedGlyph, ShapedText, Shaper,
60    compute_used_font_features,
61};
62
63pub(crate) const AFRC: Tag = Tag::new(b"afrc");
64pub(crate) const BASE: Tag = Tag::new(b"BASE");
65pub(crate) const CALT: Tag = Tag::new(b"calt");
66pub(crate) const CBDT: Tag = Tag::new(b"CBDT");
67pub(crate) const CLIG: Tag = Tag::new(b"clig");
68pub(crate) const COLR: Tag = Tag::new(b"COLR");
69pub(crate) const CWSH: Tag = Tag::new(b"cwsh");
70pub(crate) const FRAC: Tag = Tag::new(b"frac");
71pub(crate) const DLIG: Tag = Tag::new(b"dlig");
72pub(crate) const FVAR: Tag = Tag::new(b"fvar");
73pub(crate) const FWID: Tag = Tag::new(b"fwid");
74pub(crate) const GPOS: Tag = Tag::new(b"GPOS");
75pub(crate) const GSUB: Tag = Tag::new(b"GSUB");
76pub(crate) const HIST: Tag = Tag::new(b"hist");
77pub(crate) const HLIG: Tag = Tag::new(b"hlig");
78pub(crate) const ITAL: Tag = Tag::new(b"ital");
79pub(crate) const JP04: Tag = Tag::new(b"jp04");
80pub(crate) const JP78: Tag = Tag::new(b"jp78");
81pub(crate) const JP83: Tag = Tag::new(b"jp83");
82pub(crate) const JP90: Tag = Tag::new(b"jp90");
83pub(crate) const KERN: Tag = Tag::new(b"kern");
84pub(crate) const LIGA: Tag = Tag::new(b"liga");
85pub(crate) const LNUM: Tag = Tag::new(b"lnum");
86pub(crate) const NALT: Tag = Tag::new(b"nalt");
87pub(crate) const NAME: Tag = Tag::new(b"name");
88pub(crate) const ONUM: Tag = Tag::new(b"onum");
89pub(crate) const ORNM: Tag = Tag::new(b"ornm");
90pub(crate) const ORDN: Tag = Tag::new(b"ordn");
91pub(crate) const PNUM: Tag = Tag::new(b"pnum");
92pub(crate) const PWID: Tag = Tag::new(b"pwid");
93pub(crate) const RUBY: Tag = Tag::new(b"ruby");
94pub(crate) const SALT: Tag = Tag::new(b"salt");
95pub(crate) const SBIX: Tag = Tag::new(b"sbix");
96pub(crate) const SLNT: Tag = Tag::new(b"slnt");
97pub(crate) const SMPL: Tag = Tag::new(b"smpl");
98pub(crate) const SUBS: Tag = Tag::new(b"subs");
99pub(crate) const SUPS: Tag = Tag::new(b"sups");
100pub(crate) const SWSH: Tag = Tag::new(b"swsh");
101pub(crate) const TNUM: Tag = Tag::new(b"tnum");
102pub(crate) const TRAD: Tag = Tag::new(b"trad");
103pub(crate) const ZERO: Tag = Tag::new(b"zero");
104
105pub const LAST_RESORT_GLYPH_ADVANCE: FractionalPixel = 10.0;
106
107// PlatformFont encapsulates access to the platform's font API,
108// e.g. quartz, FreeType. It provides access to metrics and tables
109// needed by the text shaper as well as access to the underlying font
110// resources needed by the graphics layer to draw glyphs.
111
112pub trait PlatformFontMethods: Sized {
113    #[servo_tracing::instrument(name = "PlatformFontMethods::new_from_template", skip_all)]
114    fn new_from_template(
115        template: FontTemplateRef,
116        pt_size: Option<Au>,
117        data: &Option<FontData>,
118        synthetic_bold: bool,
119    ) -> Result<PlatformFont, &'static str> {
120        let template = template.borrow();
121        let font_identifier = template.identifier.clone();
122
123        match font_identifier {
124            FontIdentifier::Local(font_identifier) => {
125                Self::new_from_local_font_identifier(font_identifier, pt_size, synthetic_bold)
126            },
127            FontIdentifier::Web(_) | FontIdentifier::ArrayBuffer(_) => Self::new_from_data(
128                font_identifier,
129                data.as_ref()
130                    .expect("Should never create a web font without data."),
131                pt_size,
132                synthetic_bold,
133            ),
134        }
135    }
136
137    fn new_from_local_font_identifier(
138        font_identifier: LocalFontIdentifier,
139        pt_size: Option<Au>,
140        synthetic_bold: bool,
141    ) -> Result<PlatformFont, &'static str>;
142
143    fn new_from_data(
144        font_identifier: FontIdentifier,
145        data: &FontData,
146        pt_size: Option<Au>,
147        synthetic_bold: bool,
148    ) -> Result<PlatformFont, &'static str>;
149
150    /// Create a platform font with the given variations from a existing font.
151    ///
152    /// `self` is consumed to work around platform differences. On some platforms, changing the
153    /// variations requires creating an entirely new font face, whereas on others the returned
154    /// font is `self`.
155    fn copy_with_variations(
156        self,
157        _font_identifer: &FontIdentifier,
158        _variations: &[FontVariation],
159    ) -> Result<Self, &'static str>;
160
161    /// Get a [`FontTemplateDescriptor`] from a [`PlatformFont`]. This is used to get
162    /// descriptors for web fonts.
163    fn descriptor(&self) -> FontTemplateDescriptor;
164
165    fn glyph_index(&self, codepoint: char) -> Option<GlyphId>;
166    fn glyph_h_advance(&self, _: GlyphId) -> Option<FractionalPixel>;
167    fn glyph_h_kerning(&self, glyph0: GlyphId, glyph1: GlyphId) -> FractionalPixel;
168
169    fn metrics(&self) -> FontMetrics;
170    fn table_for_tag(&self, _: Tag) -> Option<FontTable>;
171    fn typographic_bounds(&self, _: GlyphId) -> Rect<f32>;
172
173    /// Get the necessary [`FontInstanceFlags`] for this font.
174    fn webrender_font_instance_flags(&self) -> FontInstanceFlags;
175
176    /// Get the necessary [`FontInstancePlatformOptions`] for this font.
177    fn webrender_font_instance_platform_options(&self) -> FontInstancePlatformOptions {
178        Default::default()
179    }
180
181    /// Return all the variation values that the font was instantiated with.
182    fn variations(&self) -> &[FontVariation];
183
184    fn descriptor_from_os2_table(os2: &Os2) -> FontTemplateDescriptor {
185        let mut style = FontStyle::NORMAL;
186        if os2.fs_selection().contains(SelectionFlags::ITALIC) {
187            style = FontStyle::ITALIC;
188        }
189
190        let weight = FontWeight::from_float(os2.us_weight_class() as f32);
191        let width = match os2.us_width_class() {
192            1 => FontWidth::ULTRA_CONDENSED,
193            2 => FontWidth::EXTRA_CONDENSED,
194            3 => FontWidth::CONDENSED,
195            4 => FontWidth::SEMI_CONDENSED,
196            5 => FontWidth::NORMAL,
197            6 => FontWidth::SEMI_EXPANDED,
198            7 => FontWidth::EXPANDED,
199            8 => FontWidth::EXTRA_EXPANDED,
200            9 => FontWidth::ULTRA_EXPANDED,
201            _ => FontWidth::NORMAL,
202        };
203
204        FontTemplateDescriptor::new(weight, width, style)
205    }
206}
207
208// Used to abstract over the shaper's choice of fixed int representation.
209pub(crate) type FractionalPixel = f64;
210
211pub(crate) trait FontTableMethods {
212    fn buffer(&self) -> &[u8];
213    fn parse_as_specific_table<'a, Table>(&'a self) -> Result<Table, ReadError>
214    where
215        Table: FontRead<'a, Args = ()>,
216    {
217        Table::read(read_fonts::FontData::new(self.buffer()))
218    }
219}
220
221#[derive(Clone, Debug, Default, Deserialize, MallocSizeOf, PartialEq, Serialize)]
222pub struct FontMetrics {
223    pub underline_size: Au,
224    pub underline_offset: Au,
225    pub strikeout_size: Au,
226    pub strikeout_offset: Au,
227    pub leading: Au,
228    pub x_height: Au,
229    pub em_size: Au,
230    pub ascent: Au,
231    pub descent: Au,
232    pub max_advance: Au,
233    pub average_advance: Au,
234    pub line_gap: Au,
235    pub zero_horizontal_advance: Option<Au>,
236    pub ic_horizontal_advance: Option<Au>,
237    /// The advance of the space character (' ') in this font or if there is no space,
238    /// the average char advance.
239    pub space_advance: Au,
240}
241
242impl FontMetrics {
243    /// Create an empty [`FontMetrics`] mainly to be used in situations where
244    /// no font can be found.
245    pub fn empty() -> Arc<Self> {
246        static EMPTY: OnceLock<Arc<FontMetrics>> = OnceLock::new();
247        EMPTY.get_or_init(Default::default).clone()
248    }
249
250    /// Whether or not the block metrics of the two `FontMetrics` instances differ in a way
251    /// that requires the resulting block size of a containing inline box to change.
252    pub fn block_metrics_meaningfully_differ(&self, other: &Self) -> bool {
253        self.ascent != other.ascent ||
254            self.descent != other.descent ||
255            self.line_gap != other.line_gap
256    }
257}
258
259#[derive(Debug, Default)]
260struct CachedShapeData {
261    glyph_advances: FxHashMap<GlyphId, FractionalPixel>,
262    glyph_indices: FxHashMap<char, Option<GlyphId>>,
263    shaped_text: HashMap<ShapeCacheEntry, Arc<ShapedText>>,
264}
265
266impl malloc_size_of::MallocSizeOf for CachedShapeData {
267    fn size_of(&self, ops: &mut malloc_size_of::MallocSizeOfOps) -> usize {
268        // Estimate the size of the shaped text cache. This will be smaller, because
269        // HashMap has some overhead, but we are mainly interested in the actual data.
270        let shaped_text_size = self
271            .shaped_text
272            .iter()
273            .map(|(key, value)| key.size_of(ops) + (*value).size_of(ops))
274            .sum::<usize>();
275        self.glyph_advances.size_of(ops) + self.glyph_indices.size_of(ops) + shaped_text_size
276    }
277}
278
279pub struct Font {
280    pub(crate) handle: PlatformFont,
281    pub(crate) template: FontTemplateRef,
282    pub metrics: OnceLock<Arc<FontMetrics>>,
283    pub descriptor: FontDescriptor,
284
285    /// The data for this font. And the index of the font within the data (in case it's a TTC)
286    /// This might be uninitialized for system fonts.
287    data_and_index: OnceLock<FontDataAndIndex>,
288
289    shaper: OnceLock<Shaper>,
290    cached_shape_data: RwLock<CachedShapeData>,
291    font_instance_key: RwLock<FxHashMap<PainterId, FontInstanceKey>>,
292
293    /// If this is a synthesized small caps font, then this font reference is for
294    /// the version of the font used to replace lowercase ASCII letters. It's up
295    /// to the consumer of this font to properly use this reference.
296    pub(crate) synthesized_small_caps: Option<FontRef>,
297
298    /// Whether or not this font supports color bitmaps or a COLR table. This is
299    /// essentially equivalent to whether or not we use it for emoji presentation.
300    /// This is cached, because getting table data is expensive.
301    has_color_bitmap_or_colr_table: OnceLock<bool>,
302
303    /// Whether or not this font can do fast shaping, ie whether or not it has
304    /// a kern table, but no GSUB and GPOS tables. When this is true, Servo will
305    /// shape Latin horizontal left-to-right text without using Harfbuzz.
306    ///
307    /// FIXME: This should be removed entirely in favor of better caching if necessary.
308    /// See <https://github.com/servo/servo/pull/11273#issuecomment-222332873>.
309    can_do_fast_shaping: OnceLock<bool>,
310
311    /// The family name of the font.
312    ///
313    /// This is the name as it is declared in the `name` table, *not* the name provided by the system
314    /// font service.
315    family_name: OnceLock<Result<Atom, NoUsableFamilyName>>,
316}
317
318/// An error indicating that the `name` table contained no usable family names.
319///
320/// For example, this can happen if the family name uses an incompatible or unknown encoding.
321#[derive(Clone)]
322struct NoUsableFamilyName;
323
324impl std::fmt::Debug for Font {
325    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
326        f.debug_struct("Font")
327            .field("template", &self.template)
328            .field("descriptor", &self.descriptor)
329            .finish()
330    }
331}
332
333impl malloc_size_of::MallocSizeOf for Font {
334    fn size_of(&self, ops: &mut malloc_size_of::MallocSizeOfOps) -> usize {
335        // TODO: Collect memory usage for platform fonts and for shapers.
336        // This skips the template, because they are already stored in the template cache.
337
338        let metrics_size = self.metrics.get().map_or(0, |metrics| metrics.size_of(ops));
339        metrics_size +
340            self.descriptor.size_of(ops) +
341            self.cached_shape_data.read().size_of(ops) +
342            self.font_instance_key
343                .read()
344                .values()
345                .map(|key| key.size_of(ops))
346                .sum::<usize>()
347    }
348}
349
350impl Font {
351    pub fn new(
352        template: FontTemplateRef,
353        descriptor: FontDescriptor,
354        data: Option<FontData>,
355        synthesized_small_caps: Option<FontRef>,
356    ) -> Result<Font, &'static str> {
357        let synthetic_bold = {
358            let is_bold = descriptor.weight >= FontWeight::BOLD_THRESHOLD;
359            let allows_synthetic_bold = matches!(descriptor.synthesis_weight, FontSynthesis::Auto);
360
361            is_bold && allows_synthetic_bold
362        };
363
364        let handle = PlatformFont::new_from_template(
365            template.clone(),
366            Some(descriptor.pt_size),
367            &data,
368            synthetic_bold,
369        )?;
370        let variation_axes = VariationAxes::from_platform_font(&handle);
371
372        // Compute and apply the OpenType variations
373        let handle = if servo_config::pref!(layout_css_font_variations_enabled) &&
374            variation_axes.contains(VariationAxes::IS_VARIABLE)
375        {
376            let used_variations = compute_variations(&descriptor, &template, variation_axes);
377            handle.copy_with_variations(&template.identifier(), &used_variations)?
378        } else {
379            handle
380        };
381
382        Ok(Font {
383            handle,
384            template,
385            metrics: OnceLock::new(),
386            descriptor,
387            data_and_index: data
388                .map(|data| OnceLock::from(FontDataAndIndex { data, index: 0 }))
389                .unwrap_or_default(),
390            shaper: OnceLock::new(),
391            cached_shape_data: Default::default(),
392            font_instance_key: Default::default(),
393            synthesized_small_caps,
394            has_color_bitmap_or_colr_table: OnceLock::new(),
395            can_do_fast_shaping: OnceLock::new(),
396            family_name: Default::default(),
397        })
398    }
399
400    /// A unique identifier for the font, allowing comparison.
401    pub fn identifier(&self) -> AtomicRef<'_, FontIdentifier> {
402        self.template.identifier()
403    }
404
405    pub fn metrics(&self) -> &Arc<FontMetrics> {
406        self.metrics.get_or_init(|| Arc::new(self.handle.metrics()))
407    }
408
409    pub(crate) fn webrender_font_instance_flags(&self) -> FontInstanceFlags {
410        self.handle.webrender_font_instance_flags()
411    }
412
413    pub(crate) fn webrender_font_instance_platform_options(&self) -> FontInstancePlatformOptions {
414        self.handle.webrender_font_instance_platform_options()
415    }
416
417    pub(crate) fn has_color_bitmap_or_colr_table(&self) -> bool {
418        *self.has_color_bitmap_or_colr_table.get_or_init(|| {
419            self.table_for_tag(SBIX).is_some() ||
420                self.table_for_tag(CBDT).is_some() ||
421                self.table_for_tag(COLR).is_some()
422        })
423    }
424
425    pub fn key(&self, painter_id: PainterId, font_context: &FontContext) -> FontInstanceKey {
426        *self
427            .font_instance_key
428            .write()
429            .entry(painter_id)
430            .or_insert_with(|| font_context.create_font_instance_key(self, painter_id))
431    }
432
433    /// Return the data for this `Font`. Note that this is currently highly inefficient for system
434    /// fonts and should not be used except in legacy canvas code.
435    pub fn font_data_and_index(&self) -> Result<&FontDataAndIndex, FontDataError> {
436        if let Some(data_and_index) = self.data_and_index.get() {
437            return Ok(data_and_index);
438        }
439
440        let FontIdentifier::Local(local_font_identifier) = &*self.identifier() else {
441            unreachable!("All web fonts should already have initialized data");
442        };
443        let Some(data_and_index) = local_font_identifier.font_data_and_index() else {
444            return Err(FontDataError::FailedToLoad);
445        };
446
447        let data_and_index = self.data_and_index.get_or_init(move || data_and_index);
448        Ok(data_and_index)
449    }
450
451    pub(crate) fn variations(&self) -> &[FontVariation] {
452        self.handle.variations()
453    }
454}
455
456bitflags! {
457    #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
458    pub struct ShapingFlags: u8 {
459        /// Set if we are to disable kerning.
460        const DISABLE_KERNING_SHAPING_FLAG = 1 << 3;
461        /// Text direction is right-to-left.
462        const RTL_FLAG = 1 << 4;
463        /// Set if word-break is set to keep-all.
464        const KEEP_ALL_FLAG = 1 << 5;
465    }
466}
467
468/// Various options that control text shaping.
469#[derive(Clone, Debug, Eq, Hash, PartialEq)]
470pub struct ShapingOptions {
471    /// Spacing to add between each letter. Corresponds to the CSS 2.1 `letter-spacing` property.
472    ///
473    /// Letter spacing is not applied to all characters. Use [Self::letter_spacing_for_character] to
474    /// determine the amount of spacing to apply.
475    pub letter_spacing: Au,
476    /// Spacing to add between each word. Corresponds to the CSS 2.1 `word-spacing` property.
477    pub word_spacing: Au,
478    /// The Unicode script property of the characters in this run.
479    pub script: Script,
480    /// The preferred language, obtained from the `lang` attribute.
481    pub language: Atom,
482    /// The `font-language-override` value from style as an OpenType language tag or `None` when
483    /// `normal`.
484    pub language_override: Option<Tag>,
485    /// The value of the `font-variant-ligatures` property.
486    pub ligatures: FontVariantLigatures,
487    /// The value of the `font-variant-numeric` property.
488    pub numeric: FontVariantNumeric,
489    /// The value of the `font-variant-east-asian` property.
490    pub east_asian: FontVariantEastAsian,
491    /// The value of the `font-feature-settings` property.
492    pub feature_settings: FontFeatureSettings,
493    /// The value of the `font-variant-position` property.
494    pub position: FontVariantPosition,
495    /// The value of the `font-variant-alternates` property.
496    pub alternates: ResolvedFontVariantAlternates,
497    /// Various flags.
498    pub flags: ShapingFlags,
499}
500
501impl ShapingOptions {
502    pub(crate) fn letter_spacing_for_character(&self, character: char) -> Au {
503        // https://drafts.csswg.org/css-text/#letter-spacing-property
504        // Letter spacing ignores invisible zero-width formatting characters (such as those from the Unicode Cf category).
505        // Spacing must be added as if those characters did not exist in the document.
506        if GeneralCategory::for_char(character) == GeneralCategory::Format {
507            return Au::zero();
508        }
509        self.letter_spacing
510    }
511}
512
513/// An entry in the shape cache.
514#[derive(Clone, Debug, Eq, Hash, PartialEq)]
515struct ShapeCacheEntry {
516    text: String,
517    letter_spacing: Au,
518    word_spacing: Au,
519    script: Script,
520    language: Atom,
521    language_override: Option<Tag>,
522    font_features: Box<[(Tag, u32)]>,
523    flags: ShapingFlags,
524}
525
526impl Font {
527    #[servo_tracing::instrument(name = "Font::shape_text", skip_all)]
528    pub fn shape_text(&self, text: &str, options: &ShapingOptions) -> Arc<ShapedText> {
529        let font_features =
530            compute_used_font_features(options, self.template.borrow().font_face_rule.as_deref())
531                .collect();
532        let lookup_key = ShapeCacheEntry {
533            text: text.to_owned(),
534            letter_spacing: options.letter_spacing,
535            word_spacing: options.word_spacing,
536            script: options.script,
537            language: options.language.clone(),
538            language_override: options.language_override,
539            flags: options.flags,
540            font_features,
541        };
542
543        if let Some(shaped_text) = self.cached_shape_data.read().shaped_text.get(&lookup_key) {
544            return shaped_text.clone();
545        }
546
547        let glyphs = if self.can_do_fast_shaping(text, options) {
548            debug!("shape_text: Using ASCII fast path.");
549            self.shape_text_fast(text, options)
550        } else {
551            debug!("shape_text: Using Harfbuzz.");
552            self.shaper.get_or_init(|| Shaper::new(self)).shape_text(
553                text,
554                options,
555                &lookup_key.font_features,
556            )
557        };
558
559        let shaped_text = Arc::new(glyphs);
560        let mut cache = self.cached_shape_data.write();
561        cache.shaped_text.insert(lookup_key, shaped_text.clone());
562
563        shaped_text
564    }
565
566    /// Whether not a particular text and [`ShapingOptions`] combination can use
567    /// "fast shaping" ie shaping without Harfbuzz.
568    ///
569    /// Note: This will eventually be removed.
570    pub fn can_do_fast_shaping(&self, text: &str, options: &ShapingOptions) -> bool {
571        options.script == Script::Latin &&
572            !options.flags.contains(ShapingFlags::RTL_FLAG) &&
573            *self.can_do_fast_shaping.get_or_init(|| {
574                self.table_for_tag(KERN).is_some() &&
575                    self.table_for_tag(GPOS).is_none() &&
576                    self.table_for_tag(GSUB).is_none()
577            }) &&
578            text.is_ascii()
579    }
580
581    /// Fast path for ASCII text that only needs simple horizontal LTR kerning.
582    fn shape_text_fast(&self, text: &str, options: &ShapingOptions) -> ShapedText {
583        let mut glyph_store = ShapedText::new(text.len(), false /* is_rtl */);
584        let mut prev_glyph_id = None;
585        for (string_byte_offset, byte) in text.bytes().enumerate() {
586            let character = byte as char;
587            let Some(glyph_id) = self.glyph_index(character) else {
588                continue;
589            };
590
591            let mut advance = Au::from_f64_px(self.glyph_h_advance(glyph_id));
592            let offset = prev_glyph_id.map(|prev| {
593                let h_kerning = Au::from_f64_px(self.glyph_h_kerning(prev, glyph_id));
594                advance += h_kerning;
595                Point2D::new(h_kerning, Au::zero())
596            });
597
598            let mut glyph = ShapedGlyph {
599                glyph_id,
600                string_byte_offset,
601                advance,
602                offset,
603            };
604            glyph.adjust_for_character(character, options);
605
606            glyph_store.add_glyph(character, &glyph);
607            prev_glyph_id = Some(glyph_id);
608        }
609        glyph_store
610    }
611
612    pub(crate) fn table_for_tag(&self, tag: Tag) -> Option<FontTable> {
613        let result = self.handle.table_for_tag(tag);
614        let status = if result.is_some() {
615            "Found"
616        } else {
617            "Didn't find"
618        };
619
620        debug!(
621            "{} font table[{}] in {:?},",
622            status,
623            str::from_utf8(tag.as_ref()).unwrap(),
624            self.identifier()
625        );
626        result
627    }
628
629    #[inline]
630    pub fn glyph_index(&self, codepoint: char) -> Option<GlyphId> {
631        {
632            let cache = self.cached_shape_data.read();
633            if let Some(glyph) = cache.glyph_indices.get(&codepoint) {
634                return *glyph;
635            }
636        }
637        let codepoint = match self.descriptor.variant {
638            font_variant_caps::T::SmallCaps => codepoint.to_ascii_uppercase(),
639            font_variant_caps::T::Normal => codepoint,
640            // The other values are behind `layout.css.font-variant-caps.all-values.enabled`
641            // which Servo does not enable, so they are never parsed.
642            font_variant_caps::T::AllSmallCaps |
643            font_variant_caps::T::PetiteCaps |
644            font_variant_caps::T::AllPetiteCaps |
645            font_variant_caps::T::Unicase |
646            font_variant_caps::T::TitlingCaps => unreachable!(),
647        };
648        let glyph_index = self.handle.glyph_index(codepoint);
649
650        let mut cache = self.cached_shape_data.write();
651        cache.glyph_indices.insert(codepoint, glyph_index);
652        glyph_index
653    }
654
655    pub fn has_glyph_for(&self, codepoint: char) -> bool {
656        self.glyph_index(codepoint).is_some()
657    }
658
659    pub(crate) fn glyph_h_kerning(
660        &self,
661        first_glyph: GlyphId,
662        second_glyph: GlyphId,
663    ) -> FractionalPixel {
664        self.handle.glyph_h_kerning(first_glyph, second_glyph)
665    }
666
667    pub fn glyph_h_advance(&self, glyph_id: GlyphId) -> FractionalPixel {
668        {
669            let cache = self.cached_shape_data.read();
670            if let Some(width) = cache.glyph_advances.get(&glyph_id) {
671                return *width;
672            }
673        }
674
675        let new_width = self
676            .handle
677            .glyph_h_advance(glyph_id)
678            .unwrap_or(LAST_RESORT_GLYPH_ADVANCE as FractionalPixel);
679        let mut cache = self.cached_shape_data.write();
680        cache.glyph_advances.insert(glyph_id, new_width);
681        new_width
682    }
683
684    pub fn typographic_bounds(&self, glyph_id: GlyphId) -> Rect<f32> {
685        self.handle.typographic_bounds(glyph_id)
686    }
687
688    /// Get the [`FontBaseline`] for this font.
689    pub fn baseline(&self) -> Option<FontBaseline> {
690        self.shaper.get_or_init(|| Shaper::new(self)).baseline()
691    }
692
693    #[cfg(not(target_os = "macos"))]
694    pub(crate) fn find_fallback_using_system_font_api(
695        &self,
696        _: &FallbackFontSelectionOptions,
697    ) -> Option<FontRef> {
698        None
699    }
700
701    fn get_family_name_from_font_data(&self) -> Result<Atom, NoUsableFamilyName> {
702        let name_table = self.table_for_tag(NAME).ok_or(NoUsableFamilyName)?;
703        let name_table = NameTable::read(read_fonts::FontData::new(name_table.buffer()))
704            .map_err(|_| NoUsableFamilyName)?;
705
706        // Find the most usable family name entry, preferring "en-US" > "en" > "everything else".
707        // TODO: If we ever have a way to get a read_fonts::FontRef out of a PlatformFont then skrifa can
708        // do this for us with LocalizedStrings::english_or_first.
709        //
710        // https://docs.rs/skrifa/latest/skrifa/string/struct.LocalizedStrings.html#method.english_or_first
711        let mut best_rank = -1;
712        let mut best_string = None;
713        for (index, name_record) in name_table
714            .name_record()
715            .iter()
716            .filter(|name_record| name_record.name_id() == NameId::FAMILY_NAME)
717            .enumerate()
718        {
719            let localized_string = LocalizedString::new(&name_table, name_record);
720            let rank = match (index, localized_string.language()) {
721                (_, Some("en-US")) => {
722                    best_string = Some(localized_string);
723                    break;
724                },
725                (_, Some("en")) => 2,
726                (_, None) => 1,
727                (0, _) => 0,
728                _ => continue,
729            };
730            if rank > best_rank {
731                best_rank = rank;
732                best_string = Some(localized_string);
733            }
734        }
735
736        best_string
737            .map(|best_string| best_string.chars().collect::<String>().into())
738            .ok_or(NoUsableFamilyName)
739    }
740
741    /// Return the font's declared family name:
742    ///  - Platform: fonts: A value from OpenType `name` table, or `None` if either the platform
743    ///    does not support that query or the font does not have a usable name.
744    ///  - Web fonts: the family name specified in the `@font-face` rule
745    pub fn family_name(&self) -> Option<Atom> {
746        self.template
747            .font_face_rule()
748            .and_then(|font_face_rule| {
749                AtomicRef::filter_map(font_face_rule, |rule| rule.descriptors.font_family.as_ref())
750            })
751            .map(|font_family| font_family.name.clone())
752            .or_else(|| {
753                self.family_name
754                    .get_or_init(|| self.get_family_name_from_font_data())
755                    .clone()
756                    .ok()
757            })
758    }
759}
760
761#[derive(Clone, Debug, MallocSizeOf)]
762pub struct FontRef(#[conditional_malloc_size_of] pub(crate) Arc<Font>);
763
764impl PartialEq for FontRef {
765    fn eq(&self, other: &Self) -> bool {
766        Arc::ptr_eq(self, other)
767    }
768}
769
770impl Deref for FontRef {
771    type Target = Arc<Font>;
772    fn deref(&self) -> &Self::Target {
773        &self.0
774    }
775}
776
777#[derive(Clone, Debug, Eq, Hash, MallocSizeOf, PartialEq)]
778pub struct FallbackKey {
779    script: Script,
780    unicode_block: Option<UnicodeBlock>,
781    language: Language,
782}
783
784impl FallbackKey {
785    fn new(options: &FallbackFontSelectionOptions) -> Self {
786        Self {
787            script: Script::from(options.character),
788            unicode_block: options.character.block(),
789            language: options.language,
790        }
791    }
792}
793
794/// A `FontGroup` is a prioritised list of fonts for a given set of font styles. It is used by
795/// `TextRun` to decide which font to render a character with. If none of the fonts listed in the
796/// styles are suitable, a fallback font may be used.
797#[derive(MallocSizeOf)]
798pub struct FontGroup {
799    /// The [`FontDescriptor`] which describes the properties of the fonts that should
800    /// be loaded for this [`FontGroup`].
801    descriptor: FontDescriptor,
802    /// The families that have been loaded for this [`FontGroup`]. This correponds to the
803    /// list of fonts specified in CSS.
804    families: SmallVec<[FontGroupFamily; 8]>,
805    /// A list of fallbacks that have been used in this [`FontGroup`]. Currently this
806    /// can grow indefinitely, but maybe in the future it should be an LRU cache.
807    /// It's unclear if this is the right thing to do. Perhaps fallbacks should
808    /// always be stored here as it's quite likely that they will be used again.
809    fallbacks: RwLock<HashMap<FallbackKey, FontRef>>,
810}
811
812impl FontGroup {
813    pub(crate) fn new(style: &FontStyleStruct, descriptor: FontDescriptor) -> FontGroup {
814        let families: SmallVec<[FontGroupFamily; 8]> = style
815            .font_family
816            .families
817            .iter()
818            .map(FontGroupFamily::local_or_web)
819            .collect();
820
821        FontGroup {
822            descriptor,
823            families,
824            fallbacks: Default::default(),
825        }
826    }
827
828    /// Finds the first font, or else the first fallback font, which contains a glyph for
829    /// `codepoint`. If no such font is found, returns the first available font or fallback font
830    /// (which will cause a "glyph not found" character to be rendered). If no font at all can be
831    /// found, returns None.
832    pub fn find_by_codepoint(
833        &self,
834        font_context: &FontContext,
835        codepoint: char,
836        next_codepoint: Option<char>,
837        language: Language,
838    ) -> Option<FontRef> {
839        // Tab characters are converted into spaces when rendering.
840        // TODO: We should not render a tab character. Instead they should be converted into tab stops
841        // based upon the width of a space character in inline formatting contexts.
842        let codepoint = match codepoint {
843            '\t' => ' ',
844            _ => codepoint,
845        };
846
847        let options = FallbackFontSelectionOptions::new(codepoint, next_codepoint, language);
848
849        let should_look_for_small_caps = self.descriptor.variant == font_variant_caps::T::SmallCaps &&
850            options.character.is_ascii_lowercase();
851        let font_or_synthesized_small_caps = |font: FontRef| {
852            if should_look_for_small_caps && font.synthesized_small_caps.is_some() {
853                return font.synthesized_small_caps.clone();
854            }
855            Some(font)
856        };
857
858        let font_has_glyph_and_presentation = |font: &FontRef| {
859            // Do not select this font if it goes against our emoji preference.
860            match options.presentation_preference {
861                EmojiPresentationPreference::Text if font.has_color_bitmap_or_colr_table() => {
862                    return false;
863                },
864                EmojiPresentationPreference::Emoji if !font.has_color_bitmap_or_colr_table() => {
865                    return false;
866                },
867                _ => {},
868            }
869            font.has_glyph_for(options.character)
870        };
871
872        let char_in_template =
873            |template: FontTemplateRef| template.char_in_unicode_range(options.character);
874
875        if let Some(font) = self.find(
876            font_context,
877            &char_in_template,
878            &font_has_glyph_and_presentation,
879        ) {
880            return font_or_synthesized_small_caps(font);
881        }
882
883        let fallback_key = FallbackKey::new(&options);
884        if let Some(fallback) = self.fallbacks.read().get(&fallback_key) &&
885            char_in_template(fallback.template.clone()) &&
886            font_has_glyph_and_presentation(fallback)
887        {
888            return font_or_synthesized_small_caps(fallback.clone());
889        }
890
891        if let Some(font) = self.find_fallback_using_system_font_list(
892            font_context,
893            options.clone(),
894            &char_in_template,
895            &font_has_glyph_and_presentation,
896        ) {
897            let fallback = font_or_synthesized_small_caps(font);
898            if let Some(fallback) = fallback.clone() {
899                self.fallbacks.write().insert(fallback_key, fallback);
900            }
901            return fallback;
902        }
903
904        let first_font = self.first(font_context);
905        if let Some(fallback) = first_font
906            .as_ref()
907            .and_then(|font| font.find_fallback_using_system_font_api(&options)) &&
908            font_has_glyph_and_presentation(&fallback)
909        {
910            return Some(fallback);
911        }
912
913        first_font
914    }
915
916    /// Find the first available font in the group, or the first available fallback font.
917    pub fn first(&self, font_context: &FontContext) -> Option<FontRef> {
918        // From https://drafts.csswg.org/css-fonts/#first-available-font:
919        // > The first available font, used for example in the definition of font-relative lengths
920        // > such as ex or in the definition of the line-height property, is defined to be the first
921        // > font for which the character U+0020 (space) is not excluded by a unicode-range, given the
922        // > font families in the font-family list (or a user agent’s default font if none are
923        // > available).
924        // > Note: it does not matter whether that font actually has a glyph for the space character.
925        let space_in_template = |template: FontTemplateRef| template.char_in_unicode_range(' ');
926        let font_predicate = |_: &FontRef| true;
927        self.find(font_context, &space_in_template, &font_predicate)
928            .or_else(|| {
929                self.find_fallback_using_system_font_list(
930                    font_context,
931                    FallbackFontSelectionOptions::default(),
932                    &space_in_template,
933                    &font_predicate,
934                )
935            })
936    }
937
938    /// Attempts to find a font which matches the given `template_predicate` and `font_predicate`.
939    /// This method mutates because we may need to load new font data in the process of finding
940    /// a suitable font.
941    fn find(
942        &self,
943        font_context: &FontContext,
944        template_predicate: &impl Fn(FontTemplateRef) -> bool,
945        font_predicate: &impl Fn(&FontRef) -> bool,
946    ) -> Option<FontRef> {
947        self.families
948            .iter()
949            .flat_map(|family| family.templates(font_context, &self.descriptor))
950            .find_map(|template| {
951                template.font_if_matches(
952                    font_context,
953                    &self.descriptor,
954                    template_predicate,
955                    font_predicate,
956                )
957            })
958    }
959
960    /// Attempts to find a suitable fallback font which matches the given `template_predicate` and
961    /// `font_predicate` using the system font list. The default family (i.e. "serif") will be tried
962    /// first, followed by platform-specific family names. If a `codepoint` is provided, then its
963    /// Unicode block may be used to refine
964    /// the list of family names which will be tried.
965    fn find_fallback_using_system_font_list(
966        &self,
967        font_context: &FontContext,
968        options: FallbackFontSelectionOptions,
969        template_predicate: &impl Fn(FontTemplateRef) -> bool,
970        font_predicate: &impl Fn(&FontRef) -> bool,
971    ) -> Option<FontRef> {
972        iter::once(FontFamilyDescriptor::default())
973            .chain(
974                fallback_font_families(options)
975                    .into_iter()
976                    .map(|family_name| {
977                        let family = SingleFontFamily::FamilyName(FamilyName {
978                            name: family_name.into(),
979                            syntax: FontFamilyNameSyntax::Quoted,
980                        });
981                        FontFamilyDescriptor::new(family, FontSearchScope::Local)
982                    }),
983            )
984            .find_map(|family_descriptor| {
985                FontGroupFamily::from(family_descriptor)
986                    .templates(font_context, &self.descriptor)
987                    .find_map(|template| {
988                        template.font_if_matches(
989                            font_context,
990                            &self.descriptor,
991                            template_predicate,
992                            font_predicate,
993                        )
994                    })
995            })
996    }
997}
998
999/// A [`FontGroupFamily`] can have multiple associated `FontTemplate`s if it is a
1000/// "composite face", meaning that it is defined by multiple `@font-face`
1001/// declarations which vary only by their `unicode-range` descriptors. In this case,
1002/// font selection will select a single member that contains the necessary unicode
1003/// character. Unicode ranges are specified by the [`FontGroupFamilyTemplate::template`]
1004/// member.
1005#[derive(MallocSizeOf)]
1006struct FontGroupFamilyTemplate {
1007    #[ignore_malloc_size_of = "This measured in the FontContext template cache."]
1008    template: FontTemplateRef,
1009    #[ignore_malloc_size_of = "This measured in the FontContext font cache."]
1010    font: OnceLock<Option<FontRef>>,
1011}
1012
1013impl From<FontTemplateRef> for FontGroupFamilyTemplate {
1014    fn from(template: FontTemplateRef) -> Self {
1015        Self {
1016            template,
1017            font: Default::default(),
1018        }
1019    }
1020}
1021
1022impl FontGroupFamilyTemplate {
1023    fn font(
1024        &self,
1025        font_context: &FontContext,
1026        font_descriptor: &FontDescriptor,
1027    ) -> Option<FontRef> {
1028        self.font
1029            .get_or_init(|| font_context.font(self.template.clone(), font_descriptor))
1030            .clone()
1031    }
1032
1033    fn font_if_matches(
1034        &self,
1035        font_context: &FontContext,
1036        font_descriptor: &FontDescriptor,
1037        template_predicate: &impl Fn(FontTemplateRef) -> bool,
1038        font_predicate: &impl Fn(&FontRef) -> bool,
1039    ) -> Option<FontRef> {
1040        if !template_predicate(self.template.clone()) {
1041            return None;
1042        }
1043        self.font(font_context, font_descriptor)
1044            .filter(font_predicate)
1045    }
1046}
1047
1048/// A `FontGroupFamily` is a single font family in a `FontGroup`. It corresponds to one of the
1049/// families listed in the `font-family` CSS property. The corresponding font data is lazy-loaded,
1050/// only if actually needed. A single `FontGroupFamily` can have multiple fonts, in the case that
1051/// individual fonts only cover part of the Unicode range.
1052#[derive(MallocSizeOf)]
1053struct FontGroupFamily {
1054    family_descriptor: FontFamilyDescriptor,
1055    members: OnceLock<Vec<FontGroupFamilyTemplate>>,
1056}
1057
1058impl From<FontFamilyDescriptor> for FontGroupFamily {
1059    fn from(family_descriptor: FontFamilyDescriptor) -> Self {
1060        Self {
1061            family_descriptor,
1062            members: Default::default(),
1063        }
1064    }
1065}
1066
1067impl FontGroupFamily {
1068    fn local_or_web(family: &SingleFontFamily) -> FontGroupFamily {
1069        FontFamilyDescriptor::new(family.clone(), FontSearchScope::Any).into()
1070    }
1071
1072    fn templates(
1073        &self,
1074        font_context: &FontContext,
1075        font_descriptor: &FontDescriptor,
1076    ) -> impl Iterator<Item = &FontGroupFamilyTemplate> {
1077        self.members
1078            .get_or_init(|| {
1079                font_context
1080                    .matching_templates(font_descriptor, &self.family_descriptor)
1081                    .into_iter()
1082                    .map(Into::into)
1083                    .collect()
1084            })
1085            .iter()
1086    }
1087}
1088
1089/// The scope within which we will look for a font.
1090#[derive(Clone, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)]
1091pub enum FontSearchScope {
1092    /// All fonts will be searched, including those specified via `@font-face` rules.
1093    Any,
1094
1095    /// Only local system fonts will be searched.
1096    Local,
1097}
1098
1099/// The font family parameters for font selection.
1100#[derive(Clone, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)]
1101pub struct FontFamilyDescriptor {
1102    pub(crate) family: SingleFontFamily,
1103    pub(crate) scope: FontSearchScope,
1104}
1105
1106impl FontFamilyDescriptor {
1107    pub fn new(family: SingleFontFamily, scope: FontSearchScope) -> FontFamilyDescriptor {
1108        FontFamilyDescriptor { family, scope }
1109    }
1110
1111    fn default() -> FontFamilyDescriptor {
1112        FontFamilyDescriptor {
1113            family: SingleFontFamily::Generic(GenericFontFamily::None),
1114            scope: FontSearchScope::Local,
1115        }
1116    }
1117}
1118
1119pub struct FontBaseline {
1120    pub ideographic_baseline: f32,
1121    pub alphabetic_baseline: f32,
1122    pub hanging_baseline: f32,
1123}
1124
1125/// Given a mapping array `mapping` and a value, map that value onto
1126/// the value specified by the array. For instance, for FontConfig
1127/// values of weights, we would map these onto the CSS [0..1000] range
1128/// by creating an array as below. Values that fall between two mapped
1129/// values, will be adjusted by the weighted mean.
1130///
1131/// ```ignore
1132/// let mapping = [
1133///     (0., 0.),
1134///     (FC_WEIGHT_REGULAR as f64, 400 as f64),
1135///     (FC_WEIGHT_BOLD as f64, 700 as f64),
1136///     (FC_WEIGHT_EXTRABLACK as f64, 1000 as f64),
1137/// ];
1138/// let mapped_weight = apply_font_config_to_style_mapping(&mapping, weight as f64);
1139/// ```
1140#[cfg(all(
1141    any(target_os = "linux", target_os = "macos", target_os = "freebsd"),
1142    not(target_env = "ohos")
1143))]
1144pub(crate) fn map_platform_values_to_style_values(mapping: &[(f64, f64)], value: f64) -> f64 {
1145    if value < mapping[0].0 {
1146        return mapping[0].1;
1147    }
1148
1149    for window in mapping.windows(2) {
1150        let (font_config_value_a, css_value_a) = window[0];
1151        let (font_config_value_b, css_value_b) = window[1];
1152
1153        if value >= font_config_value_a && value <= font_config_value_b {
1154            let ratio = (value - font_config_value_a) / (font_config_value_b - font_config_value_a);
1155            return css_value_a + ((css_value_b - css_value_a) * ratio);
1156        }
1157    }
1158
1159    mapping[mapping.len() - 1].1
1160}
1161
1162/// <https://drafts.csswg.org/css-fonts-4/#apply-font-matching-variations>
1163fn compute_variations(
1164    descriptor: &FontDescriptor,
1165    template: &FontTemplateRef,
1166    variation_axes: VariationAxes,
1167) -> Vec<FontVariation> {
1168    let font_face_rule = template.font_face_rule();
1169
1170    // The steps in this algorithm are inverted order because they are listed in ascending order of precedence.
1171    let mut variations: Vec<FontVariation> = vec![];
1172
1173    let mut add_variation = |variation: FontVariation| {
1174        if !variations
1175            .iter()
1176            .any(|existing_variation| existing_variation.tag == variation.tag)
1177        {
1178            variations.push(variation);
1179        }
1180    };
1181
1182    // Step 12. Font variations implied by the value of the font-variation-settings property are applied.
1183    // These values should be clamped to the values that are supported by the font.
1184    // NOTE: Clamping happens inside the PlatformFont.
1185    descriptor
1186        .variation_settings
1187        .iter()
1188        .copied()
1189        .for_each(&mut add_variation);
1190
1191    // Step 9. Font variations implied by the value of the font-optical-sizing property are applied.
1192    // NOTE The precise behaviour of font-optical-sizing:auto is not defined.
1193    // We choose to set "opsz" to the font size if it's not already set elsewhere. This is the easiest
1194    // at the end of this function, so we move this step down.
1195
1196    if let Some(font_face_rule) = &font_face_rule {
1197        // Step 6. If the font is defined via an @font-face rule, the font variations implied by the font-variation-settings
1198        // descriptor in the @font-face rule are applied.
1199        if let Some(variation_settings) =
1200            font_face_rule.descriptors.font_variation_settings.as_ref()
1201        {
1202            variation_settings
1203                .0
1204                .iter()
1205                .map(|variation| FontVariation {
1206                    tag: variation.tag.0,
1207                    value: variation.value.get().expect(
1208                        "The value is enforced to be resolvable at parse time \
1209                        (see FontVariationSettings::parse_for_font_face_rule).",
1210                    ),
1211                })
1212                .for_each(&mut add_variation);
1213        }
1214    }
1215
1216    // Step 2. Font variations as enabled by the font-weight, font-width, and font-style properties are applied.
1217    //
1218    // The application of the value enabled by font-style is affected by font selection, because this property might
1219    // select an italic or an oblique font. The value applied is the closest matching value as determined by the font
1220    // matching algorithm. User agents must apply at most one value due to the font-style property; both "ital" and
1221    // "slnt" values must not be set together.
1222    //
1223    // If the selected font is defined in an @font-face rule, then the values applied at this step should be clamped
1224    // to the value of the font-weight, font-width, and font-style descriptors in that @font-face rule.
1225    // TODO: Clamp weight/width to the descriptors from the @font-face rule, if any
1226    add_variation(FontVariation {
1227        tag: Tag::new(b"wght").to_u32(),
1228        value: descriptor.weight.value(),
1229    });
1230
1231    add_variation(FontVariation {
1232        tag: Tag::new(b"wdth").to_u32(),
1233        value: descriptor.width.0.to_float(),
1234    });
1235
1236    if variation_axes.intersects(VariationAxes::ITAL | VariationAxes::SLNT) {
1237        let clamped_font_style = font_face_rule
1238            .as_ref()
1239            .and_then(|font_face_rule| font_face_rule.descriptors.font_style.as_ref())
1240            .map(|font_style_range| {
1241                let computed_font_style_range =
1242                    font_style_range.compute().expect("never returns None");
1243
1244                if computed_font_style_range.0 == FontStyle::ITALIC {
1245                    debug_assert_eq!(computed_font_style_range.1, FontStyle::ITALIC);
1246                    return FontStyle::ITALIC;
1247                }
1248                debug_assert_ne!(computed_font_style_range.1, FontStyle::ITALIC);
1249
1250                let specified_angle = if descriptor.style == FontStyle::ITALIC {
1251                    FontStyle::DEFAULT_OBLIQUE_DEGREES as f32
1252                } else {
1253                    descriptor.style.oblique_degrees()
1254                };
1255
1256                let clamped_angle = specified_angle
1257                    .min(computed_font_style_range.1.oblique_degrees())
1258                    .max(computed_font_style_range.0.oblique_degrees());
1259                FontStyle::oblique(clamped_angle)
1260            })
1261            .unwrap_or(descriptor.style);
1262
1263        // TODO: We should recognize when a font has neither a ital nor a slnt axis and then
1264        // synthesize an appropriate font face if allowed by font-synthesis.
1265
1266        // When both a `ital` and a `slnt` axis are available then we prefer `ital` for
1267        // `font-style: italic` and `slnt` for `font-style: oblique`.
1268        let use_ital_axis = (variation_axes.contains(VariationAxes::ITAL) &&
1269            clamped_font_style == FontStyle::ITALIC) ||
1270            !variation_axes.contains(VariationAxes::SLNT);
1271        if use_ital_axis {
1272            add_variation(FontVariation {
1273                tag: ITAL.to_u32(),
1274                value: (clamped_font_style != FontStyle::NORMAL) as u32 as f32,
1275            });
1276        } else {
1277            // Note: CSS and OpenType measure slnt in opposite directions, so we need to negate the
1278            // angles.
1279            if clamped_font_style == FontStyle::ITALIC {
1280                add_variation(FontVariation {
1281                    tag: SLNT.to_u32(),
1282                    value: (-FontStyle::DEFAULT_OBLIQUE_DEGREES) as f32,
1283                });
1284            } else {
1285                add_variation(FontVariation {
1286                    tag: SLNT.to_u32(),
1287                    value: -clamped_font_style.oblique_degrees(),
1288                });
1289            }
1290        }
1291    }
1292
1293    // This is the implementation for Step 9. Refer to the note on Step 9 for an explanation of why it's here.
1294    if descriptor.optical_sizing == FontOpticalSizing::Auto {
1295        add_variation(FontVariation {
1296            tag: Tag::new(b"opsz").to_u32(),
1297            value: descriptor.pt_size.to_f32_px(),
1298        });
1299    }
1300
1301    variations
1302}
1303
1304bitflags! {
1305    #[derive(Clone, Copy, Debug)]
1306    struct VariationAxes: u8 {
1307        /// Whether the font has any variation axes at all.
1308        const IS_VARIABLE = 1;
1309
1310        /// Whether the font as a `ital` axis.
1311        ///
1312        /// Never set without `IS_VARIABLE`.
1313        const ITAL = 1 << 1;
1314
1315        /// Whether the font as a `slnt` axis.
1316        ///
1317        /// Never set without `IS_VARIABLE`.
1318        const SLNT = 1 << 2;
1319    }
1320}
1321
1322impl VariationAxes {
1323    fn from_platform_font(platform_font: &PlatformFont) -> Self {
1324        let Some(fvar_table) = platform_font.table_for_tag(FVAR) else {
1325            // This is not a variable font.
1326            return VariationAxes::empty();
1327        };
1328
1329        let Some(variation_axes) = fvar_table
1330            .parse_as_specific_table::<Fvar<'_>>()
1331            .ok()
1332            .and_then(|fvar: Fvar<'_>| fvar.axis_instance_arrays().ok())
1333            .map(|instance_arrays| instance_arrays.axes())
1334        else {
1335            // The fvar table is malformed.
1336            return VariationAxes::empty();
1337        };
1338
1339        if variation_axes.is_empty() {
1340            return VariationAxes::empty();
1341        }
1342
1343        let mut result = VariationAxes::IS_VARIABLE;
1344        for axis in variation_axes {
1345            match axis.axis_tag() {
1346                ITAL => result |= VariationAxes::ITAL,
1347                SLNT => result |= VariationAxes::SLNT,
1348                _ => {},
1349            }
1350        }
1351
1352        result
1353    }
1354}