Skip to main content

style/
data.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//! Per-node data used in style calculation.
6
7use crate::computed_value_flags::ComputedValueFlags;
8use crate::context::{SharedStyleContext, StackLimitChecker};
9use crate::dom::TElement;
10use crate::invalidation::element::invalidator::InvalidationResult;
11use crate::invalidation::element::restyle_hints::RestyleHint;
12use crate::properties::ComputedValues;
13use crate::selector_parser::{PseudoElement, RestyleDamage, EAGER_PSEUDO_COUNT};
14use crate::style_resolver::{PrimaryStyle, ResolvedElementStyles, ResolvedStyle};
15#[cfg(feature = "gecko")]
16use malloc_size_of::MallocSizeOfOps;
17use selectors::matching::SelectorCaches;
18use servo_arc::Arc;
19use std::ops::{Deref, DerefMut};
20use std::{fmt, mem};
21
22#[cfg(debug_assertions)]
23use atomic_refcell::{AtomicRef, AtomicRefCell, AtomicRefMut};
24
25bitflags! {
26    /// Various flags stored on ElementData.
27    #[derive(Debug, Default)]
28    pub struct ElementDataFlags: u8 {
29        /// Whether the styles changed for this restyle.
30        const WAS_RESTYLED = 1 << 0;
31        /// Whether the last traversal of this element did not do
32        /// any style computation. This is not true during the initial
33        /// styling pass, nor is it true when we restyle (in which case
34        /// WAS_RESTYLED is set).
35        ///
36        /// This bit always corresponds to the last time the element was
37        /// traversed, so each traversal simply updates it with the appropriate
38        /// value.
39        const TRAVERSED_WITHOUT_STYLING = 1 << 1;
40
41        /// Whether the primary style of this element data was reused from
42        /// another element via a rule node comparison. This allows us to
43        /// differentiate between elements that shared styles because they met
44        /// all the criteria of the style sharing cache, compared to elements
45        /// that reused style structs via rule node identity.
46        ///
47        /// The former gives us stronger transitive guarantees that allows us to
48        /// apply the style sharing cache to cousins.
49        const PRIMARY_STYLE_REUSED_VIA_RULE_NODE = 1 << 2;
50    }
51}
52
53/// A lazily-allocated list of styles for eagerly-cascaded pseudo-elements.
54///
55/// We use an Arc so that sharing these styles via the style sharing cache does
56/// not require duplicate allocations. We leverage the copy-on-write semantics of
57/// Arc::make_mut(), which is free (i.e. does not require atomic RMU operations)
58/// in servo_arc.
59#[derive(Clone, Debug, Default)]
60pub struct EagerPseudoStyles(Option<Arc<EagerPseudoArray>>);
61
62#[derive(Default)]
63struct EagerPseudoArray(EagerPseudoArrayInner);
64type EagerPseudoArrayInner = [Option<Arc<ComputedValues>>; EAGER_PSEUDO_COUNT];
65
66impl Deref for EagerPseudoArray {
67    type Target = EagerPseudoArrayInner;
68    fn deref(&self) -> &Self::Target {
69        &self.0
70    }
71}
72
73impl DerefMut for EagerPseudoArray {
74    fn deref_mut(&mut self) -> &mut Self::Target {
75        &mut self.0
76    }
77}
78
79// Manually implement `Clone` here because the derived impl of `Clone` for
80// array types assumes the value inside is `Copy`.
81impl Clone for EagerPseudoArray {
82    fn clone(&self) -> Self {
83        let mut clone = Self::default();
84        for i in 0..EAGER_PSEUDO_COUNT {
85            clone[i] = self.0[i].clone();
86        }
87        clone
88    }
89}
90
91// Override Debug to print which pseudos we have, and substitute the rule node
92// for the much-more-verbose ComputedValues stringification.
93impl fmt::Debug for EagerPseudoArray {
94    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
95        write!(f, "EagerPseudoArray {{ ")?;
96        for i in 0..EAGER_PSEUDO_COUNT {
97            if let Some(ref values) = self[i] {
98                write!(
99                    f,
100                    "{:?}: {:?}, ",
101                    PseudoElement::from_eager_index(i),
102                    &values.rules
103                )?;
104            }
105        }
106        write!(f, "}}")
107    }
108}
109
110// Can't use [None; EAGER_PSEUDO_COUNT] here because it complains
111// about Copy not being implemented for our Arc type.
112const EMPTY_PSEUDO_ARRAY: &'static EagerPseudoArrayInner = &[None, None, None, None];
113
114impl EagerPseudoStyles {
115    /// Returns whether there are any pseudo styles.
116    pub fn is_empty(&self) -> bool {
117        self.0.is_none()
118    }
119
120    /// Grabs a reference to the list of styles, if they exist.
121    pub fn as_optional_array(&self) -> Option<&EagerPseudoArrayInner> {
122        match self.0 {
123            None => None,
124            Some(ref x) => Some(&x.0),
125        }
126    }
127
128    /// Grabs a reference to the list of styles or a list of None if
129    /// there are no styles to be had.
130    pub fn as_array(&self) -> &EagerPseudoArrayInner {
131        self.as_optional_array().unwrap_or(EMPTY_PSEUDO_ARRAY)
132    }
133
134    /// Returns a reference to the style for a given eager pseudo, if it exists.
135    pub fn get(&self, pseudo: &PseudoElement) -> Option<&Arc<ComputedValues>> {
136        debug_assert!(pseudo.is_eager());
137        self.0
138            .as_ref()
139            .and_then(|p| p[pseudo.eager_index()].as_ref())
140    }
141
142    /// Sets the style for the eager pseudo.
143    pub fn set(&mut self, pseudo: &PseudoElement, value: Arc<ComputedValues>) {
144        if self.0.is_none() {
145            self.0 = Some(Arc::new(Default::default()));
146        }
147        let arr = Arc::make_mut(self.0.as_mut().unwrap());
148        arr[pseudo.eager_index()] = Some(value);
149    }
150}
151
152/// The styles associated with a node, including the styles for any
153/// pseudo-elements.
154#[derive(Clone, Default)]
155pub struct ElementStyles {
156    /// The element's style.
157    pub primary: Option<Arc<ComputedValues>>,
158    /// A list of the styles for the element's eagerly-cascaded pseudo-elements.
159    pub pseudos: EagerPseudoStyles,
160}
161
162// There's one of these per rendered elements so it better be small.
163size_of_test!(ElementStyles, 16);
164
165/// Information on how this element uses viewport units.
166#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
167pub enum ViewportUnitUsage {
168    /// No viewport units are used.
169    None = 0,
170    /// There are viewport units used from regular style rules (which means we
171    /// should re-cascade).
172    FromDeclaration,
173    /// There are viewport units used from container queries (which means we
174    /// need to re-selector-match).
175    FromQuery,
176}
177
178impl ElementStyles {
179    /// Returns the primary style.
180    pub fn get_primary(&self) -> Option<&Arc<ComputedValues>> {
181        self.primary.as_ref()
182    }
183
184    /// Returns the primary style.  Panic if no style available.
185    pub fn primary(&self) -> &Arc<ComputedValues> {
186        self.primary.as_ref().unwrap()
187    }
188
189    /// Whether this element `display` value is `none`.
190    pub fn is_display_none(&self) -> bool {
191        self.primary().get_box().clone_display().is_none()
192    }
193
194    /// Whether this element uses viewport units.
195    pub fn viewport_unit_usage(&self) -> ViewportUnitUsage {
196        fn usage_from_flags(flags: ComputedValueFlags) -> ViewportUnitUsage {
197            if flags.intersects(ComputedValueFlags::USES_VIEWPORT_UNITS_ON_CONTAINER_QUERIES) {
198                return ViewportUnitUsage::FromQuery;
199            }
200            if flags.intersects(ComputedValueFlags::USES_VIEWPORT_UNITS) {
201                return ViewportUnitUsage::FromDeclaration;
202            }
203            ViewportUnitUsage::None
204        }
205
206        let primary = self.primary();
207        let mut usage = usage_from_flags(primary.flags);
208
209        // Check cached lazy pseudos on the primary style.
210        primary.each_cached_lazy_pseudo(|style| {
211            usage = std::cmp::max(usage, usage_from_flags(style.flags));
212        });
213
214        for pseudo_style in self.pseudos.as_array() {
215            if let Some(ref pseudo_style) = pseudo_style {
216                usage = std::cmp::max(usage, usage_from_flags(pseudo_style.flags));
217                // Also check cached lazy pseudos on eager pseudo styles.
218                pseudo_style.each_cached_lazy_pseudo(|style| {
219                    usage = std::cmp::max(usage, usage_from_flags(style.flags));
220                });
221            }
222        }
223
224        usage
225    }
226
227    #[cfg(feature = "gecko")]
228    fn size_of_excluding_cvs(&self, _ops: &mut MallocSizeOfOps) -> usize {
229        // As the method name suggests, we don't measures the ComputedValues
230        // here, because they are measured on the C++ side.
231
232        // XXX: measure the EagerPseudoArray itself, but not the ComputedValues
233        // within it.
234
235        0
236    }
237}
238
239// We manually implement Debug for ElementStyles so that we can avoid the
240// verbose stringification of every property in the ComputedValues. We
241// substitute the rule node instead.
242impl fmt::Debug for ElementStyles {
243    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
244        write!(
245            f,
246            "ElementStyles {{ primary: {:?}, pseudos: {:?} }}",
247            self.primary.as_ref().map(|x| &x.rules),
248            self.pseudos
249        )
250    }
251}
252
253/// Style system data associated with an Element.
254///
255/// In Gecko, this hangs directly off the Element. Servo, this is embedded
256/// inside of layout data, which itself hangs directly off the Element. In
257/// both cases, it is wrapped inside an AtomicRefCell to ensure thread safety.
258#[derive(Debug, Default)]
259pub struct ElementData {
260    /// The styles for the element and its pseudo-elements.
261    pub styles: ElementStyles,
262
263    /// The restyle damage, indicating what kind of layout changes are required
264    /// afte restyling.
265    pub damage: RestyleDamage,
266
267    /// The restyle hint, which indicates whether selectors need to be rematched
268    /// for this element, its children, and its descendants.
269    pub hint: RestyleHint,
270
271    /// Flags.
272    pub flags: ElementDataFlags,
273}
274
275/// A struct that wraps ElementData, giving it the ability of doing thread-safety checks.
276#[derive(Debug, Default)]
277pub struct ElementDataWrapper {
278    inner: std::cell::UnsafeCell<ElementData>,
279    /// Implements optional (debug_assertions-only) thread-safety checking.
280    #[cfg(debug_assertions)]
281    refcell: AtomicRefCell<()>,
282}
283
284/// A read-only reference to ElementData.
285#[derive(Debug)]
286pub struct ElementDataMut<'a> {
287    v: &'a mut ElementData,
288    #[cfg(debug_assertions)]
289    _borrow: AtomicRefMut<'a, ()>,
290}
291
292/// A mutable reference to ElementData.
293#[derive(Debug)]
294pub struct ElementDataRef<'a> {
295    v: &'a ElementData,
296    #[cfg(debug_assertions)]
297    _borrow: AtomicRef<'a, ()>,
298}
299
300impl ElementDataWrapper {
301    /// Gets a non-exclusive reference to this ElementData.
302    #[inline(always)]
303    pub fn borrow(&self) -> ElementDataRef<'_> {
304        #[cfg(debug_assertions)]
305        let borrow = self.refcell.borrow();
306        ElementDataRef {
307            v: unsafe { &*self.inner.get() },
308            #[cfg(debug_assertions)]
309            _borrow: borrow,
310        }
311    }
312
313    /// Gets an exclusive reference to this ElementData.
314    #[inline(always)]
315    pub fn borrow_mut(&self) -> ElementDataMut<'_> {
316        #[cfg(debug_assertions)]
317        let borrow = self.refcell.borrow_mut();
318        ElementDataMut {
319            v: unsafe { &mut *self.inner.get() },
320            #[cfg(debug_assertions)]
321            _borrow: borrow,
322        }
323    }
324}
325
326impl<'a> Deref for ElementDataRef<'a> {
327    type Target = ElementData;
328    #[inline]
329    fn deref(&self) -> &Self::Target {
330        &*self.v
331    }
332}
333
334impl<'a> Deref for ElementDataMut<'a> {
335    type Target = ElementData;
336    #[inline]
337    fn deref(&self) -> &Self::Target {
338        &*self.v
339    }
340}
341
342impl<'a> DerefMut for ElementDataMut<'a> {
343    fn deref_mut(&mut self) -> &mut Self::Target {
344        &mut *self.v
345    }
346}
347
348// There's one of these per rendered elements so it better be small.
349size_of_test!(ElementData, 24);
350
351/// The kind of restyle that a single element should do.
352#[derive(Debug)]
353pub enum RestyleKind {
354    /// We need to run selector matching plus re-cascade, that is, a full
355    /// restyle.
356    MatchAndCascade,
357    /// We need to recascade with some replacement rule, such as the style
358    /// attribute, or animation rules.
359    CascadeWithReplacements(RestyleHint),
360    /// We only need to recascade, for example, because only inherited
361    /// properties in the parent changed.
362    CascadeOnly,
363}
364
365fn needs_to_match_self(hint: RestyleHint, style: &ComputedValues) -> bool {
366    if hint.intersects(RestyleHint::RESTYLE_SELF) {
367        return true;
368    }
369    if hint.intersects(RestyleHint::RESTYLE_SELF_IF_PSEUDO) && style.is_pseudo_style() {
370        return true;
371    }
372    if hint.intersects(RestyleHint::RESTYLE_IF_AFFECTED_BY_ANCESTOR_FONT)
373        && style
374            .flags
375            .intersects(ComputedValueFlags::USES_FONT_RELATIVE_UNITS_ON_CONTAINER_QUERIES)
376    {
377        return true;
378    }
379    hint.intersects(
380        RestyleHint::RESTYLE_IF_AFFECTED_BY_STYLE_QUERIES
381            | RestyleHint::RESTYLE_IF_AFFECTED_BY_NAMED_STYLE_CONTAINER,
382    ) && style
383        .flags
384        .intersects(ComputedValueFlags::DEPENDS_ON_CONTAINER_STYLE_QUERY)
385}
386
387fn needs_to_recascade_self(hint: RestyleHint, style: &ComputedValues) -> bool {
388    if hint.intersects(RestyleHint::RECASCADE_SELF) {
389        return true;
390    }
391    if hint.intersects(RestyleHint::RECASCADE_SELF_IF_INHERIT_RESET_STYLE)
392        && style
393            .flags
394            .contains(ComputedValueFlags::INHERITS_RESET_STYLE)
395    {
396        return true;
397    }
398    if hint.intersects(RestyleHint::RESTYLE_IF_AFFECTED_BY_ANCESTOR_FONT)
399        && style
400            .flags
401            .contains(ComputedValueFlags::USES_FONT_RELATIVE_UNITS)
402    {
403        return true;
404    }
405    return false;
406}
407
408impl ElementData {
409    /// Invalidates style for this element, its descendants, and later siblings,
410    /// based on the snapshot of the element that we took when attributes or
411    /// state changed.
412    pub fn invalidate_style_if_needed<'a, E: TElement>(
413        &mut self,
414        element: E,
415        shared_context: &SharedStyleContext,
416        stack_limit_checker: Option<&StackLimitChecker>,
417        selector_caches: &'a mut SelectorCaches,
418    ) -> InvalidationResult {
419        // In animation-only restyle we shouldn't touch snapshot at all.
420        if shared_context.traversal_flags.for_animation_only() {
421            return InvalidationResult::empty();
422        }
423
424        use crate::invalidation::element::invalidator::TreeStyleInvalidator;
425        use crate::invalidation::element::state_and_attributes::StateAndAttrInvalidationProcessor;
426
427        debug!(
428            "invalidate_style_if_needed: {:?}, flags: {:?}, has_snapshot: {}, \
429             handled_snapshot: {}, pseudo: {:?}",
430            element,
431            shared_context.traversal_flags,
432            element.has_snapshot(),
433            element.handled_snapshot(),
434            element.implemented_pseudo_element()
435        );
436
437        if !element.has_snapshot() || element.handled_snapshot() {
438            return InvalidationResult::empty();
439        }
440
441        let mut processor =
442            StateAndAttrInvalidationProcessor::new(shared_context, element, self, selector_caches);
443
444        let invalidator = TreeStyleInvalidator::new(element, stack_limit_checker, &mut processor);
445
446        let result = invalidator.invalidate();
447
448        unsafe { element.set_handled_snapshot() }
449        debug_assert!(element.handled_snapshot());
450
451        result
452    }
453
454    /// Returns true if this element has styles.
455    #[inline]
456    pub fn has_styles(&self) -> bool {
457        self.styles.primary.is_some()
458    }
459
460    /// Returns this element's styles as resolved styles to use for sharing.
461    pub fn share_styles(&self) -> ResolvedElementStyles {
462        ResolvedElementStyles {
463            primary: self.share_primary_style(),
464            pseudos: self.styles.pseudos.clone(),
465        }
466    }
467
468    /// Returns this element's primary style as a resolved style to use for sharing.
469    pub fn share_primary_style(&self) -> PrimaryStyle {
470        let reused_via_rule_node = self
471            .flags
472            .contains(ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE);
473
474        PrimaryStyle {
475            style: ResolvedStyle(self.styles.primary().clone()),
476            reused_via_rule_node,
477        }
478    }
479
480    /// Return a copy of the element's primary style as a resolved style with the
481    /// given flags.
482    pub fn clone_style_with_flags(&self, flags: ComputedValueFlags) -> ResolvedStyle {
483        let primary_style = self.styles.primary();
484        // We are only using this pseudo to find the correct pseudo type so it
485        // does not matter it technically belongs to a different style.
486        let pseudo = primary_style.pseudo();
487        ResolvedStyle(
488            primary_style
489                .deref()
490                .clone_with_flags(flags, pseudo.as_ref()),
491        )
492    }
493
494    /// Sets a new set of styles, returning the old ones.
495    pub fn set_styles(&mut self, new_styles: ResolvedElementStyles) -> ElementStyles {
496        self.flags.set(
497            ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE,
498            new_styles.primary.reused_via_rule_node,
499        );
500        mem::replace(&mut self.styles, new_styles.into())
501    }
502
503    /// Returns the kind of restyling that we're going to need to do on this
504    /// element, based of the stored restyle hint.
505    pub fn restyle_kind(&self, shared_context: &SharedStyleContext) -> Option<RestyleKind> {
506        let style = match self.styles.primary {
507            Some(ref s) => s,
508            None => return Some(RestyleKind::MatchAndCascade),
509        };
510
511        if shared_context.traversal_flags.for_animation_only() {
512            return self.restyle_kind_for_animation(shared_context);
513        }
514
515        let hint = self.hint;
516        if hint.is_empty() {
517            return None;
518        }
519
520        if needs_to_match_self(hint, style) {
521            return Some(RestyleKind::MatchAndCascade);
522        }
523
524        if hint.has_replacements() {
525            debug_assert!(
526                !hint.has_animation_hint(),
527                "Animation only restyle hint should have already processed"
528            );
529            return Some(RestyleKind::CascadeWithReplacements(
530                hint & RestyleHint::replacements(),
531            ));
532        }
533
534        if needs_to_recascade_self(hint, style) {
535            return Some(RestyleKind::CascadeOnly);
536        }
537
538        None
539    }
540
541    /// Returns the kind of restyling for animation-only restyle.
542    fn restyle_kind_for_animation(
543        &self,
544        shared_context: &SharedStyleContext,
545    ) -> Option<RestyleKind> {
546        debug_assert!(shared_context.traversal_flags.for_animation_only());
547        debug_assert!(self.has_styles());
548
549        // FIXME: We should ideally restyle here, but it is a hack to work around our weird
550        // animation-only traversal stuff: If we're display: none and the rules we could
551        // match could change, we consider our style up-to-date. This is because re-cascading with
552        // and old style doesn't guarantee returning the correct animation style (that's
553        // bug 1393323). So if our display changed, and it changed from display: none, we would
554        // incorrectly forget about it and wouldn't be able to correctly style our descendants
555        // later.
556        // XXX Figure out if this still makes sense.
557        let hint = self.hint;
558        if self.styles.is_display_none() && hint.intersects(RestyleHint::RESTYLE_SELF) {
559            return None;
560        }
561
562        let style = self.styles.primary();
563        // Return either CascadeWithReplacements or CascadeOnly in case of animation-only restyle.
564        // I.e. animation-only restyle never does selector matching.
565        if hint.has_animation_hint() {
566            return Some(RestyleKind::CascadeWithReplacements(
567                hint & RestyleHint::for_animations(),
568            ));
569        }
570
571        if needs_to_recascade_self(hint, style) {
572            return Some(RestyleKind::CascadeOnly);
573        }
574        return None;
575    }
576
577    /// Drops any restyle state from the element.
578    ///
579    /// FIXME(bholley): The only caller of this should probably just assert that the hint is empty
580    /// and call clear_flags_and_damage().
581    #[inline]
582    pub fn clear_restyle_state(&mut self) {
583        self.hint = RestyleHint::empty();
584        self.clear_restyle_flags_and_damage();
585    }
586
587    /// Drops restyle flags and damage from the element.
588    #[inline]
589    pub fn clear_restyle_flags_and_damage(&mut self) {
590        self.damage = RestyleDamage::empty();
591        self.flags.remove(ElementDataFlags::WAS_RESTYLED);
592    }
593
594    /// Mark this element as restyled, which is useful to know whether we need
595    /// to do a post-traversal.
596    pub fn set_restyled(&mut self) {
597        self.flags.insert(ElementDataFlags::WAS_RESTYLED);
598        self.flags
599            .remove(ElementDataFlags::TRAVERSED_WITHOUT_STYLING);
600    }
601
602    /// Returns true if this element was restyled.
603    #[inline]
604    pub fn is_restyle(&self) -> bool {
605        self.flags.contains(ElementDataFlags::WAS_RESTYLED)
606    }
607
608    /// Mark that we traversed this element without computing any style for it.
609    pub fn set_traversed_without_styling(&mut self) {
610        self.flags
611            .insert(ElementDataFlags::TRAVERSED_WITHOUT_STYLING);
612    }
613
614    /// Returns whether this element has been part of a restyle.
615    #[inline]
616    pub fn contains_restyle_data(&self) -> bool {
617        self.is_restyle() || !self.hint.is_empty() || !self.damage.is_empty()
618    }
619
620    /// Returns whether it is safe to perform cousin sharing based on the ComputedValues
621    /// identity of the primary style in this ElementData. There are a few subtle things
622    /// to check.
623    ///
624    /// First, if a parent element was already styled and we traversed past it without
625    /// restyling it, that may be because our clever invalidation logic was able to prove
626    /// that the styles of that element would remain unchanged despite changes to the id
627    /// or class attributes. However, style sharing relies on the strong guarantee that all
628    /// the classes and ids up the respective parent chains are identical. As such, if we
629    /// skipped styling for one (or both) of the parents on this traversal, we can't share
630    /// styles across cousins. Note that this is a somewhat conservative check. We could
631    /// tighten it by having the invalidation logic explicitly flag elements for which it
632    /// ellided styling.
633    ///
634    /// Second, we want to only consider elements whose ComputedValues match due to a hit
635    /// in the style sharing cache, rather than due to the rule-node-based reuse that
636    /// happens later in the styling pipeline. The former gives us the stronger guarantees
637    /// we need for style sharing, the latter does not.
638    pub fn safe_for_cousin_sharing(&self) -> bool {
639        if self.flags.intersects(
640            ElementDataFlags::TRAVERSED_WITHOUT_STYLING
641                | ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE,
642        ) {
643            return false;
644        }
645        if !self
646            .styles
647            .primary()
648            .get_box()
649            .clone_container_type()
650            .is_normal()
651        {
652            return false;
653        }
654        true
655    }
656
657    /// Measures memory usage.
658    #[cfg(feature = "gecko")]
659    pub fn size_of_excluding_cvs(&self, ops: &mut MallocSizeOfOps) -> usize {
660        let n = self.styles.size_of_excluding_cvs(ops);
661
662        // We may measure more fields in the future if DMD says it's worth it.
663
664        n
665    }
666}