/
matching.rs
1586 lines (1423 loc) · 69.9 KB
/
matching.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! High-level interface to CSS selector matching.
#![allow(unsafe_code)]
#![deny(missing_docs)]
use applicable_declarations::ApplicableDeclarationList;
use cascade_info::CascadeInfo;
use context::{CascadeInputs, SelectorFlagsMap, SharedStyleContext, StyleContext};
use data::{ElementData, ElementStyles, RestyleData};
use dom::{TElement, TNode};
use font_metrics::FontMetricsProvider;
use invalidation::element::restyle_hints::{RESTYLE_CSS_ANIMATIONS, RESTYLE_CSS_TRANSITIONS};
use invalidation::element::restyle_hints::{RESTYLE_SMIL, RESTYLE_STYLE_ATTRIBUTE};
use invalidation::element::restyle_hints::RestyleHint;
use log::LogLevel::Trace;
use properties::{AnimationRules, CascadeFlags, ComputedValues};
use properties::{IS_ROOT_ELEMENT, PROHIBIT_DISPLAY_CONTENTS, SKIP_ROOT_AND_ITEM_BASED_DISPLAY_FIXUP};
use properties::{VISITED_DEPENDENT_ONLY, cascade};
use properties::longhands::display::computed_value as display;
use rule_tree::{CascadeLevel, StrongRuleNode};
use selector_parser::{PseudoElement, RestyleDamage, SelectorImpl};
use selectors::matching::{ElementSelectorFlags, MatchingContext, MatchingMode, StyleRelations};
use selectors::matching::{VisitedHandlingMode, AFFECTED_BY_PSEUDO_ELEMENTS};
use sharing::StyleSharingBehavior;
use stylearc::Arc;
use stylist::RuleInclusion;
/// Whether we are cascading for an eager pseudo-element or something else.
///
/// Controls where we inherit styles from, and whether display:contents is
/// prohibited.
#[derive(PartialEq, Copy, Clone, Debug)]
enum CascadeTarget {
/// Inherit from the parent element, as normal CSS dictates, _or_ from the
/// closest non-Native Anonymous element in case this is Native Anonymous
/// Content. display:contents is allowed.
Normal,
/// Inherit from the primary style, this is used while computing eager
/// pseudos, like ::before and ::after when we're traversing the parent.
/// Also prohibits display:contents from having an effect.
///
/// TODO(emilio) display:contents really should apply to ::before/::after.
/// https://github.com/w3c/csswg-drafts/issues/1345
EagerPseudo,
}
/// Represents the result of comparing an element's old and new style.
pub struct StyleDifference {
/// The resulting damage.
pub damage: RestyleDamage,
/// Whether any styles changed.
pub change: StyleChange,
}
impl StyleDifference {
/// Creates a new `StyleDifference`.
pub fn new(damage: RestyleDamage, change: StyleChange) -> Self {
StyleDifference {
change: change,
damage: damage,
}
}
}
/// Represents whether or not the style of an element has changed.
#[derive(Copy, Clone)]
pub enum StyleChange {
/// The style hasn't changed.
Unchanged,
/// The style has changed.
Changed,
}
/// Whether or not newly computed values for an element need to be cascade
/// to children.
pub enum ChildCascadeRequirement {
/// Old and new computed values were the same, or we otherwise know that
/// we won't bother recomputing style for children, so we can skip cascading
/// the new values into child elements.
CanSkipCascade,
/// Old and new computed values were different, so we must cascade the
/// new values to children.
///
/// FIXME(heycam) Although this is "must" cascade, in the future we should
/// track whether child elements rely specifically on inheriting particular
/// property values. When we do that, we can treat `MustCascadeChildren` as
/// "must cascade unless we know that changes to these properties can be
/// ignored".
MustCascadeChildren,
/// The same as `MustCascadeChildren`, but for the entire subtree. This is
/// used to handle root font-size updates needing to recascade the whole
/// document.
MustCascadeDescendants,
}
impl From<StyleChange> for ChildCascadeRequirement {
fn from(change: StyleChange) -> ChildCascadeRequirement {
match change {
StyleChange::Unchanged => ChildCascadeRequirement::CanSkipCascade,
StyleChange::Changed => ChildCascadeRequirement::MustCascadeChildren,
}
}
}
bitflags! {
/// Flags that represent the result of replace_rules.
pub flags RulesChanged: u8 {
/// Normal rules are changed.
const NORMAL_RULES_CHANGED = 0x01,
/// Important rules are changed.
const IMPORTANT_RULES_CHANGED = 0x02,
}
}
impl RulesChanged {
/// Return true if there are any normal rules changed.
#[inline]
pub fn normal_rules_changed(&self) -> bool {
self.contains(NORMAL_RULES_CHANGED)
}
/// Return true if there are any important rules changed.
#[inline]
pub fn important_rules_changed(&self) -> bool {
self.contains(IMPORTANT_RULES_CHANGED)
}
}
/// Determines which styles are being cascaded currently.
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub enum CascadeVisitedMode {
/// Cascade the regular, unvisited styles.
Unvisited,
/// Cascade the styles used when an element's relevant link is visited. A
/// "relevant link" is the element being matched if it is a link or the
/// nearest ancestor link.
Visited,
}
/// Various helper methods to ease navigating the style storage locations
/// depending on the current cascade mode.
impl CascadeVisitedMode {
/// Returns whether there is a rule node based on the cascade mode.
/// Rules will be present after matching or pulled from a previous cascade
/// if no matching is expected. For visited, this means rules exist only
/// if a revelant link existed when matching was last done.
fn has_rules(&self, inputs: &CascadeInputs) -> bool {
match *self {
CascadeVisitedMode::Unvisited => inputs.has_rules(),
CascadeVisitedMode::Visited => inputs.has_visited_rules(),
}
}
/// Returns the rule node based on the cascade mode.
fn rules<'a>(&self, inputs: &'a CascadeInputs) -> &'a StrongRuleNode {
match *self {
CascadeVisitedMode::Unvisited => inputs.rules(),
CascadeVisitedMode::Visited => inputs.visited_rules(),
}
}
/// Returns a mutable rules node based on the cascade mode, if any.
fn get_rules_mut<'a>(&self, inputs: &'a mut CascadeInputs) -> Option<&'a mut StrongRuleNode> {
match *self {
CascadeVisitedMode::Unvisited => inputs.get_rules_mut(),
CascadeVisitedMode::Visited => inputs.get_visited_rules_mut(),
}
}
/// Returns the computed values based on the cascade mode. In visited mode,
/// visited values are only returned if they already exist. If they don't,
/// we fallback to the regular, unvisited styles.
fn values<'a>(&self, values: &'a Arc<ComputedValues>) -> &'a Arc<ComputedValues> {
if *self == CascadeVisitedMode::Visited && values.get_visited_style().is_some() {
return values.visited_style();
}
values
}
/// Set the primary computed values based on the cascade mode.
fn set_primary_values(&self,
styles: &mut ElementStyles,
inputs: &mut CascadeInputs,
values: Arc<ComputedValues>) {
// Unvisited values are stored in permanent storage on `ElementData`.
// Visited values are stored temporarily in `CascadeInputs` and then
// folded into the unvisited values when they cascade.
match *self {
CascadeVisitedMode::Unvisited => styles.primary = Some(values),
CascadeVisitedMode::Visited => inputs.set_visited_values(values),
}
}
/// Set the primary computed values based on the cascade mode.
fn set_pseudo_values(&self,
styles: &mut ElementStyles,
inputs: &mut CascadeInputs,
pseudo: &PseudoElement,
values: Arc<ComputedValues>) {
// Unvisited values are stored in permanent storage on `ElementData`.
// Visited values are stored temporarily in `CascadeInputs` and then
// folded into the unvisited values when they cascade.
match *self {
CascadeVisitedMode::Unvisited => styles.pseudos.set(pseudo, values),
CascadeVisitedMode::Visited => inputs.set_visited_values(values),
}
}
/// Take the primary computed values based on the cascade mode.
fn take_primary_values(&self,
styles: &mut ElementStyles,
inputs: &mut CascadeInputs)
-> Option<Arc<ComputedValues>> {
// Unvisited values are stored in permanent storage on `ElementData`.
// Visited values are stored temporarily in `CascadeInputs` and then
// folded into the unvisited values when they cascade.
match *self {
CascadeVisitedMode::Unvisited => styles.primary.take(),
CascadeVisitedMode::Visited => inputs.take_visited_values(),
}
}
/// Take the pseudo computed values based on the cascade mode.
fn take_pseudo_values(&self,
styles: &mut ElementStyles,
inputs: &mut CascadeInputs,
pseudo: &PseudoElement)
-> Option<Arc<ComputedValues>> {
// Unvisited values are stored in permanent storage on `ElementData`.
// Visited values are stored temporarily in `CascadeInputs` and then
// folded into the unvisited values when they cascade.
match *self {
CascadeVisitedMode::Unvisited => styles.pseudos.take(pseudo),
CascadeVisitedMode::Visited => inputs.take_visited_values(),
}
}
/// Returns whether there might be visited values that should be inserted
/// within the regular computed values based on the cascade mode.
fn visited_values_for_insertion(&self) -> bool {
*self == CascadeVisitedMode::Unvisited
}
/// Returns whether animations should be processed based on the cascade
/// mode. At the moment, it appears we don't need to support animating
/// visited styles.
fn should_process_animations(&self) -> bool {
*self == CascadeVisitedMode::Unvisited
}
/// Returns whether we should accumulate restyle damage based on the cascade
/// mode. At the moment, it appears we don't need to do so for visited
/// styles. TODO: Verify this is correct as part of
/// https://bugzilla.mozilla.org/show_bug.cgi?id=1364484.
fn should_accumulate_damage(&self) -> bool {
*self == CascadeVisitedMode::Unvisited
}
/// Returns whether the cascade should filter to only visited dependent
/// properties based on the cascade mode.
fn visited_dependent_only(&self) -> bool {
*self == CascadeVisitedMode::Visited
}
}
trait PrivateMatchMethods: TElement {
/// Returns the closest parent element that doesn't have a display: contents
/// style (and thus generates a box).
///
/// This is needed to correctly handle blockification of flex and grid
/// items.
///
/// Returns itself if the element has no parent. In practice this doesn't
/// happen because the root element is blockified per spec, but it could
/// happen if we decide to not blockify for roots of disconnected subtrees,
/// which is a kind of dubious beahavior.
fn layout_parent(&self) -> Self {
let mut current = self.clone();
loop {
current = match current.traversal_parent() {
Some(el) => el,
None => return current,
};
let is_display_contents =
current.borrow_data().unwrap().styles.primary().is_display_contents();
if !is_display_contents {
return current;
}
}
}
/// A common path for the cascade used by both primary elements and eager
/// pseudo-elements after collecting the appropriate rules to use.
///
/// `primary_style` is expected to be Some for eager pseudo-elements.
fn cascade_with_rules(&self,
shared_context: &SharedStyleContext,
font_metrics_provider: &FontMetricsProvider,
rule_node: &StrongRuleNode,
primary_style: Option<&Arc<ComputedValues>>,
cascade_target: CascadeTarget,
cascade_visited: CascadeVisitedMode,
visited_values_to_insert: Option<Arc<ComputedValues>>)
-> Arc<ComputedValues> {
let mut cascade_info = CascadeInfo::new();
let mut cascade_flags = CascadeFlags::empty();
if self.skip_root_and_item_based_display_fixup() {
cascade_flags.insert(SKIP_ROOT_AND_ITEM_BASED_DISPLAY_FIXUP)
}
if cascade_visited.visited_dependent_only() {
cascade_flags.insert(VISITED_DEPENDENT_ONLY);
}
if self.is_native_anonymous() || cascade_target == CascadeTarget::EagerPseudo {
cascade_flags.insert(PROHIBIT_DISPLAY_CONTENTS);
} else if self.is_root() {
debug_assert!(self.owner_doc_matches_for_testing(shared_context.stylist.device()));
cascade_flags.insert(IS_ROOT_ELEMENT);
}
// Grab the inherited values.
let parent_el;
let parent_data;
let style_to_inherit_from = match cascade_target {
CascadeTarget::Normal => {
parent_el = self.inheritance_parent();
parent_data = parent_el.as_ref().and_then(|e| e.borrow_data());
let parent_style = parent_data.as_ref().map(|d| {
// Sometimes Gecko eagerly styles things without processing
// pending restyles first. In general we'd like to avoid this,
// but there can be good reasons (for example, needing to
// construct a frame for some small piece of newly-added
// content in order to do something specific with that frame,
// but not wanting to flush all of layout).
debug_assert!(cfg!(feature = "gecko") ||
parent_el.unwrap().has_current_styles(d));
d.styles.primary()
});
parent_style.map(|s| cascade_visited.values(s))
}
CascadeTarget::EagerPseudo => {
parent_el = Some(self.clone());
Some(cascade_visited.values(primary_style.unwrap()))
}
};
let mut layout_parent_el = parent_el.clone();
let layout_parent_data;
let mut layout_parent_style = style_to_inherit_from;
if style_to_inherit_from.map_or(false, |s| s.is_display_contents()) {
layout_parent_el = Some(layout_parent_el.unwrap().layout_parent());
layout_parent_data = layout_parent_el.as_ref().unwrap().borrow_data().unwrap();
layout_parent_style = Some(cascade_visited.values(layout_parent_data.styles.primary()));
}
let style_to_inherit_from = style_to_inherit_from.map(|x| &**x);
let layout_parent_style = layout_parent_style.map(|x| &**x);
// Propagate the "can be fragmented" bit. It would be nice to
// encapsulate this better.
//
// Note that this is technically not needed for pseudos since we already
// do that when we resolve the non-pseudo style, but it doesn't hurt
// anyway.
//
// TODO(emilio): This is servo-only, move somewhere else?
if let Some(ref p) = layout_parent_style {
let can_be_fragmented =
p.is_multicol() ||
layout_parent_el.as_ref().unwrap().as_node().can_be_fragmented();
unsafe { self.as_node().set_can_be_fragmented(can_be_fragmented); }
}
// Invoke the cascade algorithm.
let values =
Arc::new(cascade(shared_context.stylist.device(),
rule_node,
&shared_context.guards,
style_to_inherit_from,
layout_parent_style,
visited_values_to_insert,
Some(&mut cascade_info),
&*shared_context.error_reporter,
font_metrics_provider,
cascade_flags,
shared_context.quirks_mode));
cascade_info.finish(&self.as_node());
values
}
/// A common path for the cascade used by both primary elements and eager
/// pseudo-elements.
///
/// `primary_style` is expected to be Some for eager pseudo-elements.
fn cascade_internal(&self,
context: &StyleContext<Self>,
primary_style: Option<&Arc<ComputedValues>>,
primary_inputs: &CascadeInputs,
eager_pseudo_inputs: Option<&CascadeInputs>,
cascade_visited: CascadeVisitedMode)
-> Arc<ComputedValues> {
if let Some(pseudo) = self.implemented_pseudo_element() {
debug_assert!(eager_pseudo_inputs.is_none());
// This is an element-backed pseudo, just grab the styles from the
// parent if it's eager, and recascade otherwise.
//
// We also recascade if the eager pseudo-style has any animation
// rules, because we don't cascade those during the eager traversal.
//
// We could make that a bit better if the complexity cost is not too
// big, but given further restyles are posted directly to
// pseudo-elements, it doesn't seem worth the effort at a glance.
//
// For the same reason as described in match_primary, if we are
// computing default styles, we aren't guaranteed the parent
// will have eagerly computed our styles, so we just handled it
// below like a lazy pseudo.
let only_default_rules = context.shared.traversal_flags.for_default_styles();
if pseudo.is_eager() && !only_default_rules {
debug_assert!(pseudo.is_before_or_after());
let parent = self.parent_element().unwrap();
if !parent.may_have_animations() ||
primary_inputs.rules().get_animation_rules().is_empty() {
let parent_data = parent.borrow_data().unwrap();
let pseudo_style =
parent_data.styles.pseudos.get(&pseudo).unwrap();
let values = cascade_visited.values(pseudo_style);
return values.clone()
}
}
}
// Find possible visited computed styles to insert within the regular
// computed values we are about to create.
let visited_values_to_insert = if cascade_visited.visited_values_for_insertion() {
match eager_pseudo_inputs {
Some(ref s) => s.clone_visited_values(),
None => primary_inputs.clone_visited_values(),
}
} else {
None
};
// Grab the rule node.
let inputs = eager_pseudo_inputs.unwrap_or(primary_inputs);
// We'd really like to take the rules here to avoid refcount traffic,
// but animation's usage of `apply_declarations` make this tricky.
// See bug 1375525.
let rule_node = cascade_visited.rules(inputs);
let cascade_target = if eager_pseudo_inputs.is_some() {
CascadeTarget::EagerPseudo
} else {
CascadeTarget::Normal
};
self.cascade_with_rules(context.shared,
&context.thread_local.font_metrics_provider,
rule_node,
primary_style,
cascade_target,
cascade_visited,
visited_values_to_insert)
}
/// Computes values and damage for the primary style of an element, setting
/// them on the ElementData.
fn cascade_primary(&self,
context: &mut StyleContext<Self>,
data: &mut ElementData,
important_rules_changed: bool,
cascade_visited: CascadeVisitedMode)
-> ChildCascadeRequirement {
debug!("Cascade primary for {:?}, visited: {:?}", self, cascade_visited);
let mut old_values = cascade_visited.take_primary_values(
&mut data.styles,
context.cascade_inputs_mut().primary_mut()
);
let mut new_values = {
let primary_inputs = context.cascade_inputs().primary();
// If there was no relevant link at the time of matching, we won't
// have any visited rules, so there may not be anything do for the
// visited case. This early return is especially important for the
// `cascade_primary_and_pseudos` path since we rely on the state of
// some previous matching run.
if !cascade_visited.has_rules(primary_inputs) {
return ChildCascadeRequirement::CanSkipCascade
}
// Compute the new values.
self.cascade_internal(context,
None,
primary_inputs,
None,
cascade_visited)
};
// NB: Animations for pseudo-elements in Gecko are handled while
// traversing the pseudo-elements themselves.
if !context.shared.traversal_flags.for_animation_only() &&
cascade_visited.should_process_animations() {
self.process_animations(context,
&mut old_values,
&mut new_values,
important_rules_changed);
}
let mut child_cascade_requirement =
ChildCascadeRequirement::CanSkipCascade;
if cascade_visited.should_accumulate_damage() {
child_cascade_requirement =
self.accumulate_damage(&context.shared,
&mut data.restyle,
old_values.as_ref().map(|v| v.as_ref()),
&new_values,
None);
// Handle root font-size changes.
if self.is_root() && !self.is_native_anonymous() {
// The new root font-size has already been updated on the Device
// in properties::apply_declarations.
let device = context.shared.stylist.device();
let new_font_size = new_values.get_font().clone_font_size();
// If the root font-size changed since last time, and something
// in the document did use rem units, ensure we recascade the
// entire tree.
if old_values.map_or(false, |v| v.get_font().clone_font_size() != new_font_size) &&
device.used_root_font_size() {
child_cascade_requirement = ChildCascadeRequirement::MustCascadeDescendants;
}
}
}
// Set the new computed values.
let primary_inputs = context.cascade_inputs_mut().primary_mut();
cascade_visited.set_primary_values(&mut data.styles,
primary_inputs,
new_values);
// Return whether the damage indicates we must cascade new inherited
// values into children.
child_cascade_requirement
}
/// Computes values and damage for the eager pseudo-element styles of an
/// element, setting them on the ElementData.
fn cascade_eager_pseudo(&self,
context: &mut StyleContext<Self>,
data: &mut ElementData,
pseudo: &PseudoElement,
cascade_visited: CascadeVisitedMode) {
debug_assert!(pseudo.is_eager());
let old_values = cascade_visited.take_pseudo_values(
&mut data.styles,
context.cascade_inputs_mut().pseudos.get_mut(pseudo).unwrap(),
pseudo
);
let new_values = {
let pseudo_inputs = context.cascade_inputs().pseudos
.get(pseudo).unwrap();
// If there was no relevant link at the time of matching, we won't
// have any visited rules, so there may not be anything do for the
// visited case. This early return is especially important for the
// `cascade_primary_and_pseudos` path since we rely on the state of
// some previous matching run.
if !cascade_visited.has_rules(pseudo_inputs) {
return
}
// Primary inputs should already have rules populated since it's
// always processed before eager pseudos.
let primary_inputs = context.cascade_inputs().primary();
debug_assert!(cascade_visited.has_rules(primary_inputs));
self.cascade_internal(context,
data.styles.get_primary(),
primary_inputs,
Some(pseudo_inputs),
cascade_visited)
};
if cascade_visited.should_accumulate_damage() {
self.accumulate_damage(&context.shared,
&mut data.restyle,
old_values.as_ref().map(|v| v.as_ref()),
&new_values,
Some(pseudo));
}
let pseudo_inputs = context.cascade_inputs_mut().pseudos
.get_mut(pseudo).unwrap();
cascade_visited.set_pseudo_values(&mut data.styles,
pseudo_inputs,
pseudo,
new_values);
}
/// get_after_change_style removes the transition rules from the ComputedValues.
/// If there is no transition rule in the ComputedValues, it returns None.
#[cfg(feature = "gecko")]
fn get_after_change_style(&self,
context: &mut StyleContext<Self>,
primary_style: &Arc<ComputedValues>)
-> Option<Arc<ComputedValues>> {
let rule_node = primary_style.rules();
let without_transition_rules =
context.shared.stylist.rule_tree().remove_transition_rule_if_applicable(rule_node);
if without_transition_rules == *rule_node {
// We don't have transition rule in this case, so return None to let the caller
// use the original ComputedValues.
return None;
}
// This currently ignores visited styles, which seems acceptable,
// as existing browsers don't appear to transition visited styles.
Some(self.cascade_with_rules(context.shared,
&context.thread_local.font_metrics_provider,
&without_transition_rules,
Some(primary_style),
CascadeTarget::Normal,
CascadeVisitedMode::Unvisited,
None))
}
#[cfg(feature = "gecko")]
fn needs_animations_update(&self,
context: &mut StyleContext<Self>,
old_values: Option<&Arc<ComputedValues>>,
new_values: &ComputedValues)
-> bool {
let new_box_style = new_values.get_box();
let has_new_animation_style = new_box_style.animation_name_count() >= 1 &&
new_box_style.animation_name_at(0).0.is_some();
let has_animations = self.has_css_animations();
old_values.map_or(has_new_animation_style, |old| {
let old_box_style = old.get_box();
let old_display_style = old_box_style.clone_display();
let new_display_style = new_box_style.clone_display();
// If the traverse is triggered by CSS rule changes, we need to
// try to update all CSS animations on the element if the element
// has CSS animation style regardless of whether the animation is
// running or not.
// TODO: We should check which @keyframes changed/added/deleted
// and update only animations corresponding to those @keyframes.
(context.shared.traversal_flags.for_css_rule_changes() &&
has_new_animation_style) ||
!old_box_style.animations_equals(&new_box_style) ||
(old_display_style == display::T::none &&
new_display_style != display::T::none &&
has_new_animation_style) ||
(old_display_style != display::T::none &&
new_display_style == display::T::none &&
has_animations)
})
}
#[cfg(feature = "gecko")]
fn process_animations(&self,
context: &mut StyleContext<Self>,
old_values: &mut Option<Arc<ComputedValues>>,
new_values: &mut Arc<ComputedValues>,
important_rules_changed: bool) {
use context::{CASCADE_RESULTS, CSS_ANIMATIONS, CSS_TRANSITIONS, EFFECT_PROPERTIES};
use context::UpdateAnimationsTasks;
let mut tasks = UpdateAnimationsTasks::empty();
if self.needs_animations_update(context, old_values.as_ref(), new_values) {
tasks.insert(CSS_ANIMATIONS);
}
let before_change_style = if self.might_need_transitions_update(old_values.as_ref().map(|s| &**s),
new_values) {
let after_change_style = if self.has_css_transitions() {
self.get_after_change_style(context, new_values)
} else {
None
};
// In order to avoid creating a SequentialTask for transitions which
// may not be updated, we check it per property to make sure Gecko
// side will really update transition.
let needs_transitions_update = {
// We borrow new_values here, so need to add a scope to make
// sure we release it before assigning a new value to it.
let after_change_style_ref =
after_change_style.as_ref().unwrap_or(&new_values);
self.needs_transitions_update(old_values.as_ref().unwrap(),
after_change_style_ref)
};
if needs_transitions_update {
if let Some(values_without_transitions) = after_change_style {
*new_values = values_without_transitions;
}
tasks.insert(CSS_TRANSITIONS);
// We need to clone old_values into SequentialTask, so we can use it later.
old_values.clone()
} else {
None
}
} else {
None
};
if self.has_animations() {
tasks.insert(EFFECT_PROPERTIES);
if important_rules_changed {
tasks.insert(CASCADE_RESULTS);
}
}
if !tasks.is_empty() {
let task = ::context::SequentialTask::update_animations(*self,
before_change_style,
tasks);
context.thread_local.tasks.push(task);
}
}
#[cfg(feature = "servo")]
fn process_animations(&self,
context: &mut StyleContext<Self>,
old_values: &mut Option<Arc<ComputedValues>>,
new_values: &mut Arc<ComputedValues>,
_important_rules_changed: bool) {
use animation;
let possibly_expired_animations =
&mut context.thread_local.current_element_info.as_mut().unwrap()
.possibly_expired_animations;
let shared_context = context.shared;
if let Some(ref mut old) = *old_values {
self.update_animations_for_cascade(shared_context, old,
possibly_expired_animations,
&context.thread_local.font_metrics_provider);
}
let new_animations_sender = &context.thread_local.new_animations_sender;
let this_opaque = self.as_node().opaque();
// Trigger any present animations if necessary.
animation::maybe_start_animations(&shared_context,
new_animations_sender,
this_opaque, &new_values);
// Trigger transitions if necessary. This will reset `new_values` back
// to its old value if it did trigger a transition.
if let Some(ref values) = *old_values {
animation::start_transitions_if_applicable(
new_animations_sender,
this_opaque,
&**values,
new_values,
&shared_context.timer,
&possibly_expired_animations);
}
}
/// Computes and applies non-redundant damage.
#[cfg(feature = "gecko")]
fn accumulate_damage_for(&self,
shared_context: &SharedStyleContext,
restyle: &mut RestyleData,
old_values: &ComputedValues,
new_values: &Arc<ComputedValues>,
pseudo: Option<&PseudoElement>)
-> ChildCascadeRequirement {
// Don't accumulate damage if we're in a restyle for reconstruction.
if shared_context.traversal_flags.for_reconstruct() {
return ChildCascadeRequirement::MustCascadeChildren;
}
// If an ancestor is already getting reconstructed by Gecko's top-down
// frame constructor, no need to apply damage. Similarly if we already
// have an explicitly stored ReconstructFrame hint.
//
// See https://bugzilla.mozilla.org/show_bug.cgi?id=1301258#c12
// for followup work to make the optimization here more optimal by considering
// each bit individually.
let skip_applying_damage =
restyle.reconstructed_self_or_ancestor();
let difference = self.compute_style_difference(&old_values,
&new_values,
pseudo);
if !skip_applying_damage {
restyle.damage |= difference.damage;
}
difference.change.into()
}
/// Computes and applies restyle damage unless we've already maxed it out.
#[cfg(feature = "servo")]
fn accumulate_damage_for(&self,
_shared_context: &SharedStyleContext,
restyle: &mut RestyleData,
old_values: &ComputedValues,
new_values: &Arc<ComputedValues>,
pseudo: Option<&PseudoElement>)
-> ChildCascadeRequirement {
let difference = self.compute_style_difference(&old_values, &new_values, pseudo);
restyle.damage |= difference.damage;
difference.change.into()
}
#[cfg(feature = "servo")]
fn update_animations_for_cascade(&self,
context: &SharedStyleContext,
style: &mut Arc<ComputedValues>,
possibly_expired_animations: &mut Vec<::animation::PropertyAnimation>,
font_metrics: &FontMetricsProvider) {
use animation::{self, Animation};
// Finish any expired transitions.
let this_opaque = self.as_node().opaque();
animation::complete_expired_transitions(this_opaque, style, context);
// Merge any running transitions into the current style, and cancel them.
let had_running_animations = context.running_animations
.read()
.get(&this_opaque)
.is_some();
if had_running_animations {
let mut all_running_animations = context.running_animations.write();
for running_animation in all_running_animations.get_mut(&this_opaque).unwrap() {
// This shouldn't happen frequently, but under some
// circumstances mainly huge load or debug builds, the
// constellation might be delayed in sending the
// `TickAllAnimations` message to layout.
//
// Thus, we can't assume all the animations have been already
// updated by layout, because other restyle due to script might
// be triggered by layout before the animation tick.
//
// See #12171 and the associated PR for an example where this
// happened while debugging other release panic.
if !running_animation.is_expired() {
animation::update_style_for_animation(context,
running_animation,
style,
font_metrics);
if let Animation::Transition(_, _, ref frame, _) = *running_animation {
possibly_expired_animations.push(frame.property_animation.clone())
}
}
}
}
}
}
impl<E: TElement> PrivateMatchMethods for E {}
/// Collects the outputs of the primary matching process, including the rule
/// node and other associated data.
#[derive(Debug)]
pub struct MatchingResults {
/// Whether the rules changed.
rules_changed: bool,
/// Whether there are any changes of important rules overriding animations.
important_rules_overriding_animation_changed: bool,
/// Records certains relations between elements noticed during matching (and
/// also extended after matching).
relations: StyleRelations,
/// Whether we encountered a "relevant link" while matching _any_ selector
/// for this element. (This differs from `RelevantLinkStatus` which tracks
/// the status for the _current_ selector only.)
relevant_link_found: bool,
}
impl MatchingResults {
/// Create `MatchingResults` with only the basic required outputs.
fn new(rules_changed: bool, important_rules: bool) -> Self {
Self {
rules_changed: rules_changed,
important_rules_overriding_animation_changed: important_rules,
relations: StyleRelations::default(),
relevant_link_found: false,
}
}
/// Create `MatchingResults` from the output fields of `MatchingContext`.
fn new_from_context(rules_changed: bool,
important_rules: bool,
context: MatchingContext)
-> Self {
Self {
rules_changed: rules_changed,
important_rules_overriding_animation_changed: important_rules,
relations: context.relations,
relevant_link_found: context.relevant_link_found,
}
}
}
/// The public API that elements expose for selector matching.
pub trait MatchMethods : TElement {
/// Performs selector matching and property cascading on an element and its
/// eager pseudos.
fn match_and_cascade(&self,
context: &mut StyleContext<Self>,
data: &mut ElementData,
sharing: StyleSharingBehavior)
-> ChildCascadeRequirement
{
debug!("Match and cascade for {:?}", self);
// Perform selector matching for the primary style.
let mut primary_results =
self.match_primary(context, data, VisitedHandlingMode::AllLinksUnvisited);
let important_rules_changed =
primary_results.important_rules_overriding_animation_changed;
// If there's a relevant link involved, match and cascade primary styles
// as if the link is visited as well. This is done before the regular
// cascade because the visited ComputedValues are placed within the
// regular ComputedValues, which is immutable after the cascade.
let relevant_link_found = primary_results.relevant_link_found;
if relevant_link_found {
self.match_primary(context, data, VisitedHandlingMode::RelevantLinkVisited);
self.cascade_primary(context, data, important_rules_changed,
CascadeVisitedMode::Visited);
}
// Cascade properties and compute primary values.
let child_cascade_requirement =
self.cascade_primary(context, data, important_rules_changed,
CascadeVisitedMode::Unvisited);
// Match and cascade eager pseudo-elements.
if !data.styles.is_display_none() {
self.match_pseudos(context, data, VisitedHandlingMode::AllLinksUnvisited);
// If there's a relevant link involved, match and cascade eager
// pseudo-element styles as if the link is visited as well.
// This runs after matching for regular styles because matching adds
// each pseudo as needed to the PseudoMap, and this runs before
// cascade for regular styles because the visited ComputedValues
// are placed within the regular ComputedValues, which is immutable
// after the cascade.
if relevant_link_found {
self.match_pseudos(context, data, VisitedHandlingMode::RelevantLinkVisited);
self.cascade_pseudos(context, data, CascadeVisitedMode::Visited);
}
self.cascade_pseudos(context, data, CascadeVisitedMode::Unvisited);
}
// If we have any pseudo elements, indicate so in the primary StyleRelations.
if !data.styles.pseudos.is_empty() {
primary_results.relations |= AFFECTED_BY_PSEUDO_ELEMENTS;
}
// If the style is shareable, add it to the LRU cache.
if sharing == StyleSharingBehavior::Allow {
// If we previously tried to match this element against the cache,
// the revalidation match results will already be cached. Otherwise
// we'll have None, and compute them later on-demand.
//
// If we do have the results, grab them here to satisfy the borrow
// checker.
let validation_data =
context.thread_local
.current_element_info
.as_mut().unwrap()
.validation_data
.take();
let dom_depth = context.thread_local.bloom_filter.matching_depth();
context.thread_local
.style_sharing_candidate_cache
.insert_if_possible(self,
data.styles.primary(),
primary_results.relations,
validation_data,
dom_depth);
}
child_cascade_requirement
}
/// Performs the cascade, without matching.
fn cascade_primary_and_pseudos(&self,