Skip to main content

style/values/specified/
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//! Specified values for font properties
6
7use crate::Atom;
8use crate::context::QuirksMode;
9use crate::derives::*;
10use crate::parser::{Parse, ParserContext};
11use crate::typed_om::NumericBaseType;
12use crate::values::computed::Percentage as ComputedPercentage;
13use crate::values::computed::font::{FamilyName, FontFamilyList, SingleFontFamily};
14use crate::values::computed::{CSSPixelLength, Context, ToComputedValue};
15use crate::values::computed::{Length, NonNegativeLength, font as computed};
16use crate::values::generics::NonNegative;
17use crate::values::generics::font::{
18    self as generics, FeatureTagValue, FontSettings, FontTag, GenericLineHeight, VariationValue,
19};
20use crate::values::specified::calc::{Leaf, PercentageContext};
21use crate::values::specified::length::{FontBaseSize, LengthUnit, LineHeightBase, PX_PER_PT};
22use crate::values::specified::number::parse_number_with_clamping_mode;
23use crate::values::specified::{AllowQuirks, Angle, Integer, LengthPercentage};
24use crate::values::specified::{
25    NoCalcLength, NonNegativeLengthPercentage, NonNegativeNumber, NonNegativePercentage, Number,
26};
27use crate::values::{CustomIdent, SelectorParseErrorKind, serialize_atom_identifier};
28use cssparser::{Parser, Token, match_ignore_ascii_case};
29#[cfg(feature = "gecko")]
30use malloc_size_of::{MallocSizeOf, MallocSizeOfOps, MallocUnconditionalSizeOf};
31use std::fmt::{self, Write};
32use style_traits::values::specified::AllowedNumericType;
33use style_traits::{CssWriter, KeywordsCollectFn, ParseError};
34use style_traits::{SpecifiedValueInfo, StyleParseErrorKind, ToCss};
35
36// FIXME(emilio): The system font code is copy-pasta, and should be cleaned up.
37macro_rules! system_font_methods {
38    ($ty:ident, $field:ident) => {
39        system_font_methods!($ty);
40
41        fn compute_system(&self, _context: &Context) -> <$ty as ToComputedValue>::ComputedValue {
42            debug_assert!(matches!(*self, $ty::System(..)));
43            #[cfg(feature = "gecko")]
44            {
45                _context.cached_system_font.as_ref().unwrap().$field.clone()
46            }
47            #[cfg(feature = "servo")]
48            {
49                unreachable!()
50            }
51        }
52    };
53
54    ($ty:ident) => {
55        /// Get a specified value that represents a system font.
56        pub fn system_font(f: SystemFont) -> Self {
57            $ty::System(f)
58        }
59
60        /// Retreive a SystemFont from the specified value.
61        pub fn get_system(&self) -> Option<SystemFont> {
62            if let $ty::System(s) = *self {
63                Some(s)
64            } else {
65                None
66            }
67        }
68    };
69}
70
71/// System fonts.
72#[repr(u8)]
73#[derive(
74    Clone, Copy, Debug, Eq, Hash, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, ToShmem,
75)]
76#[allow(missing_docs)]
77#[cfg(feature = "gecko")]
78pub enum SystemFont {
79    /// https://drafts.csswg.org/css-fonts/#valdef-font-caption
80    Caption,
81    /// https://drafts.csswg.org/css-fonts/#valdef-font-icon
82    Icon,
83    /// https://drafts.csswg.org/css-fonts/#valdef-font-menu
84    Menu,
85    /// https://drafts.csswg.org/css-fonts/#valdef-font-message-box
86    MessageBox,
87    /// https://drafts.csswg.org/css-fonts/#valdef-font-small-caption
88    SmallCaption,
89    /// https://drafts.csswg.org/css-fonts/#valdef-font-status-bar
90    StatusBar,
91    /// Internal system font, used by the `<menupopup>`s on macOS.
92    #[parse(condition = "ParserContext::chrome_rules_enabled")]
93    MozPullDownMenu,
94    /// Internal system font, used for `<button>` elements.
95    #[parse(condition = "ParserContext::chrome_rules_enabled")]
96    MozButton,
97    /// Internal font, used by `<select>` elements.
98    #[parse(condition = "ParserContext::chrome_rules_enabled")]
99    MozList,
100    /// Internal font, used by `<input>` elements.
101    #[parse(condition = "ParserContext::chrome_rules_enabled")]
102    MozField,
103    #[css(skip)]
104    End, // Just for indexing purposes.
105}
106
107// We don't parse system fonts in servo, but in the interest of not
108// littering a lot of code with `if engine == "gecko"` conditionals,
109// we have a dummy system font module that does nothing
110
111#[derive(
112    Clone, Copy, Debug, Eq, Hash, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss, ToShmem,
113)]
114#[allow(missing_docs)]
115#[cfg(feature = "servo")]
116/// Dummy struct for system font, can never be constructed.
117pub struct SystemFont {
118    #[css(skip)]
119    _forbid_construction: (),
120}
121
122#[allow(missing_docs)]
123#[cfg(feature = "servo")]
124impl SystemFont {
125    pub fn parse(_context: &ParserContext, _input: &mut Parser) -> Result<Self, ()> {
126        Err(())
127    }
128}
129
130const DEFAULT_SCRIPT_MIN_SIZE_PT: u32 = 8;
131const DEFAULT_SCRIPT_SIZE_MULTIPLIER: f64 = 0.71;
132
133/// The minimum font-weight value per:
134///
135/// https://drafts.csswg.org/css-fonts-4/#font-weight-numeric-values
136pub const MIN_FONT_WEIGHT: f32 = 1.;
137
138/// The maximum font-weight value per:
139///
140/// https://drafts.csswg.org/css-fonts-4/#font-weight-numeric-values
141pub const MAX_FONT_WEIGHT: f32 = 1000.;
142
143/// A specified font-weight value.
144///
145/// https://drafts.csswg.org/css-fonts-4/#propdef-font-weight
146#[derive(
147    Clone, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, ToShmem, ToTyped,
148)]
149pub enum FontWeight {
150    /// `<font-weight-absolute>`
151    Absolute(AbsoluteFontWeight),
152    /// Bolder variant
153    Bolder,
154    /// Lighter variant
155    Lighter,
156    /// System font variant.
157    #[css(skip)]
158    System(SystemFont),
159}
160
161impl FontWeight {
162    system_font_methods!(FontWeight, font_weight);
163
164    /// `normal`
165    #[inline]
166    pub fn normal() -> Self {
167        FontWeight::Absolute(AbsoluteFontWeight::Normal)
168    }
169
170    /// Get a specified FontWeight from a gecko keyword
171    pub fn from_gecko_keyword(kw: u32) -> Self {
172        debug_assert!(kw.is_multiple_of(100));
173        debug_assert!(kw as f32 <= MAX_FONT_WEIGHT);
174        FontWeight::Absolute(AbsoluteFontWeight::Weight(Number::new(kw as f32)))
175    }
176}
177
178impl ToComputedValue for FontWeight {
179    type ComputedValue = computed::FontWeight;
180
181    #[inline]
182    fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
183        match *self {
184            FontWeight::Absolute(ref abs) => abs.to_computed_value(context),
185            FontWeight::Bolder => context.builder.get_parent_font().get_font_weight().bolder(),
186            FontWeight::Lighter => context
187                .builder
188                .get_parent_font()
189                .get_font_weight()
190                .lighter(),
191            FontWeight::System(_) => self.compute_system(context),
192        }
193    }
194
195    #[inline]
196    fn from_computed_value(computed: &computed::FontWeight) -> Self {
197        FontWeight::Absolute(AbsoluteFontWeight::from_computed_value(computed))
198    }
199}
200
201/// An absolute font-weight value for a @font-face rule.
202///
203/// https://drafts.csswg.org/css-fonts-4/#font-weight-absolute-values
204#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss, ToShmem, ToTyped)]
205pub enum AbsoluteFontWeight {
206    /// A `<number>`, with the additional constraints specified in:
207    ///
208    ///   https://drafts.csswg.org/css-fonts-4/#font-weight-numeric-values
209    Weight(Number),
210    /// Normal font weight. Same as 400.
211    Normal,
212    /// Bold font weight. Same as 700.
213    Bold,
214}
215
216impl AbsoluteFontWeight {
217    /// Returns the computed weight for use when computed value context is unavailable.
218    /// Returns None if the weight is a calc expression that requires computed-value context.
219    pub fn compute(&self) -> Option<computed::FontWeight> {
220        match self {
221            AbsoluteFontWeight::Weight(weight) => {
222                Some(computed::FontWeight::from_float(weight.resolve()?))
223            },
224            AbsoluteFontWeight::Normal => Some(computed::FontWeight::NORMAL),
225            AbsoluteFontWeight::Bold => Some(computed::FontWeight::BOLD),
226        }
227    }
228}
229
230impl ToComputedValue for AbsoluteFontWeight {
231    type ComputedValue = computed::FontWeight;
232
233    fn to_computed_value(&self, context: &Context) -> computed::FontWeight {
234        match self {
235            AbsoluteFontWeight::Weight(weight) => {
236                computed::FontWeight::from_float(weight.to_computed_value(context))
237            },
238            AbsoluteFontWeight::Normal => computed::FontWeight::NORMAL,
239            AbsoluteFontWeight::Bold => computed::FontWeight::BOLD,
240        }
241    }
242
243    fn from_computed_value(computed: &computed::FontWeight) -> Self {
244        AbsoluteFontWeight::Weight(Number::from_computed_value(&computed.value()))
245    }
246}
247
248impl Parse for AbsoluteFontWeight {
249    fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ParseError> {
250        if let Ok(number) = input.try_parse(|input| Number::parse(context, input)) {
251            // We could add another AllowedNumericType value, but it doesn't
252            // seem worth it just for a single property with such a weird range,
253            // so we do the clamping here manually.
254            if matches!(number.get(), Some(v) if !(MIN_FONT_WEIGHT..=MAX_FONT_WEIGHT).contains(&v))
255            {
256                return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
257            }
258            return Ok(AbsoluteFontWeight::Weight(number));
259        }
260
261        Ok(try_match_ident_ignore_ascii_case! { input,
262            "normal" => AbsoluteFontWeight::Normal,
263            "bold" => AbsoluteFontWeight::Bold,
264        })
265    }
266}
267
268/// The specified value of the `font-style` property, without the system font
269/// crap.
270pub type SpecifiedFontStyle = generics::FontStyle<Angle>;
271
272impl ToCss for SpecifiedFontStyle {
273    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
274    where
275        W: Write,
276    {
277        match *self {
278            generics::FontStyle::Italic => dest.write_str("italic"),
279            generics::FontStyle::Oblique(ref angle) => {
280                // Not angle.is_zero() because we don't want to serialize
281                // `oblique calc(0deg)` as `normal`.
282                if *angle == Angle::zero() {
283                    dest.write_str("normal")?;
284                } else {
285                    dest.write_str("oblique")?;
286                    if *angle != Self::default_angle() {
287                        dest.write_char(' ')?;
288                        angle.to_css(dest)?;
289                    }
290                }
291                Ok(())
292            },
293        }
294    }
295}
296
297impl Parse for SpecifiedFontStyle {
298    fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ParseError> {
299        Ok(try_match_ident_ignore_ascii_case! { input,
300            "normal" => generics::FontStyle::normal(),
301            "italic" => generics::FontStyle::Italic,
302            "oblique" => {
303                let angle = input.try_parse(|input| Self::parse_angle(context, input))
304                    .unwrap_or_else(|_| Self::default_angle());
305
306                generics::FontStyle::Oblique(angle)
307            },
308        })
309    }
310}
311
312impl ToComputedValue for SpecifiedFontStyle {
313    type ComputedValue = computed::FontStyle;
314
315    fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
316        match *self {
317            Self::Italic => computed::FontStyle::ITALIC,
318            Self::Oblique(ref angle) => {
319                computed::FontStyle::oblique(angle.to_computed_value(context).degrees())
320            },
321        }
322    }
323
324    fn from_computed_value(computed: &Self::ComputedValue) -> Self {
325        if *computed == computed::FontStyle::ITALIC {
326            return Self::Italic;
327        }
328        let degrees = computed.oblique_degrees();
329        generics::FontStyle::Oblique(Angle::from_degrees(degrees))
330    }
331}
332
333/// From https://drafts.csswg.org/css-fonts-4/#valdef-font-style-oblique-angle:
334///
335///     Values less than -90deg or values greater than 90deg are
336///     invalid and are treated as parse errors.
337///
338/// The maximum angle value that `font-style: oblique` should compute to.
339pub const FONT_STYLE_OBLIQUE_MAX_ANGLE_DEGREES: f32 = 90.;
340
341/// The minimum angle value that `font-style: oblique` should compute to.
342pub const FONT_STYLE_OBLIQUE_MIN_ANGLE_DEGREES: f32 = -90.;
343
344impl SpecifiedFontStyle {
345    /// Parse a suitable angle for font-style: oblique.
346    pub fn parse_angle(context: &ParserContext, input: &mut Parser) -> Result<Angle, ParseError> {
347        let angle = Angle::parse(context, input)?;
348        // Calc angles can exceed the range and are clamped at computed-value time.
349        if angle.is_calc() {
350            return Ok(angle);
351        }
352
353        let degrees = angle.degrees().unwrap();
354        if !(FONT_STYLE_OBLIQUE_MIN_ANGLE_DEGREES..=FONT_STYLE_OBLIQUE_MAX_ANGLE_DEGREES)
355            .contains(&degrees)
356        {
357            return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
358        }
359        Ok(angle)
360    }
361
362    /// The default angle for `font-style: oblique`.
363    pub fn default_angle() -> Angle {
364        Angle::from_degrees(computed::FontStyle::DEFAULT_OBLIQUE_DEGREES as f32)
365    }
366}
367
368/// The specified value of the `font-style` property.
369#[derive(
370    Clone, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, ToShmem, ToTyped,
371)]
372#[allow(missing_docs)]
373#[typed(todo_derive_fields)]
374pub enum FontStyle {
375    Specified(SpecifiedFontStyle),
376    #[css(skip)]
377    System(SystemFont),
378}
379
380impl FontStyle {
381    /// Return the `normal` value.
382    #[inline]
383    pub fn normal() -> Self {
384        FontStyle::Specified(generics::FontStyle::normal())
385    }
386
387    system_font_methods!(FontStyle, font_style);
388}
389
390impl ToComputedValue for FontStyle {
391    type ComputedValue = computed::FontStyle;
392
393    fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
394        match *self {
395            FontStyle::Specified(ref specified) => specified.to_computed_value(context),
396            FontStyle::System(..) => self.compute_system(context),
397        }
398    }
399
400    fn from_computed_value(computed: &Self::ComputedValue) -> Self {
401        FontStyle::Specified(SpecifiedFontStyle::from_computed_value(computed))
402    }
403}
404
405/// A value for the `font-width` property.
406///
407/// https://drafts.csswg.org/css-fonts-4/#font-width-prop
408#[allow(missing_docs)]
409#[derive(
410    Clone, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, ToShmem, ToTyped,
411)]
412pub enum FontWidth {
413    Width(NonNegativePercentage),
414    Keyword(FontWidthKeyword),
415    #[css(skip)]
416    System(SystemFont),
417}
418
419/// A keyword value for `font-width`.
420#[derive(
421    Clone, Copy, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, ToShmem, ToTyped,
422)]
423#[allow(missing_docs)]
424pub enum FontWidthKeyword {
425    Normal,
426    Condensed,
427    UltraCondensed,
428    ExtraCondensed,
429    SemiCondensed,
430    SemiExpanded,
431    Expanded,
432    ExtraExpanded,
433    UltraExpanded,
434}
435
436impl FontWidthKeyword {
437    /// Turns the keyword into a computed value.
438    pub fn compute(&self) -> computed::FontWidth {
439        computed::FontWidth::from_keyword(*self)
440    }
441
442    /// Does the opposite operation to `compute`, in order to serialize keywords
443    /// if possible.
444    pub fn from_percentage(p: f32) -> Option<Self> {
445        computed::FontWidth::from_percentage(p).as_keyword()
446    }
447}
448
449impl FontWidth {
450    /// `normal`.
451    pub fn normal() -> Self {
452        FontWidth::Keyword(FontWidthKeyword::Normal)
453    }
454
455    system_font_methods!(FontWidth, font_width);
456}
457
458impl ToComputedValue for FontWidth {
459    type ComputedValue = computed::FontWidth;
460
461    fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
462        match *self {
463            FontWidth::Width(ref percentage) => {
464                let percentage = percentage.to_computed_value(context).0;
465                computed::FontWidth::from_percentage(percentage.0)
466            },
467            FontWidth::Keyword(ref kw) => kw.compute(),
468            FontWidth::System(_) => self.compute_system(context),
469        }
470    }
471
472    fn from_computed_value(computed: &Self::ComputedValue) -> Self {
473        FontWidth::Width(NonNegativePercentage::from_computed_value(&NonNegative(
474            computed.to_percentage(),
475        )))
476    }
477}
478
479/// CSS font keywords
480#[derive(
481    Animate,
482    Clone,
483    ComputeSquaredDistance,
484    Copy,
485    Debug,
486    Default,
487    MallocSizeOf,
488    Parse,
489    PartialEq,
490    SpecifiedValueInfo,
491    ToAnimatedValue,
492    ToAnimatedZero,
493    ToComputedValue,
494    ToCss,
495    ToResolvedValue,
496    ToShmem,
497    Serialize,
498    Deserialize,
499    ToTyped,
500)]
501#[allow(missing_docs)]
502#[repr(u8)]
503pub enum FontSizeKeyword {
504    #[css(keyword = "xx-small")]
505    XXSmall,
506    XSmall,
507    Small,
508    #[default]
509    Medium,
510    Large,
511    XLarge,
512    #[css(keyword = "xx-large")]
513    XXLarge,
514    #[css(keyword = "xxx-large")]
515    XXXLarge,
516    /// Indicate whether to apply font-size: math is specified so that extra
517    /// scaling due to math-depth changes is applied during the cascade.
518    #[cfg(feature = "gecko")]
519    Math,
520    #[css(skip)]
521    None,
522}
523
524impl FontSizeKeyword {
525    /// Convert to an HTML <font size> value
526    #[inline]
527    pub fn html_size(self) -> u8 {
528        self as u8
529    }
530
531    /// Returns true if the font size is the math keyword
532    #[cfg(feature = "gecko")]
533    pub fn is_math(self) -> bool {
534        matches!(self, Self::Math)
535    }
536
537    /// Returns true if the font size is the math keyword
538    #[cfg(feature = "servo")]
539    pub fn is_math(self) -> bool {
540        false
541    }
542}
543
544#[derive(
545    Animate,
546    Clone,
547    ComputeSquaredDistance,
548    Copy,
549    Debug,
550    Deserialize,
551    MallocSizeOf,
552    PartialEq,
553    Serialize,
554    ToAnimatedValue,
555    ToAnimatedZero,
556    ToComputedValue,
557    ToCss,
558    ToResolvedValue,
559    ToShmem,
560    ToTyped,
561)]
562/// Additional information for keyword-derived font sizes.
563pub struct KeywordInfo {
564    /// The keyword used
565    pub kw: FontSizeKeyword,
566    /// A factor to be multiplied by the computed size of the keyword
567    #[css(skip)]
568    pub factor: f32,
569    /// An additional fixed offset to add to the kw * factor in the case of
570    /// `calc()`.
571    #[css(skip)]
572    pub offset: CSSPixelLength,
573}
574
575impl KeywordInfo {
576    /// KeywordInfo value for font-size: medium
577    pub fn medium() -> Self {
578        Self::new(FontSizeKeyword::Medium)
579    }
580
581    /// KeywordInfo value for font-size: none
582    pub fn none() -> Self {
583        Self::new(FontSizeKeyword::None)
584    }
585
586    fn new(kw: FontSizeKeyword) -> Self {
587        KeywordInfo {
588            kw,
589            factor: 1.,
590            offset: CSSPixelLength::new(0.),
591        }
592    }
593
594    /// Computes the final size for this font-size keyword, accounting for
595    /// text-zoom.
596    fn to_computed_value(&self, context: &Context) -> CSSPixelLength {
597        debug_assert_ne!(self.kw, FontSizeKeyword::None);
598        #[cfg(feature = "gecko")]
599        debug_assert_ne!(self.kw, FontSizeKeyword::Math);
600        let base = context.maybe_zoom_text(self.kw.to_length(context).0);
601        let zoom_factor = context.style().effective_zoom.value();
602        CSSPixelLength::new(base.px() * self.factor * zoom_factor)
603            + context.maybe_zoom_text(self.offset)
604    }
605
606    /// Given a parent keyword info (self), apply an additional factor/offset to
607    /// it.
608    fn compose(self, factor: f32) -> Self {
609        if self.kw == FontSizeKeyword::None {
610            return self;
611        }
612        KeywordInfo {
613            kw: self.kw,
614            factor: self.factor * factor,
615            offset: self.offset * factor,
616        }
617    }
618}
619
620impl SpecifiedValueInfo for KeywordInfo {
621    fn collect_completion_keywords(f: KeywordsCollectFn) {
622        <FontSizeKeyword as SpecifiedValueInfo>::collect_completion_keywords(f);
623    }
624}
625
626#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss, ToShmem, ToTyped)]
627/// A specified font-size value
628pub enum FontSize {
629    /// A length; e.g. 10px.
630    Length(LengthPercentage),
631    /// A keyword value, along with a ratio and absolute offset.
632    /// The ratio in any specified keyword value
633    /// will be 1 (with offset 0), but we cascade keywordness even
634    /// after font-relative (percent and em) values
635    /// have been applied, which is where the ratio
636    /// comes in. The offset comes in if we cascaded a calc value,
637    /// where the font-relative portion (em and percentage) will
638    /// go into the ratio, and the remaining units all computed together
639    /// will go into the offset.
640    /// See bug 1355707.
641    Keyword(KeywordInfo),
642    /// font-size: smaller
643    Smaller,
644    /// font-size: larger
645    Larger,
646    /// Derived from a specified system font.
647    #[css(skip)]
648    System(SystemFont),
649}
650
651/// Specifies a prioritized list of font family names or generic family names.
652#[derive(Clone, Debug, Eq, Hash, PartialEq, ToCss, ToShmem, ToTyped)]
653#[typed(todo_derive_fields)]
654pub enum FontFamily {
655    /// List of `font-family`
656    #[css(comma)]
657    Values(#[css(iterable)] FontFamilyList),
658    /// System font
659    #[css(skip)]
660    System(SystemFont),
661}
662
663impl FontFamily {
664    system_font_methods!(FontFamily, font_family);
665}
666
667impl ToComputedValue for FontFamily {
668    type ComputedValue = computed::FontFamily;
669
670    fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
671        match *self {
672            FontFamily::Values(ref list) => computed::FontFamily {
673                families: list.clone(),
674                is_system_font: false,
675                is_initial: false,
676            },
677            FontFamily::System(_) => self.compute_system(context),
678        }
679    }
680
681    fn from_computed_value(other: &computed::FontFamily) -> Self {
682        FontFamily::Values(other.families.clone())
683    }
684}
685
686#[cfg(feature = "gecko")]
687impl MallocSizeOf for FontFamily {
688    fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
689        match *self {
690            FontFamily::Values(ref v) => {
691                // Although the family list is refcounted, we always attribute
692                // its size to the specified value.
693                v.list.unconditional_size_of(ops)
694            },
695            FontFamily::System(_) => 0,
696        }
697    }
698}
699
700impl Parse for FontFamily {
701    /// <family-name>#
702    /// <family-name> = <string> | [ <ident>+ ]
703    /// TODO: <generic-family>
704    fn parse(context: &ParserContext, input: &mut Parser) -> Result<FontFamily, ParseError> {
705        let values =
706            input.parse_comma_separated(|input| SingleFontFamily::parse(context, input))?;
707        Ok(FontFamily::Values(FontFamilyList {
708            list: crate::ArcSlice::from_iter(values.into_iter()),
709        }))
710    }
711}
712
713impl SpecifiedValueInfo for FontFamily {}
714
715/// `FamilyName::parse` is based on `SingleFontFamily::parse` and not the other
716/// way around because we want the former to exclude generic family keywords.
717impl Parse for FamilyName {
718    fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ParseError> {
719        match SingleFontFamily::parse(context, input) {
720            Ok(SingleFontFamily::FamilyName(name)) => Ok(name),
721            Ok(SingleFontFamily::Generic(_)) => {
722                Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError))
723            },
724            Err(e) => Err(e),
725        }
726    }
727}
728
729/// A factor for one of the font-size-adjust metrics, which may be either a number
730/// or the `from-font` keyword.
731#[derive(
732    Clone, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, ToShmem, ToTyped,
733)]
734pub enum FontSizeAdjustFactor {
735    /// An explicitly-specified number.
736    Number(NonNegativeNumber),
737    /// The from-font keyword: resolve the number from font metrics.
738    FromFont,
739}
740
741/// Specified value for font-size-adjust, intended to help
742/// preserve the readability of text when font fallback occurs.
743///
744/// https://drafts.csswg.org/css-fonts-5/#font-size-adjust-prop
745pub type FontSizeAdjust = generics::GenericFontSizeAdjust<FontSizeAdjustFactor>;
746
747impl Parse for FontSizeAdjust {
748    fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ParseError> {
749        // First check if we have an adjustment factor without a metrics-basis keyword.
750        if let Ok(factor) = input.try_parse(|i| FontSizeAdjustFactor::parse(context, i)) {
751            return Ok(Self::ExHeight(factor));
752        }
753
754        let ident = input.expect_ident()?;
755        let basis = match_ignore_ascii_case! { &ident,
756            "none" => return Ok(Self::None),
757            // Check for size adjustment basis keywords.
758            "ex-height" => Self::ExHeight,
759            "cap-height" => Self::CapHeight,
760            "ch-width" => Self::ChWidth,
761            "ic-width" => Self::IcWidth,
762            "ic-height" => Self::IcHeight,
763            // Unknown keyword.
764            _ => return Err(ParseError::custom(
765                SelectorParseErrorKind::UnexpectedIdent
766            )),
767        };
768
769        Ok(basis(FontSizeAdjustFactor::parse(context, input)?))
770    }
771}
772
773/// This is the ratio applied for font-size: larger
774/// and smaller by both Firefox and Chrome
775const LARGER_FONT_SIZE_RATIO: f32 = 1.2;
776
777/// The default font size.
778pub const FONT_MEDIUM_PX: f32 = 16.0;
779/// The default line height.
780pub const FONT_MEDIUM_LINE_HEIGHT_PX: f32 = FONT_MEDIUM_PX * 1.2;
781/// The default ex height -- https://drafts.csswg.org/css-values/#ex
782/// > In the cases where it is impossible or impractical to determine the x-height, a value of 0.5em must be assumed
783pub const FONT_MEDIUM_EX_PX: f32 = FONT_MEDIUM_PX * 0.5;
784/// The default cap height -- https://drafts.csswg.org/css-values/#cap
785/// > In the cases where it is impossible or impractical to determine the cap-height, the font’s ascent must be used
786pub const FONT_MEDIUM_CAP_PX: f32 = FONT_MEDIUM_PX;
787/// The default advance measure -- https://drafts.csswg.org/css-values/#ch
788/// > Thus, the ch unit falls back to 0.5em in the general case
789pub const FONT_MEDIUM_CH_PX: f32 = FONT_MEDIUM_PX * 0.5;
790/// The default idographic advance measure -- https://drafts.csswg.org/css-values/#ic
791/// > In the cases where it is impossible or impractical to determine the ideographic advance measure, it must be assumed to be 1em
792pub const FONT_MEDIUM_IC_PX: f32 = FONT_MEDIUM_PX;
793
794impl FontSizeKeyword {
795    #[inline]
796    fn to_length(&self, cx: &Context) -> NonNegativeLength {
797        let font = cx.style().get_font();
798
799        #[cfg(feature = "servo")]
800        let family = &font.font_family.families;
801        #[cfg(feature = "gecko")]
802        let family = &font.mFont.family.families;
803
804        let generic = family
805            .single_generic()
806            .unwrap_or(computed::GenericFontFamily::None);
807
808        #[cfg(feature = "gecko")]
809        let base_size = cx
810            .device()
811            .base_size_for_generic(&font.mLanguage.0, generic);
812        #[cfg(feature = "servo")]
813        let base_size = cx.device().base_size_for_generic(generic);
814
815        self.to_length_without_context(cx.quirks_mode, base_size)
816    }
817
818    /// Resolve a keyword length without any context, with explicit arguments.
819    #[inline]
820    pub fn to_length_without_context(
821        &self,
822        quirks_mode: QuirksMode,
823        base_size: Length,
824    ) -> NonNegativeLength {
825        #[cfg(feature = "gecko")]
826        debug_assert_ne!(*self, FontSizeKeyword::Math);
827        // The tables in this function are originally from
828        // nsRuleNode::CalcFontPointSize in Gecko:
829        //
830        // https://searchfox.org/mozilla-central/rev/c05d9d61188d32b8/layout/style/nsRuleNode.cpp#3150
831        //
832        // Mapping from base size and HTML size to pixels
833        // The first index is (base_size - 9), the second is the
834        // HTML size. "0" is CSS keyword xx-small, not HTML size 0,
835        // since HTML size 0 is the same as 1.
836        //
837        //  xxs   xs      s      m     l      xl     xxl   -
838        //  -     0/1     2      3     4      5      6     7
839        static FONT_SIZE_MAPPING: [[i32; 8]; 8] = [
840            [9, 9, 9, 9, 11, 14, 18, 27],
841            [9, 9, 9, 10, 12, 15, 20, 30],
842            [9, 9, 10, 11, 13, 17, 22, 33],
843            [9, 9, 10, 12, 14, 18, 24, 36],
844            [9, 10, 12, 13, 16, 20, 26, 39],
845            [9, 10, 12, 14, 17, 21, 28, 42],
846            [9, 10, 13, 15, 18, 23, 30, 45],
847            [9, 10, 13, 16, 18, 24, 32, 48],
848        ];
849
850        // This table gives us compatibility with WinNav4 for the default fonts only.
851        // In WinNav4, the default fonts were:
852        //
853        //     Times/12pt ==   Times/16px at 96ppi
854        //   Courier/10pt == Courier/13px at 96ppi
855        //
856        // xxs   xs     s      m      l     xl     xxl    -
857        // -     1      2      3      4     5      6      7
858        static QUIRKS_FONT_SIZE_MAPPING: [[i32; 8]; 8] = [
859            [9, 9, 9, 9, 11, 14, 18, 28],
860            [9, 9, 9, 10, 12, 15, 20, 31],
861            [9, 9, 9, 11, 13, 17, 22, 34],
862            [9, 9, 10, 12, 14, 18, 24, 37],
863            [9, 9, 10, 13, 16, 20, 26, 40],
864            [9, 9, 11, 14, 17, 21, 28, 42],
865            [9, 10, 12, 15, 17, 23, 30, 45],
866            [9, 10, 13, 16, 18, 24, 32, 48],
867        ];
868
869        static FONT_SIZE_FACTORS: [i32; 8] = [60, 75, 89, 100, 120, 150, 200, 300];
870        let base_size_px = base_size.px().round() as i32;
871        let html_size = self.html_size() as usize;
872        NonNegative(if (9..=16).contains(&base_size_px) {
873            let mapping = if quirks_mode == QuirksMode::Quirks {
874                QUIRKS_FONT_SIZE_MAPPING
875            } else {
876                FONT_SIZE_MAPPING
877            };
878            Length::new(mapping[(base_size_px - 9) as usize][html_size] as f32)
879        } else {
880            base_size * FONT_SIZE_FACTORS[html_size] as f32 / 100.0
881        })
882    }
883}
884
885impl FontSize {
886    /// <https://html.spec.whatwg.org/multipage/#rules-for-parsing-a-legacy-font-size>
887    pub fn from_html_size(size: u8) -> Self {
888        FontSize::Keyword(KeywordInfo::new(match size {
889            // If value is less than 1, let it be 1.
890            0 | 1 => FontSizeKeyword::XSmall,
891            2 => FontSizeKeyword::Small,
892            3 => FontSizeKeyword::Medium,
893            4 => FontSizeKeyword::Large,
894            5 => FontSizeKeyword::XLarge,
895            6 => FontSizeKeyword::XXLarge,
896            // If value is greater than 7, let it be 7.
897            _ => FontSizeKeyword::XXXLarge,
898        }))
899    }
900
901    /// Compute it against a given base font size
902    pub fn to_computed_value_against(
903        &self,
904        context: &Context,
905        base_size: FontBaseSize,
906        line_height_base: LineHeightBase,
907    ) -> computed::FontSize {
908        let compose_keyword = |factor| {
909            context
910                .style()
911                .get_parent_font()
912                .slow_clone_font_size()
913                .keyword_info
914                .compose(factor)
915        };
916        let mut info = KeywordInfo::none();
917        let size =
918            match *self {
919                FontSize::Length(LengthPercentage::Length(ref l)) => {
920                    if l.length_unit() == LengthUnit::Em {
921                        // If the parent font was keyword-derived, this is
922                        // too. Tack the em unit onto the factor
923                        info = compose_keyword(l.unitless_value());
924                    }
925                    let result =
926                        l.to_computed_value_with_base_size(context, base_size, line_height_base);
927                    if l.should_zoom_text() {
928                        context.maybe_zoom_text(result)
929                    } else {
930                        result
931                    }
932                },
933                FontSize::Length(LengthPercentage::Percentage(pc)) => {
934                    // If the parent font was keyword-derived, this is too.
935                    // Tack the % onto the factor
936                    info = compose_keyword(pc.get());
937                    (base_size.resolve(context).computed_size() * pc.get()).normalized()
938                },
939                FontSize::Length(LengthPercentage::Calc(ref calc)) => {
940                    let calc = calc.to_computed_value_zoomed(context, base_size, line_height_base);
941                    calc.resolve(base_size.resolve(context).computed_size())
942                },
943                FontSize::Keyword(i) => {
944                    if i.kw.is_math() {
945                        // Scaling is done in recompute_math_font_size_if_needed().
946                        info = compose_keyword(1.);
947                        // i.kw will always be FontSizeKeyword::Math here. But writing it this
948                        // allows this code to compile for servo where the Math variant is cfg'd out.
949                        info.kw = i.kw;
950                        NoCalcLength::from_em(1.).to_computed_value_with_base_size(
951                            context,
952                            base_size,
953                            line_height_base,
954                        )
955                    } else {
956                        // As a specified keyword, this is keyword derived
957                        info = i;
958                        i.to_computed_value(context).clamp_to_non_negative()
959                    }
960                },
961                FontSize::Smaller => {
962                    info = compose_keyword(1. / LARGER_FONT_SIZE_RATIO);
963                    NoCalcLength::from_em(1. / LARGER_FONT_SIZE_RATIO)
964                        .to_computed_value_with_base_size(context, base_size, line_height_base)
965                },
966                FontSize::Larger => {
967                    info = compose_keyword(LARGER_FONT_SIZE_RATIO);
968                    NoCalcLength::from_em(LARGER_FONT_SIZE_RATIO).to_computed_value_with_base_size(
969                        context,
970                        base_size,
971                        line_height_base,
972                    )
973                },
974                FontSize::System(_) => {
975                    #[cfg(feature = "servo")]
976                    {
977                        unreachable!()
978                    }
979                    #[cfg(feature = "gecko")]
980                    {
981                        context
982                            .cached_system_font
983                            .as_ref()
984                            .unwrap()
985                            .font_size
986                            .computed_size()
987                            .zoom(context.builder.effective_zoom)
988                    }
989                },
990            };
991        let size = NonNegative(Self::quantize_font_size(size));
992        computed::FontSize {
993            computed_size: size,
994            used_size: size,
995            keyword_info: info,
996        }
997    }
998
999    /// Quantize a value intended for use as a font size, to avoid creating a near-infinity
1000    /// of different styles and font instances when "random" floating-point sizes are used.
1001    #[inline]
1002    pub fn quantize_font_size(size: CSSPixelLength) -> CSSPixelLength {
1003        // If the size is < 1024px and >= 0.1px, just snap to an integer number of appUnits.
1004        if size.px() < 1024.0 && size.px() >= 0.1 {
1005            return CSSPixelLength::from(app_units::Au::from_f32_px(size.px()));
1006        }
1007
1008        // Based on the Veltkamp-Dekker float-splitting algorithm, see e.g.
1009        // https://indico.cern.ch/event/313684/contributions/1687773/attachments/600513/826490/FPArith-Part2.pdf
1010        // A 32-bit float has 24 bits of precision (23 stored, plus an implicit 1 bit
1011        // at the start of the mantissa).
1012        // (Compare also QuantizeFontSize in dom/canvas/CanvasRenderingContext2D.cpp.)
1013        // If we ever change the representation of CSSPixelLength (e.g. to f64 or some fixed-point type)
1014        // this will need to be revised.
1015        size_of_test!(CSSPixelLength, std::mem::size_of::<f32>());
1016        const BITS_TO_DROP: u32 = 14; // leaving 10 bits of precision
1017        const SCALE_PLUS_ONE: f32 = ((1 << BITS_TO_DROP) + 1) as f32;
1018        const LIMIT: f32 = f32::MAX / SCALE_PLUS_ONE;
1019        if size.px() >= LIMIT {
1020            return CSSPixelLength::new(LIMIT);
1021        }
1022        let d = size.px() * SCALE_PLUS_ONE;
1023        let t = d - size.px();
1024        let quantized = d - t;
1025        if quantized < 0.1 {
1026            // Don't snap tiny values.
1027            CSSPixelLength::new(quantized)
1028        } else {
1029            // Snap the quantized result to integer appUnits.
1030            CSSPixelLength::from(app_units::Au::from_f32_px(quantized))
1031        }
1032    }
1033}
1034
1035impl ToComputedValue for FontSize {
1036    type ComputedValue = computed::FontSize;
1037
1038    #[inline]
1039    fn to_computed_value(&self, context: &Context) -> computed::FontSize {
1040        self.to_computed_value_against(
1041            context,
1042            FontBaseSize::InheritedStyle,
1043            LineHeightBase::InheritedStyle,
1044        )
1045    }
1046
1047    #[inline]
1048    fn from_computed_value(computed: &computed::FontSize) -> Self {
1049        FontSize::Length(LengthPercentage::Length(
1050            ToComputedValue::from_computed_value(&computed.computed_size()),
1051        ))
1052    }
1053}
1054
1055impl FontSize {
1056    system_font_methods!(FontSize);
1057
1058    /// Get initial value for specified font size.
1059    #[inline]
1060    pub fn medium() -> Self {
1061        FontSize::Keyword(KeywordInfo::medium())
1062    }
1063
1064    /// Parses a font-size, with quirks.
1065    pub fn parse_quirky(
1066        context: &ParserContext,
1067        input: &mut Parser,
1068        allow_quirks: AllowQuirks,
1069    ) -> Result<FontSize, ParseError> {
1070        if let Ok(lp) = input
1071            .try_parse(|i| LengthPercentage::parse_non_negative_quirky(context, i, allow_quirks))
1072        {
1073            return Ok(FontSize::Length(lp));
1074        }
1075
1076        if let Ok(kw) = input.try_parse(|i| FontSizeKeyword::parse(i)) {
1077            return Ok(FontSize::Keyword(KeywordInfo::new(kw)));
1078        }
1079
1080        try_match_ident_ignore_ascii_case! { input,
1081            "smaller" => Ok(FontSize::Smaller),
1082            "larger" => Ok(FontSize::Larger),
1083        }
1084    }
1085}
1086
1087impl Parse for FontSize {
1088    /// <length> | <percentage> | <absolute-size> | <relative-size>
1089    fn parse(context: &ParserContext, input: &mut Parser) -> Result<FontSize, ParseError> {
1090        FontSize::parse_quirky(context, input, AllowQuirks::No)
1091    }
1092}
1093
1094bitflags! {
1095    #[derive(Clone, Copy)]
1096    /// Flags of variant alternates in bit
1097    struct VariantAlternatesParsingFlags: u8 {
1098        /// None of variant alternates enabled
1099        const NORMAL = 0;
1100        /// Historical forms
1101        const HISTORICAL_FORMS = 0x01;
1102        /// Stylistic Alternates
1103        const STYLISTIC = 0x02;
1104        /// Stylistic Sets
1105        const STYLESET = 0x04;
1106        /// Character Variant
1107        const CHARACTER_VARIANT = 0x08;
1108        /// Swash glyphs
1109        const SWASH = 0x10;
1110        /// Ornaments glyphs
1111        const ORNAMENTS = 0x20;
1112        /// Annotation forms
1113        const ANNOTATION = 0x40;
1114    }
1115}
1116
1117#[derive(
1118    Clone,
1119    Debug,
1120    Deserialize,
1121    Hash,
1122    MallocSizeOf,
1123    PartialEq,
1124    Serialize,
1125    SpecifiedValueInfo,
1126    ToCss,
1127    ToComputedValue,
1128    ToResolvedValue,
1129    ToShmem,
1130)]
1131#[repr(C, u8)]
1132/// Set of variant alternates
1133pub enum VariantAlternates {
1134    /// Enables display of stylistic alternates
1135    #[css(function)]
1136    Stylistic(CustomIdent),
1137    /// Enables display with stylistic sets
1138    #[css(comma, function)]
1139    Styleset(#[css(iterable)] crate::OwnedSlice<CustomIdent>),
1140    /// Enables display of specific character variants
1141    #[css(comma, function)]
1142    CharacterVariant(#[css(iterable)] crate::OwnedSlice<CustomIdent>),
1143    /// Enables display of swash glyphs
1144    #[css(function)]
1145    Swash(CustomIdent),
1146    /// Enables replacement of default glyphs with ornaments
1147    #[css(function)]
1148    Ornaments(CustomIdent),
1149    /// Enables display of alternate annotation forms
1150    #[css(function)]
1151    Annotation(CustomIdent),
1152    /// Enables display of historical forms
1153    HistoricalForms,
1154}
1155
1156#[derive(
1157    Clone,
1158    Debug,
1159    Default,
1160    Deserialize,
1161    Hash,
1162    MallocSizeOf,
1163    PartialEq,
1164    Serialize,
1165    SpecifiedValueInfo,
1166    ToComputedValue,
1167    ToCss,
1168    ToResolvedValue,
1169    ToShmem,
1170    ToTyped,
1171)]
1172#[repr(transparent)]
1173#[typed(todo_derive_fields)]
1174/// List of Variant Alternates
1175pub struct FontVariantAlternates(
1176    #[css(if_empty = "normal", iterable)] crate::OwnedSlice<VariantAlternates>,
1177);
1178
1179impl FontVariantAlternates {
1180    /// Returns true if the list is empty.
1181    pub fn is_empty(&self) -> bool {
1182        self.0.is_empty()
1183    }
1184
1185    /// Iterates over all alternates in the list.
1186    pub fn iter(&self) -> impl Iterator<Item = &VariantAlternates> {
1187        self.0.iter()
1188    }
1189
1190    /// Returns the length of all variant alternates.
1191    pub fn len(&self) -> usize {
1192        self.0.iter().fold(0, |acc, alternate| match *alternate {
1193            VariantAlternates::Swash(_)
1194            | VariantAlternates::Stylistic(_)
1195            | VariantAlternates::Ornaments(_)
1196            | VariantAlternates::Annotation(_) => acc + 1,
1197            VariantAlternates::Styleset(ref slice)
1198            | VariantAlternates::CharacterVariant(ref slice) => acc + slice.len(),
1199            _ => acc,
1200        })
1201    }
1202}
1203
1204impl Parse for FontVariantAlternates {
1205    /// normal |
1206    ///  [ stylistic(<feature-value-name>)           ||
1207    ///    historical-forms                          ||
1208    ///    styleset(<feature-value-name> #)          ||
1209    ///    character-variant(<feature-value-name> #) ||
1210    ///    swash(<feature-value-name>)               ||
1211    ///    ornaments(<feature-value-name>)           ||
1212    ///    annotation(<feature-value-name>) ]
1213    fn parse(_: &ParserContext, input: &mut Parser) -> Result<FontVariantAlternates, ParseError> {
1214        if input
1215            .try_parse(|input| input.expect_ident_matching("normal"))
1216            .is_ok()
1217        {
1218            return Ok(Default::default());
1219        }
1220
1221        let mut stylistic = None;
1222        let mut historical = None;
1223        let mut styleset = None;
1224        let mut character_variant = None;
1225        let mut swash = None;
1226        let mut ornaments = None;
1227        let mut annotation = None;
1228
1229        // Parse values for the various alternate types in any order.
1230        let mut parsed_alternates = VariantAlternatesParsingFlags::empty();
1231        macro_rules! check_if_parsed(
1232            ($input:expr, $flag:path) => (
1233                if parsed_alternates.contains($flag) {
1234                    return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError))
1235                }
1236                parsed_alternates |= $flag;
1237            )
1238        );
1239        while input.try_parse(|input| match *input.next()? {
1240            Token::Ident(ref value) if value.eq_ignore_ascii_case("historical-forms") => {
1241                check_if_parsed!(input, VariantAlternatesParsingFlags::HISTORICAL_FORMS);
1242                historical = Some(VariantAlternates::HistoricalForms);
1243                Ok(())
1244            },
1245            Token::Function(ref name) => {
1246                let name = name.clone();
1247                input.parse_nested_block(|i| {
1248                    match_ignore_ascii_case! { &name,
1249                        "swash" => {
1250                            check_if_parsed!(i, VariantAlternatesParsingFlags::SWASH);
1251                            let ident = CustomIdent::parse(i, &[])?;
1252                            swash = Some(VariantAlternates::Swash(ident));
1253                            Ok(())
1254                        },
1255                        "stylistic" => {
1256                            check_if_parsed!(i, VariantAlternatesParsingFlags::STYLISTIC);
1257                            let ident = CustomIdent::parse(i, &[])?;
1258                            stylistic = Some(VariantAlternates::Stylistic(ident));
1259                            Ok(())
1260                        },
1261                        "ornaments" => {
1262                            check_if_parsed!(i, VariantAlternatesParsingFlags::ORNAMENTS);
1263                            let ident = CustomIdent::parse(i, &[])?;
1264                            ornaments = Some(VariantAlternates::Ornaments(ident));
1265                            Ok(())
1266                        },
1267                        "annotation" => {
1268                            check_if_parsed!(i, VariantAlternatesParsingFlags::ANNOTATION);
1269                            let ident = CustomIdent::parse(i, &[])?;
1270                            annotation = Some(VariantAlternates::Annotation(ident));
1271                            Ok(())
1272                        },
1273                        "styleset" => {
1274                            check_if_parsed!(i, VariantAlternatesParsingFlags::STYLESET);
1275                            let idents = i.parse_comma_separated(|i| {
1276                                CustomIdent::parse(i, &[])
1277                            })?;
1278                            styleset = Some(VariantAlternates::Styleset(idents.into()));
1279                            Ok(())
1280                        },
1281                        "character-variant" => {
1282                            check_if_parsed!(i, VariantAlternatesParsingFlags::CHARACTER_VARIANT);
1283                            let idents = i.parse_comma_separated(|i| {
1284                                CustomIdent::parse(i, &[])
1285                            })?;
1286                            character_variant = Some(VariantAlternates::CharacterVariant(idents.into()));
1287                            Ok(())
1288                        },
1289                        _ => Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError)),
1290                    }
1291                })
1292            },
1293            _ => Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError)),
1294        }).is_ok() {}
1295
1296        if parsed_alternates.is_empty() {
1297            return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
1298        }
1299
1300        // Collect the parsed values in canonical order, so that we'll serialize correctly.
1301        let mut alternates = Vec::new();
1302        macro_rules! push_if_some(
1303            ($value:expr) => (
1304                if let Some(v) = $value {
1305                    alternates.push(v);
1306                }
1307            )
1308        );
1309        push_if_some!(stylistic);
1310        push_if_some!(historical);
1311        push_if_some!(styleset);
1312        push_if_some!(character_variant);
1313        push_if_some!(swash);
1314        push_if_some!(ornaments);
1315        push_if_some!(annotation);
1316
1317        Ok(FontVariantAlternates(alternates.into()))
1318    }
1319}
1320
1321#[derive(
1322    Clone,
1323    Copy,
1324    Debug,
1325    Deserialize,
1326    Eq,
1327    Hash,
1328    MallocSizeOf,
1329    PartialEq,
1330    Parse,
1331    Serialize,
1332    SpecifiedValueInfo,
1333    ToComputedValue,
1334    ToCss,
1335    ToResolvedValue,
1336    ToShmem,
1337    ToTyped,
1338)]
1339#[css(bitflags(
1340    single = "normal",
1341    mixed = "jis78,jis83,jis90,jis04,simplified,traditional,full-width,proportional-width,ruby",
1342    validate_mixed = "Self::validate_mixed_flags",
1343))]
1344#[repr(C)]
1345/// Variants for east asian variant
1346pub struct FontVariantEastAsian(u16);
1347bitflags! {
1348    impl FontVariantEastAsian: u16 {
1349        /// None of the features
1350        const NORMAL = 0;
1351        /// Enables rendering of JIS78 forms (OpenType feature: jp78)
1352        const JIS78  = 1 << 0;
1353        /// Enables rendering of JIS83 forms (OpenType feature: jp83).
1354        const JIS83 = 1 << 1;
1355        /// Enables rendering of JIS90 forms (OpenType feature: jp90).
1356        const JIS90 = 1 << 2;
1357        /// Enables rendering of JIS2004 forms (OpenType feature: jp04).
1358        const JIS04 = 1 << 3;
1359        /// Enables rendering of simplified forms (OpenType feature: smpl).
1360        const SIMPLIFIED = 1 << 4;
1361        /// Enables rendering of traditional forms (OpenType feature: trad).
1362        const TRADITIONAL = 1 << 5;
1363
1364        /// These values are exclusive with each other.
1365        const JIS_GROUP = Self::JIS78.0 | Self::JIS83.0 | Self::JIS90.0 | Self::JIS04.0 | Self::SIMPLIFIED.0 | Self::TRADITIONAL.0;
1366
1367        /// Enables rendering of full-width variants (OpenType feature: fwid).
1368        const FULL_WIDTH = 1 << 6;
1369        /// Enables rendering of proportionally-spaced variants (OpenType feature: pwid).
1370        const PROPORTIONAL_WIDTH = 1 << 7;
1371        /// Enables display of ruby variant glyphs (OpenType feature: ruby).
1372        const RUBY = 1 << 8;
1373    }
1374}
1375
1376impl FontVariantEastAsian {
1377    /// The number of variants.
1378    pub const COUNT: usize = 9;
1379
1380    fn validate_mixed_flags(&self) -> bool {
1381        if self.contains(Self::FULL_WIDTH | Self::PROPORTIONAL_WIDTH) {
1382            // full-width and proportional-width are exclusive with each other.
1383            return false;
1384        }
1385        let jis = self.intersection(Self::JIS_GROUP);
1386        if !jis.is_empty() && !jis.bits().is_power_of_two() {
1387            return false;
1388        }
1389        true
1390    }
1391}
1392
1393#[derive(
1394    Clone,
1395    Copy,
1396    Debug,
1397    Deserialize,
1398    Eq,
1399    Hash,
1400    MallocSizeOf,
1401    PartialEq,
1402    Parse,
1403    Serialize,
1404    SpecifiedValueInfo,
1405    ToComputedValue,
1406    ToCss,
1407    ToResolvedValue,
1408    ToShmem,
1409    ToTyped,
1410)]
1411#[css(bitflags(
1412    single = "normal,none",
1413    mixed = "common-ligatures,no-common-ligatures,discretionary-ligatures,no-discretionary-ligatures,historical-ligatures,no-historical-ligatures,contextual,no-contextual",
1414    validate_mixed = "Self::validate_mixed_flags",
1415))]
1416#[repr(C)]
1417/// Variants of ligatures
1418pub struct FontVariantLigatures(u16);
1419bitflags! {
1420    impl FontVariantLigatures: u16 {
1421        /// Specifies that common default features are enabled
1422        const NORMAL = 0;
1423        /// Specifies that no features are enabled;
1424        const NONE = 1;
1425        /// Enables display of common ligatures
1426        const COMMON_LIGATURES  = 1 << 1;
1427        /// Disables display of common ligatures
1428        const NO_COMMON_LIGATURES  = 1 << 2;
1429        /// Enables display of discretionary ligatures
1430        const DISCRETIONARY_LIGATURES = 1 << 3;
1431        /// Disables display of discretionary ligatures
1432        const NO_DISCRETIONARY_LIGATURES = 1 << 4;
1433        /// Enables display of historical ligatures
1434        const HISTORICAL_LIGATURES = 1 << 5;
1435        /// Disables display of historical ligatures
1436        const NO_HISTORICAL_LIGATURES = 1 << 6;
1437        /// Enables display of contextual alternates
1438        const CONTEXTUAL = 1 << 7;
1439        /// Disables display of contextual alternates
1440        const NO_CONTEXTUAL = 1 << 8;
1441    }
1442}
1443
1444impl FontVariantLigatures {
1445    /// The number of variants.
1446    pub const COUNT: usize = 9;
1447
1448    fn validate_mixed_flags(&self) -> bool {
1449        // Mixing a value and its disabling value is forbidden.
1450        if self.contains(Self::COMMON_LIGATURES | Self::NO_COMMON_LIGATURES)
1451            || self.contains(Self::DISCRETIONARY_LIGATURES | Self::NO_DISCRETIONARY_LIGATURES)
1452            || self.contains(Self::HISTORICAL_LIGATURES | Self::NO_HISTORICAL_LIGATURES)
1453            || self.contains(Self::CONTEXTUAL | Self::NO_CONTEXTUAL)
1454        {
1455            return false;
1456        }
1457        true
1458    }
1459}
1460
1461/// Variants of numeric values
1462#[derive(
1463    Clone,
1464    Copy,
1465    Debug,
1466    Deserialize,
1467    Eq,
1468    Hash,
1469    MallocSizeOf,
1470    PartialEq,
1471    Parse,
1472    Serialize,
1473    SpecifiedValueInfo,
1474    ToComputedValue,
1475    ToCss,
1476    ToResolvedValue,
1477    ToShmem,
1478    ToTyped,
1479)]
1480#[css(bitflags(
1481    single = "normal",
1482    mixed = "lining-nums,oldstyle-nums,proportional-nums,tabular-nums,diagonal-fractions,stacked-fractions,ordinal,slashed-zero",
1483    validate_mixed = "Self::validate_mixed_flags",
1484))]
1485#[repr(C)]
1486pub struct FontVariantNumeric(u8);
1487bitflags! {
1488    impl FontVariantNumeric : u8 {
1489        /// Specifies that common default features are enabled
1490        const NORMAL = 0;
1491        /// Enables display of lining numerals.
1492        const LINING_NUMS = 1 << 0;
1493        /// Enables display of old-style numerals.
1494        const OLDSTYLE_NUMS = 1 << 1;
1495        /// Enables display of proportional numerals.
1496        const PROPORTIONAL_NUMS = 1 << 2;
1497        /// Enables display of tabular numerals.
1498        const TABULAR_NUMS = 1 << 3;
1499        /// Enables display of lining diagonal fractions.
1500        const DIAGONAL_FRACTIONS = 1 << 4;
1501        /// Enables display of lining stacked fractions.
1502        const STACKED_FRACTIONS = 1 << 5;
1503        /// Enables display of slashed zeros.
1504        const SLASHED_ZERO = 1 << 6;
1505        /// Enables display of letter forms used with ordinal numbers.
1506        const ORDINAL = 1 << 7;
1507    }
1508}
1509
1510impl FontVariantNumeric {
1511    /// The number of variants.
1512    pub const COUNT: usize = 8;
1513
1514    /// normal |
1515    ///  [ <numeric-figure-values>   ||
1516    ///    <numeric-spacing-values>  ||
1517    ///    <numeric-fraction-values> ||
1518    ///    ordinal                   ||
1519    ///    slashed-zero ]
1520    /// <numeric-figure-values>   = [ lining-nums | oldstyle-nums ]
1521    /// <numeric-spacing-values>  = [ proportional-nums | tabular-nums ]
1522    /// <numeric-fraction-values> = [ diagonal-fractions | stacked-fractions ]
1523    fn validate_mixed_flags(&self) -> bool {
1524        if self.contains(Self::LINING_NUMS | Self::OLDSTYLE_NUMS)
1525            || self.contains(Self::PROPORTIONAL_NUMS | Self::TABULAR_NUMS)
1526            || self.contains(Self::DIAGONAL_FRACTIONS | Self::STACKED_FRACTIONS)
1527        {
1528            return false;
1529        }
1530        true
1531    }
1532}
1533
1534/// This property provides low-level control over OpenType or TrueType font features.
1535pub type FontFeatureSettings = FontSettings<FeatureTagValue<Integer>>;
1536
1537impl FontFeatureSettings {
1538    /// Like `parse`, but rejects calc expressions that cannot be resolved at parse time,
1539    /// since @font-face descriptors require concrete values.
1540    pub fn parse_for_font_face_rule(
1541        context: &ParserContext,
1542        input: &mut Parser,
1543    ) -> Result<Self, ParseError> {
1544        let settings = FontFeatureSettings::parse(context, input)?;
1545        if settings
1546            .0
1547            .iter()
1548            .any(|setting| setting.value.resolve().is_none())
1549        {
1550            return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
1551        }
1552        Ok(settings)
1553    }
1554}
1555
1556/// For font-language-override, use the same representation as the computed value.
1557pub use crate::values::computed::font::FontLanguageOverride;
1558
1559impl Parse for FontLanguageOverride {
1560    /// normal | <string>
1561    fn parse(_: &ParserContext, input: &mut Parser) -> Result<FontLanguageOverride, ParseError> {
1562        if input
1563            .try_parse(|input| input.expect_ident_matching("normal"))
1564            .is_ok()
1565        {
1566            return Ok(FontLanguageOverride::normal());
1567        }
1568
1569        let string = input.expect_string()?;
1570
1571        // The OpenType spec requires tags to be 1 to 4 ASCII characters:
1572        // https://learn.microsoft.com/en-gb/typography/opentype/spec/otff#data-types
1573        if string.is_empty() || string.len() > 4 || !string.is_ascii() {
1574            return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
1575        }
1576
1577        let mut bytes = [b' '; 4];
1578        for (byte, str_byte) in bytes.iter_mut().zip(string.as_bytes()) {
1579            *byte = *str_byte;
1580        }
1581
1582        Ok(FontLanguageOverride(u32::from_be_bytes(bytes)))
1583    }
1584}
1585
1586/// A value for any of the font-synthesis-{weight,small-caps,position} properties.
1587#[repr(u8)]
1588#[derive(
1589    Clone,
1590    Copy,
1591    Debug,
1592    Deserialize,
1593    Eq,
1594    Hash,
1595    MallocSizeOf,
1596    Parse,
1597    PartialEq,
1598    Serialize,
1599    SpecifiedValueInfo,
1600    ToComputedValue,
1601    ToCss,
1602    ToResolvedValue,
1603    ToShmem,
1604    ToTyped,
1605)]
1606pub enum FontSynthesis {
1607    /// This attribute may be synthesized if not supported by a face.
1608    Auto,
1609    /// Do not attempt to synthesis this style attribute.
1610    None,
1611}
1612
1613/// A value for the font-synthesis-style property.
1614#[repr(u8)]
1615#[derive(
1616    Clone,
1617    Copy,
1618    Debug,
1619    Deserialize,
1620    Eq,
1621    Hash,
1622    MallocSizeOf,
1623    Parse,
1624    PartialEq,
1625    Serialize,
1626    SpecifiedValueInfo,
1627    ToComputedValue,
1628    ToCss,
1629    ToResolvedValue,
1630    ToShmem,
1631    ToTyped,
1632)]
1633pub enum FontSynthesisStyle {
1634    /// This attribute may be synthesized if not supported by a face.
1635    Auto,
1636    /// Do not attempt to synthesis this style attribute.
1637    None,
1638    /// Allow synthesis for oblique, but not for italic.
1639    ObliqueOnly,
1640}
1641
1642#[derive(
1643    Clone,
1644    Debug,
1645    Eq,
1646    MallocSizeOf,
1647    PartialEq,
1648    SpecifiedValueInfo,
1649    ToComputedValue,
1650    ToResolvedValue,
1651    ToShmem,
1652    ToTyped,
1653)]
1654#[repr(C)]
1655#[typed(todo_derive_fields)]
1656/// Allows authors to choose a palette from those supported by a color font
1657/// (and potentially @font-palette-values overrides).
1658pub struct FontPalette(Atom);
1659
1660#[allow(missing_docs)]
1661impl FontPalette {
1662    pub fn normal() -> Self {
1663        Self(atom!("normal"))
1664    }
1665    pub fn light() -> Self {
1666        Self(atom!("light"))
1667    }
1668    pub fn dark() -> Self {
1669        Self(atom!("dark"))
1670    }
1671}
1672
1673impl Parse for FontPalette {
1674    /// normal | light | dark | dashed-ident
1675    fn parse(_context: &ParserContext, input: &mut Parser) -> Result<FontPalette, ParseError> {
1676        let ident = input.expect_ident()?;
1677        match_ignore_ascii_case! { &ident,
1678            "normal" => Ok(Self::normal()),
1679            "light" => Ok(Self::light()),
1680            "dark" => Ok(Self::dark()),
1681            _ => if ident.starts_with("--") {
1682                Ok(Self(Atom::from(ident.as_ref())))
1683            } else {
1684                Err(ParseError::custom(SelectorParseErrorKind::UnexpectedIdent))
1685            },
1686        }
1687    }
1688}
1689
1690impl ToCss for FontPalette {
1691    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
1692    where
1693        W: Write,
1694    {
1695        serialize_atom_identifier(&self.0, dest)
1696    }
1697}
1698
1699/// This property provides low-level control over OpenType or TrueType font
1700/// variations.
1701pub type FontVariationSettings = FontSettings<VariationValue<Number>>;
1702
1703fn parse_one_feature_value(
1704    context: &ParserContext,
1705    input: &mut Parser,
1706) -> Result<Integer, ParseError> {
1707    if let Ok(integer) = input.try_parse(|i| Integer::parse_non_negative(context, i)) {
1708        return Ok(integer);
1709    }
1710
1711    try_match_ident_ignore_ascii_case! { input,
1712        "on" => Ok(Integer::new(1)),
1713        "off" => Ok(Integer::new(0)),
1714    }
1715}
1716
1717impl Parse for FeatureTagValue<Integer> {
1718    /// https://drafts.csswg.org/css-fonts-4/#feature-tag-value
1719    fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ParseError> {
1720        let tag = FontTag::parse(context, input)?;
1721        let value = input
1722            .try_parse(|i| parse_one_feature_value(context, i))
1723            .unwrap_or_else(|_| Integer::new(1));
1724
1725        Ok(Self { tag, value })
1726    }
1727}
1728
1729impl Parse for VariationValue<Number> {
1730    /// This is the `<string> <number>` part of the font-variation-settings
1731    /// syntax.
1732    fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ParseError> {
1733        let tag = FontTag::parse(context, input)?;
1734        let value = Number::parse(context, input)?;
1735        Ok(Self { tag, value })
1736    }
1737}
1738
1739impl FontVariationSettings {
1740    /// Like `parse`, but rejects calc expressions that cannot be resolved at parse time,
1741    /// since @font-face descriptors require concrete values.
1742    pub fn parse_for_font_face_rule(
1743        context: &ParserContext,
1744        input: &mut Parser,
1745    ) -> Result<Self, ParseError> {
1746        let settings = FontVariationSettings::parse(context, input)?;
1747        if settings
1748            .0
1749            .iter()
1750            .any(|setting| setting.value.resolve().is_none())
1751        {
1752            return Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError));
1753        }
1754        Ok(settings)
1755    }
1756}
1757
1758/// A metrics override value for a @font-face descriptor
1759///
1760/// https://drafts.csswg.org/css-fonts/#font-metrics-override-desc
1761#[derive(Clone, Debug, MallocSizeOf, Parse, PartialEq, SpecifiedValueInfo, ToCss, ToShmem)]
1762pub enum MetricsOverride {
1763    /// A non-negative `<percentage>` of the computed font size
1764    Override(NonNegativePercentage),
1765    /// Normal metrics from the font.
1766    Normal,
1767}
1768
1769impl MetricsOverride {
1770    #[inline]
1771    /// Get default value with `normal`
1772    pub fn normal() -> MetricsOverride {
1773        MetricsOverride::Normal
1774    }
1775
1776    /// The ToComputedValue implementation, used for @font-face descriptors.
1777    ///
1778    /// Valid override percentages must be non-negative; we return -1.0 to indicate
1779    /// the absence of an override (i.e. 'normal'). Returns None if the value contains
1780    /// a calc expression that cannot be resolved at parse time.
1781    #[inline]
1782    pub fn compute(&self) -> Option<ComputedPercentage> {
1783        Some(ComputedPercentage(match self {
1784            MetricsOverride::Normal => -1.0,
1785            MetricsOverride::Override(percent) => percent.compute()?.0,
1786        }))
1787    }
1788}
1789
1790#[derive(
1791    Clone,
1792    Copy,
1793    Debug,
1794    Deserialize,
1795    MallocSizeOf,
1796    Parse,
1797    PartialEq,
1798    Serialize,
1799    SpecifiedValueInfo,
1800    ToComputedValue,
1801    ToCss,
1802    ToResolvedValue,
1803    ToShmem,
1804    ToTyped,
1805)]
1806#[repr(u8)]
1807/// How to do font-size scaling.
1808pub enum XTextScale {
1809    /// Both min-font-size and text zoom are enabled.
1810    All,
1811    /// Text-only zoom is enabled, but min-font-size is not honored.
1812    ZoomOnly,
1813    /// Neither of them is enabled.
1814    None,
1815}
1816
1817impl XTextScale {
1818    /// Returns whether text zoom is enabled.
1819    #[inline]
1820    pub fn text_zoom_enabled(self) -> bool {
1821        self != Self::None
1822    }
1823}
1824
1825#[derive(
1826    Clone,
1827    Debug,
1828    Deserialize,
1829    Eq,
1830    Hash,
1831    MallocSizeOf,
1832    PartialEq,
1833    Serialize,
1834    SpecifiedValueInfo,
1835    ToComputedValue,
1836    ToCss,
1837    ToResolvedValue,
1838    ToShmem,
1839    ToTyped,
1840)]
1841#[repr(transparent)]
1842/// Internal property that reflects the lang attribute
1843pub struct XLang(#[css(skip)] pub Atom);
1844
1845impl XLang {
1846    #[inline]
1847    /// Get default value for `-x-lang`
1848    pub fn get_initial_value() -> XLang {
1849        XLang(atom!(""))
1850    }
1851}
1852
1853impl Parse for XLang {
1854    fn parse(_: &ParserContext, _input: &mut Parser) -> Result<XLang, ParseError> {
1855        debug_assert!(
1856            false,
1857            "Should be set directly by presentation attributes only."
1858        );
1859        Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError))
1860    }
1861}
1862
1863#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss, ToShmem)]
1864/// Specifies the minimum font size allowed due to changes in scriptlevel.
1865/// Ref: https://wiki.mozilla.org/MathML:mstyle
1866pub struct MozScriptMinSize(pub NoCalcLength);
1867
1868impl MozScriptMinSize {
1869    #[inline]
1870    /// Calculate initial value of -moz-script-min-size.
1871    pub fn get_initial_value() -> Length {
1872        Length::new(DEFAULT_SCRIPT_MIN_SIZE_PT as f32 * PX_PER_PT)
1873    }
1874}
1875
1876impl Parse for MozScriptMinSize {
1877    fn parse(_: &ParserContext, _input: &mut Parser) -> Result<MozScriptMinSize, ParseError> {
1878        debug_assert!(
1879            false,
1880            "Should be set directly by presentation attributes only."
1881        );
1882        Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError))
1883    }
1884}
1885
1886/// A value for the `math-depth` property.
1887/// https://mathml-refresh.github.io/mathml-core/#the-math-script-level-property
1888#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss, ToShmem, ToTyped)]
1889pub enum MathDepth {
1890    /// Increment math-depth if math-style is compact.
1891    AutoAdd,
1892
1893    /// Add the function's argument to math-depth.
1894    #[css(function)]
1895    Add(Integer),
1896
1897    /// Set math-depth to the specified value.
1898    Absolute(Integer),
1899}
1900
1901impl Parse for MathDepth {
1902    fn parse(context: &ParserContext, input: &mut Parser) -> Result<MathDepth, ParseError> {
1903        if input
1904            .try_parse(|i| i.expect_ident_matching("auto-add"))
1905            .is_ok()
1906        {
1907            return Ok(MathDepth::AutoAdd);
1908        }
1909        if let Ok(math_depth_value) = input.try_parse(|input| Integer::parse(context, input)) {
1910            return Ok(MathDepth::Absolute(math_depth_value));
1911        }
1912        input.expect_function_matching("add")?;
1913        let math_depth_delta_value =
1914            input.parse_nested_block(|input| Integer::parse(context, input))?;
1915        Ok(MathDepth::Add(math_depth_delta_value))
1916    }
1917}
1918
1919#[derive(
1920    Clone,
1921    Copy,
1922    Debug,
1923    MallocSizeOf,
1924    PartialEq,
1925    SpecifiedValueInfo,
1926    ToComputedValue,
1927    ToCss,
1928    ToResolvedValue,
1929    ToShmem,
1930)]
1931/// Specifies the multiplier to be used to adjust font size
1932/// due to changes in scriptlevel.
1933///
1934/// Ref: https://www.w3.org/TR/MathML3/chapter3.html#presm.mstyle.attrs
1935pub struct MozScriptSizeMultiplier(pub f32);
1936
1937impl MozScriptSizeMultiplier {
1938    #[inline]
1939    /// Get default value of `-moz-script-size-multiplier`
1940    pub fn get_initial_value() -> MozScriptSizeMultiplier {
1941        MozScriptSizeMultiplier(DEFAULT_SCRIPT_SIZE_MULTIPLIER as f32)
1942    }
1943}
1944
1945impl Parse for MozScriptSizeMultiplier {
1946    fn parse(
1947        _: &ParserContext,
1948        _input: &mut Parser,
1949    ) -> Result<MozScriptSizeMultiplier, ParseError> {
1950        debug_assert!(
1951            false,
1952            "Should be set directly by presentation attributes only."
1953        );
1954        Err(ParseError::custom(StyleParseErrorKind::UnspecifiedError))
1955    }
1956}
1957
1958impl From<f32> for MozScriptSizeMultiplier {
1959    fn from(v: f32) -> Self {
1960        MozScriptSizeMultiplier(v)
1961    }
1962}
1963
1964impl From<MozScriptSizeMultiplier> for f32 {
1965    fn from(v: MozScriptSizeMultiplier) -> f32 {
1966        v.0
1967    }
1968}
1969
1970/// A specified value for the `line-height` property.
1971pub type LineHeight = GenericLineHeight<NonNegativeNumber, NonNegativeLengthPercentage>;
1972
1973/// Parses a line height <number> value. Percentages in <number>-typed calc expressions
1974/// are allowed in the `line-height` property, relative to the computed value of 1em.
1975/// https://drafts.csswg.org/css-inline/#line-height-property
1976fn parse_line_height_number(
1977    context: &ParserContext,
1978    input: &mut Parser,
1979) -> Result<NonNegativeNumber, ParseError> {
1980    parse_number_with_clamping_mode(
1981        context,
1982        input,
1983        AllowedNumericType::NonNegative,
1984        PercentageContext::allowed_with_hint(NumericBaseType::Length),
1985    )
1986    .map(NonNegative::<Number>)
1987}
1988
1989impl Parse for LineHeight {
1990    fn parse(context: &ParserContext, input: &mut Parser) -> Result<Self, ParseError> {
1991        if let Ok(v) = input.try_parse(|input| parse_line_height_number(context, input)) {
1992            return Ok(GenericLineHeight::Number(v));
1993        }
1994        if let Ok(v) = input.try_parse(|input| NonNegativeLengthPercentage::parse(context, input)) {
1995            return Ok(GenericLineHeight::Length(v));
1996        }
1997        let ident = input.expect_ident()?;
1998        match_ignore_ascii_case! { &ident,
1999            "normal" => Ok(GenericLineHeight::Normal),
2000            _ => Err(ParseError::custom(SelectorParseErrorKind::UnexpectedIdent)),
2001        }
2002    }
2003}
2004
2005/// Resolves a line-height length into an absolute pixel value, properly applying text
2006/// scaling and ensuring any `lh` lengths are resolved against the inherited line-height.
2007fn resolve_line_height_length(context: &Context, length: NoCalcLength) -> CSSPixelLength {
2008    let result = length.to_computed_value_with_base_size(
2009        context,
2010        FontBaseSize::CurrentStyle,
2011        LineHeightBase::InheritedStyle,
2012    );
2013    if length.should_zoom_text() {
2014        context.maybe_zoom_text(result)
2015    } else {
2016        result
2017    }
2018}
2019
2020/// Maps a line-height calc leaf into a resolved leaf. Percentages are replaced
2021/// with equivalent `em` lengths, and all lengths are resolved to absolute lengths.
2022fn map_line_height_leaf(context: &Context, leaf: &Leaf) -> Leaf {
2023    let length = match leaf {
2024        Leaf::Percentage(p) => NoCalcLength::from_em(p.get()),
2025        Leaf::Length(l) => *l,
2026        _ => return leaf.clone(),
2027    };
2028    Leaf::Length(NoCalcLength::from_px(
2029        resolve_line_height_length(context, length).px(),
2030    ))
2031}
2032
2033impl ToComputedValue for LineHeight {
2034    type ComputedValue = computed::LineHeight;
2035
2036    #[inline]
2037    fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
2038        match self {
2039            GenericLineHeight::Normal => GenericLineHeight::Normal,
2040            GenericLineHeight::Number(number) => {
2041                let value = match number.as_calc() {
2042                    None => number.to_computed_value(context).0,
2043                    Some(calc) => {
2044                        let resolved = calc
2045                            .node
2046                            .resolve_map(|leaf| Ok(map_line_height_leaf(context, leaf)));
2047                        let value = match resolved {
2048                            Ok(Leaf::Number(n)) => n.get(),
2049                            _ => {
2050                                debug_assert!(
2051                                    false,
2052                                    "Unexpected LineHeight number calc without resolved number"
2053                                );
2054                                f32::NAN
2055                            },
2056                        };
2057                        // The `NonNegative` clamping mode ensures that -infinity isn't produced
2058                        calc.clamping_mode
2059                            .clamp(crate::values::normalize(value).min(f32::MAX))
2060                    },
2061                };
2062                GenericLineHeight::Number(NonNegative(value))
2063            },
2064            GenericLineHeight::Length(non_negative_lp) => {
2065                let result = match non_negative_lp.0 {
2066                    LengthPercentage::Length(ref length) => {
2067                        resolve_line_height_length(context, *length)
2068                    },
2069                    LengthPercentage::Percentage(ref p) => {
2070                        resolve_line_height_length(context, NoCalcLength::from_em(p.get()))
2071                    },
2072                    LengthPercentage::Calc(ref calc) => calc
2073                        .to_computed_value_zoomed(
2074                            context,
2075                            FontBaseSize::CurrentStyle,
2076                            LineHeightBase::InheritedStyle,
2077                        )
2078                        .resolve(FontBaseSize::CurrentStyle.resolve(context).computed_size()),
2079                };
2080                GenericLineHeight::Length(result.into())
2081            },
2082        }
2083    }
2084
2085    #[inline]
2086    fn from_computed_value(computed: &Self::ComputedValue) -> Self {
2087        match *computed {
2088            GenericLineHeight::Normal => GenericLineHeight::Normal,
2089            GenericLineHeight::Number(ref number) => {
2090                GenericLineHeight::Number(NonNegativeNumber::from_computed_value(number))
2091            },
2092            GenericLineHeight::Length(ref length) => {
2093                GenericLineHeight::Length(NoCalcLength::from_computed_value(&length.0).into())
2094            },
2095        }
2096    }
2097}
2098
2099/// Flags for the query_font_metrics() function.
2100#[repr(C)]
2101pub struct QueryFontMetricsFlags(u8);
2102
2103bitflags! {
2104    impl QueryFontMetricsFlags: u8 {
2105        /// Should we use the user font set?
2106        const USE_USER_FONT_SET = 1 << 0;
2107        /// Does the caller need the `ch` unit (width of the ZERO glyph)?
2108        const NEEDS_CH = 1 << 1;
2109        /// Does the caller need the `ic` unit (width of the WATER ideograph)?
2110        const NEEDS_IC = 1 << 2;
2111        /// Does the caller need math scales to be retrieved?
2112        const NEEDS_MATH_SCALES = 1 << 3;
2113    }
2114}
2115
2116/// https://w3c.github.io/mathml-core/#the-math-shift
2117#[allow(missing_docs)]
2118#[derive(
2119    Clone,
2120    Copy,
2121    Debug,
2122    Deserialize,
2123    Eq,
2124    FromPrimitive,
2125    Hash,
2126    MallocSizeOf,
2127    Parse,
2128    PartialEq,
2129    Serialize,
2130    SpecifiedValueInfo,
2131    ToComputedValue,
2132    ToCss,
2133    ToResolvedValue,
2134    ToShmem,
2135    ToTyped,
2136)]
2137#[repr(u8)]
2138pub enum MathShift {
2139    Normal,
2140    Compact,
2141}
2142
2143/// https://mathml-refresh.github.io/mathml-core/#the-math-style-property
2144#[allow(missing_docs)]
2145#[derive(
2146    Clone,
2147    Copy,
2148    Debug,
2149    Deserialize,
2150    Eq,
2151    FromPrimitive,
2152    Hash,
2153    MallocSizeOf,
2154    Parse,
2155    PartialEq,
2156    Serialize,
2157    SpecifiedValueInfo,
2158    ToComputedValue,
2159    ToCss,
2160    ToResolvedValue,
2161    ToShmem,
2162    ToTyped,
2163)]
2164#[repr(u8)]
2165pub enum MathStyle {
2166    Normal,
2167    Compact,
2168}
2169
2170/// Internal (not web-exposed). Presentation attribute for legacy mathml mathvariant.
2171#[allow(missing_docs)]
2172#[derive(
2173    Clone,
2174    Copy,
2175    Debug,
2176    Deserialize,
2177    Eq,
2178    FromPrimitive,
2179    Hash,
2180    MallocSizeOf,
2181    Parse,
2182    PartialEq,
2183    Serialize,
2184    SpecifiedValueInfo,
2185    ToComputedValue,
2186    ToCss,
2187    ToResolvedValue,
2188    ToShmem,
2189    ToTyped,
2190)]
2191#[repr(u8)]
2192pub enum MathVariant {
2193    None,
2194    Normal,
2195    Bold,
2196    Italic,
2197    BoldItalic,
2198    Script,
2199    BoldScript,
2200    Fraktur,
2201    DoubleStruck,
2202    BoldFraktur,
2203    SansSerif,
2204    BoldSansSerif,
2205    SansSerifItalic,
2206    SansSerifBoldItalic,
2207    Monospace,
2208    Initial,
2209    Tailed,
2210    Looped,
2211    Stretched,
2212}
2213
2214/// https://drafts.csswg.org/css-fonts/#propdef-font-variant-emoji
2215#[allow(missing_docs)]
2216#[derive(
2217    Clone,
2218    Copy,
2219    Debug,
2220    Deserialize,
2221    Eq,
2222    FromPrimitive,
2223    Hash,
2224    MallocSizeOf,
2225    Parse,
2226    PartialEq,
2227    Serialize,
2228    SpecifiedValueInfo,
2229    ToComputedValue,
2230    ToCss,
2231    ToResolvedValue,
2232    ToShmem,
2233    ToTyped,
2234)]
2235#[repr(u8)]
2236pub enum FontVariantEmoji {
2237    Normal,
2238    Text,
2239    Emoji,
2240    Unicode,
2241}
2242
2243/// https://www.w3.org/TR/css-fonts-4/#font-optical-sizing-def
2244#[allow(missing_docs)]
2245#[derive(
2246    Clone,
2247    Copy,
2248    Debug,
2249    Deserialize,
2250    Eq,
2251    FromPrimitive,
2252    Hash,
2253    MallocSizeOf,
2254    Parse,
2255    PartialEq,
2256    Serialize,
2257    SpecifiedValueInfo,
2258    ToComputedValue,
2259    ToCss,
2260    ToResolvedValue,
2261    ToShmem,
2262    ToTyped,
2263)]
2264#[repr(u8)]
2265pub enum FontOpticalSizing {
2266    Auto,
2267    None,
2268}
2269
2270/// https://drafts.csswg.org/css-fonts/#propdef-font-kerning
2271#[allow(missing_docs)]
2272#[derive(
2273    Clone,
2274    Copy,
2275    Debug,
2276    Deserialize,
2277    Eq,
2278    FromPrimitive,
2279    Hash,
2280    MallocSizeOf,
2281    Parse,
2282    PartialEq,
2283    Serialize,
2284    SpecifiedValueInfo,
2285    ToComputedValue,
2286    ToCss,
2287    ToResolvedValue,
2288    ToShmem,
2289    ToTyped,
2290)]
2291#[repr(u8)]
2292pub enum FontKerning {
2293    Auto,
2294    None,
2295    Normal,
2296}
2297
2298/// Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/font-smooth)
2299#[allow(missing_docs)]
2300#[derive(
2301    Clone,
2302    Copy,
2303    Debug,
2304    Deserialize,
2305    Eq,
2306    FromPrimitive,
2307    Hash,
2308    MallocSizeOf,
2309    Parse,
2310    PartialEq,
2311    Serialize,
2312    SpecifiedValueInfo,
2313    ToComputedValue,
2314    ToCss,
2315    ToResolvedValue,
2316    ToShmem,
2317    ToTyped,
2318)]
2319#[repr(u8)]
2320pub enum FontSmoothing {
2321    Auto,
2322    #[cfg_attr(feature = "gecko", parse(aliases = "antialiased"))]
2323    Grayscale,
2324    SubpixelAntialiased,
2325}
2326
2327/// https://drafts.csswg.org/css-fonts/#propdef-font-variant-position
2328#[allow(missing_docs)]
2329#[derive(
2330    Clone,
2331    Copy,
2332    Debug,
2333    Deserialize,
2334    Eq,
2335    FromPrimitive,
2336    Hash,
2337    MallocSizeOf,
2338    Parse,
2339    PartialEq,
2340    Serialize,
2341    SpecifiedValueInfo,
2342    ToComputedValue,
2343    ToCss,
2344    ToResolvedValue,
2345    ToShmem,
2346    ToTyped,
2347)]
2348#[repr(u8)]
2349pub enum FontVariantPosition {
2350    Normal,
2351    Sub,
2352    Super,
2353}
2354
2355fn font_variant_caps_all_values_enabled(_: &ParserContext) -> bool {
2356    crate::pref!(
2357        "layout.css.font-variant-caps.all-values.enabled",
2358        gecko = true
2359    )
2360}
2361
2362/// https://drafts.csswg.org/css-fonts/#propdef-font-variant-caps
2363#[allow(missing_docs)]
2364#[derive(
2365    Clone,
2366    Copy,
2367    Debug,
2368    Deserialize,
2369    Eq,
2370    FromPrimitive,
2371    Hash,
2372    MallocSizeOf,
2373    Parse,
2374    PartialEq,
2375    Serialize,
2376    SpecifiedValueInfo,
2377    ToComputedValue,
2378    ToCss,
2379    ToResolvedValue,
2380    ToShmem,
2381    ToTyped,
2382)]
2383#[repr(u8)]
2384pub enum FontVariantCaps {
2385    Normal,
2386    SmallCaps,
2387    #[parse(condition = "font_variant_caps_all_values_enabled")]
2388    AllSmallCaps,
2389    #[parse(condition = "font_variant_caps_all_values_enabled")]
2390    PetiteCaps,
2391    #[parse(condition = "font_variant_caps_all_values_enabled")]
2392    AllPetiteCaps,
2393    #[parse(condition = "font_variant_caps_all_values_enabled")]
2394    Unicase,
2395    #[parse(condition = "font_variant_caps_all_values_enabled")]
2396    TitlingCaps,
2397}