This repository has been archived by the owner on Aug 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathServoRestyleManager.cpp
1704 lines (1491 loc) · 61.6 KB
/
ServoRestyleManager.cpp
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* 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/. */
#include "mozilla/ServoRestyleManager.h"
#include "mozilla/AutoRestyleTimelineMarker.h"
#include "mozilla/AutoTimelineMarker.h"
#include "mozilla/DocumentStyleRootIterator.h"
#include "mozilla/ServoBindings.h"
#include "mozilla/ServoStyleSet.h"
#include "mozilla/ServoStyleContext.h"
#include "mozilla/ServoStyleContextInlines.h"
#include "mozilla/Unused.h"
#include "mozilla/ViewportFrame.h"
#include "mozilla/dom/ChildIterator.h"
#include "mozilla/dom/ElementInlines.h"
#include "nsBlockFrame.h"
#include "nsBulletFrame.h"
#include "nsImageFrame.h"
#include "nsPlaceholderFrame.h"
#include "nsContentUtils.h"
#include "nsCSSFrameConstructor.h"
#include "nsPrintfCString.h"
#include "nsRefreshDriver.h"
#include "nsStyleChangeList.h"
using namespace mozilla::dom;
namespace mozilla {
#ifdef DEBUG
static bool
IsAnonBox(const nsIFrame& aFrame)
{
return aFrame.StyleContext()->IsAnonBox();
}
static const nsIFrame*
FirstContinuationOrPartOfIBSplit(const nsIFrame* aFrame)
{
if (!aFrame) {
return nullptr;
}
return nsLayoutUtils::FirstContinuationOrIBSplitSibling(aFrame);
}
static const nsIFrame*
ExpectedOwnerForChild(const nsIFrame& aFrame)
{
const nsIFrame* parent = aFrame.GetParent();
if (aFrame.IsTableFrame()) {
MOZ_ASSERT(parent->IsTableWrapperFrame());
parent = parent->GetParent();
}
if (IsAnonBox(aFrame) && !aFrame.IsTextFrame()) {
if (parent->IsLineFrame()) {
parent = parent->GetParent();
}
return parent->IsViewportFrame() ?
nullptr : FirstContinuationOrPartOfIBSplit(parent);
}
if (aFrame.IsBulletFrame()) {
return FirstContinuationOrPartOfIBSplit(parent);
}
if (aFrame.IsLineFrame()) {
// A ::first-line always ends up here via its block, which is therefore the
// right expected owner. That block can be an
// anonymous box. For example, we could have a ::first-line on a columnated
// block; the blockframe is the column-content anonymous box in that case.
// So we don't want to end up in the code below, which steps out of anon
// boxes. Just return the parent of the line frame, which is the block.
return parent;
}
if (aFrame.IsLetterFrame()) {
// Ditto for ::first-letter. A first-letter always arrives here via its
// direct parent, except when it's parented to a ::first-line.
if (parent->IsLineFrame()) {
parent = parent->GetParent();
}
return FirstContinuationOrPartOfIBSplit(parent);
}
if (parent->IsLetterFrame()) {
// Things never have ::first-letter as their expected parent. Go
// on up to the ::first-letter's parent.
parent = parent->GetParent();
}
parent = FirstContinuationOrPartOfIBSplit(parent);
// We've handled already anon boxes and bullet frames, so now we're looking at
// a frame of a DOM element or pseudo. Hop through anon and line-boxes
// generated by our DOM parent, and go find the owner frame for it.
while (parent && (IsAnonBox(*parent) || parent->IsLineFrame())) {
auto* pseudo = parent->StyleContext()->GetPseudo();
if (pseudo == nsCSSAnonBoxes::tableWrapper) {
const nsIFrame* tableFrame = parent->PrincipalChildList().FirstChild();
MOZ_ASSERT(tableFrame->IsTableFrame());
// Handle :-moz-table and :-moz-inline-table.
parent = IsAnonBox(*tableFrame) ? parent->GetParent() : tableFrame;
} else {
parent = parent->GetParent();
}
parent = FirstContinuationOrPartOfIBSplit(parent);
}
return parent;
}
void
ServoRestyleState::AssertOwner(const ServoRestyleState& aParent) const
{
MOZ_ASSERT(mOwner);
MOZ_ASSERT(!mOwner->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW));
// We allow aParent.mOwner to be null, for cases when we're not starting at
// the root of the tree. We also allow aParent.mOwner to be somewhere up our
// expected owner chain not our immediate owner, which allows us creating long
// chains of ServoRestyleStates in some cases where it's just not worth it.
#ifdef DEBUG
if (aParent.mOwner) {
const nsIFrame* owner = ExpectedOwnerForChild(*mOwner);
if (owner != aParent.mOwner) {
MOZ_ASSERT(IsAnonBox(*owner),
"Should only have expected owner weirdness when anon boxes are involved");
bool found = false;
for (; owner; owner = ExpectedOwnerForChild(*owner)) {
if (owner == aParent.mOwner) {
found = true;
break;
}
}
MOZ_ASSERT(found, "Must have aParent.mOwner on our expected owner chain");
}
}
#endif
}
nsChangeHint
ServoRestyleState::ChangesHandledFor(const nsIFrame& aFrame) const
{
if (!mOwner) {
MOZ_ASSERT(!mChangesHandled);
return mChangesHandled;
}
MOZ_ASSERT(mOwner == ExpectedOwnerForChild(aFrame),
"Missed some frame in the hierarchy?");
return mChangesHandled;
}
#endif
void
ServoRestyleState::AddPendingWrapperRestyle(nsIFrame* aWrapperFrame)
{
MOZ_ASSERT(aWrapperFrame->StyleContext()->IsWrapperAnonBox(),
"All our wrappers are anon boxes, and why would we restyle "
"non-inheriting ones?");
MOZ_ASSERT(aWrapperFrame->StyleContext()->IsInheritingAnonBox(),
"All our wrappers are anon boxes, and why would we restyle "
"non-inheriting ones?");
MOZ_ASSERT(aWrapperFrame->StyleContext()->GetPseudo() !=
nsCSSAnonBoxes::cellContent,
"Someone should be using TableAwareParentFor");
MOZ_ASSERT(aWrapperFrame->StyleContext()->GetPseudo() !=
nsCSSAnonBoxes::tableWrapper,
"Someone should be using TableAwareParentFor");
// Make sure we only add first continuations.
aWrapperFrame = aWrapperFrame->FirstContinuation();
nsIFrame* last = mPendingWrapperRestyles.SafeLastElement(nullptr);
if (last == aWrapperFrame) {
// Already queued up, nothing to do.
return;
}
// Make sure to queue up parents before children. But don't queue up
// ancestors of non-anonymous boxes here; those are handled when we traverse
// their non-anonymous kids.
if (aWrapperFrame->ParentIsWrapperAnonBox()) {
AddPendingWrapperRestyle(TableAwareParentFor(aWrapperFrame));
}
// If the append fails, we'll fail to restyle properly, but that's probably
// better than crashing.
if (mPendingWrapperRestyles.AppendElement(aWrapperFrame, fallible)) {
aWrapperFrame->SetIsWrapperAnonBoxNeedingRestyle(true);
}
}
void
ServoRestyleState::ProcessWrapperRestyles(nsIFrame* aParentFrame)
{
size_t i = mPendingWrapperRestyleOffset;
while (i < mPendingWrapperRestyles.Length()) {
i += ProcessMaybeNestedWrapperRestyle(aParentFrame, i);
}
mPendingWrapperRestyles.TruncateLength(mPendingWrapperRestyleOffset);
}
size_t
ServoRestyleState::ProcessMaybeNestedWrapperRestyle(nsIFrame* aParent,
size_t aIndex)
{
// The frame at index aIndex is something we should restyle ourselves, but
// following frames may need separate ServoRestyleStates to restyle.
MOZ_ASSERT(aIndex < mPendingWrapperRestyles.Length());
nsIFrame* cur = mPendingWrapperRestyles[aIndex];
MOZ_ASSERT(cur->StyleContext()->IsWrapperAnonBox());
// Where is cur supposed to inherit from? From its parent frame, except in
// the case when cur is a table, in which case it should be its grandparent.
// Also, not in the case when the resulting frame would be a first-line; in
// that case we should be inheriting from the block, and the first-line will
// do its fixup later if needed.
//
// Note that after we do all that fixup the parent we get might still not be
// aParent; for example aParent could be a scrollframe, in which case we
// should inherit from the scrollcontent frame. Or the parent might be some
// continuation of aParent.
//
// Try to assert as much as we can about the parent we actually end up using
// without triggering bogus asserts in all those various edge cases.
nsIFrame* parent = cur->GetParent();
if (cur->IsTableFrame()) {
MOZ_ASSERT(parent->IsTableWrapperFrame());
parent = parent->GetParent();
}
if (parent->IsLineFrame()) {
parent = parent->GetParent();
}
MOZ_ASSERT(FirstContinuationOrPartOfIBSplit(parent) == aParent ||
(parent->StyleContext()->IsInheritingAnonBox() &&
parent->GetContent() == aParent->GetContent()));
// Now "this" is a ServoRestyleState for aParent, so if parent is not a next
// continuation (possibly across ib splits) of aParent we need a new
// ServoRestyleState for the kid.
Maybe<ServoRestyleState> parentRestyleState;
nsIFrame* parentForRestyle =
nsLayoutUtils::FirstContinuationOrIBSplitSibling(parent);
if (parentForRestyle != aParent) {
parentRestyleState.emplace(*parentForRestyle, *this, nsChangeHint_Empty,
Type::InFlow);
}
ServoRestyleState& curRestyleState =
parentRestyleState ? *parentRestyleState : *this;
// This frame may already have been restyled. Even if it has, we can't just
// return, because the next frame may be a kid of it that does need restyling.
if (cur->IsWrapperAnonBoxNeedingRestyle()) {
parentForRestyle->UpdateStyleOfChildAnonBox(cur, curRestyleState);
cur->SetIsWrapperAnonBoxNeedingRestyle(false);
}
size_t numProcessed = 1;
// Note: no overflow possible here, since aIndex < length.
if (aIndex + 1 < mPendingWrapperRestyles.Length()) {
nsIFrame* next = mPendingWrapperRestyles[aIndex + 1];
if (TableAwareParentFor(next) == cur &&
next->IsWrapperAnonBoxNeedingRestyle()) {
// It might be nice if we could do better than nsChangeHint_Empty. On
// the other hand, presumably our mChangesHandled already has the bits
// we really want here so in practice it doesn't matter.
ServoRestyleState childState(*cur, curRestyleState, nsChangeHint_Empty,
Type::InFlow,
/* aAssertWrapperRestyleLength = */ false);
numProcessed += childState.ProcessMaybeNestedWrapperRestyle(cur,
aIndex + 1);
}
}
return numProcessed;
}
nsIFrame*
ServoRestyleState::TableAwareParentFor(const nsIFrame* aChild)
{
// We want to get the anon box parent for aChild. where aChild has
// ParentIsWrapperAnonBox().
//
// For the most part this is pretty straightforward, but there are two
// wrinkles. First, if aChild is a table, then we really want the parent of
// its table wrapper.
if (aChild->IsTableFrame()) {
aChild = aChild->GetParent();
MOZ_ASSERT(aChild->IsTableWrapperFrame());
}
nsIFrame* parent = aChild->GetParent();
// Now if parent is a cell-content frame, we actually want the cellframe.
if (parent->StyleContext()->GetPseudo() == nsCSSAnonBoxes::cellContent) {
parent = parent->GetParent();
} else if (parent->IsTableWrapperFrame()) {
// Must be a caption. In that case we want the table here.
MOZ_ASSERT(aChild->StyleDisplay()->mDisplay == StyleDisplay::TableCaption);
parent = parent->PrincipalChildList().FirstChild();
}
return parent;
}
ServoRestyleManager::ServoRestyleManager(nsPresContext* aPresContext)
: RestyleManager(StyleBackendType::Servo, aPresContext)
, mReentrantChanges(nullptr)
{
}
void
ServoRestyleManager::PostRestyleEvent(Element* aElement,
nsRestyleHint aRestyleHint,
nsChangeHint aMinChangeHint)
{
MOZ_ASSERT(!(aMinChangeHint & nsChangeHint_NeutralChange),
"Didn't expect explicit change hints to be neutral!");
if (MOZ_UNLIKELY(IsDisconnected()) ||
MOZ_UNLIKELY(PresContext()->PresShell()->IsDestroying())) {
return;
}
// We allow posting restyles from within change hint handling, but not from
// within the restyle algorithm itself.
MOZ_ASSERT(!ServoStyleSet::IsInServoTraversal());
if (aRestyleHint == 0 && !aMinChangeHint) {
return; // Nothing to do.
}
// Assuming the restyle hints will invalidate cached style for
// getComputedStyle, since we don't know if any of the restyling that we do
// would affect undisplayed elements.
if (aRestyleHint) {
IncrementUndisplayedRestyleGeneration();
}
// Processing change hints sometimes causes new change hints to be generated,
// and very occasionally, additional restyle hints. We collect the change
// hints manually to avoid re-traversing the DOM to find them.
if (mReentrantChanges && !aRestyleHint) {
mReentrantChanges->AppendElement(ReentrantChange { aElement, aMinChangeHint });
return;
}
if (aRestyleHint & ~eRestyle_AllHintsWithAnimations) {
mHaveNonAnimationRestyles = true;
}
if (aRestyleHint & eRestyle_LaterSiblings) {
aRestyleHint &= ~eRestyle_LaterSiblings;
nsRestyleHint siblingHint = eRestyle_Subtree;
Element* current = aElement->GetNextElementSibling();
while (current) {
Servo_NoteExplicitHints(current, siblingHint, nsChangeHint(0));
current = current->GetNextElementSibling();
}
}
if (aRestyleHint || aMinChangeHint) {
Servo_NoteExplicitHints(aElement, aRestyleHint, aMinChangeHint);
}
}
void
ServoRestyleManager::PostRestyleEventForCSSRuleChanges()
{
mRestyleForCSSRuleChanges = true;
mPresContext->PresShell()->EnsureStyleFlush();
}
void
ServoRestyleManager::PostRestyleEventForAnimations(
Element* aElement,
CSSPseudoElementType aPseudoType,
nsRestyleHint aRestyleHint)
{
Element* elementToRestyle =
EffectCompositor::GetElementToRestyle(aElement, aPseudoType);
if (!elementToRestyle) {
// FIXME: Bug 1371107: When reframing happens,
// EffectCompositor::mElementsToRestyle still has unbinded old pseudo
// element. We should drop it.
return;
}
AutoRestyleTimelineMarker marker(mPresContext->GetDocShell(),
true /* animation-only */);
Servo_NoteExplicitHints(elementToRestyle, aRestyleHint, nsChangeHint(0));
}
void
ServoRestyleManager::RebuildAllStyleData(nsChangeHint aExtraHint,
nsRestyleHint aRestyleHint)
{
// NOTE(emilio): GeckoRestlyeManager does a sync style flush, which seems not
// to be needed in my testing.
PostRebuildAllStyleDataEvent(aExtraHint, aRestyleHint);
}
void
ServoRestyleManager::PostRebuildAllStyleDataEvent(nsChangeHint aExtraHint,
nsRestyleHint aRestyleHint)
{
// NOTE(emilio): The semantics of these methods are quite funny, in the sense
// that we're not supposed to need to rebuild the actual stylist data.
//
// That's handled as part of the MediumFeaturesChanged stuff, if needed.
StyleSet()->ClearCachedStyleData();
DocumentStyleRootIterator iter(mPresContext->Document());
while (Element* root = iter.GetNextStyleRoot()) {
PostRestyleEvent(root, aRestyleHint, aExtraHint);
}
// TODO(emilio, bz): Extensions can add/remove stylesheets that can affect
// non-inheriting anon boxes. It's not clear if we want to support that, but
// if we do, we need to re-selector-match them here.
}
/* static */ void
ServoRestyleManager::ClearServoDataFromSubtree(Element* aElement)
{
if (!aElement->HasServoData()) {
MOZ_ASSERT(!aElement->HasDirtyDescendantsForServo());
MOZ_ASSERT(!aElement->HasAnimationOnlyDirtyDescendantsForServo());
return;
}
StyleChildrenIterator it(aElement);
for (nsIContent* n = it.GetNextChild(); n; n = it.GetNextChild()) {
if (n->IsElement()) {
ClearServoDataFromSubtree(n->AsElement());
}
}
aElement->ClearServoData();
}
/* static */ void
ServoRestyleManager::ClearRestyleStateFromSubtree(Element* aElement)
{
if (aElement->HasAnyOfFlags(Element::kAllServoDescendantBits)) {
StyleChildrenIterator it(aElement);
for (nsIContent* n = it.GetNextChild(); n; n = it.GetNextChild()) {
if (n->IsElement()) {
ClearRestyleStateFromSubtree(n->AsElement());
}
}
}
bool wasRestyled;
Unused << Servo_TakeChangeHint(aElement, &wasRestyled);
aElement->UnsetFlags(Element::kAllServoDescendantBits);
}
/**
* This struct takes care of encapsulating some common state that text nodes may
* need to track during the post-traversal.
*
* This is currently used to properly compute change hints when the parent
* element of this node is a display: contents node, and also to avoid computing
* the style for text children more than once per element.
*/
struct ServoRestyleManager::TextPostTraversalState
{
public:
TextPostTraversalState(Element& aParentElement,
ServoStyleContext* aParentContext,
bool aDisplayContentsParentStyleChanged,
ServoRestyleState& aParentRestyleState)
: mParentElement(aParentElement)
, mParentContext(aParentContext)
, mParentRestyleState(aParentRestyleState)
, mStyle(nullptr)
, mShouldPostHints(aDisplayContentsParentStyleChanged)
, mShouldComputeHints(aDisplayContentsParentStyleChanged)
, mComputedHint(nsChangeHint_Empty)
{}
nsStyleChangeList& ChangeList() { return mParentRestyleState.ChangeList(); }
nsStyleContext& ComputeStyle(nsIContent* aTextNode)
{
if (!mStyle) {
mStyle = mParentRestyleState.StyleSet().ResolveStyleForText(
aTextNode, &ParentStyle());
}
MOZ_ASSERT(mStyle);
return *mStyle;
}
void ComputeHintIfNeeded(nsIContent* aContent,
nsIFrame* aTextFrame,
nsStyleContext& aNewContext)
{
MOZ_ASSERT(aTextFrame);
MOZ_ASSERT(aNewContext.GetPseudo() == nsCSSAnonBoxes::mozText);
if (MOZ_LIKELY(!mShouldPostHints)) {
return;
}
ServoStyleContext* oldContext = aTextFrame->StyleContext()->AsServo();
MOZ_ASSERT(oldContext->GetPseudo() == nsCSSAnonBoxes::mozText);
// We rely on the fact that all the text children for the same element share
// style to avoid recomputing style differences for all of them.
//
// TODO(emilio): The above may not be true for ::first-{line,letter}, but
// we'll cross that bridge when we support those in stylo.
if (mShouldComputeHints) {
mShouldComputeHints = false;
uint32_t equalStructs, samePointerStructs;
mComputedHint =
oldContext->CalcStyleDifference(&aNewContext,
&equalStructs,
&samePointerStructs);
mComputedHint = NS_RemoveSubsumedHints(
mComputedHint, mParentRestyleState.ChangesHandledFor(*aTextFrame));
}
if (mComputedHint) {
mParentRestyleState.ChangeList().AppendChange(
aTextFrame, aContent, mComputedHint);
}
}
private:
ServoStyleContext& ParentStyle() {
if (!mParentContext) {
mLazilyResolvedParentContext =
mParentRestyleState.StyleSet().ResolveServoStyle(&mParentElement);
mParentContext = mLazilyResolvedParentContext;
}
return *mParentContext;
}
Element& mParentElement;
ServoStyleContext* mParentContext;
RefPtr<ServoStyleContext> mLazilyResolvedParentContext;
ServoRestyleState& mParentRestyleState;
RefPtr<nsStyleContext> mStyle;
bool mShouldPostHints;
bool mShouldComputeHints;
nsChangeHint mComputedHint;
};
static void
UpdateBackdropIfNeeded(nsIFrame* aFrame,
ServoStyleSet& aStyleSet,
nsStyleChangeList& aChangeList)
{
const nsStyleDisplay* display = aFrame->StyleContext()->StyleDisplay();
if (display->mTopLayer != NS_STYLE_TOP_LAYER_TOP) {
return;
}
// Elements in the top layer are guaranteed to have absolute or fixed
// position per https://fullscreen.spec.whatwg.org/#new-stacking-layer.
MOZ_ASSERT(display->IsAbsolutelyPositionedStyle());
nsIFrame* backdropPlaceholder =
aFrame->GetChildList(nsIFrame::kBackdropList).FirstChild();
if (!backdropPlaceholder) {
return;
}
MOZ_ASSERT(backdropPlaceholder->IsPlaceholderFrame());
nsIFrame* backdropFrame =
nsPlaceholderFrame::GetRealFrameForPlaceholder(backdropPlaceholder);
MOZ_ASSERT(backdropFrame->IsBackdropFrame());
MOZ_ASSERT(backdropFrame->StyleContext()->GetPseudoType() ==
CSSPseudoElementType::backdrop);
RefPtr<nsStyleContext> newContext =
aStyleSet.ResolvePseudoElementStyle(aFrame->GetContent()->AsElement(),
CSSPseudoElementType::backdrop,
aFrame->StyleContext()->AsServo(),
/* aPseudoElement = */ nullptr);
// NOTE(emilio): We can't use the changes handled for the owner of the
// backdrop frame, since it's out of flow, and parented to the viewport or
// canvas frame (depending on the `position` value).
MOZ_ASSERT(backdropFrame->GetParent()->IsViewportFrame() ||
backdropFrame->GetParent()->IsCanvasFrame());
nsTArray<nsIFrame*> wrappersToRestyle;
ServoRestyleState state(aStyleSet, aChangeList, wrappersToRestyle);
aFrame->UpdateStyleOfOwnedChildFrame(backdropFrame, newContext, state);
}
static void
UpdateFirstLetterIfNeeded(nsIFrame* aFrame, ServoRestyleState& aRestyleState)
{
MOZ_ASSERT(!aFrame->IsFrameOfType(nsIFrame::eBlockFrame),
"You're probably duplicating work with UpdatePseudoElementStyles!");
if (!aFrame->HasFirstLetterChild()) {
return;
}
// We need to find the block the first-letter is associated with so we can
// find the right element for the first-letter's style resolution. Might as
// well just delegate the whole thing to that block.
nsIFrame* block = aFrame->GetParent();
while (!block->IsFrameOfType(nsIFrame::eBlockFrame)) {
block = block->GetParent();
}
static_cast<nsBlockFrame*>(block->FirstContinuation())->
UpdateFirstLetterStyle(aRestyleState);
}
static void
UpdateOneAdditionalStyleContext(nsIFrame* aFrame,
uint32_t aIndex,
ServoStyleContext& aOldContext,
ServoRestyleState& aRestyleState)
{
auto pseudoType = aOldContext.GetPseudoType();
MOZ_ASSERT(pseudoType != CSSPseudoElementType::NotPseudo);
MOZ_ASSERT(
!nsCSSPseudoElements::PseudoElementSupportsUserActionState(pseudoType));
RefPtr<ServoStyleContext> newContext =
aRestyleState.StyleSet().ResolvePseudoElementStyle(
aFrame->GetContent()->AsElement(),
pseudoType,
aFrame->StyleContext()->AsServo(),
/* aPseudoElement = */ nullptr);
uint32_t equalStructs, samePointerStructs; // Not used, actually.
nsChangeHint childHint = aOldContext.CalcStyleDifference(
newContext,
&equalStructs,
&samePointerStructs);
if (!aFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW)) {
childHint = NS_RemoveSubsumedHints(
childHint, aRestyleState.ChangesHandledFor(*aFrame));
}
if (childHint) {
aRestyleState.ChangeList().AppendChange(
aFrame, aFrame->GetContent(), childHint);
}
aFrame->SetAdditionalStyleContext(aIndex, newContext);
}
static void
UpdateAdditionalStyleContexts(nsIFrame* aFrame,
ServoRestyleState& aRestyleState)
{
MOZ_ASSERT(aFrame);
MOZ_ASSERT(aFrame->GetContent() && aFrame->GetContent()->IsElement());
// FIXME(emilio): Consider adding a bit or something to avoid the initial
// virtual call?
uint32_t index = 0;
while (auto* oldContext = aFrame->GetAdditionalStyleContext(index)) {
UpdateOneAdditionalStyleContext(
aFrame, index++, *oldContext->AsServo(), aRestyleState);
}
}
static void
UpdateFramePseudoElementStyles(nsIFrame* aFrame,
ServoRestyleState& aRestyleState)
{
if (aFrame->IsFrameOfType(nsIFrame::eBlockFrame)) {
static_cast<nsBlockFrame*>(aFrame)->UpdatePseudoElementStyles(aRestyleState);
} else {
UpdateFirstLetterIfNeeded(aFrame, aRestyleState);
}
UpdateBackdropIfNeeded(
aFrame, aRestyleState.StyleSet(), aRestyleState.ChangeList());
}
enum class ServoPostTraversalFlags : uint32_t
{
Empty = 0,
// Whether parent was restyled.
ParentWasRestyled = 1 << 0,
// Skip sending accessibility notifications for all descendants.
SkipA11yNotifications = 1 << 1,
// Always send accessibility notifications if the element is shown.
// The SkipA11yNotifications flag above overrides this flag.
SendA11yNotificationsIfShown = 1 << 2,
};
MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(ServoPostTraversalFlags)
// Send proper accessibility notifications and return post traversal
// flags for kids.
static ServoPostTraversalFlags
SendA11yNotifications(nsPresContext* aPresContext,
Element* aElement,
nsStyleContext* aOldStyleContext,
nsStyleContext* aNewStyleContext,
ServoPostTraversalFlags aFlags)
{
using Flags = ServoPostTraversalFlags;
MOZ_ASSERT(!(aFlags & Flags::SkipA11yNotifications) ||
!(aFlags & Flags::SendA11yNotificationsIfShown),
"The two a11y flags should never be set together");
#ifdef ACCESSIBILITY
nsAccessibilityService* accService = GetAccService();
if (!accService) {
// If we don't have accessibility service, accessibility is not
// enabled. Just skip everything.
return Flags::Empty;
}
if (aFlags & Flags::SkipA11yNotifications) {
// Propogate the skipping flag to descendants.
return Flags::SkipA11yNotifications;
}
bool needsNotify = false;
bool isVisible = aNewStyleContext->StyleVisibility()->IsVisible();
if (aFlags & Flags::SendA11yNotificationsIfShown) {
if (!isVisible) {
// Propagate the sending-if-shown flag to descendants.
return Flags::SendA11yNotificationsIfShown;
}
// We have asked accessibility service to remove the whole subtree
// of element which becomes invisible from the accessible tree, but
// this element is visible, so we need to add it back.
needsNotify = true;
} else {
// If we shouldn't skip in any case, we need to check whether our
// own visibility has changed.
bool wasVisible = aOldStyleContext->StyleVisibility()->IsVisible();
needsNotify = wasVisible != isVisible;
}
if (needsNotify) {
nsIPresShell* presShell = aPresContext->PresShell();
if (isVisible) {
accService->ContentRangeInserted(presShell, aElement->GetParent(),
aElement, aElement->GetNextSibling());
// We are adding the subtree. Accessibility service would handle
// descendants, so we should just skip them from notifying.
return Flags::SkipA11yNotifications;
}
// Remove the subtree of this invisible element, and ask any shown
// descendant to add themselves back.
accService->ContentRemoved(presShell, aElement);
return Flags::SendA11yNotificationsIfShown;
}
#endif
return Flags::Empty;
}
bool
ServoRestyleManager::ProcessPostTraversal(
Element* aElement,
ServoStyleContext* aParentContext,
ServoRestyleState& aRestyleState,
ServoPostTraversalFlags aFlags)
{
nsIFrame* styleFrame = nsLayoutUtils::GetStyleFrame(aElement);
nsIFrame* primaryFrame = aElement->GetPrimaryFrame();
// NOTE(emilio): This is needed because for table frames the bit is set on the
// table wrapper (which is the primary frame), not on the table itself.
const bool isOutOfFlow =
primaryFrame &&
primaryFrame->HasAnyStateBits(NS_FRAME_OUT_OF_FLOW);
// Grab the change hint from Servo.
bool wasRestyled;
nsChangeHint changeHint =
static_cast<nsChangeHint>(Servo_TakeChangeHint(aElement, &wasRestyled));
// We should really fix the weird primary frame mapping for image maps
// (bug 135040)...
if (styleFrame && styleFrame->GetContent() != aElement) {
MOZ_ASSERT(static_cast<nsImageFrame*>(do_QueryFrame(styleFrame)));
styleFrame = nullptr;
}
// Handle lazy frame construction by posting a reconstruct for any lazily-
// constructed roots.
if (aElement->HasFlag(NODE_NEEDS_FRAME)) {
changeHint |= nsChangeHint_ReconstructFrame;
MOZ_ASSERT(!styleFrame);
}
if (styleFrame) {
MOZ_ASSERT(primaryFrame);
nsIFrame* maybeAnonBoxChild;
if (isOutOfFlow) {
maybeAnonBoxChild = primaryFrame->GetPlaceholderFrame();
} else {
maybeAnonBoxChild = primaryFrame;
changeHint = NS_RemoveSubsumedHints(
changeHint, aRestyleState.ChangesHandledFor(*styleFrame));
}
// If the parent wasn't restyled, the styles of our anon box parents won't
// change either.
if ((aFlags & ServoPostTraversalFlags::ParentWasRestyled) &&
maybeAnonBoxChild->ParentIsWrapperAnonBox()) {
aRestyleState.AddPendingWrapperRestyle(
ServoRestyleState::TableAwareParentFor(maybeAnonBoxChild));
}
}
// Although we shouldn't generate non-ReconstructFrame hints for elements with
// no frames, we can still get them here if they were explicitly posted by
// PostRestyleEvent, such as a RepaintFrame hint when a :link changes to be
// :visited. Skip processing these hints if there is no frame.
if ((styleFrame || (changeHint & nsChangeHint_ReconstructFrame)) && changeHint) {
aRestyleState.ChangeList().AppendChange(styleFrame, aElement, changeHint);
}
// If our change hint is reconstruct, we delegate to the frame constructor,
// which consumes the new style and expects the old style to be on the frame.
//
// XXXbholley: We should teach the frame constructor how to clear the dirty
// descendants bit to avoid the traversal here.
if (changeHint & nsChangeHint_ReconstructFrame) {
ClearRestyleStateFromSubtree(aElement);
return true;
}
// TODO(emilio): We could avoid some refcount traffic here, specially in the
// ServoStyleContext case, which uses atomic refcounting.
//
// Hold the old style context alive, because it could become a dangling
// pointer during the replacement. In practice it's not a huge deal, but
// better not playing with dangling pointers if not needed.
RefPtr<ServoStyleContext> oldStyleContext =
styleFrame ? styleFrame->StyleContext()->AsServo() : nullptr;
nsStyleContext* displayContentsStyle = nullptr;
// FIXME(emilio, bug 1303605): This can be simpler for Servo.
// Note that we intentionally don't check for display: none content.
if (!oldStyleContext) {
displayContentsStyle =
PresContext()->FrameConstructor()->GetDisplayContentsStyleFor(aElement);
if (displayContentsStyle) {
oldStyleContext = displayContentsStyle->AsServo();
}
}
Maybe<ServoRestyleState> thisFrameRestyleState;
if (styleFrame) {
auto type = isOutOfFlow
? ServoRestyleState::Type::OutOfFlow
: ServoRestyleState::Type::InFlow;
thisFrameRestyleState.emplace(*styleFrame, aRestyleState, changeHint, type);
}
// We can't really assume as used changes from display: contents elements (or
// other elements without frames).
ServoRestyleState& childrenRestyleState =
thisFrameRestyleState ? *thisFrameRestyleState : aRestyleState;
RefPtr<ServoStyleContext> upToDateContext =
wasRestyled
? aRestyleState.StyleSet().ResolveServoStyle(aElement)
: oldStyleContext;
ServoPostTraversalFlags childrenFlags =
wasRestyled ? ServoPostTraversalFlags::ParentWasRestyled
: ServoPostTraversalFlags::Empty;
if (wasRestyled && oldStyleContext) {
MOZ_ASSERT(styleFrame || displayContentsStyle);
MOZ_ASSERT(oldStyleContext->ComputedData() != upToDateContext->ComputedData());
upToDateContext->ResolveSameStructsAs(oldStyleContext);
// We want to walk all the continuations here, even the ones with different
// styles. In practice, the only reason we get continuations with different
// styles here is ::first-line (::first-letter never affects element
// styles). But in that case, newContext is the right context for the
// _later_ continuations anyway (the ones not affected by ::first-line), not
// the earlier ones, so there is no point stopping right at the point when
// we'd actually be setting the right style context.
//
// This does mean that we may be setting the wrong style context on our
// initial continuations; ::first-line fixes that up after the fact.
for (nsIFrame* f = styleFrame; f; f = f->GetNextContinuation()) {
MOZ_ASSERT_IF(f != styleFrame, !f->GetAdditionalStyleContext(0));
f->SetStyleContext(upToDateContext);
}
if (MOZ_UNLIKELY(displayContentsStyle)) {
MOZ_ASSERT(!styleFrame);
PresContext()->FrameConstructor()->
ChangeRegisteredDisplayContentsStyleFor(aElement, upToDateContext);
}
if (styleFrame) {
UpdateAdditionalStyleContexts(styleFrame, aRestyleState);
styleFrame->UpdateStyleOfOwnedAnonBoxes(childrenRestyleState);
}
if (!aElement->GetParent()) {
// This is the root. Update styles on the viewport as needed.
ViewportFrame* viewport =
do_QueryFrame(mPresContext->PresShell()->GetRootFrame());
if (viewport) {
// NB: The root restyle state, not the one for our children!
viewport->UpdateStyle(aRestyleState);
}
}
// Some changes to animations don't affect the computed style and yet still
// require the layer to be updated. For example, pausing an animation via
// the Web Animations API won't affect an element's style but still
// requires to update the animation on the layer.
//
// We can sometimes reach this when the animated style is being removed.
// Since AddLayerChangesForAnimation checks if |styleFrame| has a transform
// style or not, we need to call it *after* setting |newContext| to
// |styleFrame| to ensure the animated transform has been removed first.
AddLayerChangesForAnimation(
styleFrame, aElement, aRestyleState.ChangeList());
childrenFlags |= SendA11yNotifications(mPresContext, aElement,
oldStyleContext,
upToDateContext, aFlags);
}
const bool traverseElementChildren =
aElement->HasAnyOfFlags(Element::kAllServoDescendantBits);
const bool traverseTextChildren =
wasRestyled || aElement->HasFlag(NODE_DESCENDANTS_NEED_FRAMES);
bool recreatedAnyContext = wasRestyled;
if (traverseElementChildren || traverseTextChildren) {
StyleChildrenIterator it(aElement);
TextPostTraversalState textState(*aElement,
upToDateContext,
displayContentsStyle && wasRestyled,
childrenRestyleState);
for (nsIContent* n = it.GetNextChild(); n; n = it.GetNextChild()) {
if (traverseElementChildren && n->IsElement()) {
recreatedAnyContext |= ProcessPostTraversal(n->AsElement(),
upToDateContext,
childrenRestyleState,
childrenFlags);
} else if (traverseTextChildren && n->IsNodeOfType(nsINode::eTEXT)) {
recreatedAnyContext |= ProcessPostTraversalForText(n, textState,
childrenRestyleState,
childrenFlags);
}
}
}
// We want to update frame pseudo-element styles after we've traversed our
// kids, because some of those updates (::first-line/::first-letter) need to
// modify the styles of the kids, and the child traversal above would just
// clobber those modifications.
if (styleFrame) {
// Process anon box wrapper frames before ::first-line bits.
childrenRestyleState.ProcessWrapperRestyles(styleFrame);
if (wasRestyled) {
UpdateFramePseudoElementStyles(styleFrame, childrenRestyleState);
} else if (traverseElementChildren &&
styleFrame->IsFrameOfType(nsIFrame::eBlockFrame)) {
// Even if we were not restyled, if we're a block with a first-line and
// one of our descendant elements which is on the first line was restyled,
// we need to update the styles of things on the first line, because
// they're wrong now.
//
// FIXME(bz) Could we do better here? For example, could we keep track of
// frames that are "block with a ::first-line so we could avoid
// IsFrameOfType() and digging about for the first-line frame if not?
// Could we keep track of whether the element children we actually restyle
// are affected by first-line? Something else? Bug 1385443 tracks making
// this better.
nsIFrame* firstLineFrame =
static_cast<nsBlockFrame*>(styleFrame)->GetFirstLineFrame();
if (firstLineFrame) {
for (nsIFrame* kid : firstLineFrame->PrincipalChildList()) {
ReparentStyleContext(kid);
}
}
}
}
aElement->UnsetFlags(Element::kAllServoDescendantBits);
return recreatedAnyContext;
}