Skip to main content

style/values/computed/
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
5//! Computed values for font properties
6
7use crate::Atom;
8use crate::derives::*;
9use crate::parser::{Parse, ParserContext};
10use crate::properties::CSSWideKeyword;
11use crate::typed_om::{ToTyped, TypedValue};
12use crate::values::animated::ToAnimatedValue;
13use crate::values::computed::{
14    Angle, Context, Integer, Length, NonNegativeLength, NonNegativeNumber, Number, Percentage,
15    ToComputedValue, Zoom,
16};
17use crate::values::generics::font::{
18    FeatureTagValue, FontSettings, TaggedFontValue, VariationValue,
19};
20use crate::values::generics::{NonNegative, font as generics};
21use crate::values::resolved::{Context as ResolvedContext, ToResolvedValue};
22use crate::values::specified::font::{
23    self as specified, KeywordInfo, MAX_FONT_WEIGHT, MIN_FONT_WEIGHT,
24};
25use crate::values::specified::length::{FontBaseSize, LineHeightBase};
26use crate::values::{CSSInteger, StyleParseErrorKind};
27use cssparser::{CssStringWriter, Parser, serialize_identifier};
28use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
29use num_traits::abs;
30use num_traits::cast::AsPrimitive;
31use std::fmt::{self, Write};
32use style_traits::{CssWriter, ParseError, ToCss};
33use thin_vec::ThinVec;
34
35pub use crate::values::computed::Length as MozScriptMinSize;
36pub use crate::values::specified::Integer as SpecifiedInteger;
37pub use crate::values::specified::Number as SpecifiedNumber;
38pub use crate::values::specified::font::{
39    FontKerning, FontOpticalSizing, FontPalette, FontSmoothing, FontSynthesis, FontSynthesisStyle,
40    FontVariantCaps, FontVariantEmoji, FontVariantPosition, MathShift, MathStyle, MathVariant,
41    MozScriptSizeMultiplier,
42};
43pub use crate::values::specified::font::{
44    FontVariantAlternates, FontVariantEastAsian, FontVariantLigatures, FontVariantNumeric,
45    QueryFontMetricsFlags, XLang, XTextScale,
46};
47
48/// Generic template for font property type classes that use a fixed-point
49/// internal representation with `FRACTION_BITS` for the fractional part.
50///
51/// Values are constructed from and exposed as floating-point, but stored
52/// internally as fixed point, so there will be a quantization effect on
53/// fractional values, depending on the number of fractional bits used.
54///
55/// Using (16-bit) fixed-point types rather than floats for these style
56/// attributes reduces the memory footprint of gfxFontEntry and gfxFontStyle; it
57/// will also tend to reduce the number of distinct font instances that get
58/// created, particularly when styles are animated or set to arbitrary values
59/// (e.g. by sliders in the UI), which should reduce pressure on graphics
60/// resources and improve cache hit rates.
61///
62/// cbindgen:derive-lt
63/// cbindgen:derive-lte
64/// cbindgen:derive-gt
65/// cbindgen:derive-gte
66#[repr(C)]
67#[derive(
68    Clone,
69    ComputeSquaredDistance,
70    Copy,
71    Debug,
72    Deserialize,
73    Eq,
74    Hash,
75    MallocSizeOf,
76    PartialEq,
77    PartialOrd,
78    Serialize,
79    ToResolvedValue,
80)]
81pub struct FixedPoint<T, const FRACTION_BITS: u16> {
82    /// The actual representation.
83    pub value: T,
84}
85
86impl<T, const FRACTION_BITS: u16> FixedPoint<T, FRACTION_BITS>
87where
88    T: AsPrimitive<f32>,
89    f32: AsPrimitive<T>,
90    u16: AsPrimitive<T>,
91{
92    const SCALE: u16 = 1 << FRACTION_BITS;
93    const INVERSE_SCALE: f32 = 1.0 / Self::SCALE as f32;
94
95    /// Returns a fixed-point bit from a floating-point context.
96    pub fn from_float(v: f32) -> Self {
97        Self {
98            value: (v * Self::SCALE as f32).round().as_(),
99        }
100    }
101
102    /// Returns the floating-point representation.
103    pub fn to_float(&self) -> f32 {
104        self.value.as_() * Self::INVERSE_SCALE
105    }
106}
107
108// We implement this and mul below only for u16 types, because u32 types might need more care about
109// overflow. But it's not hard to implement in either case.
110impl<const FRACTION_BITS: u16> std::ops::Div for FixedPoint<u16, FRACTION_BITS> {
111    type Output = Self;
112    fn div(self, rhs: Self) -> Self {
113        Self {
114            value: (((self.value as u32) << (FRACTION_BITS as u32)) / (rhs.value as u32)) as u16,
115        }
116    }
117}
118impl<const FRACTION_BITS: u16> std::ops::Mul for FixedPoint<u16, FRACTION_BITS> {
119    type Output = Self;
120    fn mul(self, rhs: Self) -> Self {
121        Self {
122            value: (((self.value as u32) * (rhs.value as u32)) >> (FRACTION_BITS as u32)) as u16,
123        }
124    }
125}
126
127/// font-weight: range 1..1000, fractional values permitted; keywords
128/// 'normal', 'bold' aliased to 400, 700 respectively.
129///
130/// We use an unsigned 10.6 fixed-point value (range 0.0 - 1023.984375)
131pub const FONT_WEIGHT_FRACTION_BITS: u16 = 6;
132
133/// This is an alias which is useful mostly as a cbindgen / C++ inference
134/// workaround.
135pub type FontWeightFixedPoint = FixedPoint<u16, FONT_WEIGHT_FRACTION_BITS>;
136
137/// A value for the font-weight property per:
138///
139/// https://drafts.csswg.org/css-fonts-4/#propdef-font-weight
140///
141/// cbindgen:derive-lt
142/// cbindgen:derive-lte
143/// cbindgen:derive-gt
144/// cbindgen:derive-gte
145#[derive(
146    Clone,
147    ComputeSquaredDistance,
148    Copy,
149    Debug,
150    Deserialize,
151    Hash,
152    MallocSizeOf,
153    PartialEq,
154    PartialOrd,
155    Serialize,
156    ToResolvedValue,
157)]
158#[repr(C)]
159pub struct FontWeight(FontWeightFixedPoint);
160impl ToAnimatedValue for FontWeight {
161    type AnimatedValue = Number;
162
163    #[inline]
164    fn to_animated_value(self, _: &crate::values::animated::Context) -> Self::AnimatedValue {
165        self.value()
166    }
167
168    #[inline]
169    fn from_animated_value(animated: Self::AnimatedValue) -> Self {
170        FontWeight::from_float(animated)
171    }
172}
173
174impl ToCss for FontWeight {
175    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
176    where
177        W: fmt::Write,
178    {
179        self.value().to_css(dest)
180    }
181}
182
183impl ToTyped for FontWeight {
184    fn to_typed(&self, dest: &mut ThinVec<TypedValue>) -> Result<(), ()> {
185        self.value().to_typed(dest)
186    }
187}
188
189impl FontWeight {
190    /// The `normal` keyword.
191    pub const NORMAL: FontWeight = FontWeight(FontWeightFixedPoint {
192        value: 400 << FONT_WEIGHT_FRACTION_BITS,
193    });
194
195    /// The `bold` value.
196    pub const BOLD: FontWeight = FontWeight(FontWeightFixedPoint {
197        value: 700 << FONT_WEIGHT_FRACTION_BITS,
198    });
199
200    /// The threshold from which we consider a font bold.
201    pub const BOLD_THRESHOLD: FontWeight = FontWeight(FontWeightFixedPoint {
202        value: 600 << FONT_WEIGHT_FRACTION_BITS,
203    });
204
205    /// The threshold above which CSS font matching prefers bolder faces
206    /// over lighter ones.
207    pub const PREFER_BOLD_THRESHOLD: FontWeight = FontWeight(FontWeightFixedPoint {
208        value: 500 << FONT_WEIGHT_FRACTION_BITS,
209    });
210
211    /// Returns the `normal` keyword value.
212    pub fn normal() -> Self {
213        Self::NORMAL
214    }
215
216    /// Whether this weight is bold
217    pub fn is_bold(&self) -> bool {
218        *self >= Self::BOLD_THRESHOLD
219    }
220
221    /// Returns the value as a float.
222    pub fn value(&self) -> f32 {
223        self.0.to_float()
224    }
225
226    /// Construct a valid weight from a float value.
227    pub fn from_float(v: f32) -> Self {
228        Self(FixedPoint::from_float(
229            v.max(MIN_FONT_WEIGHT).min(MAX_FONT_WEIGHT),
230        ))
231    }
232
233    /// Return the bolder weight.
234    ///
235    /// See the table in:
236    /// https://drafts.csswg.org/css-fonts-4/#font-weight-numeric-values
237    pub fn bolder(self) -> Self {
238        let value = self.value();
239        if value < 350. {
240            return Self::NORMAL;
241        }
242        if value < 550. {
243            return Self::BOLD;
244        }
245        Self::from_float(value.max(900.))
246    }
247
248    /// Return the lighter weight.
249    ///
250    /// See the table in:
251    /// https://drafts.csswg.org/css-fonts-4/#font-weight-numeric-values
252    pub fn lighter(self) -> Self {
253        let value = self.value();
254        if value < 550. {
255            return Self::from_float(value.min(100.));
256        }
257        if value < 750. {
258            return Self::NORMAL;
259        }
260        Self::BOLD
261    }
262}
263
264#[derive(
265    Animate,
266    Clone,
267    ComputeSquaredDistance,
268    Copy,
269    Debug,
270    Deserialize,
271    MallocSizeOf,
272    PartialEq,
273    Serialize,
274    ToAnimatedZero,
275    ToCss,
276    ToTyped,
277)]
278/// The computed value of font-size
279pub struct FontSize {
280    /// The computed size, that we use to compute ems etc. This accounts for
281    /// e.g., text-zoom.
282    pub computed_size: NonNegativeLength,
283    /// The actual used size. This is the computed font size, potentially
284    /// constrained by other factors like minimum font-size settings and so on.
285    #[css(skip)]
286    pub used_size: NonNegativeLength,
287    /// If derived from a keyword, the keyword and additional transformations applied to it
288    #[css(skip)]
289    pub keyword_info: KeywordInfo,
290}
291
292impl FontSize {
293    /// The actual computed font size.
294    #[inline]
295    pub fn computed_size(&self) -> Length {
296        self.computed_size.0
297    }
298
299    /// The actual used font size.
300    #[inline]
301    pub fn used_size(&self) -> Length {
302        self.used_size.0
303    }
304
305    /// Apply zoom to the font-size. This is usually done by ToComputedValue.
306    #[inline]
307    pub fn zoom(&self, zoom: Zoom) -> Self {
308        Self {
309            computed_size: NonNegative(Length::new(zoom.zoom(self.computed_size.0.px()))),
310            used_size: NonNegative(Length::new(zoom.zoom(self.used_size.0.px()))),
311            keyword_info: self.keyword_info,
312        }
313    }
314
315    #[inline]
316    /// Get default value of font size.
317    pub fn medium() -> Self {
318        Self {
319            computed_size: NonNegative(Length::new(specified::FONT_MEDIUM_PX)),
320            used_size: NonNegative(Length::new(specified::FONT_MEDIUM_PX)),
321            keyword_info: KeywordInfo::medium(),
322        }
323    }
324}
325
326impl ToAnimatedValue for FontSize {
327    type AnimatedValue = Length;
328
329    #[inline]
330    fn to_animated_value(self, context: &crate::values::animated::Context) -> Self::AnimatedValue {
331        self.computed_size.0.to_animated_value(context)
332    }
333
334    #[inline]
335    fn from_animated_value(animated: Self::AnimatedValue) -> Self {
336        FontSize {
337            computed_size: NonNegative(animated.clamp_to_non_negative()),
338            used_size: NonNegative(animated.clamp_to_non_negative()),
339            keyword_info: KeywordInfo::none(),
340        }
341    }
342}
343
344impl ToResolvedValue for FontSize {
345    type ResolvedValue = NonNegativeLength;
346
347    #[inline]
348    fn to_resolved_value(self, context: &ResolvedContext) -> Self::ResolvedValue {
349        self.computed_size.to_resolved_value(context)
350    }
351
352    #[inline]
353    fn from_resolved_value(resolved: Self::ResolvedValue) -> Self {
354        let computed_size = NonNegativeLength::from_resolved_value(resolved);
355        Self {
356            computed_size,
357            used_size: computed_size,
358            keyword_info: KeywordInfo::none(),
359        }
360    }
361}
362
363#[derive(
364    Clone,
365    Debug,
366    Deserialize,
367    Eq,
368    Hash,
369    PartialEq,
370    Serialize,
371    ToComputedValue,
372    ToResolvedValue,
373    ToTyped,
374)]
375/// Specifies a prioritized list of font family names or generic family names.
376#[repr(C)]
377#[typed(todo_derive_fields)]
378pub struct FontFamily {
379    /// The actual list of family names.
380    pub families: FontFamilyList,
381    /// Whether this font-family came from a specified system-font.
382    pub is_system_font: bool,
383    /// Whether this is the initial font-family that might react to language
384    /// changes.
385    pub is_initial: bool,
386}
387
388macro_rules! static_font_family {
389    ($ident:ident, $family:expr) => {
390        static $ident: std::sync::LazyLock<FontFamily> = std::sync::LazyLock::new(|| FontFamily {
391            families: FontFamilyList {
392                list: crate::ArcSlice::from_iter_leaked(std::iter::once($family)),
393            },
394            is_system_font: false,
395            is_initial: false,
396        });
397    };
398}
399
400impl FontFamily {
401    #[inline]
402    /// Get default font family as `serif` which is a generic font-family
403    pub fn serif() -> Self {
404        Self::generic(GenericFontFamily::Serif).clone()
405    }
406
407    /// Returns the font family for `-moz-bullet-font`.
408    #[cfg(feature = "gecko")]
409    pub(crate) fn moz_bullet() -> &'static Self {
410        static_font_family!(
411            MOZ_BULLET,
412            SingleFontFamily::FamilyName(FamilyName {
413                name: atom!("-moz-bullet-font"),
414                syntax: FontFamilyNameSyntax::Identifiers,
415            })
416        );
417
418        &MOZ_BULLET
419    }
420
421    /// Returns a font family for a single system font.
422    #[cfg(feature = "gecko")]
423    pub fn for_system_font(name: &str) -> Self {
424        Self {
425            families: FontFamilyList {
426                list: crate::ArcSlice::from_iter(std::iter::once(SingleFontFamily::FamilyName(
427                    FamilyName {
428                        name: Atom::from(name),
429                        syntax: FontFamilyNameSyntax::Identifiers,
430                    },
431                ))),
432            },
433            is_system_font: true,
434            is_initial: false,
435        }
436    }
437
438    /// Returns a generic font family.
439    pub fn generic(generic: GenericFontFamily) -> &'static Self {
440        macro_rules! generic_font_family {
441            ($ident:ident, $family:ident) => {
442                static_font_family!(
443                    $ident,
444                    SingleFontFamily::Generic(GenericFontFamily::$family)
445                )
446            };
447        }
448
449        generic_font_family!(SERIF, Serif);
450        generic_font_family!(SANS_SERIF, SansSerif);
451        generic_font_family!(MONOSPACE, Monospace);
452        generic_font_family!(CURSIVE, Cursive);
453        generic_font_family!(FANTASY, Fantasy);
454        #[cfg(feature = "gecko")]
455        generic_font_family!(MATH, Math);
456        #[cfg(feature = "gecko")]
457        generic_font_family!(MOZ_EMOJI, MozEmoji);
458        generic_font_family!(SYSTEM_UI, SystemUi);
459
460        let family = match generic {
461            GenericFontFamily::None => {
462                debug_assert!(false, "Bogus caller!");
463                &*SERIF
464            },
465            GenericFontFamily::Serif => &*SERIF,
466            GenericFontFamily::SansSerif => &*SANS_SERIF,
467            GenericFontFamily::Monospace => &*MONOSPACE,
468            GenericFontFamily::Cursive => &*CURSIVE,
469            GenericFontFamily::Fantasy => &*FANTASY,
470            #[cfg(feature = "gecko")]
471            GenericFontFamily::Math => &*MATH,
472            #[cfg(feature = "gecko")]
473            GenericFontFamily::MozEmoji => &*MOZ_EMOJI,
474            GenericFontFamily::SystemUi => &*SYSTEM_UI,
475        };
476        debug_assert_eq!(
477            *family.families.iter().next().unwrap(),
478            SingleFontFamily::Generic(generic)
479        );
480        family
481    }
482}
483
484impl MallocSizeOf for FontFamily {
485    fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
486        use malloc_size_of::MallocUnconditionalSizeOf;
487        // SharedFontList objects are generally measured from the pointer stored
488        // in the specified value. So only count this if the SharedFontList is
489        // unshared.
490        let shared_font_list = &self.families.list;
491        if shared_font_list.is_unique() {
492            shared_font_list.unconditional_size_of(ops)
493        } else {
494            0
495        }
496    }
497}
498
499impl ToCss for FontFamily {
500    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
501    where
502        W: fmt::Write,
503    {
504        let mut iter = self.families.iter();
505        match iter.next() {
506            Some(f) => f.to_css(dest)?,
507            None => return Ok(()),
508        }
509        for family in iter {
510            dest.write_str(", ")?;
511            family.to_css(dest)?;
512        }
513        Ok(())
514    }
515}
516
517/// The name of a font family of choice.
518#[derive(
519    Clone,
520    Debug,
521    Deserialize,
522    Eq,
523    Hash,
524    MallocSizeOf,
525    PartialEq,
526    Serialize,
527    ToComputedValue,
528    ToResolvedValue,
529    ToShmem,
530)]
531#[repr(C)]
532pub struct FamilyName {
533    /// Name of the font family.
534    pub name: Atom,
535    /// Syntax of the font family.
536    pub syntax: FontFamilyNameSyntax,
537}
538
539#[cfg(feature = "gecko")]
540impl FamilyName {
541    fn is_known_icon_font_family(&self) -> bool {
542        use crate::gecko_bindings::bindings;
543        unsafe { bindings::Gecko_IsKnownIconFontFamily(self.name.as_ptr()) }
544    }
545}
546
547#[cfg(feature = "servo")]
548impl FamilyName {
549    fn is_known_icon_font_family(&self) -> bool {
550        false
551    }
552}
553
554impl ToCss for FamilyName {
555    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
556    where
557        W: fmt::Write,
558    {
559        match self.syntax {
560            FontFamilyNameSyntax::Quoted => {
561                dest.write_char('"')?;
562                write!(CssStringWriter::new(dest), "{}", self.name)?;
563                dest.write_char('"')
564            },
565            FontFamilyNameSyntax::Identifiers => {
566                let mut first = true;
567                for ident in self.name.to_string().split(' ') {
568                    if first {
569                        first = false;
570                    } else {
571                        dest.write_char(' ')?;
572                    }
573                    debug_assert!(
574                        !ident.is_empty(),
575                        "Family name with leading, \
576                         trailing, or consecutive white spaces should \
577                         have been marked quoted by the parser"
578                    );
579                    serialize_identifier(ident, dest)?;
580                }
581                Ok(())
582            },
583        }
584    }
585}
586
587#[derive(
588    Clone,
589    Copy,
590    Debug,
591    Deserialize,
592    Eq,
593    Hash,
594    MallocSizeOf,
595    PartialEq,
596    Serialize,
597    ToComputedValue,
598    ToResolvedValue,
599    ToShmem,
600)]
601/// Font family names must either be given quoted as strings,
602/// or unquoted as a sequence of one or more identifiers.
603#[repr(u8)]
604pub enum FontFamilyNameSyntax {
605    /// The family name was specified in a quoted form, e.g. "Font Name"
606    /// or 'Font Name'.
607    Quoted,
608
609    /// The family name was specified in an unquoted form as a sequence of
610    /// identifiers.
611    Identifiers,
612}
613
614/// A set of faces that vary in weight, width or slope.
615/// cbindgen:derive-mut-casts=true
616#[derive(
617    Clone,
618    Debug,
619    Deserialize,
620    Eq,
621    Hash,
622    MallocSizeOf,
623    PartialEq,
624    Serialize,
625    ToCss,
626    ToComputedValue,
627    ToResolvedValue,
628    ToShmem,
629)]
630#[repr(u8)]
631pub enum SingleFontFamily {
632    /// The name of a font family of choice.
633    FamilyName(FamilyName),
634    /// Generic family name.
635    Generic(GenericFontFamily),
636}
637
638fn system_ui_enabled(_: &ParserContext) -> bool {
639    crate::pref!("layout.css.system-ui.enabled")
640}
641
642/// A generic font-family name.
643///
644/// The order here is important, if you change it make sure that
645/// `gfxPlatformFontList.h`s ranged array and `gfxFontFamilyList`'s
646/// sSingleGenerics are updated as well.
647///
648/// NOTE(emilio): Should be u8, but it's a u32 because of ABI issues between GCC
649/// and LLVM see https://bugs.llvm.org/show_bug.cgi?id=44228 / bug 1600735 /
650/// bug 1726515.
651#[derive(
652    Clone,
653    Copy,
654    Debug,
655    Deserialize,
656    Eq,
657    Hash,
658    MallocSizeOf,
659    PartialEq,
660    Parse,
661    Serialize,
662    ToCss,
663    ToComputedValue,
664    ToResolvedValue,
665    ToShmem,
666)]
667#[repr(u32)]
668#[allow(missing_docs)]
669pub enum GenericFontFamily {
670    /// No generic family specified, only for internal usage.
671    ///
672    /// NOTE(emilio): Gecko code relies on this variant being zero.
673    #[css(skip)]
674    None = 0,
675    Serif,
676    SansSerif,
677    #[parse(aliases = "-moz-fixed")]
678    Monospace,
679    Cursive,
680    Fantasy,
681    #[cfg(feature = "gecko")]
682    Math,
683    #[parse(condition = "system_ui_enabled")]
684    SystemUi,
685    /// An internal value for emoji font selection.
686    #[css(skip)]
687    #[cfg(feature = "gecko")]
688    MozEmoji,
689}
690
691impl GenericFontFamily {
692    /// When we disallow websites to override fonts, we ignore some generic
693    /// families that the website might specify, since they're not configured by
694    /// the user. See bug 789788 and bug 1730098.
695    pub(crate) fn valid_for_user_font_prioritization(self) -> bool {
696        match self {
697            Self::None | Self::Cursive | Self::Fantasy | Self::SystemUi => false,
698            #[cfg(feature = "gecko")]
699            Self::Math | Self::MozEmoji => false,
700            Self::Serif | Self::SansSerif | Self::Monospace => true,
701        }
702    }
703}
704
705impl Parse for SingleFontFamily {
706    /// Parse a font-family value.
707    fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ParseError> {
708        // CSS-wide keywords must be quoted if used as a font-family name.
709        // The 'default' keyword is also reserved.
710        // (https://drafts.csswg.org/css-values-4/#custom-idents)
711        let is_reserved_kw = |s: &str| -> bool {
712            CSSWideKeyword::from_ident(s).is_ok() || s.eq_ignore_ascii_case("default")
713        };
714
715        // Determine the canonical syntax for a given font-family name: either as a
716        // quoted string or as space-separated identifiers.
717        let canonical_syntax_for = |s: &str| -> FontFamilyNameSyntax {
718            // The name will need quoting if:
719            // - it contains a word that begins with a digit;
720            // - any non-alphanumeric/dash/underscore ASCII codepoints are present;
721            // - it has leading, trailing, or repeated spaces.
722            // (https://github.com/w3c/csswg-drafts/issues/5846)
723            let mut in_word = false;
724            for b in s.as_bytes() {
725                if in_word && *b == b' ' {
726                    in_word = false;
727                    continue;
728                }
729                if !in_word && b.is_ascii_digit() {
730                    return FontFamilyNameSyntax::Quoted;
731                }
732                if b.is_ascii_alphanumeric() || *b == b'-' || *b == b'_' || !b.is_ascii() {
733                    in_word = true;
734                    continue;
735                }
736                return FontFamilyNameSyntax::Quoted;
737            }
738            if !in_word {
739                return FontFamilyNameSyntax::Quoted;
740            }
741            // Quotes also required if it matches one of the CSS-wide keywords...
742            if is_reserved_kw(s) {
743                return FontFamilyNameSyntax::Quoted;
744            }
745            // ...or if it parses as a generic-font-family.
746            if GenericFontFamily::parse(context, &mut Parser::new(&s)).is_ok() {
747                return FontFamilyNameSyntax::Quoted;
748            }
749            FontFamilyNameSyntax::Identifiers
750        };
751
752        if let Ok(value) = input.try_parse(|i| i.expect_string_cloned()) {
753            return Ok(SingleFontFamily::FamilyName(FamilyName {
754                name: Atom::from(&*value),
755                syntax: canonical_syntax_for(&value),
756            }));
757        }
758
759        if let Ok(generic) = input.try_parse(|i| GenericFontFamily::parse(context, i)) {
760            return Ok(SingleFontFamily::Generic(generic));
761        }
762
763        let first_ident = input.expect_ident_cloned()?;
764        let mut value = first_ident.as_ref().to_owned();
765        while let Ok(ident) = input.try_parse(|i| i.expect_ident_cloned()) {
766            value.push(' ');
767            value.push_str(&ident);
768        }
769
770        if is_reserved_kw(&value) {
771            return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
772        }
773
774        Ok(SingleFontFamily::FamilyName(FamilyName {
775            name: Atom::from(&*value),
776            syntax: canonical_syntax_for(&value),
777        }))
778    }
779}
780
781/// A list of font families.
782#[derive(
783    Clone,
784    Debug,
785    Deserialize,
786    Hash,
787    Serialize,
788    ToComputedValue,
789    ToResolvedValue,
790    ToShmem,
791    PartialEq,
792    Eq,
793)]
794#[repr(C)]
795pub struct FontFamilyList {
796    /// The actual list of font families specified.
797    pub list: crate::ArcSlice<SingleFontFamily>,
798}
799
800impl FontFamilyList {
801    /// Return iterator of SingleFontFamily
802    pub fn iter(&self) -> impl Iterator<Item = &SingleFontFamily> {
803        self.list.iter()
804    }
805
806    /// If there's a generic font family on the list which is suitable for user
807    /// font prioritization, then move it ahead of the other families in the list,
808    /// except for any families known to be ligature-based icon fonts, where using a
809    /// generic instead of the site's specified font may cause substantial breakage.
810    /// If no suitable generic is found in the list, insert the default generic ahead
811    /// of all the listed families except for known ligature-based icon fonts.
812    #[cfg_attr(feature = "servo", allow(unused))]
813    pub(crate) fn prioritize_first_generic_or_prepend(&mut self, generic: GenericFontFamily) {
814        let mut index_of_first_generic = None;
815        let mut target_index = None;
816
817        for (i, f) in self.iter().enumerate() {
818            match f {
819                SingleFontFamily::Generic(f) => {
820                    if index_of_first_generic.is_none() && f.valid_for_user_font_prioritization() {
821                        // If we haven't found a target position, there's nothing to do;
822                        // this entry is already ahead of everything except any whitelisted
823                        // icon fonts.
824                        if target_index.is_none() {
825                            return;
826                        }
827                        index_of_first_generic = Some(i);
828                        break;
829                    }
830                    // A non-prioritized generic (e.g. cursive, fantasy) becomes the target
831                    // position for prioritization, just like arbitrary named families.
832                    if target_index.is_none() {
833                        target_index = Some(i);
834                    }
835                },
836                SingleFontFamily::FamilyName(fam) => {
837                    // Target position for the first generic is in front of the first
838                    // non-whitelisted icon font family we find.
839                    if target_index.is_none() && !fam.is_known_icon_font_family() {
840                        target_index = Some(i);
841                    }
842                },
843            }
844        }
845
846        let mut new_list = self.list.iter().cloned().collect::<Vec<_>>();
847        let first_generic = match index_of_first_generic {
848            Some(i) => new_list.remove(i),
849            None => SingleFontFamily::Generic(generic),
850        };
851
852        if let Some(i) = target_index {
853            new_list.insert(i, first_generic);
854        } else {
855            new_list.push(first_generic);
856        }
857        self.list = crate::ArcSlice::from_iter(new_list.into_iter());
858    }
859
860    /// Returns whether we need to prioritize user fonts.
861    #[cfg_attr(feature = "servo", allow(unused))]
862    pub(crate) fn needs_user_font_prioritization(&self) -> bool {
863        self.iter().next().is_none_or(|f| match f {
864            SingleFontFamily::Generic(f) => !f.valid_for_user_font_prioritization(),
865            _ => true,
866        })
867    }
868
869    /// Return the generic ID if it is a single generic font
870    pub fn single_generic(&self) -> Option<GenericFontFamily> {
871        let mut iter = self.iter();
872        if let Some(SingleFontFamily::Generic(f)) = iter.next()
873            && iter.next().is_none()
874        {
875            return Some(*f);
876        }
877        None
878    }
879}
880
881/// Preserve the readability of text when font fallback occurs.
882pub type FontSizeAdjust = generics::GenericFontSizeAdjust<NonNegativeNumber>;
883
884impl FontSizeAdjust {
885    #[inline]
886    /// Default value of font-size-adjust
887    pub fn none() -> Self {
888        FontSizeAdjust::None
889    }
890}
891
892impl ToComputedValue for specified::FontSizeAdjust {
893    type ComputedValue = FontSizeAdjust;
894
895    fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
896        use crate::font_metrics::FontMetricsOrientation;
897
898        let font_metrics = |vertical, flags| {
899            let orient = if vertical {
900                FontMetricsOrientation::MatchContextPreferVertical
901            } else {
902                FontMetricsOrientation::Horizontal
903            };
904            let metrics = context.query_font_metrics(FontBaseSize::CurrentStyle, orient, flags);
905            let font_size = context
906                .style()
907                .get_font()
908                .slow_clone_font_size()
909                .used_size
910                .0;
911            (metrics, font_size)
912        };
913
914        // Macro to resolve a from-font value using the given metric field. If not present,
915        // returns the fallback value, or if that is negative, resolves using ascent instead
916        // of the missing field (this is the fallback for cap-height).
917        macro_rules! resolve {
918            ($basis:ident, $value:expr, $vertical:expr, $field:ident, $fallback:expr, $flags:expr) => {{
919                match $value {
920                    specified::FontSizeAdjustFactor::Number(f) => {
921                        FontSizeAdjust::$basis(f.to_computed_value(context))
922                    },
923                    specified::FontSizeAdjustFactor::FromFont => {
924                        let (metrics, font_size) = font_metrics($vertical, $flags);
925                        let ratio = if let Some(metric) = metrics.$field {
926                            metric / font_size
927                        } else if $fallback >= 0.0 {
928                            $fallback
929                        } else {
930                            metrics.ascent / font_size
931                        };
932                        if ratio.is_nan() {
933                            FontSizeAdjust::$basis(NonNegative(abs($fallback)))
934                        } else {
935                            FontSizeAdjust::$basis(NonNegative(ratio))
936                        }
937                    },
938                }
939            }};
940        }
941
942        match self {
943            Self::None => FontSizeAdjust::None,
944            Self::ExHeight(val) => {
945                resolve!(
946                    ExHeight,
947                    val,
948                    false,
949                    x_height,
950                    0.5,
951                    QueryFontMetricsFlags::empty()
952                )
953            },
954            Self::CapHeight(val) => {
955                resolve!(
956                    CapHeight,
957                    val,
958                    false,
959                    cap_height,
960                    -1.0, /* fall back to ascent */
961                    QueryFontMetricsFlags::empty()
962                )
963            },
964            Self::ChWidth(val) => {
965                resolve!(
966                    ChWidth,
967                    val,
968                    false,
969                    zero_advance_measure,
970                    0.5,
971                    QueryFontMetricsFlags::NEEDS_CH
972                )
973            },
974            Self::IcWidth(val) => {
975                resolve!(
976                    IcWidth,
977                    val,
978                    false,
979                    ic_width,
980                    1.0,
981                    QueryFontMetricsFlags::NEEDS_IC
982                )
983            },
984            Self::IcHeight(val) => {
985                resolve!(
986                    IcHeight,
987                    val,
988                    true,
989                    ic_width,
990                    1.0,
991                    QueryFontMetricsFlags::NEEDS_IC
992                )
993            },
994        }
995    }
996
997    fn from_computed_value(computed: &Self::ComputedValue) -> Self {
998        macro_rules! case {
999            ($basis:ident, $val:expr) => {
1000                Self::$basis(specified::FontSizeAdjustFactor::Number(
1001                    ToComputedValue::from_computed_value($val),
1002                ))
1003            };
1004        }
1005        match *computed {
1006            FontSizeAdjust::None => Self::None,
1007            FontSizeAdjust::ExHeight(ref val) => case!(ExHeight, val),
1008            FontSizeAdjust::CapHeight(ref val) => case!(CapHeight, val),
1009            FontSizeAdjust::ChWidth(ref val) => case!(ChWidth, val),
1010            FontSizeAdjust::IcWidth(ref val) => case!(IcWidth, val),
1011            FontSizeAdjust::IcHeight(ref val) => case!(IcHeight, val),
1012        }
1013    }
1014}
1015
1016/// Use FontSettings as computed type of FontFeatureSettings.
1017pub type FontFeatureSettings = FontSettings<FeatureTagValue<Integer>>;
1018
1019/// The computed value for font-variation-settings.
1020pub type FontVariationSettings = FontSettings<VariationValue<Number>>;
1021
1022// The computed value of font-{feature,variation}-settings discards values
1023// with duplicate tags, keeping only the last occurrence of each tag.
1024fn dedup_font_settings<T>(settings_list: &mut ThinVec<T>)
1025where
1026    T: TaggedFontValue,
1027{
1028    if settings_list.len() > 1 {
1029        settings_list.sort_by_key(|k| k.tag().0);
1030        // dedup() keeps the first of any duplicates, but we want the last,
1031        // so swap elements in the dedup_by closure if their tags are equal.
1032        settings_list.dedup_by(|a, b| {
1033            if a.tag() == b.tag() {
1034                std::mem::swap(a, b);
1035                true
1036            } else {
1037                false
1038            }
1039        });
1040    }
1041}
1042
1043impl<T> ToComputedValue for FontSettings<T>
1044where
1045    T: ToComputedValue,
1046    <T as ToComputedValue>::ComputedValue: TaggedFontValue,
1047{
1048    type ComputedValue = FontSettings<T::ComputedValue>;
1049
1050    fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
1051        let mut v = self
1052            .0
1053            .iter()
1054            .map(|item| item.to_computed_value(context))
1055            .collect::<ThinVec<_>>();
1056        dedup_font_settings(&mut v);
1057        FontSettings(v)
1058    }
1059
1060    fn from_computed_value(computed: &Self::ComputedValue) -> Self {
1061        Self(computed.0.iter().map(T::from_computed_value).collect())
1062    }
1063}
1064
1065/// font-language-override can only have a single 1-4 ASCII character
1066/// OpenType "language system" tag, so we should be able to compute
1067/// it and store it as a 32-bit integer
1068/// (see http://www.microsoft.com/typography/otspec/languagetags.htm).
1069#[derive(
1070    Clone,
1071    Copy,
1072    Debug,
1073    Deserialize,
1074    Eq,
1075    MallocSizeOf,
1076    PartialEq,
1077    Serialize,
1078    SpecifiedValueInfo,
1079    ToComputedValue,
1080    ToResolvedValue,
1081    ToShmem,
1082    ToTyped,
1083)]
1084#[repr(C)]
1085#[typed(todo_derive_fields)]
1086#[value_info(other_values = "normal")]
1087pub struct FontLanguageOverride(pub u32);
1088
1089impl FontLanguageOverride {
1090    #[inline]
1091    /// Get computed default value of `font-language-override` with 0
1092    pub fn normal() -> FontLanguageOverride {
1093        FontLanguageOverride(0)
1094    }
1095
1096    /// Returns this value as a `&str`, backed by `storage`.
1097    #[inline]
1098    pub(crate) fn to_str(self, storage: &mut [u8; 4]) -> &str {
1099        *storage = u32::to_be_bytes(self.0);
1100        // Safe because we ensure it's ASCII during parsing
1101        let slice = if cfg!(debug_assertions) {
1102            std::str::from_utf8(&storage[..]).unwrap()
1103        } else {
1104            unsafe { std::str::from_utf8_unchecked(&storage[..]) }
1105        };
1106        slice.trim_end()
1107    }
1108
1109    /// Unsafe because `Self::to_str` requires the value to represent a UTF-8
1110    /// string.
1111    #[inline]
1112    pub unsafe fn from_u32(value: u32) -> Self {
1113        Self(value)
1114    }
1115}
1116
1117impl ToCss for FontLanguageOverride {
1118    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
1119    where
1120        W: fmt::Write,
1121    {
1122        if self.0 == 0 {
1123            return dest.write_str("normal");
1124        }
1125        self.to_str(&mut [0; 4]).to_css(dest)
1126    }
1127}
1128
1129impl ToComputedValue for specified::MozScriptMinSize {
1130    type ComputedValue = MozScriptMinSize;
1131
1132    fn to_computed_value(&self, cx: &Context) -> MozScriptMinSize {
1133        // this value is used in the computation of font-size, so
1134        // we use the parent size
1135        let base_size = FontBaseSize::InheritedStyle;
1136        let line_height_base = LineHeightBase::InheritedStyle;
1137        self.0
1138            .to_computed_value_with_base_size(cx, base_size, line_height_base)
1139    }
1140
1141    fn from_computed_value(other: &MozScriptMinSize) -> Self {
1142        specified::MozScriptMinSize(ToComputedValue::from_computed_value(other))
1143    }
1144}
1145
1146/// The computed value of the math-depth property.
1147pub type MathDepth = i8;
1148
1149impl ToComputedValue for specified::MathDepth {
1150    type ComputedValue = MathDepth;
1151
1152    fn to_computed_value(&self, cx: &Context) -> i8 {
1153        use crate::properties::longhands::math_style::SpecifiedValue as MathStyleValue;
1154
1155        let int = match self {
1156            specified::MathDepth::AutoAdd => {
1157                let parent = *cx.builder.get_parent_font().get_math_depth() as i32;
1158                let style = *cx.builder.get_parent_font().get_math_style();
1159                if style == MathStyleValue::Compact {
1160                    parent.saturating_add(1)
1161                } else {
1162                    parent
1163                }
1164            },
1165            specified::MathDepth::Add(rel) => {
1166                let parent = *cx.builder.get_parent_font().get_math_depth();
1167                (parent as i32).saturating_add(rel.to_computed_value(cx))
1168            },
1169            specified::MathDepth::Absolute(abs) => abs.to_computed_value(cx),
1170        };
1171        std::cmp::min(int, i8::MAX as i32) as i8
1172    }
1173
1174    fn from_computed_value(other: &i8) -> Self {
1175        let computed_value = *other as i32;
1176        specified::MathDepth::Absolute(SpecifiedInteger::from_computed_value(&computed_value))
1177    }
1178}
1179
1180impl ToAnimatedValue for MathDepth {
1181    type AnimatedValue = CSSInteger;
1182
1183    #[inline]
1184    fn to_animated_value(self, _: &crate::values::animated::Context) -> Self::AnimatedValue {
1185        self.into()
1186    }
1187
1188    #[inline]
1189    fn from_animated_value(animated: Self::AnimatedValue) -> Self {
1190        std::cmp::min(animated, i8::MAX as i32) as i8
1191    }
1192}
1193
1194/// - Use a signed 8.8 fixed-point value (representable range -128.0..128)
1195///
1196/// Values of <angle> below -90 or above 90 are not permitted, so we use an out
1197/// of range value to represent `italic`.
1198pub const FONT_STYLE_FRACTION_BITS: u16 = 8;
1199
1200/// This is an alias which is useful mostly as a cbindgen / C++ inference
1201/// workaround.
1202pub type FontStyleFixedPoint = FixedPoint<i16, FONT_STYLE_FRACTION_BITS>;
1203
1204/// The computed value of `font-style`.
1205///
1206/// - Define angle of zero degrees as `normal`
1207/// - Define out-of-range value 100 degrees as `italic`
1208/// - Other values represent `oblique <angle>`
1209///
1210/// cbindgen:derive-lt
1211/// cbindgen:derive-lte
1212/// cbindgen:derive-gt
1213/// cbindgen:derive-gte
1214#[derive(
1215    Clone,
1216    ComputeSquaredDistance,
1217    Copy,
1218    Debug,
1219    Deserialize,
1220    Eq,
1221    Hash,
1222    MallocSizeOf,
1223    PartialEq,
1224    PartialOrd,
1225    Serialize,
1226    ToResolvedValue,
1227    ToTyped,
1228)]
1229#[repr(C)]
1230#[typed(todo_derive_fields)]
1231pub struct FontStyle(FontStyleFixedPoint);
1232
1233impl FontStyle {
1234    /// The `normal` keyword, equal to `oblique` with angle zero.
1235    pub const NORMAL: FontStyle = FontStyle(FontStyleFixedPoint {
1236        value: 0 << FONT_STYLE_FRACTION_BITS,
1237    });
1238
1239    /// The italic keyword.
1240    pub const ITALIC: FontStyle = FontStyle(FontStyleFixedPoint {
1241        value: 100 << FONT_STYLE_FRACTION_BITS,
1242    });
1243
1244    /// The default angle for `font-style: oblique`.
1245    /// See also https://github.com/w3c/csswg-drafts/issues/2295
1246    pub const DEFAULT_OBLIQUE_DEGREES: i16 = 14;
1247
1248    /// The `oblique` keyword with the default degrees.
1249    pub const OBLIQUE: FontStyle = FontStyle(FontStyleFixedPoint {
1250        value: Self::DEFAULT_OBLIQUE_DEGREES << FONT_STYLE_FRACTION_BITS,
1251    });
1252
1253    /// The `normal` value.
1254    #[inline]
1255    pub fn normal() -> Self {
1256        Self::NORMAL
1257    }
1258
1259    /// Returns the oblique angle for this style.
1260    pub fn oblique(degrees: f32) -> Self {
1261        Self(FixedPoint::from_float(
1262            degrees
1263                .max(specified::FONT_STYLE_OBLIQUE_MIN_ANGLE_DEGREES)
1264                .min(specified::FONT_STYLE_OBLIQUE_MAX_ANGLE_DEGREES),
1265        ))
1266    }
1267
1268    /// Returns the oblique angle for this style.
1269    pub fn oblique_degrees(&self) -> f32 {
1270        debug_assert_ne!(*self, Self::ITALIC);
1271        self.0.to_float()
1272    }
1273}
1274
1275impl ToCss for FontStyle {
1276    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
1277    where
1278        W: fmt::Write,
1279    {
1280        if *self == Self::NORMAL {
1281            return dest.write_str("normal");
1282        }
1283        if *self == Self::ITALIC {
1284            return dest.write_str("italic");
1285        }
1286        dest.write_str("oblique")?;
1287        if *self != Self::OBLIQUE {
1288            // It's not the default oblique amount, so append the angle in degrees.
1289            dest.write_char(' ')?;
1290            Angle::from_degrees(self.oblique_degrees()).to_css(dest)?;
1291        }
1292        Ok(())
1293    }
1294}
1295
1296impl ToAnimatedValue for FontStyle {
1297    type AnimatedValue = generics::FontStyle<Angle>;
1298
1299    #[inline]
1300    fn to_animated_value(self, _: &crate::values::animated::Context) -> Self::AnimatedValue {
1301        if self == Self::ITALIC {
1302            return generics::FontStyle::Italic;
1303        }
1304        generics::FontStyle::Oblique(Angle::from_degrees(self.oblique_degrees()))
1305    }
1306
1307    #[inline]
1308    fn from_animated_value(animated: Self::AnimatedValue) -> Self {
1309        match animated {
1310            generics::FontStyle::Italic => Self::ITALIC,
1311            generics::FontStyle::Oblique(ref angle) => Self::oblique(angle.degrees()),
1312        }
1313    }
1314}
1315
1316/// font-width is a percentage relative to normal.
1317///
1318/// We use an unsigned 10.6 fixed-point value (range 0.0 - 1023.984375)
1319///
1320/// We arbitrarily limit here to 1000%. (If that becomes a problem, we could
1321/// reduce the number of fractional bits and increase the limit.)
1322pub const FONT_WIDTH_FRACTION_BITS: u16 = 6;
1323
1324/// This is an alias which is useful mostly as a cbindgen / C++ inference
1325/// workaround.
1326pub type FontWidthFixedPoint = FixedPoint<u16, FONT_WIDTH_FRACTION_BITS>;
1327
1328/// A value for the font-width property per:
1329///
1330/// https://drafts.csswg.org/css-fonts-4/#propdef-font-width
1331///
1332/// (Note that this property was formerly named font-stretch.)
1333///
1334/// cbindgen:derive-lt
1335/// cbindgen:derive-lte
1336/// cbindgen:derive-gt
1337/// cbindgen:derive-gte
1338#[derive(
1339    Clone,
1340    ComputeSquaredDistance,
1341    Copy,
1342    Debug,
1343    Deserialize,
1344    Hash,
1345    MallocSizeOf,
1346    PartialEq,
1347    PartialOrd,
1348    Serialize,
1349    ToResolvedValue,
1350)]
1351#[repr(C)]
1352pub struct FontWidth(pub FontWidthFixedPoint);
1353
1354impl FontWidth {
1355    /// The fraction bits, as an easy-to-access-constant.
1356    pub const FRACTION_BITS: u16 = FONT_WIDTH_FRACTION_BITS;
1357    /// 0.5 in our floating point representation.
1358    pub const HALF: u16 = 1 << (Self::FRACTION_BITS - 1);
1359
1360    /// The `ultra-condensed` keyword.
1361    pub const ULTRA_CONDENSED: FontWidth = FontWidth(FontWidthFixedPoint {
1362        value: 50 << Self::FRACTION_BITS,
1363    });
1364    /// The `extra-condensed` keyword.
1365    pub const EXTRA_CONDENSED: FontWidth = FontWidth(FontWidthFixedPoint {
1366        value: (62 << Self::FRACTION_BITS) + Self::HALF,
1367    });
1368    /// The `condensed` keyword.
1369    pub const CONDENSED: FontWidth = FontWidth(FontWidthFixedPoint {
1370        value: 75 << Self::FRACTION_BITS,
1371    });
1372    /// The `semi-condensed` keyword.
1373    pub const SEMI_CONDENSED: FontWidth = FontWidth(FontWidthFixedPoint {
1374        value: (87 << Self::FRACTION_BITS) + Self::HALF,
1375    });
1376    /// The `normal` keyword.
1377    pub const NORMAL: FontWidth = FontWidth(FontWidthFixedPoint {
1378        value: 100 << Self::FRACTION_BITS,
1379    });
1380    /// The `semi-expanded` keyword.
1381    pub const SEMI_EXPANDED: FontWidth = FontWidth(FontWidthFixedPoint {
1382        value: (112 << Self::FRACTION_BITS) + Self::HALF,
1383    });
1384    /// The `expanded` keyword.
1385    pub const EXPANDED: FontWidth = FontWidth(FontWidthFixedPoint {
1386        value: 125 << Self::FRACTION_BITS,
1387    });
1388    /// The `extra-expanded` keyword.
1389    pub const EXTRA_EXPANDED: FontWidth = FontWidth(FontWidthFixedPoint {
1390        value: 150 << Self::FRACTION_BITS,
1391    });
1392    /// The `ultra-expanded` keyword.
1393    pub const ULTRA_EXPANDED: FontWidth = FontWidth(FontWidthFixedPoint {
1394        value: 200 << Self::FRACTION_BITS,
1395    });
1396
1397    /// 100%
1398    pub fn hundred() -> Self {
1399        Self::NORMAL
1400    }
1401
1402    /// Converts to a computed percentage.
1403    #[inline]
1404    pub fn to_percentage(&self) -> Percentage {
1405        Percentage(self.0.to_float() / 100.0)
1406    }
1407
1408    /// Converts from a computed percentage value.
1409    pub fn from_percentage(p: f32) -> Self {
1410        Self(FixedPoint::from_float((p * 100.).max(0.0).min(1000.0)))
1411    }
1412
1413    /// Returns a relevant width value from a keyword.
1414    /// https://drafts.csswg.org/css-fonts-4/#font-width-prop
1415    pub fn from_keyword(kw: specified::FontWidthKeyword) -> Self {
1416        use specified::FontWidthKeyword::*;
1417        match kw {
1418            UltraCondensed => Self::ULTRA_CONDENSED,
1419            ExtraCondensed => Self::EXTRA_CONDENSED,
1420            Condensed => Self::CONDENSED,
1421            SemiCondensed => Self::SEMI_CONDENSED,
1422            Normal => Self::NORMAL,
1423            SemiExpanded => Self::SEMI_EXPANDED,
1424            Expanded => Self::EXPANDED,
1425            ExtraExpanded => Self::EXTRA_EXPANDED,
1426            UltraExpanded => Self::ULTRA_EXPANDED,
1427        }
1428    }
1429
1430    /// Returns the width keyword if we map to one of the relevant values.
1431    pub fn as_keyword(&self) -> Option<specified::FontWidthKeyword> {
1432        use specified::FontWidthKeyword::*;
1433        // TODO: Can we use match here?
1434        if *self == Self::ULTRA_CONDENSED {
1435            return Some(UltraCondensed);
1436        }
1437        if *self == Self::EXTRA_CONDENSED {
1438            return Some(ExtraCondensed);
1439        }
1440        if *self == Self::CONDENSED {
1441            return Some(Condensed);
1442        }
1443        if *self == Self::SEMI_CONDENSED {
1444            return Some(SemiCondensed);
1445        }
1446        if *self == Self::NORMAL {
1447            return Some(Normal);
1448        }
1449        if *self == Self::SEMI_EXPANDED {
1450            return Some(SemiExpanded);
1451        }
1452        if *self == Self::EXPANDED {
1453            return Some(Expanded);
1454        }
1455        if *self == Self::EXTRA_EXPANDED {
1456            return Some(ExtraExpanded);
1457        }
1458        if *self == Self::ULTRA_EXPANDED {
1459            return Some(UltraExpanded);
1460        }
1461        None
1462    }
1463}
1464
1465impl ToCss for FontWidth {
1466    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
1467    where
1468        W: fmt::Write,
1469    {
1470        self.to_percentage().to_css(dest)
1471    }
1472}
1473
1474impl ToTyped for FontWidth {
1475    fn to_typed(&self, dest: &mut ThinVec<TypedValue>) -> Result<(), ()> {
1476        match self.as_keyword() {
1477            Some(keyword) => keyword.to_typed(dest),
1478            None => self.to_percentage().to_typed(dest),
1479        }
1480    }
1481}
1482
1483impl ToAnimatedValue for FontWidth {
1484    type AnimatedValue = Percentage;
1485
1486    #[inline]
1487    fn to_animated_value(self, _: &crate::values::animated::Context) -> Self::AnimatedValue {
1488        self.to_percentage()
1489    }
1490
1491    #[inline]
1492    fn from_animated_value(animated: Self::AnimatedValue) -> Self {
1493        Self::from_percentage(animated.0)
1494    }
1495}
1496
1497/// A computed value for the `line-height` property.
1498pub type LineHeight = generics::GenericLineHeight<NonNegativeNumber, NonNegativeLength>;
1499
1500impl ToResolvedValue for LineHeight {
1501    type ResolvedValue = Self;
1502
1503    fn to_resolved_value(self, context: &ResolvedContext) -> Self::ResolvedValue {
1504        #[cfg(feature = "gecko")]
1505        {
1506            // Resolve <number> to an absolute <length> based on font size.
1507            if matches!(self, Self::Normal) {
1508                return self;
1509            }
1510            let wm = context.style.writing_mode;
1511            Self::Length(
1512                context
1513                    .device
1514                    .calc_line_height(
1515                        context.style.get_font(),
1516                        wm,
1517                        Some(context.element_info.element),
1518                    )
1519                    .to_resolved_value(context),
1520            )
1521        }
1522        #[cfg(feature = "servo")]
1523        {
1524            if let LineHeight::Number(num) = &self {
1525                let size = context
1526                    .style
1527                    .get_font()
1528                    .slow_clone_font_size()
1529                    .computed_size();
1530                LineHeight::Length(NonNegativeLength::new(size.px() * num.0))
1531            } else {
1532                self
1533            }
1534        }
1535    }
1536
1537    #[inline]
1538    fn from_resolved_value(value: Self::ResolvedValue) -> Self {
1539        value
1540    }
1541}