Skip to main content

style/invalidation/
stylesheets.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//! A collection of invalidations due to changes in which stylesheets affect a
6//! document.
7
8#![deny(unsafe_code)]
9
10use crate::Atom;
11use crate::LocalName as SelectorLocalName;
12use crate::context::QuirksMode;
13use crate::data::ElementData;
14use crate::derives::*;
15use crate::device::Device;
16use crate::dom::{TDocument, TElement, TNode};
17use crate::invalidation::element::element_wrapper::{ElementSnapshot, ElementWrapper, Snapshots};
18use crate::invalidation::element::restyle_hints::RestyleHint;
19use crate::selector_map::{MaybeCaseInsensitiveHashMap, PrecomputedHashMap, PrecomputedHashSet};
20use crate::selector_parser::{SelectorImpl, Snapshot, SnapshotMap};
21use crate::shared_lock::SharedRwLockReadGuard;
22use crate::simple_buckets_map::SimpleBucketsMap;
23use crate::stylesheets::{
24    CssRule, CssRuleRef, CustomMediaMap, EffectiveRules, EffectiveRulesIterator,
25    StylesheetInDocument,
26};
27use crate::stylist::CascadeDataDifference;
28use crate::values::AtomIdent;
29use crate::values::specified::position::PositionTryFallbacksItem;
30use selectors::parser::{Component, LocalName, Selector};
31
32/// The kind of change that happened for a given rule.
33#[repr(u32)]
34#[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, PartialEq)]
35pub enum RuleChangeKind {
36    /// Some change in the rule which we don't know about, and could have made
37    /// the rule change in any way.
38    Generic = 0,
39    /// The rule was inserted.
40    Insertion,
41    /// The rule was removed.
42    Removal,
43    /// A change in the declarations of a style rule.
44    StyleRuleDeclarations,
45    /// A change in the declarations of an @position-try rule.
46    PositionTryDeclarations,
47}
48
49/// A style sheet invalidation represents a kind of element or subtree that may
50/// need to be restyled. Whether it represents a whole subtree or just a single
51/// element is determined by the given InvalidationKind in
52/// StylesheetInvalidationSet's maps.
53#[derive(Clone, Copy, Debug, Eq, PartialEq)]
54enum Invalidation<'a> {
55    /// An element with a given id.
56    ID(&'a AtomIdent),
57    /// An element with a given class name.
58    Class(&'a AtomIdent),
59    /// An element with a given local name.
60    LocalName {
61        name: &'a SelectorLocalName,
62        lower_name: &'a SelectorLocalName,
63    },
64}
65
66impl Invalidation<'_> {
67    fn is_id(&self) -> bool {
68        matches!(*self, Invalidation::ID(..))
69    }
70
71    fn is_id_or_class(&self) -> bool {
72        matches!(*self, Invalidation::ID(..) | Invalidation::Class(..))
73    }
74}
75
76/// Whether we should invalidate just the element, or the whole subtree within
77/// it.
78#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, Ord, PartialEq, PartialOrd)]
79enum InvalidationKind {
80    None = 0,
81    Element,
82    Scope,
83}
84
85impl std::ops::BitOrAssign for InvalidationKind {
86    #[inline]
87    fn bitor_assign(&mut self, other: Self) {
88        *self = std::cmp::max(*self, other);
89    }
90}
91
92impl InvalidationKind {
93    #[inline]
94    fn is_scope(self) -> bool {
95        matches!(self, Self::Scope)
96    }
97
98    #[inline]
99    fn add(&mut self, other: Option<&InvalidationKind>) {
100        if let Some(other) = other {
101            *self |= *other;
102        }
103    }
104}
105
106/// A set of invalidations due to stylesheet changes.
107///
108/// TODO(emilio): We might be able to do the same analysis for media query changes too (or even
109/// selector changes?) specially now that we take the cascade data difference into account.
110#[derive(Debug, Default, MallocSizeOf)]
111pub struct StylesheetInvalidationSet {
112    buckets: SimpleBucketsMap<InvalidationKind>,
113    style_fully_invalid: bool,
114    /// The difference between the old and new cascade data, incrementally collected until flush()
115    /// returns it.
116    pub cascade_data_difference: CascadeDataDifference,
117}
118
119impl StylesheetInvalidationSet {
120    /// Create an empty `StylesheetInvalidationSet`.
121    pub fn new() -> Self {
122        Default::default()
123    }
124
125    /// Mark the DOM tree styles' as fully invalid.
126    pub fn invalidate_fully(&mut self) {
127        debug!("StylesheetInvalidationSet::invalidate_fully");
128        self.buckets.clear();
129        self.style_fully_invalid = true;
130    }
131
132    /// Analyze the given stylesheet, and collect invalidations from their rules, in order to avoid
133    /// doing a full restyle when we style the document next time.
134    pub fn collect_invalidations_for<S>(
135        &mut self,
136        device: &Device,
137        custom_media: &CustomMediaMap,
138        stylesheet: &S,
139        guard: &SharedRwLockReadGuard,
140    ) where
141        S: StylesheetInDocument,
142    {
143        debug!("StylesheetInvalidationSet::collect_invalidations_for");
144        if self.style_fully_invalid {
145            debug!(" > Fully invalid already");
146            return;
147        }
148
149        if !stylesheet.enabled() || !stylesheet.is_effective_for_device(device, custom_media, guard)
150        {
151            debug!(" > Stylesheet was not effective");
152            return; // Nothing to do here.
153        }
154
155        let quirks_mode = device.quirks_mode();
156        for rule in stylesheet
157            .contents(guard)
158            .effective_rules(device, custom_media, guard)
159        {
160            self.collect_invalidations_for_rule(
161                rule,
162                guard,
163                device,
164                quirks_mode,
165                /* is_generic_change = */ false,
166                // Note(dshin): Technically, the iterator should provide the ancestor chain as it
167                // traverses down, but it shouldn't make a difference.
168                &[],
169            );
170            if self.style_fully_invalid {
171                break;
172            }
173        }
174
175        debug!(
176            " > resulting class invalidations: {:?}",
177            self.buckets.classes
178        );
179        debug!(" > resulting id invalidations: {:?}", self.buckets.ids);
180        debug!(
181            " > resulting local name invalidations: {:?}",
182            self.buckets.local_names
183        );
184        debug!(" > style_fully_invalid: {}", self.style_fully_invalid);
185    }
186
187    /// Returns whether there's no invalidation to process.
188    pub fn is_empty(&self) -> bool {
189        !self.style_fully_invalid
190            && self.buckets.is_empty()
191            && self.cascade_data_difference.is_empty()
192    }
193
194    fn invalidation_kind_for<E>(
195        &self,
196        element: E,
197        snapshot: Option<&Snapshot>,
198        quirks_mode: QuirksMode,
199    ) -> InvalidationKind
200    where
201        E: TElement,
202    {
203        debug_assert!(!self.style_fully_invalid);
204
205        let mut kind = InvalidationKind::None;
206
207        if !self.buckets.classes.is_empty() {
208            element.each_class(|c| {
209                kind.add(self.buckets.classes.get(c, quirks_mode));
210            });
211
212            if kind.is_scope() {
213                return kind;
214            }
215
216            if let Some(snapshot) = snapshot {
217                snapshot.each_class(|c| {
218                    kind.add(self.buckets.classes.get(c, quirks_mode));
219                });
220
221                if kind.is_scope() {
222                    return kind;
223                }
224            }
225        }
226
227        if !self.buckets.ids.is_empty() {
228            if let Some(id) = element.id() {
229                kind.add(self.buckets.ids.get(id, quirks_mode));
230                if kind.is_scope() {
231                    return kind;
232                }
233            }
234
235            if let Some(old_id) = snapshot.and_then(|s| s.id_attr()) {
236                kind.add(self.buckets.ids.get(old_id, quirks_mode));
237                if kind.is_scope() {
238                    return kind;
239                }
240            }
241        }
242
243        if !self.buckets.local_names.is_empty() {
244            kind.add(self.buckets.local_names.get(element.local_name()));
245        }
246
247        kind
248    }
249
250    /// Processes the style invalidation set, invalidating elements as needed.
251    /// Returns true if any style invalidations occurred.
252    pub fn process_style<E>(&self, root: E, snapshots: Option<&SnapshotMap>) -> bool
253    where
254        E: TElement,
255    {
256        debug!(
257            "StylesheetInvalidationSet::process_style({root:?}, snapshots: {})",
258            snapshots.is_some()
259        );
260
261        {
262            let mut data = match root.mutate_data() {
263                Some(data) => data,
264                None => return false,
265            };
266
267            if self.style_fully_invalid || self.cascade_data_difference.layer_order_changed {
268                debug!(
269                    "fully_invalid = {}, layer_order_changed = {}",
270                    self.style_fully_invalid, self.cascade_data_difference.layer_order_changed,
271                );
272                data.hint.insert(RestyleHint::restyle_subtree());
273                return true;
274            }
275        }
276
277        if self.buckets.is_empty() {
278            debug!("process_invalidations: empty invalidation set");
279            return false;
280        }
281
282        let quirks_mode = root.as_node().owner_doc().quirks_mode();
283        let snapshots = snapshots.map(Snapshots::new);
284        self.process_invalidations_in_subtree(root, snapshots.as_ref(), quirks_mode)
285    }
286
287    /// Process style invalidations in a given subtree. This traverses the
288    /// subtree looking for elements that match the invalidations in our hash
289    /// map members.
290    ///
291    /// Returns whether it invalidated at least one element's style.
292    #[allow(unsafe_code)]
293    fn process_invalidations_in_subtree<E>(
294        &self,
295        element: E,
296        snapshots: Option<&Snapshots>,
297        quirks_mode: QuirksMode,
298    ) -> bool
299    where
300        E: TElement,
301    {
302        debug!("process_invalidations_in_subtree({:?})", element);
303        let mut data = match element.mutate_data() {
304            Some(data) => data,
305            None => return false,
306        };
307
308        if !data.has_styles() {
309            return false;
310        }
311
312        if data.hint.contains_subtree() {
313            debug!(
314                "process_invalidations_in_subtree: {:?} was already invalid",
315                element
316            );
317            return false;
318        }
319
320        let element_wrapper = snapshots.map(|s| ElementWrapper::new(element, s));
321        let snapshot = element_wrapper.as_ref().and_then(|e| e.snapshot());
322
323        match self.invalidation_kind_for(element, snapshot, quirks_mode) {
324            InvalidationKind::None => {},
325            InvalidationKind::Element => {
326                debug!(
327                    "process_invalidations_in_subtree: {:?} matched self",
328                    element
329                );
330                data.hint.insert(RestyleHint::RESTYLE_SELF);
331            },
332            InvalidationKind::Scope => {
333                debug!(
334                    "process_invalidations_in_subtree: {:?} matched subtree",
335                    element
336                );
337                data.hint.insert(RestyleHint::restyle_subtree());
338                return true;
339            },
340        }
341
342        let mut any_children_invalid = false;
343
344        for child in element.traversal_children() {
345            let child = match child.as_element() {
346                Some(e) => e,
347                None => continue,
348            };
349
350            any_children_invalid |=
351                self.process_invalidations_in_subtree(child, snapshots, quirks_mode);
352        }
353
354        if any_children_invalid {
355            debug!(
356                "Children of {:?} changed, setting dirty descendants",
357                element
358            );
359            unsafe { element.set_dirty_descendants() }
360        }
361
362        data.hint.contains(RestyleHint::RESTYLE_SELF) || any_children_invalid
363    }
364
365    /// TODO(emilio): Reuse the bucket stuff from selectormap? That handles :is() / :where() etc.
366    fn scan_component<'a>(
367        component: &'a Component<SelectorImpl>,
368        invalidation: &mut Option<Invalidation<'a>>,
369    ) {
370        match *component {
371            Component::LocalName(LocalName {
372                ref name,
373                ref lower_name,
374            }) => {
375                if invalidation.is_none() {
376                    *invalidation = Some(Invalidation::LocalName { name, lower_name });
377                }
378            },
379            Component::Class(ref class) => {
380                if invalidation.is_none_or(|s| !s.is_id_or_class()) {
381                    *invalidation = Some(Invalidation::Class(class));
382                }
383            },
384            Component::ID(ref id) if invalidation.is_none_or(|s| !s.is_id()) => {
385                *invalidation = Some(Invalidation::ID(id));
386            },
387            _ => {
388                // Ignore everything else, at least for now.
389            },
390        }
391    }
392
393    /// Collect invalidations for a given selector.
394    ///
395    /// We look at the outermost local name, class, or ID selector to the left
396    /// of an ancestor combinator, in order to restyle only a given subtree.
397    ///
398    /// If the selector has no ancestor combinator, then we do the same for
399    /// the only sequence it has, but record it as an element invalidation
400    /// instead of a subtree invalidation.
401    ///
402    /// We prefer IDs to classs, and classes to local names, on the basis
403    /// that the former should be more specific than the latter. We also
404    /// prefer to generate subtree invalidations for the outermost part
405    /// of the selector, to reduce the amount of traversal we need to do
406    /// when flushing invalidations.
407    fn collect_invalidations(
408        &mut self,
409        selector: &Selector<SelectorImpl>,
410        quirks_mode: QuirksMode,
411    ) {
412        debug!(
413            "StylesheetInvalidationSet::collect_invalidations({:?})",
414            selector
415        );
416
417        let mut element_invalidation: Option<Invalidation> = None;
418        let mut subtree_invalidation: Option<Invalidation> = None;
419
420        let mut scan_for_element_invalidation = true;
421        let mut scan_for_subtree_invalidation = false;
422
423        let mut iter = selector.iter();
424
425        loop {
426            for component in &mut iter {
427                if scan_for_element_invalidation {
428                    Self::scan_component(component, &mut element_invalidation);
429                } else if scan_for_subtree_invalidation {
430                    Self::scan_component(component, &mut subtree_invalidation);
431                }
432            }
433            match iter.next_sequence() {
434                None => break,
435                Some(combinator) => {
436                    scan_for_subtree_invalidation = combinator.is_ancestor();
437                },
438            }
439            scan_for_element_invalidation = false;
440        }
441
442        if let Some(s) = subtree_invalidation {
443            debug!(" > Found subtree invalidation: {:?}", s);
444            if self.insert_invalidation(s, InvalidationKind::Scope, quirks_mode) {
445                return;
446            }
447        }
448
449        if let Some(s) = element_invalidation {
450            debug!(" > Found element invalidation: {:?}", s);
451            if self.insert_invalidation(s, InvalidationKind::Element, quirks_mode) {
452                return;
453            }
454        }
455
456        // The selector was of a form that we can't handle. Any element could
457        // match it, so let's just bail out.
458        debug!(" > Can't handle selector or OOMd, marking fully invalid");
459        self.invalidate_fully()
460    }
461
462    fn insert_invalidation(
463        &mut self,
464        invalidation: Invalidation,
465        kind: InvalidationKind,
466        quirks_mode: QuirksMode,
467    ) -> bool {
468        fn insert_atom(
469            map: &mut MaybeCaseInsensitiveHashMap<Atom, InvalidationKind>,
470            key: &AtomIdent,
471            kind: InvalidationKind,
472            quirks_mode: QuirksMode,
473        ) -> bool {
474            match map.try_get_or_insert_with(&key.0, quirks_mode, || InvalidationKind::None) {
475                Ok(existing) => {
476                    *existing |= kind;
477                    true
478                },
479                Err(..) => false,
480            }
481        }
482
483        fn insert_local_name(
484            map: &mut PrecomputedHashMap<SelectorLocalName, InvalidationKind>,
485            key: &SelectorLocalName,
486            kind: InvalidationKind,
487        ) -> bool {
488            if map.try_reserve(1).is_err() {
489                return false;
490            }
491            *map.entry_ref(key).or_insert(InvalidationKind::None) |= kind;
492            true
493        }
494
495        match invalidation {
496            Invalidation::Class(c) => insert_atom(&mut self.buckets.classes, c, kind, quirks_mode),
497            Invalidation::ID(i) => insert_atom(&mut self.buckets.ids, i, kind, quirks_mode),
498            Invalidation::LocalName { name, lower_name } => {
499                insert_local_name(&mut self.buckets.local_names, name, kind)
500                    && (name == lower_name
501                        || insert_local_name(&mut self.buckets.local_names, lower_name, kind))
502            },
503        }
504    }
505
506    /// Collects invalidations for a given CSS rule, if not fully invalid already.
507    pub fn rule_changed<S>(
508        &mut self,
509        stylesheet: &S,
510        rule: &CssRule,
511        guard: &SharedRwLockReadGuard,
512        device: &Device,
513        quirks_mode: QuirksMode,
514        custom_media: &CustomMediaMap,
515        change_kind: RuleChangeKind,
516        ancestors: &[CssRuleRef],
517    ) where
518        S: StylesheetInDocument,
519    {
520        debug!("StylesheetInvalidationSet::rule_changed");
521        if !stylesheet.enabled() || !stylesheet.is_effective_for_device(device, custom_media, guard)
522        {
523            debug!(" > Stylesheet was not effective");
524            return; // Nothing to do here.
525        }
526
527        if ancestors
528            .iter()
529            .any(|r| !EffectiveRules::is_effective(guard, device, quirks_mode, custom_media, r))
530        {
531            debug!(" > Ancestor rules not effective");
532            return;
533        }
534
535        if change_kind == RuleChangeKind::PositionTryDeclarations {
536            // @position-try declaration changes need to be dealt explicitly, since the
537            // declarations are mutable and we can't otherwise detect changes to them.
538            match *rule {
539                CssRule::PositionTry(ref pt) => {
540                    self.cascade_data_difference
541                        .changed_position_try_names
542                        .insert(pt.read_with(guard).name.0.clone());
543                },
544                _ => debug_assert!(false, "how did position-try decls change on anything else?"),
545            }
546            return;
547        }
548
549        if self.style_fully_invalid {
550            return;
551        }
552
553        // If the change is generic, we don't have the old rule information to know e.g., the old
554        // media condition, or the old selector text, so we might need to invalidate more
555        // aggressively. That only applies to the changed rules, for other rules we can just
556        // collect invalidations as normal.
557        let is_generic_change = change_kind == RuleChangeKind::Generic;
558        self.collect_invalidations_for_rule(
559            rule,
560            guard,
561            device,
562            quirks_mode,
563            is_generic_change,
564            ancestors,
565        );
566        if self.style_fully_invalid {
567            return;
568        }
569
570        if !is_generic_change
571            && !EffectiveRules::is_effective(guard, device, quirks_mode, custom_media, &rule.into())
572        {
573            return;
574        }
575
576        let rules = EffectiveRulesIterator::effective_children(
577            device,
578            quirks_mode,
579            custom_media,
580            guard,
581            rule,
582        );
583        for rule in rules {
584            self.collect_invalidations_for_rule(
585                rule,
586                guard,
587                device,
588                quirks_mode,
589                /* is_generic_change = */ false,
590                // Note(dshin): Technically, the iterator should provide the ancestor chain as it traverses down, which sould be appended to `ancestors`, but it shouldn't matter.
591                &[],
592            );
593            if self.style_fully_invalid {
594                break;
595            }
596        }
597    }
598
599    /// Collects invalidations for a given CSS rule.
600    fn collect_invalidations_for_rule(
601        &mut self,
602        rule: &CssRule,
603        guard: &SharedRwLockReadGuard,
604        device: &Device,
605        quirks_mode: QuirksMode,
606        is_generic_change: bool,
607        ancestors: &[CssRuleRef],
608    ) {
609        use crate::stylesheets::CssRule::*;
610        debug!("StylesheetInvalidationSet::collect_invalidations_for_rule");
611        debug_assert!(!self.style_fully_invalid, "Not worth being here!");
612
613        match *rule {
614            Style(ref lock) => {
615                if is_generic_change {
616                    // TODO(emilio): We need to do this for selector / keyframe
617                    // name / font-face changes, because we don't have the old
618                    // selector / name.  If we distinguish those changes
619                    // specially, then we can at least use this invalidation for
620                    // style declaration changes.
621                    return self.invalidate_fully();
622                }
623
624                let style_rule = lock.read_with(guard);
625                for selector in style_rule.selectors.slice() {
626                    self.collect_invalidations(selector, quirks_mode);
627                    if self.style_fully_invalid {
628                        return;
629                    }
630                }
631            },
632            NestedDeclarations(..) => {
633                if ancestors.iter().any(|r| matches!(r, CssRuleRef::Scope(_))) {
634                    self.invalidate_fully();
635                }
636            },
637            Namespace(..) => {
638                // It's not clear what handling changes for this correctly would
639                // look like.
640            },
641            LayerStatement(..) => {
642                // Layer insertions might alter styling order, but are dealt via
643                // cascade_data_difference.
644            },
645            Document(..) | Import(..) | Media(..) | Supports(..) | Container(..)
646            | LayerBlock(..) | StartingStyle(..) | AppearanceBase(..) => {
647                // Do nothing, relevant nested rules are visited as part of rule iteration.
648            },
649            FontFace(..) => {
650                // Do nothing, @font-face doesn't affect computed style information on it's own.
651                // We'll restyle when the font face loads, if needed.
652            },
653            Page(..) | Margin(..) => {
654                // Do nothing, we don't support OM mutations on print documents, and page rules
655                // can't affect anything else.
656            },
657            Keyframes(ref lock) => {
658                if is_generic_change {
659                    return self.invalidate_fully();
660                }
661                let keyframes_rule = lock.read_with(guard);
662                if device.animation_name_may_be_referenced(&keyframes_rule.name) {
663                    debug!(
664                        " > Found @keyframes rule potentially referenced \
665                         from the page, marking the whole tree invalid."
666                    );
667                    self.invalidate_fully();
668                } else {
669                    // Do nothing, this animation can't affect the style of existing elements.
670                }
671            },
672            CounterStyle(..) | Property(..) | FontFeatureValues(..) | FontPaletteValues(..) => {
673                debug!(" > Found unsupported rule, marking the whole subtree invalid.");
674                self.invalidate_fully();
675            },
676            Scope(..) => {
677                // Addition/removal of @scope requires re-evaluation of scope proximity to properly
678                // figure out the styling order.
679                self.invalidate_fully();
680            },
681            PositionTry(..) => {
682                // @position-try changes doesn't change style-time information (only layout
683                // information) and is handled by invalidate_position_try. So do nothing.
684            },
685            ViewTransition(..) => {
686                // @view-transition doesn't affect element styles.
687            },
688            CustomMedia(..) => {
689                // @custom-media might be referenced by other rules which we can't get a hand on in
690                // here, so we don't know which elements are affected.
691                //
692                // TODO: Maybe track referenced custom-media rules like we do for @keyframe?
693                self.invalidate_fully();
694            },
695        }
696    }
697}
698
699/// Invalidates for any absolutely positioned element that references the given @position-try fallback names.
700pub fn invalidate_position_try<E>(
701    element: E,
702    changed_names: &PrecomputedHashSet<Atom>,
703    invalidate_self: &mut impl FnMut(E, &mut ElementData),
704    invalidated_descendants: &mut impl FnMut(E),
705) -> bool
706where
707    E: TElement,
708{
709    debug_assert!(
710        !changed_names.is_empty(),
711        "Don't call me if there's nothing to do"
712    );
713    let mut data = match element.mutate_data() {
714        Some(data) => data,
715        None => return false,
716    };
717
718    let mut self_invalid = false;
719    let style = data.styles.primary();
720    if style.get_box().get_position().is_absolutely_positioned() {
721        let fallbacks = style.get_position_try_fallbacks();
722        let referenced = fallbacks.value.0.iter().any(|f| match f {
723            PositionTryFallbacksItem::IdentAndOrTactic(ident_or_tactic) => {
724                changed_names.contains(&ident_or_tactic.ident.0)
725            },
726            PositionTryFallbacksItem::PositionArea(..) => false,
727        });
728
729        if referenced {
730            self_invalid = true;
731            invalidate_self(element, &mut data);
732        }
733    }
734    let mut any_children_invalid = false;
735    for child in element.traversal_children() {
736        let Some(e) = child.as_element() else {
737            continue;
738        };
739        any_children_invalid |=
740            invalidate_position_try(e, changed_names, invalidate_self, invalidated_descendants);
741    }
742    if any_children_invalid {
743        invalidated_descendants(element);
744    }
745    self_invalid || any_children_invalid
746}