1use 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 #[derive(Debug, Default)]
28 pub struct ElementDataFlags: u8 {
29 const WAS_RESTYLED = 1 << 0;
31 const TRAVERSED_WITHOUT_STYLING = 1 << 1;
40
41 const PRIMARY_STYLE_REUSED_VIA_RULE_NODE = 1 << 2;
50 }
51}
52
53#[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
79impl 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
91impl 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
110const EMPTY_PSEUDO_ARRAY: &'static EagerPseudoArrayInner = &[None, None, None, None];
113
114impl EagerPseudoStyles {
115 pub fn is_empty(&self) -> bool {
117 self.0.is_none()
118 }
119
120 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 pub fn as_array(&self) -> &EagerPseudoArrayInner {
131 self.as_optional_array().unwrap_or(EMPTY_PSEUDO_ARRAY)
132 }
133
134 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 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#[derive(Clone, Default)]
155pub struct ElementStyles {
156 pub primary: Option<Arc<ComputedValues>>,
158 pub pseudos: EagerPseudoStyles,
160}
161
162size_of_test!(ElementStyles, 16);
164
165#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
167pub enum ViewportUnitUsage {
168 None = 0,
170 FromDeclaration,
173 FromQuery,
176}
177
178impl ElementStyles {
179 pub fn get_primary(&self) -> Option<&Arc<ComputedValues>> {
181 self.primary.as_ref()
182 }
183
184 pub fn primary(&self) -> &Arc<ComputedValues> {
186 self.primary.as_ref().unwrap()
187 }
188
189 pub fn is_display_none(&self) -> bool {
191 self.primary().get_box().clone_display().is_none()
192 }
193
194 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 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 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 0
236 }
237}
238
239impl 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#[derive(Debug, Default)]
259pub struct ElementData {
260 pub styles: ElementStyles,
262
263 pub damage: RestyleDamage,
266
267 pub hint: RestyleHint,
270
271 pub flags: ElementDataFlags,
273}
274
275#[derive(Debug, Default)]
277pub struct ElementDataWrapper {
278 inner: std::cell::UnsafeCell<ElementData>,
279 #[cfg(debug_assertions)]
281 refcell: AtomicRefCell<()>,
282}
283
284#[derive(Debug)]
286pub struct ElementDataMut<'a> {
287 v: &'a mut ElementData,
288 #[cfg(debug_assertions)]
289 _borrow: AtomicRefMut<'a, ()>,
290}
291
292#[derive(Debug)]
294pub struct ElementDataRef<'a> {
295 v: &'a ElementData,
296 #[cfg(debug_assertions)]
297 _borrow: AtomicRef<'a, ()>,
298}
299
300impl ElementDataWrapper {
301 #[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 #[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
348size_of_test!(ElementData, 24);
350
351#[derive(Debug)]
353pub enum RestyleKind {
354 MatchAndCascade,
357 CascadeWithReplacements(RestyleHint),
360 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_METRICS)
373 && style
374 .flags
375 .contains(ComputedValueFlags::DEPENDS_ON_FONT_METRICS_IN_CONTAINER_QUERY)
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 .contains(ComputedValueFlags::DEPENDS_ON_CONTAINER_STYLE_QUERY)
385}
386
387impl ElementData {
388 pub fn invalidate_style_if_needed<'a, E: TElement>(
392 &mut self,
393 element: E,
394 shared_context: &SharedStyleContext,
395 stack_limit_checker: Option<&StackLimitChecker>,
396 selector_caches: &'a mut SelectorCaches,
397 ) -> InvalidationResult {
398 if shared_context.traversal_flags.for_animation_only() {
400 return InvalidationResult::empty();
401 }
402
403 use crate::invalidation::element::invalidator::TreeStyleInvalidator;
404 use crate::invalidation::element::state_and_attributes::StateAndAttrInvalidationProcessor;
405
406 debug!(
407 "invalidate_style_if_needed: {:?}, flags: {:?}, has_snapshot: {}, \
408 handled_snapshot: {}, pseudo: {:?}",
409 element,
410 shared_context.traversal_flags,
411 element.has_snapshot(),
412 element.handled_snapshot(),
413 element.implemented_pseudo_element()
414 );
415
416 if !element.has_snapshot() || element.handled_snapshot() {
417 return InvalidationResult::empty();
418 }
419
420 let mut processor =
421 StateAndAttrInvalidationProcessor::new(shared_context, element, self, selector_caches);
422
423 let invalidator = TreeStyleInvalidator::new(element, stack_limit_checker, &mut processor);
424
425 let result = invalidator.invalidate();
426
427 unsafe { element.set_handled_snapshot() }
428 debug_assert!(element.handled_snapshot());
429
430 result
431 }
432
433 #[inline]
435 pub fn has_styles(&self) -> bool {
436 self.styles.primary.is_some()
437 }
438
439 pub fn share_styles(&self) -> ResolvedElementStyles {
441 ResolvedElementStyles {
442 primary: self.share_primary_style(),
443 pseudos: self.styles.pseudos.clone(),
444 }
445 }
446
447 pub fn share_primary_style(&self) -> PrimaryStyle {
449 let reused_via_rule_node = self
450 .flags
451 .contains(ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE);
452
453 PrimaryStyle {
454 style: ResolvedStyle(self.styles.primary().clone()),
455 reused_via_rule_node,
456 }
457 }
458
459 pub fn clone_style_with_flags(&self, flags: ComputedValueFlags) -> ResolvedStyle {
462 let primary_style = self.styles.primary();
463 let pseudo = primary_style.pseudo();
466 ResolvedStyle(
467 primary_style
468 .deref()
469 .clone_with_flags(flags, pseudo.as_ref()),
470 )
471 }
472
473 pub fn set_styles(&mut self, new_styles: ResolvedElementStyles) -> ElementStyles {
475 self.flags.set(
476 ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE,
477 new_styles.primary.reused_via_rule_node,
478 );
479 mem::replace(&mut self.styles, new_styles.into())
480 }
481
482 pub fn restyle_kind(&self, shared_context: &SharedStyleContext) -> Option<RestyleKind> {
485 let style = match self.styles.primary {
486 Some(ref s) => s,
487 None => return Some(RestyleKind::MatchAndCascade),
488 };
489
490 if shared_context.traversal_flags.for_animation_only() {
491 return self.restyle_kind_for_animation(shared_context);
492 }
493
494 let hint = self.hint;
495 if hint.is_empty() {
496 return None;
497 }
498
499 if needs_to_match_self(hint, style) {
500 return Some(RestyleKind::MatchAndCascade);
501 }
502
503 if hint.has_replacements() {
504 debug_assert!(
505 !hint.has_animation_hint(),
506 "Animation only restyle hint should have already processed"
507 );
508 return Some(RestyleKind::CascadeWithReplacements(
509 hint & RestyleHint::replacements(),
510 ));
511 }
512
513 let needs_to_recascade_self = hint.intersects(RestyleHint::RECASCADE_SELF)
514 || (hint.intersects(RestyleHint::RECASCADE_SELF_IF_INHERIT_RESET_STYLE)
515 && style
516 .flags
517 .contains(ComputedValueFlags::INHERITS_RESET_STYLE));
518 if needs_to_recascade_self {
519 return Some(RestyleKind::CascadeOnly);
520 }
521
522 None
523 }
524
525 fn restyle_kind_for_animation(
527 &self,
528 shared_context: &SharedStyleContext,
529 ) -> Option<RestyleKind> {
530 debug_assert!(shared_context.traversal_flags.for_animation_only());
531 debug_assert!(self.has_styles());
532
533 let hint = self.hint;
542 if self.styles.is_display_none() && hint.intersects(RestyleHint::RESTYLE_SELF) {
543 return None;
544 }
545
546 let style = self.styles.primary();
547 if hint.has_animation_hint() {
550 return Some(RestyleKind::CascadeWithReplacements(
551 hint & RestyleHint::for_animations(),
552 ));
553 }
554
555 let needs_to_recascade_self = hint.intersects(RestyleHint::RECASCADE_SELF)
556 || (hint.intersects(RestyleHint::RECASCADE_SELF_IF_INHERIT_RESET_STYLE)
557 && style
558 .flags
559 .contains(ComputedValueFlags::INHERITS_RESET_STYLE));
560 if needs_to_recascade_self {
561 return Some(RestyleKind::CascadeOnly);
562 }
563 return None;
564 }
565
566 #[inline]
571 pub fn clear_restyle_state(&mut self) {
572 self.hint = RestyleHint::empty();
573 self.clear_restyle_flags_and_damage();
574 }
575
576 #[inline]
578 pub fn clear_restyle_flags_and_damage(&mut self) {
579 self.damage = RestyleDamage::empty();
580 self.flags.remove(ElementDataFlags::WAS_RESTYLED);
581 }
582
583 pub fn set_restyled(&mut self) {
586 self.flags.insert(ElementDataFlags::WAS_RESTYLED);
587 self.flags
588 .remove(ElementDataFlags::TRAVERSED_WITHOUT_STYLING);
589 }
590
591 #[inline]
593 pub fn is_restyle(&self) -> bool {
594 self.flags.contains(ElementDataFlags::WAS_RESTYLED)
595 }
596
597 pub fn set_traversed_without_styling(&mut self) {
599 self.flags
600 .insert(ElementDataFlags::TRAVERSED_WITHOUT_STYLING);
601 }
602
603 #[inline]
605 pub fn contains_restyle_data(&self) -> bool {
606 self.is_restyle() || !self.hint.is_empty() || !self.damage.is_empty()
607 }
608
609 pub fn safe_for_cousin_sharing(&self) -> bool {
628 if self.flags.intersects(
629 ElementDataFlags::TRAVERSED_WITHOUT_STYLING
630 | ElementDataFlags::PRIMARY_STYLE_REUSED_VIA_RULE_NODE,
631 ) {
632 return false;
633 }
634 if !self
635 .styles
636 .primary()
637 .get_box()
638 .clone_container_type()
639 .is_normal()
640 {
641 return false;
642 }
643 true
644 }
645
646 #[cfg(feature = "gecko")]
648 pub fn size_of_excluding_cvs(&self, ops: &mut MallocSizeOfOps) -> usize {
649 let n = self.styles.size_of_excluding_cvs(ops);
650
651 n
654 }
655}