Skip to main content

fonts_traits/
font_template.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::fmt::{Debug, Error, Formatter};
6use std::ops::{Deref, RangeInclusive};
7use std::sync::Arc;
8
9use atomic_refcell::{AtomicRef, AtomicRefCell};
10use malloc_size_of_derive::MallocSizeOf;
11use serde::{Deserialize, Serialize};
12use servo_arc::Arc as ServoArc;
13use skrifa::Font as SkrifaFont;
14use skrifa::font::attribute::Style;
15use style::computed_values::font_style::T as FontStyle;
16use style::computed_values::font_width::T as FontWidth;
17use style::font_face::{ComputedFontStyleRange, ComputedFontWeightRange, ComputedFontWidthRange};
18use style::values::computed::font::FontWeight;
19
20use crate::tag::{WDTH, WGHT};
21use crate::{CSSFontFaceDescriptors, FontDescriptor, FontFaceRuleInfo, FontIdentifier};
22
23/// A reference to a [`FontTemplate`] with shared ownership and mutability.
24#[derive(Clone, Debug, MallocSizeOf)]
25pub struct FontTemplateRef(#[conditional_malloc_size_of] Arc<AtomicRefCell<FontTemplate>>);
26
27impl FontTemplateRef {
28    pub fn new(template: FontTemplate) -> Self {
29        Self(Arc::new(AtomicRefCell::new(template)))
30    }
31}
32
33impl Deref for FontTemplateRef {
34    type Target = Arc<AtomicRefCell<FontTemplate>>;
35    fn deref(&self) -> &Self::Target {
36        &self.0
37    }
38}
39
40/// Describes how to select a font from a given family. This is very basic at the moment and needs
41/// to be expanded or refactored when we support more of the font styling parameters.
42///
43/// NB: If you change this, you will need to update `style::properties::compute_font_hash()`.
44#[derive(Clone, Debug, Deserialize, Hash, MallocSizeOf, PartialEq, Serialize)]
45pub struct FontTemplateDescriptor {
46    pub weight: ComputedFontWeightRange,
47    pub width: ComputedFontWidthRange,
48    pub style: ComputedFontStyleRange,
49    pub unicode_range: Option<Vec<RangeInclusive<u32>>>,
50}
51
52impl Default for FontTemplateDescriptor {
53    fn default() -> Self {
54        Self::new(FontWeight::normal(), FontWidth::NORMAL, FontStyle::NORMAL)
55    }
56}
57
58impl FontTemplateDescriptor {
59    /// Create a [`FontTemplateDescriptor`] given a [`SkrifaFont`]. This is used during the
60    /// creation of web fonts and is aware of font variations.
61    pub fn from_skrifa_font(font: &SkrifaFont) -> FontTemplateDescriptor {
62        let attributes = font.default_attributes();
63
64        let mut descriptor = Self::new(
65            FontWeight::from_float(attributes.weight.value()),
66            FontWidth::from_percentage(attributes.width.ratio()),
67            match attributes.style {
68                Style::Normal => FontStyle::NORMAL,
69                Style::Oblique(Some(degrees)) => FontStyle::oblique(degrees),
70                Style::Oblique(None) => FontStyle::OBLIQUE,
71                Style::Italic => FontStyle::ITALIC,
72            },
73        );
74
75        for axis in font.axes().iter() {
76            match axis.tag() {
77                WDTH => {
78                    descriptor.width = ComputedFontWidthRange(
79                        FontWidth::from_percentage(axis.min_value() / 100.0),
80                        FontWidth::from_percentage(axis.max_value() / 100.0),
81                    )
82                },
83                WGHT => {
84                    descriptor.weight = ComputedFontWeightRange(
85                        FontWeight::from_float(axis.min_value()),
86                        FontWeight::from_float(axis.max_value()),
87                    )
88                },
89                _ => {},
90            }
91        }
92
93        descriptor
94    }
95
96    #[inline]
97    pub fn new(weight: FontWeight, width: FontWidth, style: FontStyle) -> Self {
98        Self {
99            weight: ComputedFontWeightRange(weight, weight),
100            width: ComputedFontWidthRange(width, width),
101            style: ComputedFontStyleRange(style, style),
102            unicode_range: None,
103        }
104    }
105
106    pub fn is_variation_font(&self) -> bool {
107        self.weight.0 != self.weight.1 ||
108            self.width.0 != self.width.1 ||
109            self.style.0 != self.style.1
110    }
111
112    /// Returns a score indicating how far apart visually the two font descriptors are. This is
113    /// used for implmenting the CSS Font Matching algorithm:
114    /// <https://drafts.csswg.org/css-fonts/#font-matching-algorithm>.
115    ///
116    /// The smaller the score, the better the fonts match. 0 indicates an exact match. This must
117    /// be commutative (distance(A, B) == distance(B, A)).
118    #[inline]
119    fn distance_from(&self, target: &FontDescriptor) -> f32 {
120        let width_distance = target.width.match_distance(&self.width);
121        let style_distance = target.style.match_distance(&self.style);
122        let weight_distance = target.weight.match_distance(&self.weight);
123
124        // Sanity-check that the distances are within the expected range
125        // (update if implementation of the distance functions is changed).
126        assert!((0.0..=2000.0).contains(&width_distance));
127        assert!((0.0..=500.0).contains(&style_distance));
128        assert!((0.0..=1600.0).contains(&weight_distance));
129
130        // Factors used to weight the distances between the available and target font
131        // properties during font-matching. These ensure that we respect the CSS-fonts
132        // requirement that font-width >> font-style >> font-weight; and in addition,
133        // a mismatch between the desired and actual glyph presentation (emoji vs text)
134        // will take precedence over any of the style attributes.
135        //
136        // Also relevant for font selection is the emoji presentation preference, but this
137        // is handled later when filtering fonts based on the glyphs they contain.
138        const WIDTH_FACTOR: f32 = 1.0e8;
139        const STYLE_FACTOR: f32 = 1.0e4;
140        const WEIGHT_FACTOR: f32 = 1.0e0;
141
142        width_distance * WIDTH_FACTOR +
143            style_distance * STYLE_FACTOR +
144            weight_distance * WEIGHT_FACTOR
145    }
146
147    fn matches(&self, descriptor_to_match: &FontDescriptor) -> bool {
148        self.weight.0 <= descriptor_to_match.weight &&
149            self.weight.1 >= descriptor_to_match.weight &&
150            self.style.0 <= descriptor_to_match.style &&
151            self.style.1 >= descriptor_to_match.style &&
152            self.width.0 <= descriptor_to_match.width &&
153            self.width.1 >= descriptor_to_match.width
154    }
155
156    pub fn override_values_with_css_font_template_descriptors(
157        &mut self,
158        css_font_template_descriptors: &CSSFontFaceDescriptors,
159    ) {
160        if let Some(ref weight) = css_font_template_descriptors.weight {
161            self.weight = weight.clone();
162        }
163        if let Some(ref style) = css_font_template_descriptors.style {
164            self.style = style.clone();
165        }
166        if let Some(ref width) = css_font_template_descriptors.width {
167            self.width = width.clone();
168        }
169        if let Some(ref unicode_range) = css_font_template_descriptors.unicode_range {
170            self.unicode_range = Some(unicode_range.clone());
171        }
172    }
173}
174
175/// This describes all the information needed to create
176/// font instance handles. It contains a unique
177/// FontTemplateData structure that is platform specific.
178#[derive(Clone, Deserialize, MallocSizeOf, Serialize)]
179pub struct FontTemplate {
180    pub identifier: FontIdentifier,
181    pub descriptor: FontTemplateDescriptor,
182
183    /// If this font is a web font, this is a reference to the `@font-face` rule that
184    /// created it.
185    #[serde(skip)]
186    #[conditional_malloc_size_of]
187    pub font_face_rule: Option<ServoArc<FontFaceRuleInfo>>,
188}
189
190impl Debug for FontTemplate {
191    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
192        self.identifier.fmt(f)
193    }
194}
195
196/// Holds all of the template information for a font that
197/// is common, regardless of the number of instances of
198/// this font handle per thread.
199impl FontTemplate {
200    /// Create a new [`FontTemplate`].
201    pub fn new(
202        identifier: FontIdentifier,
203        descriptor: FontTemplateDescriptor,
204        font_face_rule: Option<ServoArc<FontFaceRuleInfo>>,
205    ) -> FontTemplate {
206        FontTemplate {
207            identifier,
208            descriptor,
209            font_face_rule,
210        }
211    }
212
213    /// Create a new [`FontTemplate`] for a `@font-family` with a `local(...)` `src`. This takes in
214    /// the template of the local font and creates a new one that reflects the properties specified
215    /// by `@font-family` in the stylesheet.
216    pub fn new_for_local_web_font(
217        local_template: FontTemplateRef,
218        css_font_template_descriptors: &CSSFontFaceDescriptors,
219        font_face_rule: Option<ServoArc<FontFaceRuleInfo>>,
220    ) -> Result<FontTemplate, &'static str> {
221        let mut alias_template = local_template.borrow().clone();
222        alias_template
223            .descriptor
224            .override_values_with_css_font_template_descriptors(css_font_template_descriptors);
225        alias_template.font_face_rule = font_face_rule;
226        Ok(alias_template)
227    }
228
229    pub fn identifier(&self) -> &FontIdentifier {
230        &self.identifier
231    }
232
233    pub fn is_defined_by_font_face_rule(&self, rule: &ServoArc<FontFaceRuleInfo>) -> bool {
234        self.font_face_rule
235            .as_ref()
236            .is_some_and(|defining_rule| ServoArc::ptr_eq(rule, defining_rule))
237    }
238}
239
240pub trait FontTemplateRefMethods {
241    /// Get the descriptor.
242    fn descriptor(&self) -> AtomicRef<'_, FontTemplateDescriptor>;
243    /// Get the [`FontIdentifier`] for this template.
244    fn identifier(&self) -> AtomicRef<'_, FontIdentifier>;
245    /// Returns true if the given descriptor matches the one in this [`FontTemplate`].
246    fn matches_font_descriptor(&self, descriptor_to_match: &FontDescriptor) -> bool;
247    /// Calculate the distance from this [`FontTemplate`]s descriptor and return it
248    /// or None if this is not a valid [`FontTemplate`].
249    fn descriptor_distance(&self, descriptor_to_match: &FontDescriptor) -> f32;
250    /// Whether or not this character is in the unicode ranges specified in
251    /// this temlates `@font-face` definition, if any.
252    fn char_in_unicode_range(&self, character: char) -> bool;
253
254    /// Return the `@font-face` rule that defined this template, if any.
255    fn font_face_rule(&self) -> Option<AtomicRef<'_, ServoArc<FontFaceRuleInfo>>>;
256}
257
258impl FontTemplateRefMethods for FontTemplateRef {
259    fn descriptor(&self) -> AtomicRef<'_, FontTemplateDescriptor> {
260        AtomicRef::map(self.borrow(), |font_template_ref| {
261            &font_template_ref.descriptor
262        })
263    }
264
265    fn identifier(&self) -> AtomicRef<'_, FontIdentifier> {
266        AtomicRef::map(self.borrow(), |font_template_ref| {
267            &font_template_ref.identifier
268        })
269    }
270
271    fn matches_font_descriptor(&self, descriptor_to_match: &FontDescriptor) -> bool {
272        self.descriptor().matches(descriptor_to_match)
273    }
274
275    fn descriptor_distance(&self, descriptor_to_match: &FontDescriptor) -> f32 {
276        self.descriptor().distance_from(descriptor_to_match)
277    }
278
279    fn char_in_unicode_range(&self, character: char) -> bool {
280        let character = character as u32;
281        self.borrow()
282            .descriptor
283            .unicode_range
284            .as_ref()
285            .is_none_or(|ranges| ranges.iter().any(|range| range.contains(&character)))
286    }
287
288    fn font_face_rule(&self) -> Option<AtomicRef<'_, ServoArc<FontFaceRuleInfo>>> {
289        AtomicRef::filter_map(self.borrow(), |template| template.font_face_rule.as_ref())
290    }
291}
292
293/// A trait for implementing the CSS font matching algorithm against various font features.
294/// See <https://drafts.csswg.org/css-fonts/#font-matching-algorithm>.
295///
296/// This implementation is ported from Gecko at:
297/// <https://searchfox.org/mozilla-central/rev/0529464f0d2981347ef581f7521ace8b7af7f7ac/gfx/thebes/gfxFontUtils.h#1217>.
298trait FontMatchDistanceMethod<T>: Sized {
299    fn match_distance(&self, range: &T) -> f32;
300    fn to_float(&self) -> f32;
301}
302
303impl FontMatchDistanceMethod<ComputedFontWidthRange> for FontWidth {
304    fn match_distance(&self, range: &ComputedFontWidthRange) -> f32 {
305        // width distance ==> [0,2000]
306        const REVERSE_DISTANCE: f32 = 1000.0;
307
308        let min_width = range.0;
309        let max_width = range.1;
310
311        // The width value is a (non-negative) percentage; currently we support
312        // values in the range 0 .. 1000. (If the upper limit is ever increased,
313        // the kReverseDistance value used here may need to be adjusted.)
314        // If aTargetWidth is >100, we prefer larger values if available;
315        // if <=100, we prefer smaller values if available.
316        if *self < min_width {
317            if *self > FontWidth::NORMAL {
318                return min_width.to_float() - self.to_float();
319            }
320            return (min_width.to_float() - self.to_float()) + REVERSE_DISTANCE;
321        }
322
323        if *self > max_width {
324            if *self <= FontWidth::NORMAL {
325                return self.to_float() - max_width.to_float();
326            }
327            return (self.to_float() - max_width.to_float()) + REVERSE_DISTANCE;
328        }
329        0.0
330    }
331
332    fn to_float(&self) -> f32 {
333        self.0.to_float()
334    }
335}
336
337impl FontMatchDistanceMethod<ComputedFontWeightRange> for FontWeight {
338    // Calculate weight distance with values in the range (0..1000). In general,
339    // heavier weights match towards even heavier weights while lighter weights
340    // match towards even lighter weights. Target weight values in the range
341    // [400..500] are special, since they will first match up to 500, then down
342    // towards 0, then up again towards 999.
343    //
344    // Example: with target 600 and font weight 800, distance will be 200. With
345    // target 300 and font weight 600, distance will be 900, since heavier
346    // weights are farther away than lighter weights. If the target is 5 and the
347    // font weight 995, the distance would be 1590 for the same reason.
348
349    fn match_distance(&self, range: &ComputedFontWeightRange) -> f32 {
350        // weight distance ==> [0,1600]
351        const NOT_WITHIN_CENTRAL_RANGE: f32 = 100.0;
352        const REVERSE_DISTANCE: f32 = 600.0;
353
354        let min_weight = range.0;
355        let max_weight = range.1;
356
357        if *self >= min_weight && *self <= max_weight {
358            // Target is within the face's range, so it's a perfect match
359            return 0.0;
360        }
361
362        if *self < FontWeight::NORMAL {
363            // Requested a lighter-than-400 weight
364            if max_weight < *self {
365                return self.to_float() - max_weight.to_float();
366            }
367
368            // Add reverse-search penalty for bolder faces
369            return (min_weight.to_float() - self.to_float()) + REVERSE_DISTANCE;
370        }
371
372        if *self > FontWeight::from_float(500.) {
373            // Requested a bolder-than-500 weight
374            if min_weight > *self {
375                return min_weight.to_float() - self.to_float();
376            }
377            // Add reverse-search penalty for lighter faces
378            return (self.to_float() - max_weight.to_float()) + REVERSE_DISTANCE;
379        }
380
381        // Special case for requested weight in the [400..500] range
382        if min_weight > *self {
383            if min_weight <= FontWeight::from_float(500.) {
384                // Bolder weight up to 500 is first choice
385                return min_weight.to_float() - self.to_float();
386            }
387            // Other bolder weights get a reverse-search penalty
388            return (min_weight.to_float() - self.to_float()) + REVERSE_DISTANCE;
389        }
390        // Lighter weights are not as good as bolder ones within [400..500]
391        (self.to_float() - max_weight.to_float()) + NOT_WITHIN_CENTRAL_RANGE
392    }
393
394    fn to_float(&self) -> f32 {
395        self.value()
396    }
397}
398
399impl FontMatchDistanceMethod<ComputedFontStyleRange> for FontStyle {
400    fn match_distance(&self, range: &ComputedFontStyleRange) -> f32 {
401        // style distance ==> [0,500]
402        let min_style = range.0;
403        if *self == min_style {
404            return 0.0; // styles match exactly ==> 0
405        }
406
407        // bias added to angle difference when searching in the non-preferred
408        // direction from a target angle
409        const REVERSE: f32 = 100.0;
410
411        // bias added when we've crossed from positive to negative angles or
412        // vice versa
413        const NEGATE: f32 = 200.0;
414
415        if *self == FontStyle::NORMAL {
416            if min_style.is_oblique() {
417                // to distinguish oblique 0deg from normal, we add 1.0 to the angle
418                let min_angle = min_style.oblique_degrees();
419                if min_angle >= 0.0 {
420                    return 1.0 + min_angle;
421                }
422                let max_style = range.1;
423                let max_angle = max_style.oblique_degrees();
424                if max_angle >= 0.0 {
425                    // [min,max] range includes 0.0, so just return our minimum
426                    return 1.0;
427                }
428                // negative oblique is even worse than italic
429                return NEGATE - max_angle;
430            }
431            // must be italic, which is worse than any non-negative oblique;
432            // treat as a match in the wrong search direction
433            assert!(min_style == FontStyle::ITALIC);
434            return REVERSE;
435        }
436
437        let default_oblique_angle = FontStyle::OBLIQUE.oblique_degrees();
438        if *self == FontStyle::ITALIC {
439            if min_style.is_oblique() {
440                let min_angle = min_style.oblique_degrees();
441                if min_angle >= default_oblique_angle {
442                    return 1.0 + (min_angle - default_oblique_angle);
443                }
444                let max_style = range.1;
445                let max_angle = max_style.oblique_degrees();
446                if max_angle >= default_oblique_angle {
447                    return 1.0;
448                }
449                if max_angle > 0.0 {
450                    // wrong direction but still > 0, add bias of 100
451                    return REVERSE + (default_oblique_angle - max_angle);
452                }
453                // negative oblique angle, add bias of 300
454                return REVERSE + NEGATE + (default_oblique_angle - max_angle);
455            }
456            // normal is worse than oblique > 0, but better than oblique <= 0
457            assert!(min_style == FontStyle::NORMAL);
458            return NEGATE;
459        }
460
461        // target is oblique <angle>: four different cases depending on
462        // the value of the <angle>, which determines the preferred direction
463        // of search
464        let target_angle = self.oblique_degrees();
465        if target_angle >= default_oblique_angle {
466            if min_style.is_oblique() {
467                let min_angle = min_style.oblique_degrees();
468                if min_angle >= target_angle {
469                    return min_angle - target_angle;
470                }
471                let max_style = range.1;
472                let max_angle = max_style.oblique_degrees();
473                if max_angle >= target_angle {
474                    return 0.0;
475                }
476                if max_angle > 0.0 {
477                    return REVERSE + (target_angle - max_angle);
478                }
479                return REVERSE + NEGATE + (target_angle - max_angle);
480            }
481            if min_style == FontStyle::ITALIC {
482                return REVERSE + NEGATE;
483            }
484            return REVERSE + NEGATE + 1.0;
485        }
486
487        if target_angle <= -default_oblique_angle {
488            if min_style.is_oblique() {
489                let max_style = range.1;
490                let max_angle = max_style.oblique_degrees();
491                if max_angle <= target_angle {
492                    return target_angle - max_angle;
493                }
494                let min_angle = min_style.oblique_degrees();
495                if min_angle <= target_angle {
496                    return 0.0;
497                }
498                if min_angle < 0.0 {
499                    return REVERSE + (min_angle - target_angle);
500                }
501                return REVERSE + NEGATE + (min_angle - target_angle);
502            }
503            if min_style == FontStyle::ITALIC {
504                return REVERSE + NEGATE;
505            }
506            return REVERSE + NEGATE + 1.0;
507        }
508
509        if target_angle >= 0.0 {
510            if min_style.is_oblique() {
511                let min_angle = min_style.oblique_degrees();
512                if min_angle > target_angle {
513                    return REVERSE + (min_angle - target_angle);
514                }
515                let max_style = range.1;
516                let max_angle = max_style.oblique_degrees();
517                if max_angle >= target_angle {
518                    return 0.0;
519                }
520                if max_angle > 0.0 {
521                    return target_angle - max_angle;
522                }
523                return REVERSE + NEGATE + (target_angle - max_angle);
524            }
525            if min_style == FontStyle::ITALIC {
526                return REVERSE + NEGATE - 2.0;
527            }
528            return REVERSE + NEGATE - 1.0;
529        }
530
531        // last case: (targetAngle < 0.0 && targetAngle > kDefaultAngle)
532        if min_style.is_oblique() {
533            let max_style = range.1;
534            let max_angle = max_style.oblique_degrees();
535            if max_angle < target_angle {
536                return REVERSE + (target_angle - max_angle);
537            }
538            let min_angle = min_style.oblique_degrees();
539            if min_angle <= target_angle {
540                return 0.0;
541            }
542            if min_angle < 0.0 {
543                return min_angle - target_angle;
544            }
545            return REVERSE + NEGATE + (min_angle - target_angle);
546        }
547        if min_style == FontStyle::ITALIC {
548            return REVERSE + NEGATE - 2.0;
549        }
550        REVERSE + NEGATE - 1.0
551    }
552
553    fn to_float(&self) -> f32 {
554        unimplemented!("Don't know how to convert FontStyle to float.");
555    }
556}
557
558pub trait IsOblique {
559    fn is_oblique(&self) -> bool;
560}
561
562impl IsOblique for FontStyle {
563    fn is_oblique(&self) -> bool {
564        *self != FontStyle::NORMAL && *self != FontStyle::ITALIC
565    }
566}