Skip to main content

style/properties/
cascade.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//! The main cascading algorithm of the style system.
6
7use crate::applicable_declarations::CascadePriority;
8use crate::color::AbsoluteColor;
9use crate::computed_value_flags::ComputedValueFlags;
10use crate::custom_properties::{
11    CustomPropertiesBuilder, DeferFontRelativeCustomPropertyResolution,
12};
13use crate::dom::{AttributeTracker, TElement};
14#[cfg(feature = "gecko")]
15use crate::font_metrics::FontMetricsOrientation;
16use crate::logical_geometry::WritingMode;
17use crate::properties::{
18    property_counts, CSSWideKeyword, ComputedValues, DeclarationImportanceIterator, Importance,
19    LonghandId, LonghandIdSet, PrioritaryPropertyId, PropertyDeclaration, PropertyDeclarationId,
20    PropertyFlags, ShorthandsWithPropertyReferencesCache, StyleBuilder, CASCADE_PROPERTY,
21};
22use crate::rule_cache::{RuleCache, RuleCacheConditions};
23use crate::rule_tree::{CascadeLevel, StrongRuleNode};
24use crate::selector_parser::PseudoElement;
25use crate::shared_lock::StylesheetGuards;
26use crate::style_adjuster::StyleAdjuster;
27use crate::stylesheets::container_rule::ContainerSizeQuery;
28use crate::stylesheets::{layer_rule::LayerOrder, Origin};
29use crate::stylist::Stylist;
30#[cfg(feature = "gecko")]
31use crate::values::specified::length::FontBaseSize;
32use crate::values::specified::position::PositionTryFallbacksTryTactic;
33use crate::values::{computed, specified};
34use rustc_hash::FxHashMap;
35use servo_arc::Arc;
36use smallvec::SmallVec;
37use std::borrow::Cow;
38
39/// Whether we're resolving a style with the purposes of reparenting for ::first-line.
40#[derive(Copy, Clone)]
41#[allow(missing_docs)]
42pub enum FirstLineReparenting<'a> {
43    No,
44    Yes {
45        /// The style we're re-parenting for ::first-line. ::first-line only affects inherited
46        /// properties so we use this to avoid some work and also ensure correctness by copying the
47        /// reset structs from this style.
48        style_to_reparent: &'a ComputedValues,
49    },
50}
51
52/// Performs the CSS cascade, computing new styles for an element from its parent style.
53///
54/// The arguments are:
55///
56///   * `device`: Used to get the initial viewport and other external state.
57///
58///   * `rule_node`: The rule node in the tree that represent the CSS rules that
59///   matched.
60///
61///   * `parent_style`: The parent style, if applicable; if `None`, this is the root node.
62///
63/// Returns the computed values.
64///   * `flags`: Various flags.
65///
66pub fn cascade<E>(
67    stylist: &Stylist,
68    pseudo: Option<&PseudoElement>,
69    rule_node: &StrongRuleNode,
70    guards: &StylesheetGuards,
71    parent_style: Option<&ComputedValues>,
72    layout_parent_style: Option<&ComputedValues>,
73    first_line_reparenting: FirstLineReparenting,
74    try_tactic: &PositionTryFallbacksTryTactic,
75    visited_rules: Option<&StrongRuleNode>,
76    cascade_input_flags: ComputedValueFlags,
77    rule_cache: Option<&RuleCache>,
78    rule_cache_conditions: &mut RuleCacheConditions,
79    element: Option<E>,
80) -> Arc<ComputedValues>
81where
82    E: TElement,
83{
84    cascade_rules(
85        stylist,
86        pseudo,
87        rule_node,
88        guards,
89        parent_style,
90        layout_parent_style,
91        first_line_reparenting,
92        try_tactic,
93        CascadeMode::Unvisited { visited_rules },
94        cascade_input_flags,
95        rule_cache,
96        rule_cache_conditions,
97        element,
98    )
99}
100
101struct DeclarationIterator<'a> {
102    // Global to the iteration.
103    guards: &'a StylesheetGuards<'a>,
104    restriction: Option<PropertyFlags>,
105    // The rule we're iterating over.
106    current_rule_node: Option<&'a StrongRuleNode>,
107    // Per rule state.
108    declarations: DeclarationImportanceIterator<'a>,
109    origin: Origin,
110    importance: Importance,
111    priority: CascadePriority,
112}
113
114impl<'a> DeclarationIterator<'a> {
115    #[inline]
116    fn new(
117        rule_node: &'a StrongRuleNode,
118        guards: &'a StylesheetGuards,
119        pseudo: Option<&PseudoElement>,
120    ) -> Self {
121        let restriction = pseudo.and_then(|p| p.property_restriction());
122        let mut iter = Self {
123            guards,
124            current_rule_node: Some(rule_node),
125            origin: Origin::UserAgent,
126            importance: Importance::Normal,
127            priority: CascadePriority::new(CascadeLevel::UANormal, LayerOrder::root()),
128            declarations: DeclarationImportanceIterator::default(),
129            restriction,
130        };
131        iter.update_for_node(rule_node);
132        iter
133    }
134
135    fn update_for_node(&mut self, node: &'a StrongRuleNode) {
136        self.priority = node.cascade_priority();
137        let level = self.priority.cascade_level();
138        self.origin = level.origin();
139        self.importance = level.importance();
140        let guard = match self.origin {
141            Origin::Author => self.guards.author,
142            Origin::User | Origin::UserAgent => self.guards.ua_or_user,
143        };
144        self.declarations = match node.style_source() {
145            Some(source) => source.read(guard).declaration_importance_iter(),
146            None => DeclarationImportanceIterator::default(),
147        };
148    }
149}
150
151impl<'a> Iterator for DeclarationIterator<'a> {
152    type Item = (&'a PropertyDeclaration, CascadePriority);
153
154    #[inline]
155    fn next(&mut self) -> Option<Self::Item> {
156        loop {
157            if let Some((decl, importance)) = self.declarations.next_back() {
158                if self.importance != importance {
159                    continue;
160                }
161
162                if let Some(restriction) = self.restriction {
163                    // decl.id() is either a longhand or a custom
164                    // property.  Custom properties are always allowed, but
165                    // longhands are only allowed if they have our
166                    // restriction flag set.
167                    if let PropertyDeclarationId::Longhand(id) = decl.id() {
168                        if !id.flags().contains(restriction) && self.origin != Origin::UserAgent {
169                            continue;
170                        }
171                    }
172                }
173
174                return Some((decl, self.priority));
175            }
176
177            let next_node = self.current_rule_node.take()?.parent()?;
178            self.current_rule_node = Some(next_node);
179            self.update_for_node(next_node);
180        }
181    }
182}
183
184fn cascade_rules<E>(
185    stylist: &Stylist,
186    pseudo: Option<&PseudoElement>,
187    rule_node: &StrongRuleNode,
188    guards: &StylesheetGuards,
189    parent_style: Option<&ComputedValues>,
190    layout_parent_style: Option<&ComputedValues>,
191    first_line_reparenting: FirstLineReparenting,
192    try_tactic: &PositionTryFallbacksTryTactic,
193    cascade_mode: CascadeMode,
194    cascade_input_flags: ComputedValueFlags,
195    rule_cache: Option<&RuleCache>,
196    rule_cache_conditions: &mut RuleCacheConditions,
197    element: Option<E>,
198) -> Arc<ComputedValues>
199where
200    E: TElement,
201{
202    apply_declarations(
203        stylist,
204        pseudo,
205        rule_node,
206        guards,
207        DeclarationIterator::new(rule_node, guards, pseudo),
208        parent_style,
209        layout_parent_style,
210        first_line_reparenting,
211        try_tactic,
212        cascade_mode,
213        cascade_input_flags,
214        rule_cache,
215        rule_cache_conditions,
216        element,
217    )
218}
219
220/// Whether we're cascading for visited or unvisited styles.
221#[derive(Clone, Copy)]
222pub enum CascadeMode<'a, 'b> {
223    /// We're cascading for unvisited styles.
224    Unvisited {
225        /// The visited rules that should match the visited style.
226        visited_rules: Option<&'a StrongRuleNode>,
227    },
228    /// We're cascading for visited styles.
229    Visited {
230        /// The cascade for our unvisited style.
231        unvisited_context: &'a computed::Context<'b>,
232    },
233}
234
235fn iter_declarations<'builder, 'decls: 'builder>(
236    iter: impl Iterator<Item = (&'decls PropertyDeclaration, CascadePriority)>,
237    declarations: &mut Declarations<'decls>,
238    mut custom_builder: Option<&mut CustomPropertiesBuilder<'builder, 'decls>>,
239    attribute_tracker: &mut AttributeTracker,
240) {
241    for (declaration, priority) in iter {
242        if let PropertyDeclaration::Custom(ref declaration) = *declaration {
243            if let Some(ref mut builder) = custom_builder {
244                builder.cascade(declaration, priority, attribute_tracker);
245            }
246        } else {
247            let id = declaration.id().as_longhand().unwrap();
248            declarations.note_declaration(declaration, priority, id);
249            if CustomPropertiesBuilder::might_have_non_custom_dependency(id, declaration) {
250                if let Some(ref mut builder) = custom_builder {
251                    builder.maybe_note_non_custom_dependency(id, declaration);
252                }
253            }
254        }
255    }
256}
257
258/// NOTE: This function expects the declaration with more priority to appear
259/// first.
260pub fn apply_declarations<'a, E, I>(
261    stylist: &'a Stylist,
262    pseudo: Option<&'a PseudoElement>,
263    rules: &StrongRuleNode,
264    guards: &StylesheetGuards,
265    iter: I,
266    parent_style: Option<&'a ComputedValues>,
267    layout_parent_style: Option<&ComputedValues>,
268    first_line_reparenting: FirstLineReparenting<'a>,
269    try_tactic: &'a PositionTryFallbacksTryTactic,
270    cascade_mode: CascadeMode,
271    cascade_input_flags: ComputedValueFlags,
272    rule_cache: Option<&'a RuleCache>,
273    rule_cache_conditions: &'a mut RuleCacheConditions,
274    element: Option<E>,
275) -> Arc<ComputedValues>
276where
277    E: TElement + 'a,
278    I: Iterator<Item = (&'a PropertyDeclaration, CascadePriority)>,
279{
280    debug_assert!(layout_parent_style.is_none() || parent_style.is_some());
281    let device = stylist.device();
282    let inherited_style = parent_style.unwrap_or(device.default_computed_values());
283    let is_root_element = pseudo.is_none() && element.map_or(false, |e| e.is_root());
284
285    let container_size_query =
286        ContainerSizeQuery::for_option_element(element, Some(inherited_style), pseudo.is_some());
287
288    let mut context = computed::Context::new(
289        // We'd really like to own the rules here to avoid refcount traffic, but
290        // animation's usage of `apply_declarations` make this tricky. See bug
291        // 1375525.
292        StyleBuilder::new(
293            device,
294            Some(stylist),
295            parent_style,
296            pseudo,
297            Some(rules.clone()),
298            is_root_element,
299        ),
300        stylist.quirks_mode(),
301        rule_cache_conditions,
302        container_size_query,
303    );
304
305    context.style().add_flags(cascade_input_flags);
306
307    let using_cached_reset_properties;
308    let ignore_colors = context.builder.device.forced_colors().is_active();
309    let mut cascade = Cascade::new(first_line_reparenting, try_tactic, ignore_colors);
310    let mut declarations = Default::default();
311    let mut shorthand_cache = ShorthandsWithPropertyReferencesCache::default();
312    let mut attribute_tracker = match element {
313        Some(ref attr_provider) => AttributeTracker::new(attr_provider),
314        None => AttributeTracker::new_dummy(),
315    };
316    let properties_to_apply = match cascade_mode {
317        CascadeMode::Visited { unvisited_context } => {
318            context.builder.custom_properties = unvisited_context.builder.custom_properties.clone();
319            context.builder.writing_mode = unvisited_context.builder.writing_mode;
320            context.builder.color_scheme = unvisited_context.builder.color_scheme;
321            // We never insert visited styles into the cache so we don't need to try looking it up.
322            // It also wouldn't be super-profitable, only a handful :visited properties are
323            // non-inherited.
324            using_cached_reset_properties = false;
325            // TODO(bug 1859385): If we match the same rules when visited and unvisited, we could
326            // try to avoid gathering the declarations. That'd be:
327            //      unvisited_context.builder.rules.as_ref() == Some(rules)
328            iter_declarations(iter, &mut declarations, None, &mut attribute_tracker);
329
330            LonghandIdSet::visited_dependent()
331        },
332        CascadeMode::Unvisited { visited_rules } => {
333            let deferred_custom_properties = {
334                let mut builder = CustomPropertiesBuilder::new(stylist, &mut context);
335                iter_declarations(
336                    iter,
337                    &mut declarations,
338                    Some(&mut builder),
339                    &mut attribute_tracker,
340                );
341                // Detect cycles, remove properties participating in them, and resolve properties, except:
342                // * Registered custom properties that depend on font-relative properties (Resolved)
343                //   when prioritary properties are resolved), and
344                // * Any property that, in turn, depend on properties like above.
345                builder.build(
346                    DeferFontRelativeCustomPropertyResolution::Yes,
347                    &mut attribute_tracker,
348                )
349            };
350
351            // Resolve prioritary properties - Guaranteed to not fall into a cycle with existing custom
352            // properties.
353            cascade.apply_prioritary_properties(
354                &mut context,
355                &declarations,
356                &mut shorthand_cache,
357                &mut attribute_tracker,
358            );
359
360            // Resolve the deferred custom properties.
361            if let Some(deferred) = deferred_custom_properties {
362                CustomPropertiesBuilder::build_deferred(
363                    deferred,
364                    stylist,
365                    &mut context,
366                    &mut attribute_tracker,
367                );
368            }
369
370            if let Some(visited_rules) = visited_rules {
371                cascade.compute_visited_style_if_needed(
372                    &mut context,
373                    element,
374                    parent_style,
375                    layout_parent_style,
376                    visited_rules,
377                    guards,
378                );
379            }
380
381            using_cached_reset_properties = cascade.try_to_use_cached_reset_properties(
382                &mut context.builder,
383                rule_cache,
384                guards,
385            );
386
387            if using_cached_reset_properties {
388                LonghandIdSet::late_group_only_inherited()
389            } else {
390                LonghandIdSet::late_group()
391            }
392        },
393    };
394
395    cascade.apply_non_prioritary_properties(
396        &mut context,
397        &declarations.longhand_declarations,
398        &mut shorthand_cache,
399        &properties_to_apply,
400        &mut attribute_tracker,
401    );
402
403    context.builder.attribute_references = attribute_tracker.finalize();
404
405    cascade.finished_applying_properties(&mut context.builder);
406
407    std::mem::drop(cascade);
408
409    context.builder.clear_modified_reset();
410
411    if matches!(cascade_mode, CascadeMode::Unvisited { .. }) {
412        StyleAdjuster::new(&mut context.builder).adjust(
413            layout_parent_style.unwrap_or(inherited_style),
414            element,
415            try_tactic,
416        );
417    }
418
419    if context.builder.modified_reset() || using_cached_reset_properties {
420        // If we adjusted any reset structs, we can't cache this ComputedValues.
421        //
422        // Also, if we re-used existing reset structs, don't bother caching it back again. (Aside
423        // from being wasted effort, it will be wrong, since context.rule_cache_conditions won't be
424        // set appropriately if we didn't compute those reset properties.)
425        context.rule_cache_conditions.borrow_mut().set_uncacheable();
426    }
427
428    context.builder.build()
429}
430
431/// For ignored colors mode, we sometimes want to do something equivalent to
432/// "revert-or-initial", where we `revert` for a given origin, but then apply a
433/// given initial value if nothing in other origins did override it.
434///
435/// This is a bit of a clunky way of achieving this.
436type DeclarationsToApplyUnlessOverriden = SmallVec<[PropertyDeclaration; 2]>;
437
438fn tweak_when_ignoring_colors(
439    context: &computed::Context,
440    longhand_id: LonghandId,
441    origin: Origin,
442    declaration: &mut Cow<PropertyDeclaration>,
443    declarations_to_apply_unless_overridden: &mut DeclarationsToApplyUnlessOverriden,
444) {
445    use crate::values::computed::ToComputedValue;
446    use crate::values::specified::Color;
447
448    if !longhand_id.ignored_when_document_colors_disabled() {
449        return;
450    }
451
452    let is_ua_or_user_rule = matches!(origin, Origin::User | Origin::UserAgent);
453    if is_ua_or_user_rule {
454        return;
455    }
456
457    // Always honor colors if forced-color-adjust is set to none.
458    #[cfg(feature = "gecko")]
459    {
460        let forced = context
461            .builder
462            .get_inherited_text()
463            .clone_forced_color_adjust();
464        if forced == computed::ForcedColorAdjust::None {
465            return;
466        }
467    }
468
469    fn alpha_channel(color: &Color, context: &computed::Context) -> f32 {
470        // We assume here currentColor is opaque.
471        color
472            .to_computed_value(context)
473            .resolve_to_absolute(&AbsoluteColor::BLACK)
474            .alpha
475    }
476
477    // A few special-cases ahead.
478    match **declaration {
479        // Honor CSS-wide keywords like unset / revert / initial...
480        PropertyDeclaration::CSSWideKeyword(..) => return,
481        PropertyDeclaration::BackgroundColor(ref color) => {
482            // We honor system colors and transparent colors unconditionally.
483            //
484            // NOTE(emilio): We honor transparent unconditionally, like we do
485            // for color, even though it causes issues like bug 1625036. The
486            // reasoning is that the conditions that trigger that (having
487            // mismatched widget and default backgrounds) are both uncommon, and
488            // broken in other applications as well, and not honoring
489            // transparent makes stuff uglier or break unconditionally
490            // (bug 1666059, bug 1755713).
491            if color.honored_in_forced_colors_mode(/* allow_transparent = */ true) {
492                return;
493            }
494            // For background-color, we revert or initial-with-preserved-alpha
495            // otherwise, this is needed to preserve semi-transparent
496            // backgrounds.
497            let alpha = alpha_channel(color, context);
498            if alpha == 0.0 {
499                return;
500            }
501            let mut color = context.builder.device.default_background_color();
502            color.alpha = alpha;
503            declarations_to_apply_unless_overridden
504                .push(PropertyDeclaration::BackgroundColor(color.into()))
505        },
506        PropertyDeclaration::Color(ref color) => {
507            // We honor color: transparent and system colors.
508            if color
509                .0
510                .honored_in_forced_colors_mode(/* allow_transparent = */ true)
511            {
512                return;
513            }
514            // If the inherited color would be transparent, but we would
515            // override this with a non-transparent color, then override it with
516            // the default color. Otherwise just let it inherit through.
517            if context
518                .builder
519                .get_parent_inherited_text()
520                .clone_color()
521                .alpha
522                == 0.0
523            {
524                let color = context.builder.device.default_color();
525                declarations_to_apply_unless_overridden.push(PropertyDeclaration::Color(
526                    specified::ColorPropertyValue(color.into()),
527                ))
528            }
529        },
530        // We honor url background-images if backplating.
531        #[cfg(feature = "gecko")]
532        PropertyDeclaration::BackgroundImage(ref bkg) => {
533            use crate::values::generics::image::Image;
534            if static_prefs::pref!("browser.display.permit_backplate") {
535                if bkg
536                    .0
537                    .iter()
538                    .all(|image| matches!(*image, Image::Url(..) | Image::None))
539                {
540                    return;
541                }
542            }
543        },
544        _ => {
545            // We honor system colors more generally for all colors.
546            //
547            // We used to honor transparent but that causes accessibility
548            // regressions like bug 1740924.
549            //
550            // NOTE(emilio): This doesn't handle caret-color and accent-color
551            // because those use a slightly different syntax (<color> | auto for
552            // example).
553            //
554            // That's probably fine though, as using a system color for
555            // caret-color doesn't make sense (using currentColor is fine), and
556            // we ignore accent-color in high-contrast-mode anyways.
557            if let Some(color) = declaration.color_value() {
558                if color.honored_in_forced_colors_mode(/* allow_transparent = */ false) {
559                    return;
560                }
561            }
562        },
563    }
564
565    *declaration.to_mut() =
566        PropertyDeclaration::css_wide_keyword(longhand_id, CSSWideKeyword::Revert);
567}
568
569/// We track the index only for prioritary properties. For other properties we can just iterate.
570type DeclarationIndex = u16;
571
572/// "Prioritary" properties are properties that other properties depend on in one way or another.
573///
574/// We keep track of their position in the declaration vector, in order to be able to cascade them
575/// separately in precise order.
576#[derive(Copy, Clone)]
577struct PrioritaryDeclarationPosition {
578    // DeclarationIndex::MAX signals no index.
579    most_important: DeclarationIndex,
580    least_important: DeclarationIndex,
581}
582
583impl Default for PrioritaryDeclarationPosition {
584    fn default() -> Self {
585        Self {
586            most_important: DeclarationIndex::MAX,
587            least_important: DeclarationIndex::MAX,
588        }
589    }
590}
591
592#[derive(Copy, Clone)]
593struct Declaration<'a> {
594    decl: &'a PropertyDeclaration,
595    priority: CascadePriority,
596    next_index: DeclarationIndex,
597}
598
599/// The set of property declarations from our rules.
600#[derive(Default)]
601struct Declarations<'a> {
602    /// Whether we have any prioritary property. This is just a minor optimization.
603    has_prioritary_properties: bool,
604    /// A list of all the applicable longhand declarations.
605    longhand_declarations: SmallVec<[Declaration<'a>; 64]>,
606    /// The prioritary property position data.
607    prioritary_positions: [PrioritaryDeclarationPosition; property_counts::PRIORITARY],
608}
609
610impl<'a> Declarations<'a> {
611    fn note_prioritary_property(&mut self, id: PrioritaryPropertyId) {
612        let new_index = self.longhand_declarations.len();
613        if new_index >= DeclarationIndex::MAX as usize {
614            // This prioritary property is past the amount of declarations we can track. Let's give
615            // up applying it to prevent getting confused.
616            return;
617        }
618
619        self.has_prioritary_properties = true;
620        let new_index = new_index as DeclarationIndex;
621        let position = &mut self.prioritary_positions[id as usize];
622        if position.most_important == DeclarationIndex::MAX {
623            // We still haven't seen this property, record the current position as the most
624            // prioritary index.
625            position.most_important = new_index;
626        } else {
627            // Let the previous item in the list know about us.
628            self.longhand_declarations[position.least_important as usize].next_index = new_index;
629        }
630        position.least_important = new_index;
631    }
632
633    fn note_declaration(
634        &mut self,
635        decl: &'a PropertyDeclaration,
636        priority: CascadePriority,
637        id: LonghandId,
638    ) {
639        if let Some(id) = PrioritaryPropertyId::from_longhand(id) {
640            self.note_prioritary_property(id);
641        }
642        self.longhand_declarations.push(Declaration {
643            decl,
644            priority,
645            next_index: 0,
646        });
647    }
648}
649
650struct Cascade<'b> {
651    first_line_reparenting: FirstLineReparenting<'b>,
652    try_tactic: &'b PositionTryFallbacksTryTactic,
653    ignore_colors: bool,
654    seen: LonghandIdSet,
655    author_specified: LonghandIdSet,
656    reverted_set: LonghandIdSet,
657    reverted: FxHashMap<LonghandId, (CascadePriority, bool)>,
658    declarations_to_apply_unless_overridden: DeclarationsToApplyUnlessOverriden,
659}
660
661impl<'b> Cascade<'b> {
662    fn new(
663        first_line_reparenting: FirstLineReparenting<'b>,
664        try_tactic: &'b PositionTryFallbacksTryTactic,
665        ignore_colors: bool,
666    ) -> Self {
667        Self {
668            first_line_reparenting,
669            try_tactic,
670            ignore_colors,
671            seen: LonghandIdSet::default(),
672            author_specified: LonghandIdSet::default(),
673            reverted_set: Default::default(),
674            reverted: Default::default(),
675            declarations_to_apply_unless_overridden: Default::default(),
676        }
677    }
678
679    fn substitute_variables_if_needed<'cache, 'decl>(
680        &self,
681        context: &mut computed::Context,
682        shorthand_cache: &'cache mut ShorthandsWithPropertyReferencesCache,
683        declaration: &'decl PropertyDeclaration,
684        attribute_tracker: &mut AttributeTracker,
685    ) -> Cow<'decl, PropertyDeclaration>
686    where
687        'cache: 'decl,
688    {
689        let declaration = match *declaration {
690            PropertyDeclaration::WithVariables(ref declaration) => declaration,
691            ref d => return Cow::Borrowed(d),
692        };
693
694        if !declaration.id.inherited() {
695            context.rule_cache_conditions.borrow_mut().set_uncacheable();
696
697            // NOTE(emilio): We only really need to add the `display` /
698            // `content` flag if the CSS variable has not been specified on our
699            // declarations, but we don't have that information at this point,
700            // and it doesn't seem like an important enough optimization to
701            // warrant it.
702            match declaration.id {
703                LonghandId::Display => {
704                    context
705                        .builder
706                        .add_flags(ComputedValueFlags::DISPLAY_DEPENDS_ON_INHERITED_STYLE);
707                },
708                LonghandId::Content => {
709                    context
710                        .builder
711                        .add_flags(ComputedValueFlags::CONTENT_DEPENDS_ON_INHERITED_STYLE);
712                },
713                _ => {},
714            }
715        }
716
717        debug_assert!(
718            context.builder.stylist.is_some(),
719            "Need a Stylist to substitute variables!"
720        );
721        declaration.value.substitute_variables(
722            declaration.id,
723            context.builder.custom_properties(),
724            context.builder.stylist.unwrap(),
725            context,
726            shorthand_cache,
727            attribute_tracker,
728        )
729    }
730
731    fn apply_one_prioritary_property(
732        &mut self,
733        context: &mut computed::Context,
734        decls: &Declarations,
735        cache: &mut ShorthandsWithPropertyReferencesCache,
736        id: PrioritaryPropertyId,
737        attr_provider: &mut AttributeTracker,
738    ) -> bool {
739        let mut index = decls.prioritary_positions[id as usize].most_important;
740        if index == DeclarationIndex::MAX {
741            return false;
742        }
743
744        let longhand_id = id.to_longhand();
745        debug_assert!(
746            !longhand_id.is_logical(),
747            "That could require more book-keeping"
748        );
749        loop {
750            let decl = decls.longhand_declarations[index as usize];
751            self.apply_one_longhand(
752                context,
753                longhand_id,
754                decl.decl,
755                decl.priority,
756                cache,
757                attr_provider,
758            );
759            if self.seen.contains(longhand_id) {
760                return true; // Common case, we're done.
761            }
762            debug_assert!(
763                self.reverted_set.contains(longhand_id),
764                "How else can we fail to apply a prioritary property?"
765            );
766            debug_assert!(
767                decl.next_index == 0 || decl.next_index > index,
768                "should make progress! {} -> {}",
769                index,
770                decl.next_index,
771            );
772            index = decl.next_index;
773            if index == 0 {
774                break;
775            }
776        }
777        false
778    }
779
780    fn apply_prioritary_properties(
781        &mut self,
782        context: &mut computed::Context,
783        decls: &Declarations,
784        cache: &mut ShorthandsWithPropertyReferencesCache,
785        attribute_tracker: &mut AttributeTracker,
786    ) {
787        // Keeps apply_one_prioritary_property calls readable, considering the repititious
788        // arguments.
789        macro_rules! apply {
790            ($prop:ident) => {
791                self.apply_one_prioritary_property(
792                    context,
793                    decls,
794                    cache,
795                    PrioritaryPropertyId::$prop,
796                    attribute_tracker,
797                )
798            };
799        }
800
801        if !decls.has_prioritary_properties {
802            return;
803        }
804
805        let has_writing_mode = apply!(WritingMode) | apply!(Direction);
806        #[cfg(feature = "gecko")]
807        let has_writing_mode = has_writing_mode | apply!(TextOrientation);
808
809        if has_writing_mode {
810            context.builder.writing_mode = WritingMode::new(context.builder.get_inherited_box())
811        }
812
813        if apply!(Zoom) {
814            context.builder.recompute_effective_zooms();
815            if !context.builder.effective_zoom_for_inheritance.is_one() {
816                // NOTE(emilio): This is a bit of a hack, but matches the shipped WebKit and Blink
817                // behavior for now. Ideally, in the future, we have a pass over all
818                // implicitly-or-explicitly-inherited properties that can contain lengths and
819                // re-compute them properly, see https://github.com/w3c/csswg-drafts/issues/9397.
820                // TODO(emilio): we need to eagerly do this for line-height as well, probably.
821                self.recompute_font_size_for_zoom_change(&mut context.builder);
822            }
823        }
824
825        // Compute font-family.
826        let has_font_family = apply!(FontFamily);
827        let has_lang = apply!(XLang);
828        #[cfg(feature = "gecko")]
829        {
830            if has_lang {
831                self.recompute_initial_font_family_if_needed(&mut context.builder);
832            }
833            if has_font_family {
834                self.prioritize_user_fonts_if_needed(&mut context.builder);
835            }
836
837            // Compute font-size.
838            if apply!(XTextScale) {
839                self.unzoom_fonts_if_needed(&mut context.builder);
840            }
841            let has_font_size = apply!(FontSize);
842            let has_math_depth = apply!(MathDepth);
843            let has_min_font_size_ratio = apply!(MozMinFontSizeRatio);
844
845            if has_math_depth && has_font_size {
846                self.recompute_math_font_size_if_needed(context);
847            }
848            if has_lang || has_font_family {
849                self.recompute_keyword_font_size_if_needed(context);
850            }
851            if has_font_size || has_min_font_size_ratio || has_lang || has_font_family {
852                self.constrain_font_size_if_needed(&mut context.builder);
853            }
854        }
855
856        #[cfg(feature = "servo")]
857        {
858            apply!(FontSize);
859            if has_lang || has_font_family {
860                self.recompute_keyword_font_size_if_needed(context);
861            }
862        }
863
864        // Compute the rest of the first-available-font-affecting properties.
865        apply!(FontWeight);
866        apply!(FontStretch);
867        apply!(FontStyle);
868        #[cfg(feature = "gecko")]
869        apply!(FontSizeAdjust);
870
871        #[cfg(feature = "gecko")]
872        apply!(ForcedColorAdjust);
873        // color-scheme needs to be after forced-color-adjust, since it's one of the "skipped in
874        // forced-colors-mode" properties.
875        if apply!(ColorScheme) {
876            context.builder.color_scheme = context.builder.get_inherited_ui().color_scheme_bits();
877        }
878        apply!(LineHeight);
879    }
880
881    fn apply_non_prioritary_properties(
882        &mut self,
883        context: &mut computed::Context,
884        longhand_declarations: &[Declaration],
885        shorthand_cache: &mut ShorthandsWithPropertyReferencesCache,
886        properties_to_apply: &LonghandIdSet,
887        attribute_tracker: &mut AttributeTracker,
888    ) {
889        debug_assert!(!properties_to_apply.contains_any(LonghandIdSet::prioritary_properties()));
890        debug_assert!(self.declarations_to_apply_unless_overridden.is_empty());
891        for declaration in &*longhand_declarations {
892            let mut longhand_id = declaration.decl.id().as_longhand().unwrap();
893            if !properties_to_apply.contains(longhand_id) {
894                continue;
895            }
896            debug_assert!(PrioritaryPropertyId::from_longhand(longhand_id).is_none());
897            let is_logical = longhand_id.is_logical();
898            if is_logical {
899                let wm = context.builder.writing_mode;
900                context
901                    .rule_cache_conditions
902                    .borrow_mut()
903                    .set_writing_mode_dependency(wm);
904                longhand_id = longhand_id.to_physical(wm);
905            }
906            self.apply_one_longhand(
907                context,
908                longhand_id,
909                declaration.decl,
910                declaration.priority,
911                shorthand_cache,
912                attribute_tracker,
913            );
914        }
915        if !self.declarations_to_apply_unless_overridden.is_empty() {
916            debug_assert!(self.ignore_colors);
917            for declaration in std::mem::take(&mut self.declarations_to_apply_unless_overridden) {
918                let longhand_id = declaration.id().as_longhand().unwrap();
919                debug_assert!(!longhand_id.is_logical());
920                if !self.seen.contains(longhand_id) {
921                    unsafe {
922                        self.do_apply_declaration(context, longhand_id, &declaration);
923                    }
924                }
925            }
926        }
927
928        if !context.builder.effective_zoom_for_inheritance.is_one() {
929            self.recompute_zoom_dependent_inherited_lengths(context);
930        }
931    }
932
933    #[cold]
934    fn recompute_zoom_dependent_inherited_lengths(&self, context: &mut computed::Context) {
935        debug_assert!(self.seen.contains(LonghandId::Zoom));
936        for prop in LonghandIdSet::zoom_dependent_inherited_properties().iter() {
937            if self.seen.contains(prop) {
938                continue;
939            }
940            let declaration = PropertyDeclaration::css_wide_keyword(prop, CSSWideKeyword::Inherit);
941            unsafe {
942                self.do_apply_declaration(context, prop, &declaration);
943            }
944        }
945    }
946
947    fn apply_one_longhand(
948        &mut self,
949        context: &mut computed::Context,
950        longhand_id: LonghandId,
951        declaration: &PropertyDeclaration,
952        priority: CascadePriority,
953        cache: &mut ShorthandsWithPropertyReferencesCache,
954        attribute_tracker: &mut AttributeTracker,
955    ) {
956        debug_assert!(!longhand_id.is_logical());
957        let origin = priority.cascade_level().origin();
958        if self.seen.contains(longhand_id) {
959            return;
960        }
961
962        if self.reverted_set.contains(longhand_id) {
963            if let Some(&(reverted_priority, is_origin_revert)) = self.reverted.get(&longhand_id) {
964                if !reverted_priority.allows_when_reverted(&priority, is_origin_revert) {
965                    return;
966                }
967            }
968        }
969
970        let mut declaration =
971            self.substitute_variables_if_needed(context, cache, declaration, attribute_tracker);
972
973        // When document colors are disabled, do special handling of
974        // properties that are marked as ignored in that mode.
975        if self.ignore_colors {
976            tweak_when_ignoring_colors(
977                context,
978                longhand_id,
979                origin,
980                &mut declaration,
981                &mut self.declarations_to_apply_unless_overridden,
982            );
983        }
984        let can_skip_apply = match declaration.get_css_wide_keyword() {
985            Some(keyword) => {
986                if matches!(
987                    keyword,
988                    CSSWideKeyword::RevertLayer | CSSWideKeyword::Revert
989                ) {
990                    let origin_revert = keyword == CSSWideKeyword::Revert;
991                    // We intentionally don't want to insert it into `self.seen`, `reverted` takes
992                    // care of rejecting other declarations as needed.
993                    self.reverted_set.insert(longhand_id);
994                    self.reverted.insert(longhand_id, (priority, origin_revert));
995                    return;
996                }
997
998                let inherited = longhand_id.inherited();
999                let zoomed = !context.builder.effective_zoom_for_inheritance.is_one()
1000                    && longhand_id.zoom_dependent();
1001                match keyword {
1002                    CSSWideKeyword::Revert | CSSWideKeyword::RevertLayer => unreachable!(),
1003                    CSSWideKeyword::Unset => !zoomed || !inherited,
1004                    CSSWideKeyword::Inherit => inherited && !zoomed,
1005                    CSSWideKeyword::Initial => !inherited,
1006                }
1007            },
1008            None => false,
1009        };
1010
1011        self.seen.insert(longhand_id);
1012        if origin == Origin::Author {
1013            self.author_specified.insert(longhand_id);
1014        }
1015
1016        if !can_skip_apply {
1017            // Set context.scope to this declaration's cascade level so that
1018            // tree-scoped properties (anchor-name, position-anchor, anchor-scope)
1019            // get the correct scope when converted to computed values.
1020            let old_scope = context.scope;
1021            let cascade_level = priority.cascade_level();
1022            context.scope = cascade_level;
1023            unsafe { self.do_apply_declaration(context, longhand_id, &declaration) }
1024            context.scope = old_scope;
1025        }
1026    }
1027
1028    #[inline]
1029    unsafe fn do_apply_declaration(
1030        &self,
1031        context: &mut computed::Context,
1032        longhand_id: LonghandId,
1033        declaration: &PropertyDeclaration,
1034    ) {
1035        debug_assert!(!longhand_id.is_logical());
1036        // We could (and used to) use a pattern match here, but that bloats this
1037        // function to over 100K of compiled code!
1038        //
1039        // To improve i-cache behavior, we outline the individual functions and
1040        // use virtual dispatch instead.
1041        (CASCADE_PROPERTY[longhand_id as usize])(&declaration, context);
1042    }
1043
1044    fn compute_visited_style_if_needed<E>(
1045        &self,
1046        context: &mut computed::Context,
1047        element: Option<E>,
1048        parent_style: Option<&ComputedValues>,
1049        layout_parent_style: Option<&ComputedValues>,
1050        visited_rules: &StrongRuleNode,
1051        guards: &StylesheetGuards,
1052    ) where
1053        E: TElement,
1054    {
1055        let is_link = context.builder.pseudo.is_none() && element.unwrap().is_link();
1056
1057        macro_rules! visited_parent {
1058            ($parent:expr) => {
1059                if is_link {
1060                    $parent
1061                } else {
1062                    $parent.map(|p| p.visited_style().unwrap_or(p))
1063                }
1064            };
1065        }
1066
1067        // We could call apply_declarations directly, but that'd cause
1068        // another instantiation of this function which is not great.
1069        let style = cascade_rules(
1070            context.builder.stylist.unwrap(),
1071            context.builder.pseudo,
1072            visited_rules,
1073            guards,
1074            visited_parent!(parent_style),
1075            visited_parent!(layout_parent_style),
1076            self.first_line_reparenting,
1077            self.try_tactic,
1078            CascadeMode::Visited {
1079                unvisited_context: &*context,
1080            },
1081            // Cascade input flags don't matter for the visited style, they are
1082            // in the main (unvisited) style.
1083            Default::default(),
1084            // The rule cache doesn't care about caching :visited
1085            // styles, we cache the unvisited style instead. We still do
1086            // need to set the caching dependencies properly if present
1087            // though, so the cache conditions need to match.
1088            None, // rule_cache
1089            &mut *context.rule_cache_conditions.borrow_mut(),
1090            element,
1091        );
1092        context.builder.visited_style = Some(style);
1093    }
1094
1095    fn finished_applying_properties(&self, builder: &mut StyleBuilder) {
1096        #[cfg(feature = "gecko")]
1097        {
1098            if let Some(bg) = builder.get_background_if_mutated() {
1099                bg.fill_arrays();
1100            }
1101
1102            if let Some(svg) = builder.get_svg_if_mutated() {
1103                svg.fill_arrays();
1104            }
1105        }
1106
1107        if self
1108            .author_specified
1109            .contains_any(LonghandIdSet::border_background_properties())
1110        {
1111            builder.add_flags(ComputedValueFlags::HAS_AUTHOR_SPECIFIED_BORDER_BACKGROUND);
1112        }
1113
1114        if self.author_specified.contains(LonghandId::FontFamily) {
1115            builder.add_flags(ComputedValueFlags::HAS_AUTHOR_SPECIFIED_FONT_FAMILY);
1116        }
1117
1118        if self.author_specified.contains(LonghandId::Color) {
1119            builder.add_flags(ComputedValueFlags::HAS_AUTHOR_SPECIFIED_TEXT_COLOR);
1120        }
1121
1122        if self.author_specified.contains(LonghandId::TextShadow) {
1123            builder.add_flags(ComputedValueFlags::HAS_AUTHOR_SPECIFIED_TEXT_SHADOW);
1124        }
1125
1126        if self.author_specified.contains(LonghandId::LetterSpacing) {
1127            builder.add_flags(ComputedValueFlags::HAS_AUTHOR_SPECIFIED_LETTER_SPACING);
1128        }
1129
1130        if self.author_specified.contains(LonghandId::WordSpacing) {
1131            builder.add_flags(ComputedValueFlags::HAS_AUTHOR_SPECIFIED_WORD_SPACING);
1132        }
1133
1134        if self
1135            .author_specified
1136            .contains(LonghandId::FontSynthesisWeight)
1137        {
1138            builder.add_flags(ComputedValueFlags::HAS_AUTHOR_SPECIFIED_FONT_SYNTHESIS_WEIGHT);
1139        }
1140
1141        #[cfg(feature = "gecko")]
1142        if self
1143            .author_specified
1144            .contains(LonghandId::FontSynthesisStyle)
1145        {
1146            builder.add_flags(ComputedValueFlags::HAS_AUTHOR_SPECIFIED_FONT_SYNTHESIS_STYLE);
1147        }
1148
1149        #[cfg(feature = "servo")]
1150        {
1151            if let Some(font) = builder.get_font_if_mutated() {
1152                font.compute_font_hash();
1153            }
1154        }
1155    }
1156
1157    fn try_to_use_cached_reset_properties(
1158        &self,
1159        builder: &mut StyleBuilder<'b>,
1160        cache: Option<&'b RuleCache>,
1161        guards: &StylesheetGuards,
1162    ) -> bool {
1163        let style = match self.first_line_reparenting {
1164            FirstLineReparenting::Yes { style_to_reparent } => style_to_reparent,
1165            FirstLineReparenting::No => {
1166                let Some(cache) = cache else { return false };
1167                let Some(style) = cache.find(guards, builder) else {
1168                    return false;
1169                };
1170                style
1171            },
1172        };
1173
1174        builder.copy_reset_from(style);
1175
1176        // We're using the same reset style as another element, and we'll skip
1177        // applying the relevant properties. So we need to do the relevant
1178        // bookkeeping here to keep these bits correct.
1179        //
1180        // Note that the border/background properties are non-inherited, so we
1181        // don't need to do anything else other than just copying the bits over.
1182        //
1183        // When using this optimization, we also need to copy whether the old
1184        // style specified viewport units / used font-relative lengths, this one
1185        // would as well.  It matches the same rules, so it is the right thing
1186        // to do anyways, even if it's only used on inherited properties.
1187        let bits_to_copy = ComputedValueFlags::HAS_AUTHOR_SPECIFIED_BORDER_BACKGROUND
1188            | ComputedValueFlags::DEPENDS_ON_SELF_FONT_METRICS
1189            | ComputedValueFlags::DEPENDS_ON_INHERITED_FONT_METRICS
1190            | ComputedValueFlags::USES_CONTAINER_UNITS
1191            | ComputedValueFlags::USES_VIEWPORT_UNITS;
1192        builder.add_flags(style.flags & bits_to_copy);
1193
1194        true
1195    }
1196
1197    /// The initial font depends on the current lang group so we may need to
1198    /// recompute it if the language changed.
1199    #[inline]
1200    #[cfg(feature = "gecko")]
1201    fn recompute_initial_font_family_if_needed(&self, builder: &mut StyleBuilder) {
1202        use crate::gecko_bindings::bindings;
1203        use crate::values::computed::font::FontFamily;
1204
1205        let default_font_type = {
1206            let font = builder.get_font();
1207
1208            if !font.mFont.family.is_initial {
1209                return;
1210            }
1211
1212            let default_font_type = unsafe {
1213                bindings::Gecko_nsStyleFont_ComputeFallbackFontTypeForLanguage(
1214                    builder.device.document(),
1215                    font.mLanguage.mRawPtr,
1216                )
1217            };
1218
1219            let initial_generic = font.mFont.family.families.single_generic();
1220            debug_assert!(
1221                initial_generic.is_some(),
1222                "Initial font should be just one generic font"
1223            );
1224            if initial_generic == Some(default_font_type) {
1225                return;
1226            }
1227
1228            default_font_type
1229        };
1230
1231        // NOTE: Leaves is_initial untouched.
1232        builder.mutate_font().mFont.family.families =
1233            FontFamily::generic(default_font_type).families.clone();
1234    }
1235
1236    /// Prioritize user fonts if needed by pref.
1237    #[inline]
1238    #[cfg(feature = "gecko")]
1239    fn prioritize_user_fonts_if_needed(&self, builder: &mut StyleBuilder) {
1240        use crate::gecko_bindings::bindings;
1241
1242        // Check the use_document_fonts setting for content, but for chrome
1243        // documents they're treated as always enabled.
1244        if static_prefs::pref!("browser.display.use_document_fonts") != 0
1245            || builder.device.chrome_rules_enabled_for_document()
1246        {
1247            return;
1248        }
1249
1250        let default_font_type = {
1251            let font = builder.get_font();
1252
1253            if font.mFont.family.is_system_font {
1254                return;
1255            }
1256
1257            if !font.mFont.family.families.needs_user_font_prioritization() {
1258                return;
1259            }
1260
1261            unsafe {
1262                bindings::Gecko_nsStyleFont_ComputeFallbackFontTypeForLanguage(
1263                    builder.device.document(),
1264                    font.mLanguage.mRawPtr,
1265                )
1266            }
1267        };
1268
1269        let font = builder.mutate_font();
1270        font.mFont
1271            .family
1272            .families
1273            .prioritize_first_generic_or_prepend(default_font_type);
1274    }
1275
1276    /// Some keyword sizes depend on the font family and language.
1277    fn recompute_keyword_font_size_if_needed(&self, context: &mut computed::Context) {
1278        use crate::values::computed::ToComputedValue;
1279
1280        if !self.seen.contains(LonghandId::XLang) && !self.seen.contains(LonghandId::FontFamily) {
1281            return;
1282        }
1283
1284        let new_size = {
1285            let font = context.builder.get_font();
1286            let info = font.clone_font_size().keyword_info;
1287            let new_size = match info.kw {
1288                specified::FontSizeKeyword::None => return,
1289                _ => {
1290                    context.for_non_inherited_property = false;
1291                    specified::FontSize::Keyword(info).to_computed_value(context)
1292                },
1293            };
1294
1295            #[cfg(feature = "gecko")]
1296            if font.mScriptUnconstrainedSize == new_size.computed_size {
1297                return;
1298            }
1299
1300            new_size
1301        };
1302
1303        context.builder.mutate_font().set_font_size(new_size);
1304    }
1305
1306    /// Some properties, plus setting font-size itself, may make us go out of
1307    /// our minimum font-size range.
1308    #[cfg(feature = "gecko")]
1309    fn constrain_font_size_if_needed(&self, builder: &mut StyleBuilder) {
1310        use crate::gecko_bindings::bindings;
1311        use crate::values::generics::NonNegative;
1312
1313        let min_font_size = {
1314            let font = builder.get_font();
1315            let min_font_size = unsafe {
1316                bindings::Gecko_nsStyleFont_ComputeMinSize(&**font, builder.device.document())
1317            };
1318
1319            if font.mFont.size.0 >= min_font_size {
1320                return;
1321            }
1322
1323            NonNegative(min_font_size)
1324        };
1325
1326        builder.mutate_font().mFont.size = min_font_size;
1327    }
1328
1329    /// <svg:text> is not affected by text zoom, and it uses a preshint to disable it. We fix up
1330    /// the struct when this happens by unzooming its contained font values, which will have been
1331    /// zoomed in the parent.
1332    #[cfg(feature = "gecko")]
1333    fn unzoom_fonts_if_needed(&self, builder: &mut StyleBuilder) {
1334        debug_assert!(self.seen.contains(LonghandId::XTextScale));
1335
1336        let parent_text_scale = builder.get_parent_font().clone__x_text_scale();
1337        let text_scale = builder.get_font().clone__x_text_scale();
1338        if parent_text_scale == text_scale {
1339            return;
1340        }
1341        debug_assert_ne!(
1342            parent_text_scale.text_zoom_enabled(),
1343            text_scale.text_zoom_enabled(),
1344            "There's only one value that disables it"
1345        );
1346        debug_assert!(
1347            !text_scale.text_zoom_enabled(),
1348            "We only ever disable text zoom never enable it"
1349        );
1350        let device = builder.device;
1351        builder.mutate_font().unzoom_fonts(device);
1352    }
1353
1354    fn recompute_font_size_for_zoom_change(&self, builder: &mut StyleBuilder) {
1355        debug_assert!(self.seen.contains(LonghandId::Zoom));
1356        // NOTE(emilio): Intentionally not using the effective zoom here, since all the inherited
1357        // zooms are already applied.
1358        let old_size = builder.get_font().clone_font_size();
1359        let new_size = old_size.zoom(builder.effective_zoom_for_inheritance);
1360        if old_size == new_size {
1361            return;
1362        }
1363        builder.mutate_font().set_font_size(new_size);
1364    }
1365
1366    /// Special handling of font-size: math (used for MathML).
1367    /// https://w3c.github.io/mathml-core/#the-math-script-level-property
1368    /// TODO: Bug: 1548471: MathML Core also does not specify a script min size
1369    /// should we unship that feature or standardize it?
1370    #[cfg(feature = "gecko")]
1371    fn recompute_math_font_size_if_needed(&self, context: &mut computed::Context) {
1372        use crate::values::generics::NonNegative;
1373
1374        // Do not do anything if font-size: math or math-depth is not set.
1375        if context.builder.get_font().clone_font_size().keyword_info.kw
1376            != specified::FontSizeKeyword::Math
1377        {
1378            return;
1379        }
1380
1381        const SCALE_FACTOR_WHEN_INCREMENTING_MATH_DEPTH_BY_ONE: f32 = 0.71;
1382
1383        // Helper function that calculates the scale factor applied to font-size
1384        // when math-depth goes from parent_math_depth to computed_math_depth.
1385        // This function is essentially a modification of the MathML3's formula
1386        // 0.71^(parent_math_depth - computed_math_depth) so that a scale factor
1387        // of parent_script_percent_scale_down is applied when math-depth goes
1388        // from 0 to 1 and parent_script_script_percent_scale_down is applied
1389        // when math-depth goes from 0 to 2. This is also a straightforward
1390        // implementation of the specification's algorithm:
1391        // https://w3c.github.io/mathml-core/#the-math-script-level-property
1392        fn scale_factor_for_math_depth_change(
1393            parent_math_depth: i32,
1394            computed_math_depth: i32,
1395            parent_script_percent_scale_down: Option<f32>,
1396            parent_script_script_percent_scale_down: Option<f32>,
1397        ) -> f32 {
1398            let mut a = parent_math_depth;
1399            let mut b = computed_math_depth;
1400            let c = SCALE_FACTOR_WHEN_INCREMENTING_MATH_DEPTH_BY_ONE;
1401            let scale_between_0_and_1 = parent_script_percent_scale_down.unwrap_or_else(|| c);
1402            let scale_between_0_and_2 =
1403                parent_script_script_percent_scale_down.unwrap_or_else(|| c * c);
1404            let mut s = 1.0;
1405            let mut invert_scale_factor = false;
1406            if a == b {
1407                return s;
1408            }
1409            if b < a {
1410                std::mem::swap(&mut a, &mut b);
1411                invert_scale_factor = true;
1412            }
1413            let mut e = b - a;
1414            if a <= 0 && b >= 2 {
1415                s *= scale_between_0_and_2;
1416                e -= 2;
1417            } else if a == 1 {
1418                s *= scale_between_0_and_2 / scale_between_0_and_1;
1419                e -= 1;
1420            } else if b == 1 {
1421                s *= scale_between_0_and_1;
1422                e -= 1;
1423            }
1424            s *= (c as f32).powi(e);
1425            if invert_scale_factor {
1426                1.0 / s.max(f32::MIN_POSITIVE)
1427            } else {
1428                s
1429            }
1430        }
1431
1432        let (new_size, new_unconstrained_size) = {
1433            use crate::values::specified::font::QueryFontMetricsFlags;
1434
1435            let builder = &context.builder;
1436            let font = builder.get_font();
1437            let parent_font = builder.get_parent_font();
1438
1439            let delta = font.mMathDepth.saturating_sub(parent_font.mMathDepth);
1440
1441            if delta == 0 {
1442                return;
1443            }
1444
1445            let mut min = parent_font.mScriptMinSize;
1446            if font.mXTextScale.text_zoom_enabled() {
1447                min = builder.device.zoom_text(min);
1448            }
1449
1450            // Calculate scale factor following MathML Core's algorithm.
1451            let scale = {
1452                // Script scale factors are independent of orientation.
1453                let font_metrics = context.query_font_metrics(
1454                    FontBaseSize::InheritedStyle,
1455                    FontMetricsOrientation::Horizontal,
1456                    QueryFontMetricsFlags::NEEDS_MATH_SCALES,
1457                );
1458                scale_factor_for_math_depth_change(
1459                    parent_font.mMathDepth as i32,
1460                    font.mMathDepth as i32,
1461                    font_metrics.script_percent_scale_down,
1462                    font_metrics.script_script_percent_scale_down,
1463                )
1464            };
1465
1466            let parent_size = parent_font.mSize.0;
1467            let parent_unconstrained_size = parent_font.mScriptUnconstrainedSize.0;
1468            let new_size = parent_size.scale_by(scale);
1469            let new_unconstrained_size = parent_unconstrained_size.scale_by(scale);
1470
1471            if scale <= 1. {
1472                // The parent size can be smaller than scriptminsize, e.g. if it
1473                // was specified explicitly. Don't scale in this case, but we
1474                // don't want to set it to scriptminsize either since that will
1475                // make it larger.
1476                if parent_size <= min {
1477                    (parent_size, new_unconstrained_size)
1478                } else {
1479                    (min.max(new_size), new_unconstrained_size)
1480                }
1481            } else {
1482                // If the new unconstrained size is larger than the min size,
1483                // this means we have escaped the grasp of scriptminsize and can
1484                // revert to using the unconstrained size.
1485                // However, if the new size is even larger (perhaps due to usage
1486                // of em units), use that instead.
1487                (
1488                    new_size.min(new_unconstrained_size.max(min)),
1489                    new_unconstrained_size,
1490                )
1491            }
1492        };
1493        let font = context.builder.mutate_font();
1494        font.mFont.size = NonNegative(new_size);
1495        font.mSize = NonNegative(new_size);
1496        font.mScriptUnconstrainedSize = NonNegative(new_unconstrained_size);
1497    }
1498}