1#![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#[repr(u32)]
34#[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, PartialEq)]
35pub enum RuleChangeKind {
36 Generic = 0,
39 Insertion,
41 Removal,
43 StyleRuleDeclarations,
45 PositionTryDeclarations,
47}
48
49#[derive(Clone, Copy, Debug, Eq, PartialEq)]
54enum Invalidation<'a> {
55 ID(&'a AtomIdent),
57 Class(&'a AtomIdent),
59 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#[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#[derive(Debug, Default, MallocSizeOf)]
111pub struct StylesheetInvalidationSet {
112 buckets: SimpleBucketsMap<InvalidationKind>,
113 style_fully_invalid: bool,
114 pub cascade_data_difference: CascadeDataDifference,
117}
118
119impl StylesheetInvalidationSet {
120 pub fn new() -> Self {
122 Default::default()
123 }
124
125 pub fn invalidate_fully(&mut self) {
127 debug!("StylesheetInvalidationSet::invalidate_fully");
128 self.buckets.clear();
129 self.style_fully_invalid = true;
130 }
131
132 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; }
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 false,
166 &[],
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 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 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 #[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 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 },
390 }
391 }
392
393 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 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 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; }
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 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 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 false,
590 &[],
592 );
593 if self.style_fully_invalid {
594 break;
595 }
596 }
597 }
598
599 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 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 },
641 LayerStatement(..) => {
642 },
645 Document(..) | Import(..) | Media(..) | Supports(..) | Container(..)
646 | LayerBlock(..) | StartingStyle(..) | AppearanceBase(..) => {
647 },
649 FontFace(..) => {
650 },
653 Page(..) | Margin(..) => {
654 },
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 }
671 },
672 CounterStyle(..) | Property(..) | FontFeatureValues(..) | FontPaletteValues(..) => {
673 debug!(" > Found unsupported rule, marking the whole subtree invalid.");
674 self.invalidate_fully();
675 },
676 Scope(..) => {
677 self.invalidate_fully();
680 },
681 PositionTry(..) => {
682 },
685 ViewTransition(..) => {
686 },
688 CustomMedia(..) => {
689 self.invalidate_fully();
694 },
695 }
696 }
697}
698
699pub 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}