Backed out 5 changesets (bug 1731541) for causing multiple wpt failures. CLOSED TREE
[gecko.git] / servo / components / style / data.rs
blob88b34d2b512bbbdb9b448df0cb4eed2b1ad4f744
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/. */
5 //! Per-node data used in style calculation.
7 use crate::computed_value_flags::ComputedValueFlags;
8 use crate::context::{SharedStyleContext, StackLimitChecker};
9 use crate::dom::TElement;
10 use crate::invalidation::element::invalidator::InvalidationResult;
11 use crate::invalidation::element::restyle_hints::RestyleHint;
12 use crate::properties::ComputedValues;
13 use crate::selector_parser::{PseudoElement, RestyleDamage, EAGER_PSEUDO_COUNT};
14 use crate::style_resolver::{PrimaryStyle, ResolvedElementStyles, ResolvedStyle};
15 #[cfg(feature = "gecko")]
16 use malloc_size_of::MallocSizeOfOps;
17 use selectors::matching::SelectorCaches;
18 use servo_arc::Arc;
19 use std::fmt;
20 use std::mem;
21 use std::ops::{Deref, DerefMut};
23 bitflags! {
24     /// Various flags stored on ElementData.
25     #[derive(Debug, Default)]
26     pub struct ElementDataFlags: u8 {
27         /// Whether the styles changed for this restyle.
28         const WAS_RESTYLED = 1 << 0;
29         /// Whether the last traversal of this element did not do
30         /// any style computation. This is not true during the initial
31         /// styling pass, nor is it true when we restyle (in which case
32         /// WAS_RESTYLED is set).
33         ///
34         /// This bit always corresponds to the last time the element was
35         /// traversed, so each traversal simply updates it with the appropriate
36         /// value.
37         const TRAVERSED_WITHOUT_STYLING = 1 << 1;
39         /// Whether the primary style of this element data was reused from
40         /// another element via a rule node comparison. This allows us to
41         /// differentiate between elements that shared styles because they met
42         /// all the criteria of the style sharing cache, compared to elements
43         /// that reused style structs via rule node identity.
44         ///
45         /// The former gives us stronger transitive guarantees that allows us to
46         /// apply the style sharing cache to cousins.
47         const PRIMARY_STYLE_REUSED_VIA_RULE_NODE = 1 << 2;
48     }
51 /// A lazily-allocated list of styles for eagerly-cascaded pseudo-elements.
52 ///
53 /// We use an Arc so that sharing these styles via the style sharing cache does
54 /// not require duplicate allocations. We leverage the copy-on-write semantics of
55 /// Arc::make_mut(), which is free (i.e. does not require atomic RMU operations)
56 /// in servo_arc.
57 #[derive(Clone, Debug, Default)]
58 pub struct EagerPseudoStyles(Option<Arc<EagerPseudoArray>>);
60 #[derive(Default)]
61 struct EagerPseudoArray(EagerPseudoArrayInner);
62 type EagerPseudoArrayInner = [Option<Arc<ComputedValues>>; EAGER_PSEUDO_COUNT];
64 impl Deref for EagerPseudoArray {
65     type Target = EagerPseudoArrayInner;
66     fn deref(&self) -> &Self::Target {
67         &self.0
68     }
71 impl DerefMut for EagerPseudoArray {
72     fn deref_mut(&mut self) -> &mut Self::Target {
73         &mut self.0
74     }
77 // Manually implement `Clone` here because the derived impl of `Clone` for
78 // array types assumes the value inside is `Copy`.
79 impl Clone for EagerPseudoArray {
80     fn clone(&self) -> Self {
81         let mut clone = Self::default();
82         for i in 0..EAGER_PSEUDO_COUNT {
83             clone[i] = self.0[i].clone();
84         }
85         clone
86     }
89 // Override Debug to print which pseudos we have, and substitute the rule node
90 // for the much-more-verbose ComputedValues stringification.
91 impl fmt::Debug for EagerPseudoArray {
92     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
93         write!(f, "EagerPseudoArray {{ ")?;
94         for i in 0..EAGER_PSEUDO_COUNT {
95             if let Some(ref values) = self[i] {
96                 write!(
97                     f,
98                     "{:?}: {:?}, ",
99                     PseudoElement::from_eager_index(i),
100                     &values.rules
101                 )?;
102             }
103         }
104         write!(f, "}}")
105     }
108 // Can't use [None; EAGER_PSEUDO_COUNT] here because it complains
109 // about Copy not being implemented for our Arc type.
110 #[cfg(feature = "gecko")]
111 const EMPTY_PSEUDO_ARRAY: &'static EagerPseudoArrayInner = &[None, None, None, None];
112 #[cfg(feature = "servo")]
113 const EMPTY_PSEUDO_ARRAY: &'static EagerPseudoArrayInner = &[None, None, None];
115 impl EagerPseudoStyles {
116     /// Returns whether there are any pseudo styles.
117     pub fn is_empty(&self) -> bool {
118         self.0.is_none()
119     }
121     /// Grabs a reference to the list of styles, if they exist.
122     pub fn as_optional_array(&self) -> Option<&EagerPseudoArrayInner> {
123         match self.0 {
124             None => None,
125             Some(ref x) => Some(&x.0),
126         }
127     }
129     /// Grabs a reference to the list of styles or a list of None if
130     /// there are no styles to be had.
131     pub fn as_array(&self) -> &EagerPseudoArrayInner {
132         self.as_optional_array().unwrap_or(EMPTY_PSEUDO_ARRAY)
133     }
135     /// Returns a reference to the style for a given eager pseudo, if it exists.
136     pub fn get(&self, pseudo: &PseudoElement) -> Option<&Arc<ComputedValues>> {
137         debug_assert!(pseudo.is_eager());
138         self.0
139             .as_ref()
140             .and_then(|p| p[pseudo.eager_index()].as_ref())
141     }
143     /// Sets the style for the eager pseudo.
144     pub fn set(&mut self, pseudo: &PseudoElement, value: Arc<ComputedValues>) {
145         if self.0.is_none() {
146             self.0 = Some(Arc::new(Default::default()));
147         }
148         let arr = Arc::make_mut(self.0.as_mut().unwrap());
149         arr[pseudo.eager_index()] = Some(value);
150     }
153 /// The styles associated with a node, including the styles for any
154 /// pseudo-elements.
155 #[derive(Clone, Default)]
156 pub struct ElementStyles {
157     /// The element's style.
158     pub primary: Option<Arc<ComputedValues>>,
159     /// A list of the styles for the element's eagerly-cascaded pseudo-elements.
160     pub pseudos: EagerPseudoStyles,
163 // There's one of these per rendered elements so it better be small.
164 size_of_test!(ElementStyles, 16);
166 /// Information on how this element uses viewport units.
167 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
168 pub enum ViewportUnitUsage {
169     /// No viewport units are used.
170     None = 0,
171     /// There are viewport units used from regular style rules (which means we
172     /// should re-cascade).
173     FromDeclaration,
174     /// There are viewport units used from container queries (which means we
175     /// need to re-selector-match).
176     FromQuery,
179 impl ElementStyles {
180     /// Returns the primary style.
181     pub fn get_primary(&self) -> Option<&Arc<ComputedValues>> {
182         self.primary.as_ref()
183     }
185     /// Returns the primary style.  Panic if no style available.
186     pub fn primary(&self) -> &Arc<ComputedValues> {
187         self.primary.as_ref().unwrap()
188     }
190     /// Whether this element `display` value is `none`.
191     pub fn is_display_none(&self) -> bool {
192         self.primary().get_box().clone_display().is_none()
193     }
195     /// Whether this element uses viewport units.
196     pub fn viewport_unit_usage(&self) -> ViewportUnitUsage {
197         fn usage_from_flags(flags: ComputedValueFlags) -> ViewportUnitUsage {
198             if flags.intersects(ComputedValueFlags::USES_VIEWPORT_UNITS_ON_CONTAINER_QUERIES) {
199                 return ViewportUnitUsage::FromQuery;
200             }
201             if flags.intersects(ComputedValueFlags::USES_VIEWPORT_UNITS) {
202                 return ViewportUnitUsage::FromDeclaration;
203             }
204             ViewportUnitUsage::None
205         }
207         let mut usage = usage_from_flags(self.primary().flags);
208         for pseudo_style in self.pseudos.as_array() {
209             if let Some(ref pseudo_style) = pseudo_style {
210                 usage = std::cmp::max(usage, usage_from_flags(pseudo_style.flags));
211             }
212         }
214         usage
215     }
217     #[cfg(feature = "gecko")]
218     fn size_of_excluding_cvs(&self, _ops: &mut MallocSizeOfOps) -> usize {
219         // As the method name suggests, we don't measures the ComputedValues
220         // here, because they are measured on the C++ side.
222         // XXX: measure the EagerPseudoArray itself, but not the ComputedValues
223         // within it.
225         0
226     }
229 // We manually implement Debug for ElementStyles so that we can avoid the
230 // verbose stringification of every property in the ComputedValues. We
231 // substitute the rule node instead.
232 impl fmt::Debug for ElementStyles {
233     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
234         write!(
235             f,
236             "ElementStyles {{ primary: {:?}, pseudos: {:?} }}",
237             self.primary.as_ref().map(|x| &x.rules),
238             self.pseudos
239         )
240     }
243 /// Style system data associated with an Element.
245 /// In Gecko, this hangs directly off the Element. Servo, this is embedded
246 /// inside of layout data, which itself hangs directly off the Element. In
247 /// both cases, it is wrapped inside an AtomicRefCell to ensure thread safety.
248 #[derive(Debug, Default)]
249 pub struct ElementData {
250     /// The styles for the element and its pseudo-elements.
251     pub styles: ElementStyles,
253     /// The restyle damage, indicating what kind of layout changes are required
254     /// afte restyling.
255     pub damage: RestyleDamage,
257     /// The restyle hint, which indicates whether selectors need to be rematched
258     /// for this element, its children, and its descendants.
259     pub hint: RestyleHint,
261     /// Flags.
262     pub flags: ElementDataFlags,
265 // There's one of these per rendered elements so it better be small.
266 size_of_test!(ElementData, 24);
268 /// The kind of restyle that a single element should do.
269 #[derive(Debug)]
270 pub enum RestyleKind {
271     /// We need to run selector matching plus re-cascade, that is, a full
272     /// restyle.
273     MatchAndCascade,
274     /// We need to recascade with some replacement rule, such as the style
275     /// attribute, or animation rules.
276     CascadeWithReplacements(RestyleHint),
277     /// We only need to recascade, for example, because only inherited
278     /// properties in the parent changed.
279     CascadeOnly,
282 impl ElementData {
283     /// Invalidates style for this element, its descendants, and later siblings,
284     /// based on the snapshot of the element that we took when attributes or
285     /// state changed.
286     pub fn invalidate_style_if_needed<'a, E: TElement>(
287         &mut self,
288         element: E,
289         shared_context: &SharedStyleContext,
290         stack_limit_checker: Option<&StackLimitChecker>,
291         selector_caches: &'a mut SelectorCaches,
292     ) -> InvalidationResult {
293         // In animation-only restyle we shouldn't touch snapshot at all.
294         if shared_context.traversal_flags.for_animation_only() {
295             return InvalidationResult::empty();
296         }
298         use crate::invalidation::element::invalidator::TreeStyleInvalidator;
299         use crate::invalidation::element::state_and_attributes::StateAndAttrInvalidationProcessor;
301         debug!(
302             "invalidate_style_if_needed: {:?}, flags: {:?}, has_snapshot: {}, \
303              handled_snapshot: {}, pseudo: {:?}",
304             element,
305             shared_context.traversal_flags,
306             element.has_snapshot(),
307             element.handled_snapshot(),
308             element.implemented_pseudo_element()
309         );
311         if !element.has_snapshot() || element.handled_snapshot() {
312             return InvalidationResult::empty();
313         }
315         let mut processor = StateAndAttrInvalidationProcessor::new(
316             shared_context,
317             element,
318             self,
319             selector_caches,
320         );
322         let invalidator = TreeStyleInvalidator::new(element, stack_limit_checker, &mut processor);
324         let result = invalidator.invalidate();
326         unsafe { element.set_handled_snapshot() }
327         debug_assert!(element.handled_snapshot());
329         result
330     }
332     /// Returns true if this element has styles.
333     #[inline]
334     pub fn has_styles(&self) -> bool {
335         self.styles.primary.is_some()
336     }
338     /// Returns this element's styles as resolved styles to use for sharing.
339     pub fn share_styles(&self) -> ResolvedElementStyles {
340         ResolvedElementStyles {
341             primary: self.share_primary_style(),
342             pseudos: self.styles.pseudos.clone(),
343         }
344     }
346     /// Returns this element's primary style as a resolved style to use for sharing.
347     pub fn share_primary_style(&self) -> PrimaryStyle {
348         let reused_via_rule_node = self
349             .flags
350             .contains(ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE);
352         PrimaryStyle {
353             style: ResolvedStyle(self.styles.primary().clone()),
354             reused_via_rule_node,
355         }
356     }
358     /// Sets a new set of styles, returning the old ones.
359     pub fn set_styles(&mut self, new_styles: ResolvedElementStyles) -> ElementStyles {
360         if new_styles.primary.reused_via_rule_node {
361             self.flags
362                 .insert(ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE);
363         } else {
364             self.flags
365                 .remove(ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE);
366         }
367         mem::replace(&mut self.styles, new_styles.into())
368     }
370     /// Returns the kind of restyling that we're going to need to do on this
371     /// element, based of the stored restyle hint.
372     pub fn restyle_kind(&self, shared_context: &SharedStyleContext) -> Option<RestyleKind> {
373         if shared_context.traversal_flags.for_animation_only() {
374             return self.restyle_kind_for_animation(shared_context);
375         }
377         let style = match self.styles.primary {
378             Some(ref s) => s,
379             None => return Some(RestyleKind::MatchAndCascade),
380         };
382         let hint = self.hint;
383         if hint.is_empty() {
384             return None;
385         }
387         let needs_to_match_self = hint.intersects(RestyleHint::RESTYLE_SELF) ||
388             (hint.intersects(RestyleHint::RESTYLE_SELF_IF_PSEUDO) && style.is_pseudo_style());
389         if needs_to_match_self {
390             return Some(RestyleKind::MatchAndCascade);
391         }
393         if hint.has_replacements() {
394             debug_assert!(
395                 !hint.has_animation_hint(),
396                 "Animation only restyle hint should have already processed"
397             );
398             return Some(RestyleKind::CascadeWithReplacements(
399                 hint & RestyleHint::replacements(),
400             ));
401         }
403         let needs_to_recascade_self = hint.intersects(RestyleHint::RECASCADE_SELF) ||
404             (hint.intersects(RestyleHint::RECASCADE_SELF_IF_INHERIT_RESET_STYLE) &&
405                 style
406                     .flags
407                     .contains(ComputedValueFlags::INHERITS_RESET_STYLE));
408         if needs_to_recascade_self {
409             return Some(RestyleKind::CascadeOnly);
410         }
412         None
413     }
415     /// Returns the kind of restyling for animation-only restyle.
416     fn restyle_kind_for_animation(
417         &self,
418         shared_context: &SharedStyleContext,
419     ) -> Option<RestyleKind> {
420         debug_assert!(shared_context.traversal_flags.for_animation_only());
421         debug_assert!(
422             self.has_styles(),
423             "animation traversal doesn't care about unstyled elements"
424         );
426         // FIXME: We should ideally restyle here, but it is a hack to work around our weird
427         // animation-only traversal stuff: If we're display: none and the rules we could
428         // match could change, we consider our style up-to-date. This is because re-cascading with
429         // and old style doesn't guarantee returning the correct animation style (that's
430         // bug 1393323). So if our display changed, and it changed from display: none, we would
431         // incorrectly forget about it and wouldn't be able to correctly style our descendants
432         // later.
433         // XXX Figure out if this still makes sense.
434         let hint = self.hint;
435         if self.styles.is_display_none() && hint.intersects(RestyleHint::RESTYLE_SELF) {
436             return None;
437         }
439         let style = self.styles.primary();
440         // Return either CascadeWithReplacements or CascadeOnly in case of
441         // animation-only restyle. I.e. animation-only restyle never does
442         // selector matching.
443         if hint.has_animation_hint() {
444             return Some(RestyleKind::CascadeWithReplacements(
445                 hint & RestyleHint::for_animations(),
446             ));
447         }
449         let needs_to_recascade_self = hint.intersects(RestyleHint::RECASCADE_SELF) ||
450             (hint.intersects(RestyleHint::RECASCADE_SELF_IF_INHERIT_RESET_STYLE) &&
451                 style
452                     .flags
453                     .contains(ComputedValueFlags::INHERITS_RESET_STYLE));
454         if needs_to_recascade_self {
455             return Some(RestyleKind::CascadeOnly);
456         }
457         return None;
458     }
460     /// Drops any restyle state from the element.
461     ///
462     /// FIXME(bholley): The only caller of this should probably just assert that
463     /// the hint is empty and call clear_flags_and_damage().
464     #[inline]
465     pub fn clear_restyle_state(&mut self) {
466         self.hint = RestyleHint::empty();
467         self.clear_restyle_flags_and_damage();
468     }
470     /// Drops restyle flags and damage from the element.
471     #[inline]
472     pub fn clear_restyle_flags_and_damage(&mut self) {
473         self.damage = RestyleDamage::empty();
474         self.flags.remove(ElementDataFlags::WAS_RESTYLED);
475     }
477     /// Mark this element as restyled, which is useful to know whether we need
478     /// to do a post-traversal.
479     pub fn set_restyled(&mut self) {
480         self.flags.insert(ElementDataFlags::WAS_RESTYLED);
481         self.flags
482             .remove(ElementDataFlags::TRAVERSED_WITHOUT_STYLING);
483     }
485     /// Returns true if this element was restyled.
486     #[inline]
487     pub fn is_restyle(&self) -> bool {
488         self.flags.contains(ElementDataFlags::WAS_RESTYLED)
489     }
491     /// Mark that we traversed this element without computing any style for it.
492     pub fn set_traversed_without_styling(&mut self) {
493         self.flags
494             .insert(ElementDataFlags::TRAVERSED_WITHOUT_STYLING);
495     }
497     /// Returns whether this element has been part of a restyle.
498     #[inline]
499     pub fn contains_restyle_data(&self) -> bool {
500         self.is_restyle() || !self.hint.is_empty() || !self.damage.is_empty()
501     }
503     /// Returns whether it is safe to perform cousin sharing based on the ComputedValues
504     /// identity of the primary style in this ElementData. There are a few subtle things
505     /// to check.
506     ///
507     /// First, if a parent element was already styled and we traversed past it without
508     /// restyling it, that may be because our clever invalidation logic was able to prove
509     /// that the styles of that element would remain unchanged despite changes to the id
510     /// or class attributes. However, style sharing relies on the strong guarantee that all
511     /// the classes and ids up the respective parent chains are identical. As such, if we
512     /// skipped styling for one (or both) of the parents on this traversal, we can't share
513     /// styles across cousins. Note that this is a somewhat conservative check. We could
514     /// tighten it by having the invalidation logic explicitly flag elements for which it
515     /// ellided styling.
516     ///
517     /// Second, we want to only consider elements whose ComputedValues match due to a hit
518     /// in the style sharing cache, rather than due to the rule-node-based reuse that
519     /// happens later in the styling pipeline. The former gives us the stronger guarantees
520     /// we need for style sharing, the latter does not.
521     pub fn safe_for_cousin_sharing(&self) -> bool {
522         if self.flags.intersects(
523             ElementDataFlags::TRAVERSED_WITHOUT_STYLING |
524                 ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE,
525         ) {
526             return false;
527         }
528         if !self
529             .styles
530             .primary()
531             .get_box()
532             .clone_container_type()
533             .is_normal()
534         {
535             return false;
536         }
537         true
538     }
540     /// Measures memory usage.
541     #[cfg(feature = "gecko")]
542     pub fn size_of_excluding_cvs(&self, ops: &mut MallocSizeOfOps) -> usize {
543         let n = self.styles.size_of_excluding_cvs(ops);
545         // We may measure more fields in the future if DMD says it's worth it.
547         n
548     }