-
Notifications
You must be signed in to change notification settings - Fork 54
/
KeyframeEffect.cpp
2028 lines (1742 loc) · 71.2 KB
/
KeyframeEffect.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/dom/KeyframeEffect.h"
#include "FrameLayerBuilder.h"
#include "mozilla/dom/Animation.h"
#include "mozilla/dom/KeyframeAnimationOptionsBinding.h"
// For UnrestrictedDoubleOrKeyframeAnimationOptions;
#include "mozilla/dom/KeyframeEffectBinding.h"
#include "mozilla/dom/MutationObservers.h"
#include "mozilla/AnimationUtils.h"
#include "mozilla/AutoRestore.h"
#include "mozilla/ComputedStyleInlines.h"
#include "mozilla/EffectSet.h"
#include "mozilla/FloatingPoint.h" // For IsFinite
#include "mozilla/LayerAnimationInfo.h"
#include "mozilla/LookAndFeel.h" // For LookAndFeel::GetInt
#include "mozilla/KeyframeUtils.h"
#include "mozilla/PresShell.h"
#include "mozilla/PresShellInlines.h"
#include "mozilla/ServoBindings.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/StaticPrefs_gfx.h"
#include "mozilla/StaticPrefs_layers.h"
#include "Layers.h" // For Layer
#include "nsComputedDOMStyle.h" // nsComputedDOMStyle::GetComputedStyle
#include "nsContentUtils.h"
#include "nsCSSPropertyIDSet.h"
#include "nsCSSProps.h" // For nsCSSProps::PropHasFlags
#include "nsCSSPseudoElements.h" // For PseudoStyleType
#include "nsDOMMutationObserver.h" // For nsAutoAnimationMutationBatch
#include "nsIFrame.h"
#include "nsIFrameInlines.h"
#include "nsPresContextInlines.h"
#include "nsRefreshDriver.h"
namespace mozilla {
void AnimationProperty::SetPerformanceWarning(
const AnimationPerformanceWarning& aWarning, const dom::Element* aElement) {
if (mPerformanceWarning && *mPerformanceWarning == aWarning) {
return;
}
mPerformanceWarning = Some(aWarning);
nsAutoString localizedString;
if (StaticPrefs::layers_offmainthreadcomposition_log_animations() &&
mPerformanceWarning->ToLocalizedString(localizedString)) {
nsAutoCString logMessage = NS_ConvertUTF16toUTF8(localizedString);
AnimationUtils::LogAsyncAnimationFailure(logMessage, aElement);
}
}
bool PropertyValuePair::operator==(const PropertyValuePair& aOther) const {
if (mProperty != aOther.mProperty) {
return false;
}
if (mServoDeclarationBlock == aOther.mServoDeclarationBlock) {
return true;
}
if (!mServoDeclarationBlock || !aOther.mServoDeclarationBlock) {
return false;
}
return Servo_DeclarationBlock_Equals(mServoDeclarationBlock,
aOther.mServoDeclarationBlock);
}
namespace dom {
NS_IMPL_CYCLE_COLLECTION_INHERITED(KeyframeEffect, AnimationEffect,
mTarget.mElement)
NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN_INHERITED(KeyframeEffect, AnimationEffect)
NS_IMPL_CYCLE_COLLECTION_TRACE_END
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(KeyframeEffect)
NS_INTERFACE_MAP_END_INHERITING(AnimationEffect)
NS_IMPL_ADDREF_INHERITED(KeyframeEffect, AnimationEffect)
NS_IMPL_RELEASE_INHERITED(KeyframeEffect, AnimationEffect)
KeyframeEffect::KeyframeEffect(Document* aDocument,
OwningAnimationTarget&& aTarget,
TimingParams&& aTiming,
const KeyframeEffectParams& aOptions)
: AnimationEffect(aDocument, std::move(aTiming)),
mTarget(std::move(aTarget)),
mEffectOptions(aOptions),
mCumulativeChangeHint(nsChangeHint(0)) {}
JSObject* KeyframeEffect::WrapObject(JSContext* aCx,
JS::Handle<JSObject*> aGivenProto) {
return KeyframeEffect_Binding::Wrap(aCx, this, aGivenProto);
}
IterationCompositeOperation KeyframeEffect::IterationComposite() const {
return mEffectOptions.mIterationComposite;
}
void KeyframeEffect::SetIterationComposite(
const IterationCompositeOperation& aIterationComposite) {
if (mEffectOptions.mIterationComposite == aIterationComposite) {
return;
}
if (mAnimation && mAnimation->IsRelevant()) {
MutationObservers::NotifyAnimationChanged(mAnimation);
}
mEffectOptions.mIterationComposite = aIterationComposite;
RequestRestyle(EffectCompositor::RestyleType::Layer);
}
CompositeOperation KeyframeEffect::Composite() const {
return mEffectOptions.mComposite;
}
void KeyframeEffect::SetComposite(const CompositeOperation& aComposite) {
if (mEffectOptions.mComposite == aComposite) {
return;
}
mEffectOptions.mComposite = aComposite;
if (mAnimation && mAnimation->IsRelevant()) {
MutationObservers::NotifyAnimationChanged(mAnimation);
}
if (mTarget) {
RefPtr<ComputedStyle> computedStyle = GetTargetComputedStyle(Flush::None);
if (computedStyle) {
UpdateProperties(computedStyle);
}
}
}
void KeyframeEffect::NotifySpecifiedTimingUpdated() {
// Use the same document for a pseudo element and its parent element.
// Use nullptr if we don't have mTarget, so disable the mutation batch.
nsAutoAnimationMutationBatch mb(mTarget ? mTarget.mElement->OwnerDoc()
: nullptr);
if (mAnimation) {
mAnimation->NotifyEffectTimingUpdated();
if (mAnimation->IsRelevant()) {
MutationObservers::NotifyAnimationChanged(mAnimation);
}
RequestRestyle(EffectCompositor::RestyleType::Layer);
}
}
void KeyframeEffect::NotifyAnimationTimingUpdated(
PostRestyleMode aPostRestyle) {
UpdateTargetRegistration();
// If the effect is not relevant it will be removed from the target
// element's effect set. However, effects not in the effect set
// will not be included in the set of candidate effects for running on
// the compositor and hence they won't have their compositor status
// updated. As a result, we need to make sure we clear their compositor
// status here.
bool isRelevant = mAnimation && mAnimation->IsRelevant();
if (!isRelevant) {
ResetIsRunningOnCompositor();
}
// Request restyle if necessary.
if (aPostRestyle == PostRestyleMode::IfNeeded && mAnimation &&
!mProperties.IsEmpty() && HasComputedTimingChanged()) {
EffectCompositor::RestyleType restyleType =
CanThrottle() ? EffectCompositor::RestyleType::Throttled
: EffectCompositor::RestyleType::Standard;
RequestRestyle(restyleType);
}
// Detect changes to "in effect" status since we need to recalculate the
// animation cascade for this element whenever that changes.
// Note that updating mInEffectOnLastAnimationTimingUpdate has to be done
// after above CanThrottle() call since the function uses the flag inside it.
bool inEffect = IsInEffect();
if (inEffect != mInEffectOnLastAnimationTimingUpdate) {
MarkCascadeNeedsUpdate();
mInEffectOnLastAnimationTimingUpdate = inEffect;
}
// If we're no longer "in effect", our ComposeStyle method will never be
// called and we will never have a chance to update mProgressOnLastCompose
// and mCurrentIterationOnLastCompose.
// We clear them here to ensure that if we later become "in effect" we will
// request a restyle (above).
if (!inEffect) {
mProgressOnLastCompose.SetNull();
mCurrentIterationOnLastCompose = 0;
}
}
static bool KeyframesEqualIgnoringComputedOffsets(
const nsTArray<Keyframe>& aLhs, const nsTArray<Keyframe>& aRhs) {
if (aLhs.Length() != aRhs.Length()) {
return false;
}
for (size_t i = 0, len = aLhs.Length(); i < len; ++i) {
const Keyframe& a = aLhs[i];
const Keyframe& b = aRhs[i];
if (a.mOffset != b.mOffset || a.mTimingFunction != b.mTimingFunction ||
a.mPropertyValues != b.mPropertyValues) {
return false;
}
}
return true;
}
// https://drafts.csswg.org/web-animations/#dom-keyframeeffect-setkeyframes
void KeyframeEffect::SetKeyframes(JSContext* aContext,
JS::Handle<JSObject*> aKeyframes,
ErrorResult& aRv) {
nsTArray<Keyframe> keyframes = KeyframeUtils::GetKeyframesFromObject(
aContext, mDocument, aKeyframes, "KeyframeEffect.setKeyframes", aRv);
if (aRv.Failed()) {
return;
}
RefPtr<ComputedStyle> style = GetTargetComputedStyle(Flush::None);
SetKeyframes(std::move(keyframes), style);
}
void KeyframeEffect::SetKeyframes(nsTArray<Keyframe>&& aKeyframes,
const ComputedStyle* aStyle) {
if (KeyframesEqualIgnoringComputedOffsets(aKeyframes, mKeyframes)) {
return;
}
mKeyframes = std::move(aKeyframes);
KeyframeUtils::DistributeKeyframes(mKeyframes);
if (mAnimation && mAnimation->IsRelevant()) {
MutationObservers::NotifyAnimationChanged(mAnimation);
}
// We need to call UpdateProperties() unless the target element doesn't have
// style (e.g. the target element is not associated with any document).
if (aStyle) {
UpdateProperties(aStyle);
}
}
void KeyframeEffect::ReplaceTransitionStartValue(AnimationValue&& aStartValue) {
if (!aStartValue.mServo) {
return;
}
// A typical transition should have a single property and a single segment.
//
// (And for atypical transitions, that is, those updated by script, we don't
// apply the replacing behavior.)
if (mProperties.Length() != 1 || mProperties[0].mSegments.Length() != 1) {
return;
}
// Likewise, check that the keyframes are of the expected shape.
if (mKeyframes.Length() != 2 || mKeyframes[0].mPropertyValues.Length() != 1) {
return;
}
// Check that the value we are about to substitute in is actually for the
// same property.
if (Servo_AnimationValue_GetPropertyId(aStartValue.mServo) !=
mProperties[0].mProperty) {
return;
}
mKeyframes[0].mPropertyValues[0].mServoDeclarationBlock =
Servo_AnimationValue_Uncompute(aStartValue.mServo).Consume();
mProperties[0].mSegments[0].mFromValue = std::move(aStartValue);
}
static bool IsEffectiveProperty(const EffectSet& aEffects,
nsCSSPropertyID aProperty) {
return !aEffects.PropertiesWithImportantRules().HasProperty(aProperty) ||
!aEffects.PropertiesForAnimationsLevel().HasProperty(aProperty);
}
const AnimationProperty* KeyframeEffect::GetEffectiveAnimationOfProperty(
nsCSSPropertyID aProperty, const EffectSet& aEffects) const {
MOZ_ASSERT(mTarget &&
&aEffects == EffectSet::GetEffectSet(mTarget.mElement,
mTarget.mPseudoType));
for (const AnimationProperty& property : mProperties) {
if (aProperty != property.mProperty) {
continue;
}
const AnimationProperty* result = nullptr;
// Only include the property if it is not overridden by !important rules in
// the transitions level.
if (IsEffectiveProperty(aEffects, property.mProperty)) {
result = &property;
}
return result;
}
return nullptr;
}
bool KeyframeEffect::HasEffectiveAnimationOfPropertySet(
const nsCSSPropertyIDSet& aPropertySet, const EffectSet& aEffectSet) const {
for (const AnimationProperty& property : mProperties) {
if (aPropertySet.HasProperty(property.mProperty) &&
IsEffectiveProperty(aEffectSet, property.mProperty)) {
return true;
}
}
return false;
}
nsCSSPropertyIDSet KeyframeEffect::GetPropertiesForCompositor(
EffectSet& aEffects, const nsIFrame* aFrame) const {
MOZ_ASSERT(&aEffects ==
EffectSet::GetEffectSet(mTarget.mElement, mTarget.mPseudoType));
nsCSSPropertyIDSet properties;
if (!mAnimation || !mAnimation->IsRelevant()) {
return properties;
}
static constexpr nsCSSPropertyIDSet compositorAnimatables =
nsCSSPropertyIDSet::CompositorAnimatables();
static constexpr nsCSSPropertyIDSet transformLikeProperties =
nsCSSPropertyIDSet::TransformLikeProperties();
nsCSSPropertyIDSet transformSet;
AnimationPerformanceWarning::Type dummyWarning;
for (const AnimationProperty& property : mProperties) {
if (!compositorAnimatables.HasProperty(property.mProperty)) {
continue;
}
// Transform-like properties are combined together on the compositor so we
// need to evaluate them as a group. We build up a separate set here then
// evaluate it as a separate step below.
if (transformLikeProperties.HasProperty(property.mProperty)) {
transformSet.AddProperty(property.mProperty);
continue;
}
KeyframeEffect::MatchForCompositor matchResult = IsMatchForCompositor(
nsCSSPropertyIDSet{property.mProperty}, aFrame, aEffects, dummyWarning);
if (matchResult ==
KeyframeEffect::MatchForCompositor::NoAndBlockThisProperty ||
matchResult == KeyframeEffect::MatchForCompositor::No) {
continue;
}
properties.AddProperty(property.mProperty);
}
if (!transformSet.IsEmpty()) {
KeyframeEffect::MatchForCompositor matchResult =
IsMatchForCompositor(transformSet, aFrame, aEffects, dummyWarning);
if (matchResult == KeyframeEffect::MatchForCompositor::Yes ||
matchResult == KeyframeEffect::MatchForCompositor::IfNeeded) {
properties |= transformSet;
}
}
return properties;
}
nsCSSPropertyIDSet KeyframeEffect::GetPropertySet() const {
nsCSSPropertyIDSet result;
for (const AnimationProperty& property : mProperties) {
result.AddProperty(property.mProperty);
}
return result;
}
#ifdef DEBUG
bool SpecifiedKeyframeArraysAreEqual(const nsTArray<Keyframe>& aA,
const nsTArray<Keyframe>& aB) {
if (aA.Length() != aB.Length()) {
return false;
}
for (size_t i = 0; i < aA.Length(); i++) {
const Keyframe& a = aA[i];
const Keyframe& b = aB[i];
if (a.mOffset != b.mOffset || a.mTimingFunction != b.mTimingFunction ||
a.mPropertyValues != b.mPropertyValues) {
return false;
}
}
return true;
}
#endif
static bool HasCurrentColor(
const nsTArray<AnimationPropertySegment>& aSegments) {
for (const AnimationPropertySegment& segment : aSegments) {
if ((!segment.mFromValue.IsNull() && segment.mFromValue.IsCurrentColor()) ||
(!segment.mToValue.IsNull() && segment.mToValue.IsCurrentColor())) {
return true;
}
}
return false;
}
void KeyframeEffect::UpdateProperties(const ComputedStyle* aStyle) {
MOZ_ASSERT(aStyle);
nsTArray<AnimationProperty> properties = BuildProperties(aStyle);
bool propertiesChanged = mProperties != properties;
// We need to update base styles even if any properties are not changed at all
// since base styles might have been changed due to parent style changes, etc.
bool baseStylesChanged = false;
EnsureBaseStyles(aStyle, properties,
!propertiesChanged ? &baseStylesChanged : nullptr);
if (!propertiesChanged) {
if (baseStylesChanged) {
RequestRestyle(EffectCompositor::RestyleType::Layer);
}
// Check if we need to update the cumulative change hint because we now have
// style data.
if (mNeedsStyleData && mTarget && mTarget.mElement->HasServoData()) {
CalculateCumulativeChangeHint(aStyle);
}
return;
}
// Preserve the state of the mIsRunningOnCompositor flag.
nsCSSPropertyIDSet runningOnCompositorProperties;
for (const AnimationProperty& property : mProperties) {
if (property.mIsRunningOnCompositor) {
runningOnCompositorProperties.AddProperty(property.mProperty);
}
}
mProperties = std::move(properties);
UpdateEffectSet();
mHasCurrentColor = false;
for (AnimationProperty& property : mProperties) {
property.mIsRunningOnCompositor =
runningOnCompositorProperties.HasProperty(property.mProperty);
if (property.mProperty == eCSSProperty_background_color &&
!mHasCurrentColor) {
if (HasCurrentColor(property.mSegments)) {
mHasCurrentColor = true;
break;
}
}
}
CalculateCumulativeChangeHint(aStyle);
MarkCascadeNeedsUpdate();
if (mAnimation) {
mAnimation->NotifyEffectPropertiesUpdated();
}
RequestRestyle(EffectCompositor::RestyleType::Layer);
}
void KeyframeEffect::EnsureBaseStyles(
const ComputedStyle* aComputedValues,
const nsTArray<AnimationProperty>& aProperties, bool* aBaseStylesChanged) {
if (aBaseStylesChanged != nullptr) {
*aBaseStylesChanged = false;
}
if (!mTarget) {
return;
}
BaseValuesHashmap previousBaseStyles;
if (aBaseStylesChanged != nullptr) {
previousBaseStyles = std::move(mBaseValues);
}
mBaseValues.Clear();
nsPresContext* presContext =
nsContentUtils::GetContextForContent(mTarget.mElement);
// If |aProperties| is empty we're not going to dereference |presContext| so
// we don't care if it is nullptr.
//
// We could just return early when |aProperties| is empty and save looking up
// the pres context, but that won't save any effort normally since we don't
// call this function if we have no keyframes to begin with. Furthermore, the
// case where |presContext| is nullptr is so rare (we've only ever seen in
// fuzzing, and even then we've never been able to reproduce it reliably)
// it's not worth the runtime cost of an extra branch.
MOZ_ASSERT(presContext || aProperties.IsEmpty(),
"Typically presContext should not be nullptr but if it is"
" we should have also failed to calculate the computed values"
" passed-in as aProperties");
RefPtr<ComputedStyle> baseComputedStyle;
for (const AnimationProperty& property : aProperties) {
EnsureBaseStyle(property, presContext, aComputedValues, baseComputedStyle);
}
if (aBaseStylesChanged != nullptr) {
for (auto iter = mBaseValues.Iter(); !iter.Done(); iter.Next()) {
if (AnimationValue(iter.Data()) !=
AnimationValue(previousBaseStyles.Get(iter.Key()))) {
*aBaseStylesChanged = true;
break;
}
}
}
}
void KeyframeEffect::EnsureBaseStyle(
const AnimationProperty& aProperty, nsPresContext* aPresContext,
const ComputedStyle* aComputedStyle,
RefPtr<ComputedStyle>& aBaseComputedStyle) {
bool hasAdditiveValues = false;
for (const AnimationPropertySegment& segment : aProperty.mSegments) {
if (!segment.HasReplaceableValues()) {
hasAdditiveValues = true;
break;
}
}
if (!hasAdditiveValues) {
return;
}
if (!aBaseComputedStyle) {
MOZ_ASSERT(mTarget, "Should have a valid target");
Element* animatingElement = EffectCompositor::GetElementToRestyle(
mTarget.mElement, mTarget.mPseudoType);
if (!animatingElement) {
return;
}
aBaseComputedStyle = aPresContext->StyleSet()->GetBaseContextForElement(
animatingElement, aComputedStyle);
}
RefPtr<RawServoAnimationValue> baseValue =
Servo_ComputedValues_ExtractAnimationValue(aBaseComputedStyle,
aProperty.mProperty)
.Consume();
mBaseValues.Put(aProperty.mProperty, std::move(baseValue));
}
void KeyframeEffect::WillComposeStyle() {
ComputedTiming computedTiming = GetComputedTiming();
mProgressOnLastCompose = computedTiming.mProgress;
mCurrentIterationOnLastCompose = computedTiming.mCurrentIteration;
}
void KeyframeEffect::ComposeStyleRule(
RawServoAnimationValueMap& aAnimationValues,
const AnimationProperty& aProperty,
const AnimationPropertySegment& aSegment,
const ComputedTiming& aComputedTiming) {
auto* opaqueTable =
reinterpret_cast<RawServoAnimationValueTable*>(&mBaseValues);
Servo_AnimationCompose(&aAnimationValues, opaqueTable, aProperty.mProperty,
&aSegment, &aProperty.mSegments.LastElement(),
&aComputedTiming, mEffectOptions.mIterationComposite);
}
void KeyframeEffect::ComposeStyle(RawServoAnimationValueMap& aComposeResult,
const nsCSSPropertyIDSet& aPropertiesToSkip) {
ComputedTiming computedTiming = GetComputedTiming();
// If the progress is null, we don't have fill data for the current
// time so we shouldn't animate.
if (computedTiming.mProgress.IsNull()) {
return;
}
for (size_t propIdx = 0, propEnd = mProperties.Length(); propIdx != propEnd;
++propIdx) {
const AnimationProperty& prop = mProperties[propIdx];
MOZ_ASSERT(prop.mSegments[0].mFromKey == 0.0, "incorrect first from key");
MOZ_ASSERT(prop.mSegments[prop.mSegments.Length() - 1].mToKey == 1.0,
"incorrect last to key");
if (aPropertiesToSkip.HasProperty(prop.mProperty)) {
continue;
}
MOZ_ASSERT(prop.mSegments.Length() > 0,
"property should not be in animations if it has no segments");
// FIXME: Maybe cache the current segment?
const AnimationPropertySegment *segment = prop.mSegments.Elements(),
*segmentEnd =
segment + prop.mSegments.Length();
while (segment->mToKey <= computedTiming.mProgress.Value()) {
MOZ_ASSERT(segment->mFromKey <= segment->mToKey, "incorrect keys");
if ((segment + 1) == segmentEnd) {
break;
}
++segment;
MOZ_ASSERT(segment->mFromKey == (segment - 1)->mToKey, "incorrect keys");
}
MOZ_ASSERT(segment->mFromKey <= segment->mToKey, "incorrect keys");
MOZ_ASSERT(segment >= prop.mSegments.Elements() &&
size_t(segment - prop.mSegments.Elements()) <
prop.mSegments.Length(),
"out of array bounds");
ComposeStyleRule(aComposeResult, prop, *segment, computedTiming);
}
// If the animation produces a change hint that affects the overflow region,
// we need to record the current time to unthrottle the animation
// periodically when the animation is being throttled because it's scrolled
// out of view.
if (HasPropertiesThatMightAffectOverflow()) {
nsPresContext* presContext =
nsContentUtils::GetContextForContent(mTarget.mElement);
EffectSet* effectSet =
EffectSet::GetEffectSet(mTarget.mElement, mTarget.mPseudoType);
if (presContext && effectSet) {
TimeStamp now = presContext->RefreshDriver()->MostRecentRefresh();
effectSet->UpdateLastOverflowAnimationSyncTime(now);
}
}
}
bool KeyframeEffect::IsRunningOnCompositor() const {
// We consider animation is running on compositor if there is at least
// one property running on compositor.
// Animation.IsRunningOnCompotitor will return more fine grained
// information in bug 1196114.
for (const AnimationProperty& property : mProperties) {
if (property.mIsRunningOnCompositor) {
return true;
}
}
return false;
}
void KeyframeEffect::SetIsRunningOnCompositor(nsCSSPropertyID aProperty,
bool aIsRunning) {
MOZ_ASSERT(
nsCSSProps::PropHasFlags(aProperty, CSSPropFlags::CanAnimateOnCompositor),
"Property being animated on compositor is a recognized "
"compositor-animatable property");
for (AnimationProperty& property : mProperties) {
if (property.mProperty == aProperty) {
property.mIsRunningOnCompositor = aIsRunning;
// We currently only set a performance warning message when animations
// cannot be run on the compositor, so if this animation is running
// on the compositor we don't need a message.
if (aIsRunning) {
property.mPerformanceWarning.reset();
}
return;
}
}
}
void KeyframeEffect::SetIsRunningOnCompositor(
const nsCSSPropertyIDSet& aPropertySet, bool aIsRunning) {
for (AnimationProperty& property : mProperties) {
if (aPropertySet.HasProperty(property.mProperty)) {
MOZ_ASSERT(nsCSSProps::PropHasFlags(property.mProperty,
CSSPropFlags::CanAnimateOnCompositor),
"Property being animated on compositor is a recognized "
"compositor-animatable property");
property.mIsRunningOnCompositor = aIsRunning;
// We currently only set a performance warning message when animations
// cannot be run on the compositor, so if this animation is running
// on the compositor we don't need a message.
if (aIsRunning) {
property.mPerformanceWarning.reset();
}
}
}
}
void KeyframeEffect::ResetIsRunningOnCompositor() {
for (AnimationProperty& property : mProperties) {
property.mIsRunningOnCompositor = false;
}
}
static bool IsSupportedPseudoForWebAnimation(PseudoStyleType aType) {
// FIXME: Bug 1615469: Support first-line and first-letter for Web Animation.
return aType == PseudoStyleType::before || aType == PseudoStyleType::after ||
aType == PseudoStyleType::marker;
}
static const KeyframeEffectOptions& KeyframeEffectOptionsFromUnion(
const UnrestrictedDoubleOrKeyframeEffectOptions& aOptions) {
MOZ_ASSERT(aOptions.IsKeyframeEffectOptions());
return aOptions.GetAsKeyframeEffectOptions();
}
static const KeyframeEffectOptions& KeyframeEffectOptionsFromUnion(
const UnrestrictedDoubleOrKeyframeAnimationOptions& aOptions) {
MOZ_ASSERT(aOptions.IsKeyframeAnimationOptions());
return aOptions.GetAsKeyframeAnimationOptions();
}
template <class OptionsType>
static KeyframeEffectParams KeyframeEffectParamsFromUnion(
const OptionsType& aOptions, CallerType aCallerType, ErrorResult& aRv) {
KeyframeEffectParams result;
if (aOptions.IsUnrestrictedDouble()) {
return result;
}
const KeyframeEffectOptions& options =
KeyframeEffectOptionsFromUnion(aOptions);
// If dom.animations-api.compositing.enabled is turned off,
// iterationComposite and composite are the default value 'replace' in the
// dictionary.
result.mIterationComposite = options.mIterationComposite;
result.mComposite = options.mComposite;
result.mPseudoType = PseudoStyleType::NotPseudo;
if (DOMStringIsNull(options.mPseudoElement)) {
return result;
}
RefPtr<nsAtom> pseudoAtom =
nsCSSPseudoElements::GetPseudoAtom(options.mPseudoElement);
if (!pseudoAtom) {
// Per the spec, we throw SyntaxError for syntactically invalid pseudos.
aRv.ThrowSyntaxError(
nsPrintfCString("'%s' is a syntactically invalid pseudo-element.",
NS_ConvertUTF16toUTF8(options.mPseudoElement).get()));
return result;
}
result.mPseudoType = nsCSSPseudoElements::GetPseudoType(
pseudoAtom, CSSEnabledState::ForAllContent);
if (!IsSupportedPseudoForWebAnimation(result.mPseudoType)) {
// Per the spec, we throw SyntaxError for unsupported pseudos.
aRv.ThrowSyntaxError(
nsPrintfCString("'%s' is an unsupported pseudo-element.",
NS_ConvertUTF16toUTF8(options.mPseudoElement).get()));
}
return result;
}
template <class OptionsType>
/* static */
already_AddRefed<KeyframeEffect> KeyframeEffect::ConstructKeyframeEffect(
const GlobalObject& aGlobal, Element* aTarget,
JS::Handle<JSObject*> aKeyframes, const OptionsType& aOptions,
ErrorResult& aRv) {
// We should get the document from `aGlobal` instead of the current Realm
// to make this works in Xray case.
//
// In all non-Xray cases, `aGlobal` matches the current Realm, so this
// matches the spec behavior.
//
// In Xray case, the new objects should be created using the document of
// the target global, but the KeyframeEffect constructors are called in the
// caller's compartment to access `aKeyframes` object.
Document* doc = AnimationUtils::GetDocumentFromGlobal(aGlobal.Get());
if (!doc) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
KeyframeEffectParams effectOptions =
KeyframeEffectParamsFromUnion(aOptions, aGlobal.CallerType(), aRv);
// An invalid Pseudo-element aborts all further steps.
if (aRv.Failed()) {
return nullptr;
}
TimingParams timingParams =
TimingParams::FromOptionsUnion(aOptions, doc, aRv);
if (aRv.Failed()) {
return nullptr;
}
RefPtr<KeyframeEffect> effect = new KeyframeEffect(
doc, OwningAnimationTarget(aTarget, effectOptions.mPseudoType),
std::move(timingParams), effectOptions);
effect->SetKeyframes(aGlobal.Context(), aKeyframes, aRv);
if (aRv.Failed()) {
return nullptr;
}
return effect.forget();
}
nsTArray<AnimationProperty> KeyframeEffect::BuildProperties(
const ComputedStyle* aStyle) {
MOZ_ASSERT(aStyle);
nsTArray<AnimationProperty> result;
// If mTarget is false (i.e. mTarget.mElement is null), return an empty
// property array.
if (!mTarget) {
return result;
}
// When GetComputedKeyframeValues or GetAnimationPropertiesFromKeyframes
// calculate computed values from |mKeyframes|, they could possibly
// trigger a subsequent restyle in which we rebuild animations. If that
// happens we could find that |mKeyframes| is overwritten while it is
// being iterated over. Normally that shouldn't happen but just in case we
// make a copy of |mKeyframes| first and iterate over that instead.
auto keyframesCopy(mKeyframes);
result = KeyframeUtils::GetAnimationPropertiesFromKeyframes(
keyframesCopy, mTarget.mElement, aStyle, mEffectOptions.mComposite);
#ifdef DEBUG
MOZ_ASSERT(SpecifiedKeyframeArraysAreEqual(mKeyframes, keyframesCopy),
"Apart from the computed offset members, the keyframes array"
" should not be modified");
#endif
mKeyframes.SwapElements(keyframesCopy);
return result;
}
template <typename FrameEnumFunc>
static void EnumerateContinuationsOrIBSplitSiblings(nsIFrame* aFrame,
FrameEnumFunc&& aFunc) {
while (aFrame) {
aFunc(aFrame);
aFrame = nsLayoutUtils::GetNextContinuationOrIBSplitSibling(aFrame);
}
}
void KeyframeEffect::UpdateTarget(Element* aElement,
PseudoStyleType aPseudoType) {
OwningAnimationTarget newTarget(aElement, aPseudoType);
if (mTarget == newTarget) {
// Assign the same target, skip it.
return;
}
if (mTarget) {
UnregisterTarget();
ResetIsRunningOnCompositor();
RequestRestyle(EffectCompositor::RestyleType::Layer);
nsAutoAnimationMutationBatch mb(mTarget.mElement->OwnerDoc());
if (mAnimation) {
MutationObservers::NotifyAnimationRemoved(mAnimation);
}
}
mTarget = newTarget;
if (mTarget) {
UpdateTargetRegistration();
RefPtr<ComputedStyle> computedStyle = GetTargetComputedStyle(Flush::None);
if (computedStyle) {
UpdateProperties(computedStyle);
}
RequestRestyle(EffectCompositor::RestyleType::Layer);
nsAutoAnimationMutationBatch mb(mTarget.mElement->OwnerDoc());
if (mAnimation) {
MutationObservers::NotifyAnimationAdded(mAnimation);
mAnimation->ReschedulePendingTasks();
}
}
if (mAnimation) {
mAnimation->NotifyEffectTargetUpdated();
}
}
void KeyframeEffect::UpdateTargetRegistration() {
if (!mTarget) {
return;
}
bool isRelevant = mAnimation && mAnimation->IsRelevant();
// Animation::IsRelevant() returns a cached value. It only updates when
// something calls Animation::UpdateRelevance. Whenever our timing changes,
// we should be notifying our Animation before calling this, so
// Animation::IsRelevant() should be up-to-date by the time we get here.
MOZ_ASSERT(isRelevant ==
((IsCurrent() || IsInEffect()) && mAnimation &&
mAnimation->ReplaceState() != AnimationReplaceState::Removed),
"Out of date Animation::IsRelevant value");
if (isRelevant && !mInEffectSet) {
EffectSet* effectSet =
EffectSet::GetOrCreateEffectSet(mTarget.mElement, mTarget.mPseudoType);
effectSet->AddEffect(*this);
mInEffectSet = true;
UpdateEffectSet(effectSet);
nsIFrame* frame = GetPrimaryFrame();
EnumerateContinuationsOrIBSplitSiblings(
frame, [](nsIFrame* aFrame) { aFrame->MarkNeedsDisplayItemRebuild(); });
} else if (!isRelevant && mInEffectSet) {
UnregisterTarget();
}
}
void KeyframeEffect::UnregisterTarget() {
if (!mInEffectSet) {
return;
}
EffectSet* effectSet =
EffectSet::GetEffectSet(mTarget.mElement, mTarget.mPseudoType);
MOZ_ASSERT(effectSet,
"If mInEffectSet is true, there must be an EffectSet"
" on the target element");
mInEffectSet = false;
if (effectSet) {
effectSet->RemoveEffect(*this);
if (effectSet->IsEmpty()) {
EffectSet::DestroyEffectSet(mTarget.mElement, mTarget.mPseudoType);
}
}
nsIFrame* frame = GetPrimaryFrame();
EnumerateContinuationsOrIBSplitSiblings(
frame, [](nsIFrame* aFrame) { aFrame->MarkNeedsDisplayItemRebuild(); });
}
void KeyframeEffect::RequestRestyle(
EffectCompositor::RestyleType aRestyleType) {
if (!mTarget) {
return;
}
nsPresContext* presContext =
nsContentUtils::GetContextForContent(mTarget.mElement);
if (presContext && mAnimation) {
presContext->EffectCompositor()->RequestRestyle(
mTarget.mElement, mTarget.mPseudoType, aRestyleType,
mAnimation->CascadeLevel());
}
}
already_AddRefed<ComputedStyle> KeyframeEffect::GetTargetComputedStyle(
Flush aFlushType) const {
if (!GetRenderedDocument()) {
return nullptr;
}
MOZ_ASSERT(mTarget,
"Should only have a document when we have a target element");
nsAtom* pseudo = PseudoStyle::IsPseudoElement(mTarget.mPseudoType)
? nsCSSPseudoElements::GetPseudoAtom(mTarget.mPseudoType)
: nullptr;
OwningAnimationTarget kungfuDeathGrip(mTarget.mElement, mTarget.mPseudoType);
return aFlushType == Flush::Style
? nsComputedDOMStyle::GetComputedStyle(mTarget.mElement, pseudo)
: nsComputedDOMStyle::GetComputedStyleNoFlush(mTarget.mElement,
pseudo);
}
#ifdef DEBUG
void DumpAnimationProperties(
const RawServoStyleSet* aRawSet,
nsTArray<AnimationProperty>& aAnimationProperties) {
for (auto& p : aAnimationProperties) {
printf("%s\n", nsCString(nsCSSProps::GetStringValue(p.mProperty)).get());
for (auto& s : p.mSegments) {
nsString fromValue, toValue;
s.mFromValue.SerializeSpecifiedValue(p.mProperty, aRawSet, fromValue);
s.mToValue.SerializeSpecifiedValue(p.mProperty, aRawSet, toValue);
printf(" %f..%f: %s..%s\n", s.mFromKey, s.mToKey,
NS_ConvertUTF16toUTF8(fromValue).get(),
NS_ConvertUTF16toUTF8(toValue).get());
}
}
}