forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Animation.cpp
1536 lines (1330 loc) · 45.7 KB
/
Animation.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 "Animation.h"
#include "AnimationUtils.h"
#include "mozilla/dom/AnimationBinding.h"
#include "mozilla/dom/AnimationPlaybackEvent.h"
#include "mozilla/dom/DocumentTimeline.h"
#include "mozilla/AnimationTarget.h"
#include "mozilla/AutoRestore.h"
#include "mozilla/AsyncEventDispatcher.h" // For AsyncEventDispatcher
#include "mozilla/Maybe.h" // For Maybe
#include "mozilla/TypeTraits.h" // For Forward<>
#include "nsAnimationManager.h" // For CSSAnimation
#include "nsDOMMutationObserver.h" // For nsAutoAnimationMutationBatch
#include "nsIDocument.h" // For nsIDocument
#include "nsIPresShell.h" // For nsIPresShell
#include "nsThreadUtils.h" // For nsRunnableMethod and nsRevocableEventPtr
#include "nsTransitionManager.h" // For CSSTransition
#include "PendingAnimationTracker.h" // For PendingAnimationTracker
namespace mozilla {
namespace dom {
// Static members
uint64_t Animation::sNextAnimationIndex = 0;
NS_IMPL_CYCLE_COLLECTION_INHERITED(Animation, DOMEventTargetHelper,
mTimeline,
mEffect,
mReady,
mFinished)
NS_IMPL_ADDREF_INHERITED(Animation, DOMEventTargetHelper)
NS_IMPL_RELEASE_INHERITED(Animation, DOMEventTargetHelper)
NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(Animation)
NS_INTERFACE_MAP_END_INHERITING(DOMEventTargetHelper)
JSObject*
Animation::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto)
{
return dom::AnimationBinding::Wrap(aCx, this, aGivenProto);
}
// ---------------------------------------------------------------------------
//
// Utility methods
//
// ---------------------------------------------------------------------------
namespace {
// A wrapper around nsAutoAnimationMutationBatch that looks up the
// appropriate document from the supplied animation.
class MOZ_RAII AutoMutationBatchForAnimation {
public:
explicit AutoMutationBatchForAnimation(const Animation& aAnimation
MOZ_GUARD_OBJECT_NOTIFIER_PARAM) {
MOZ_GUARD_OBJECT_NOTIFIER_INIT;
Maybe<NonOwningAnimationTarget> target =
nsNodeUtils::GetTargetForAnimation(&aAnimation);
if (!target) {
return;
}
// For mutation observers, we use the OwnerDoc.
nsIDocument* doc = target->mElement->OwnerDoc();
if (!doc) {
return;
}
mAutoBatch.emplace(doc);
}
private:
MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
Maybe<nsAutoAnimationMutationBatch> mAutoBatch;
};
}
// ---------------------------------------------------------------------------
//
// Animation interface:
//
// ---------------------------------------------------------------------------
/* static */ already_AddRefed<Animation>
Animation::Constructor(const GlobalObject& aGlobal,
AnimationEffectReadOnly* aEffect,
const Optional<AnimationTimeline*>& aTimeline,
ErrorResult& aRv)
{
nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(aGlobal.GetAsSupports());
RefPtr<Animation> animation = new Animation(global);
AnimationTimeline* timeline;
if (aTimeline.WasPassed()) {
timeline = aTimeline.Value();
} else {
nsIDocument* document =
AnimationUtils::GetCurrentRealmDocument(aGlobal.Context());
if (!document) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
timeline = document->Timeline();
}
animation->SetTimelineNoUpdate(timeline);
animation->SetEffectNoUpdate(aEffect);
return animation.forget();
}
void
Animation::SetId(const nsAString& aId)
{
if (mId == aId) {
return;
}
mId = aId;
nsNodeUtils::AnimationChanged(this);
}
void
Animation::SetEffect(AnimationEffectReadOnly* aEffect)
{
SetEffectNoUpdate(aEffect);
PostUpdate();
}
// https://w3c.github.io/web-animations/#setting-the-target-effect
void
Animation::SetEffectNoUpdate(AnimationEffectReadOnly* aEffect)
{
RefPtr<Animation> kungFuDeathGrip(this);
if (mEffect == aEffect) {
return;
}
AutoMutationBatchForAnimation mb(*this);
bool wasRelevant = mIsRelevant;
if (mEffect) {
if (!aEffect) {
// If the new effect is null, call ResetPendingTasks before clearing
// mEffect since ResetPendingTasks needs it to get the appropriate
// PendingAnimationTracker.
ResetPendingTasks();
}
// We need to notify observers now because once we set mEffect to null
// we won't be able to find the target element to notify.
if (mIsRelevant) {
nsNodeUtils::AnimationRemoved(this);
}
// Break links with the old effect and then drop it.
RefPtr<AnimationEffectReadOnly> oldEffect = mEffect;
mEffect = nullptr;
oldEffect->SetAnimation(nullptr);
// The following will not do any notification because mEffect is null.
UpdateRelevance();
}
if (aEffect) {
// Break links from the new effect to its previous animation, if any.
RefPtr<AnimationEffectReadOnly> newEffect = aEffect;
Animation* prevAnim = aEffect->GetAnimation();
if (prevAnim) {
prevAnim->SetEffect(nullptr);
}
// Create links with the new effect. SetAnimation(this) will also update
// mIsRelevant of this animation, and then notify mutation observer if
// needed by calling Animation::UpdateRelevance(), so we don't need to
// call it again.
mEffect = newEffect;
mEffect->SetAnimation(this);
// Notify possible add or change.
// If the target is different, the change notification will be ignored by
// AutoMutationBatchForAnimation.
if (wasRelevant && mIsRelevant) {
nsNodeUtils::AnimationChanged(this);
}
// Reschedule pending pause or pending play tasks.
// If we have a pending animation, it will either be registered
// in the pending animation tracker and have a null pending ready time,
// or, after it has been painted, it will be removed from the tracker
// and assigned a pending ready time.
// After updating the effect we'll typically need to repaint so if we've
// already been assigned a pending ready time, we should clear it and put
// the animation back in the tracker.
if (!mPendingReadyTime.IsNull()) {
mPendingReadyTime.SetNull();
nsIDocument* doc = GetRenderedDocument();
if (doc) {
PendingAnimationTracker* tracker =
doc->GetOrCreatePendingAnimationTracker();
if (mPendingState == PendingState::PlayPending) {
tracker->AddPlayPending(*this);
} else {
tracker->AddPausePending(*this);
}
}
}
}
UpdateTiming(SeekFlag::NoSeek, SyncNotifyFlag::Async);
}
void
Animation::SetTimeline(AnimationTimeline* aTimeline)
{
SetTimelineNoUpdate(aTimeline);
PostUpdate();
}
// https://w3c.github.io/web-animations/#setting-the-timeline
void
Animation::SetTimelineNoUpdate(AnimationTimeline* aTimeline)
{
if (mTimeline == aTimeline) {
return;
}
StickyTimeDuration activeTime = mEffect
? mEffect->GetComputedTiming().mActiveTime
: StickyTimeDuration();
RefPtr<AnimationTimeline> oldTimeline = mTimeline;
if (oldTimeline) {
oldTimeline->RemoveAnimation(this);
}
mTimeline = aTimeline;
if (!mStartTime.IsNull()) {
mHoldTime.SetNull();
}
if (!aTimeline) {
MaybeQueueCancelEvent(activeTime);
}
UpdateTiming(SeekFlag::NoSeek, SyncNotifyFlag::Async);
}
// https://w3c.github.io/web-animations/#set-the-animation-start-time
void
Animation::SetStartTime(const Nullable<TimeDuration>& aNewStartTime)
{
if (aNewStartTime == mStartTime) {
return;
}
AutoMutationBatchForAnimation mb(*this);
Nullable<TimeDuration> timelineTime;
if (mTimeline) {
// The spec says to check if the timeline is active (has a resolved time)
// before using it here, but we don't need to since it's harmless to set
// the already null time to null.
timelineTime = mTimeline->GetCurrentTime();
}
if (timelineTime.IsNull() && !aNewStartTime.IsNull()) {
mHoldTime.SetNull();
}
Nullable<TimeDuration> previousCurrentTime = GetCurrentTime();
mStartTime = aNewStartTime;
if (!aNewStartTime.IsNull()) {
if (mPlaybackRate != 0.0) {
mHoldTime.SetNull();
}
} else {
mHoldTime = previousCurrentTime;
}
CancelPendingTasks();
if (mReady) {
// We may have already resolved mReady, but in that case calling
// MaybeResolve is a no-op, so that's okay.
mReady->MaybeResolve(this);
}
UpdateTiming(SeekFlag::DidSeek, SyncNotifyFlag::Async);
if (IsRelevant()) {
nsNodeUtils::AnimationChanged(this);
}
PostUpdate();
}
// https://w3c.github.io/web-animations/#current-time
Nullable<TimeDuration>
Animation::GetCurrentTime() const
{
Nullable<TimeDuration> result;
if (!mHoldTime.IsNull()) {
result = mHoldTime;
return result;
}
if (mTimeline && !mStartTime.IsNull()) {
Nullable<TimeDuration> timelineTime = mTimeline->GetCurrentTime();
if (!timelineTime.IsNull()) {
result.SetValue((timelineTime.Value() - mStartTime.Value())
.MultDouble(mPlaybackRate));
}
}
return result;
}
// https://w3c.github.io/web-animations/#set-the-current-time
void
Animation::SetCurrentTime(const TimeDuration& aSeekTime)
{
// Return early if the current time has not changed. However, if we
// are pause-pending, then setting the current time to any value
// including the current value has the effect of aborting the
// pause so we should not return early in that case.
if (mPendingState != PendingState::PausePending &&
Nullable<TimeDuration>(aSeekTime) == GetCurrentTime()) {
return;
}
AutoMutationBatchForAnimation mb(*this);
SilentlySetCurrentTime(aSeekTime);
if (mPendingState == PendingState::PausePending) {
// Finish the pause operation
mHoldTime.SetValue(aSeekTime);
mStartTime.SetNull();
if (mReady) {
mReady->MaybeResolve(this);
}
CancelPendingTasks();
}
UpdateTiming(SeekFlag::DidSeek, SyncNotifyFlag::Async);
if (IsRelevant()) {
nsNodeUtils::AnimationChanged(this);
}
PostUpdate();
}
// https://w3c.github.io/web-animations/#set-the-animation-playback-rate
void
Animation::SetPlaybackRate(double aPlaybackRate)
{
if (aPlaybackRate == mPlaybackRate) {
return;
}
AutoMutationBatchForAnimation mb(*this);
Nullable<TimeDuration> previousTime = GetCurrentTime();
mPlaybackRate = aPlaybackRate;
if (!previousTime.IsNull()) {
SetCurrentTime(previousTime.Value());
}
// In the case where GetCurrentTime() returns the same result before and
// after updating mPlaybackRate, SetCurrentTime will return early since,
// as far as it can tell, nothing has changed.
// As a result, we need to perform the following updates here:
// - update timing (since, if the sign of the playback rate has changed, our
// finished state may have changed),
// - dispatch a change notification for the changed playback rate, and
// - update the playback rate on animations on layers.
UpdateTiming(SeekFlag::DidSeek, SyncNotifyFlag::Async);
if (IsRelevant()) {
nsNodeUtils::AnimationChanged(this);
}
PostUpdate();
}
// https://w3c.github.io/web-animations/#play-state
AnimationPlayState
Animation::PlayState() const
{
if (mPendingState != PendingState::NotPending) {
return AnimationPlayState::Pending;
}
Nullable<TimeDuration> currentTime = GetCurrentTime();
if (currentTime.IsNull()) {
return AnimationPlayState::Idle;
}
if (mStartTime.IsNull()) {
return AnimationPlayState::Paused;
}
if ((mPlaybackRate > 0.0 && currentTime.Value() >= EffectEnd()) ||
(mPlaybackRate < 0.0 && currentTime.Value() <= TimeDuration())) {
return AnimationPlayState::Finished;
}
return AnimationPlayState::Running;
}
Promise*
Animation::GetReady(ErrorResult& aRv)
{
nsCOMPtr<nsIGlobalObject> global = GetOwnerGlobal();
if (!mReady && global) {
mReady = Promise::Create(global, aRv); // Lazily create on demand
}
if (!mReady) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
if (PlayState() != AnimationPlayState::Pending) {
mReady->MaybeResolve(this);
}
return mReady;
}
Promise*
Animation::GetFinished(ErrorResult& aRv)
{
nsCOMPtr<nsIGlobalObject> global = GetOwnerGlobal();
if (!mFinished && global) {
mFinished = Promise::Create(global, aRv); // Lazily create on demand
}
if (!mFinished) {
aRv.Throw(NS_ERROR_FAILURE);
return nullptr;
}
if (mFinishedIsResolved) {
MaybeResolveFinishedPromise();
}
return mFinished;
}
void
Animation::Cancel()
{
CancelNoUpdate();
PostUpdate();
}
// https://w3c.github.io/web-animations/#finish-an-animation
void
Animation::Finish(ErrorResult& aRv)
{
if (mPlaybackRate == 0 ||
(mPlaybackRate > 0 && EffectEnd() == TimeDuration::Forever())) {
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
return;
}
AutoMutationBatchForAnimation mb(*this);
// Seek to the end
TimeDuration limit =
mPlaybackRate > 0 ? TimeDuration(EffectEnd()) : TimeDuration(0);
bool didChange = GetCurrentTime() != Nullable<TimeDuration>(limit);
SilentlySetCurrentTime(limit);
// If we are paused or play-pending we need to fill in the start time in
// order to transition to the finished state.
//
// We only do this, however, if we have an active timeline. If we have an
// inactive timeline we can't transition into the finished state just like
// we can't transition to the running state (this finished state is really
// a substate of the running state).
if (mStartTime.IsNull() &&
mTimeline &&
!mTimeline->GetCurrentTime().IsNull()) {
mStartTime.SetValue(mTimeline->GetCurrentTime().Value() -
limit.MultDouble(1.0 / mPlaybackRate));
didChange = true;
}
// If we just resolved the start time for a pause or play-pending
// animation, we need to clear the task. We don't do this as a branch of
// the above however since we can have a play-pending animation with a
// resolved start time if we aborted a pause operation.
if (!mStartTime.IsNull() &&
(mPendingState == PendingState::PlayPending ||
mPendingState == PendingState::PausePending)) {
if (mPendingState == PendingState::PausePending) {
mHoldTime.SetNull();
}
CancelPendingTasks();
didChange = true;
if (mReady) {
mReady->MaybeResolve(this);
}
}
UpdateTiming(SeekFlag::DidSeek, SyncNotifyFlag::Sync);
if (didChange && IsRelevant()) {
nsNodeUtils::AnimationChanged(this);
}
PostUpdate();
}
void
Animation::Play(ErrorResult& aRv, LimitBehavior aLimitBehavior)
{
PlayNoUpdate(aRv, aLimitBehavior);
PostUpdate();
}
void
Animation::Pause(ErrorResult& aRv)
{
PauseNoUpdate(aRv);
PostUpdate();
}
// https://w3c.github.io/web-animations/#reverse-an-animation
void
Animation::Reverse(ErrorResult& aRv)
{
if (!mTimeline || mTimeline->GetCurrentTime().IsNull()) {
aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
return;
}
if (mPlaybackRate == 0.0) {
return;
}
AutoMutationBatchForAnimation mb(*this);
SilentlySetPlaybackRate(-mPlaybackRate);
Play(aRv, LimitBehavior::AutoRewind);
// If Play() threw, restore state and don't report anything to mutation
// observers.
if (aRv.Failed()) {
SilentlySetPlaybackRate(-mPlaybackRate);
return;
}
if (IsRelevant()) {
nsNodeUtils::AnimationChanged(this);
}
// Play(), above, unconditionally calls PostUpdate so we don't need to do
// it here.
}
// ---------------------------------------------------------------------------
//
// JS wrappers for Animation interface:
//
// ---------------------------------------------------------------------------
Nullable<double>
Animation::GetStartTimeAsDouble() const
{
return AnimationUtils::TimeDurationToDouble(mStartTime);
}
void
Animation::SetStartTimeAsDouble(const Nullable<double>& aStartTime)
{
return SetStartTime(AnimationUtils::DoubleToTimeDuration(aStartTime));
}
Nullable<double>
Animation::GetCurrentTimeAsDouble() const
{
return AnimationUtils::TimeDurationToDouble(GetCurrentTime());
}
void
Animation::SetCurrentTimeAsDouble(const Nullable<double>& aCurrentTime,
ErrorResult& aRv)
{
if (aCurrentTime.IsNull()) {
if (!GetCurrentTime().IsNull()) {
aRv.Throw(NS_ERROR_DOM_TYPE_ERR);
}
return;
}
return SetCurrentTime(TimeDuration::FromMilliseconds(aCurrentTime.Value()));
}
// ---------------------------------------------------------------------------
void
Animation::Tick()
{
// Finish pending if we have a pending ready time, but only if we also
// have an active timeline.
if (mPendingState != PendingState::NotPending &&
!mPendingReadyTime.IsNull() &&
mTimeline &&
!mTimeline->GetCurrentTime().IsNull()) {
// Even though mPendingReadyTime is initialized using TimeStamp::Now()
// during the *previous* tick of the refresh driver, it can still be
// ahead of the *current* timeline time when we are using the
// vsync timer so we need to clamp it to the timeline time.
mPendingReadyTime.SetValue(std::min(mTimeline->GetCurrentTime().Value(),
mPendingReadyTime.Value()));
FinishPendingAt(mPendingReadyTime.Value());
mPendingReadyTime.SetNull();
}
if (IsPossiblyOrphanedPendingAnimation()) {
MOZ_ASSERT(mTimeline && !mTimeline->GetCurrentTime().IsNull(),
"Orphaned pending animations should have an active timeline");
FinishPendingAt(mTimeline->GetCurrentTime().Value());
}
UpdateTiming(SeekFlag::NoSeek, SyncNotifyFlag::Async);
if (!mEffect) {
return;
}
// Update layers if we are newly finished.
KeyframeEffectReadOnly* keyframeEffect = mEffect->AsKeyframeEffect();
if (keyframeEffect &&
!keyframeEffect->Properties().IsEmpty() &&
!mFinishedAtLastComposeStyle &&
PlayState() == AnimationPlayState::Finished) {
PostUpdate();
}
}
void
Animation::TriggerOnNextTick(const Nullable<TimeDuration>& aReadyTime)
{
// Normally we expect the play state to be pending but it's possible that,
// due to the handling of possibly orphaned animations in Tick(), this
// animation got started whilst still being in another document's pending
// animation map.
if (PlayState() != AnimationPlayState::Pending) {
return;
}
// If aReadyTime.IsNull() we'll detect this in Tick() where we check for
// orphaned animations and trigger this animation anyway
mPendingReadyTime = aReadyTime;
}
void
Animation::TriggerNow()
{
// Normally we expect the play state to be pending but when an animation
// is cancelled and its rendered document can't be reached, we can end up
// with the animation still in a pending player tracker even after it is
// no longer pending.
if (PlayState() != AnimationPlayState::Pending) {
return;
}
// If we don't have an active timeline we can't trigger the animation.
// However, this is a test-only method that we don't expect to be used in
// conjunction with animations without an active timeline so generate
// a warning if we do find ourselves in that situation.
if (!mTimeline || mTimeline->GetCurrentTime().IsNull()) {
NS_WARNING("Failed to trigger an animation with an active timeline");
return;
}
FinishPendingAt(mTimeline->GetCurrentTime().Value());
}
Nullable<TimeDuration>
Animation::GetCurrentOrPendingStartTime() const
{
Nullable<TimeDuration> result;
if (!mStartTime.IsNull()) {
result = mStartTime;
return result;
}
if (mPendingReadyTime.IsNull() || mHoldTime.IsNull()) {
return result;
}
// Calculate the equivalent start time from the pending ready time.
result = StartTimeFromReadyTime(mPendingReadyTime.Value());
return result;
}
TimeDuration
Animation::StartTimeFromReadyTime(const TimeDuration& aReadyTime) const
{
MOZ_ASSERT(!mHoldTime.IsNull(), "Hold time should be set in order to"
" convert a ready time to a start time");
if (mPlaybackRate == 0) {
return aReadyTime;
}
return aReadyTime - mHoldTime.Value().MultDouble(1 / mPlaybackRate);
}
TimeStamp
Animation::AnimationTimeToTimeStamp(const StickyTimeDuration& aTime) const
{
// Initializes to null. Return the same object every time to benefit from
// return-value-optimization.
TimeStamp result;
// We *don't* check for mTimeline->TracksWallclockTime() here because that
// method only tells us if the timeline times can be converted to
// TimeStamps that can be compared to TimeStamp::Now() or not, *not*
// whether the timelines can be converted to TimeStamp values at all.
//
// Furthermore, we want to be able to use this method when the refresh driver
// is under test control (in which case TracksWallclockTime() will return
// false).
//
// Once we introduce timelines that are not time-based we will need to
// differentiate between them here and determine how to sort their events.
if (!mTimeline) {
return result;
}
// Check the time is convertible to a timestamp
if (aTime == TimeDuration::Forever() ||
mPlaybackRate == 0.0 ||
mStartTime.IsNull()) {
return result;
}
// Invert the standard relation:
// animation time = (timeline time - start time) * playback rate
TimeDuration timelineTime =
TimeDuration(aTime).MultDouble(1.0 / mPlaybackRate) + mStartTime.Value();
result = mTimeline->ToTimeStamp(timelineTime);
return result;
}
TimeStamp
Animation::ElapsedTimeToTimeStamp(
const StickyTimeDuration& aElapsedTime) const
{
TimeDuration delay = mEffect
? mEffect->SpecifiedTiming().Delay()
: TimeDuration();
return AnimationTimeToTimeStamp(aElapsedTime + delay);
}
// https://w3c.github.io/web-animations/#silently-set-the-current-time
void
Animation::SilentlySetCurrentTime(const TimeDuration& aSeekTime)
{
if (!mHoldTime.IsNull() ||
mStartTime.IsNull() ||
!mTimeline ||
mTimeline->GetCurrentTime().IsNull() ||
mPlaybackRate == 0.0) {
mHoldTime.SetValue(aSeekTime);
if (!mTimeline || mTimeline->GetCurrentTime().IsNull()) {
mStartTime.SetNull();
}
} else {
mStartTime.SetValue(mTimeline->GetCurrentTime().Value() -
(aSeekTime.MultDouble(1 / mPlaybackRate)));
}
mPreviousCurrentTime.SetNull();
}
void
Animation::SilentlySetPlaybackRate(double aPlaybackRate)
{
Nullable<TimeDuration> previousTime = GetCurrentTime();
mPlaybackRate = aPlaybackRate;
if (!previousTime.IsNull()) {
SilentlySetCurrentTime(previousTime.Value());
}
}
// https://w3c.github.io/web-animations/#cancel-an-animation
void
Animation::CancelNoUpdate()
{
ResetPendingTasks();
if (mFinished) {
mFinished->MaybeReject(NS_ERROR_DOM_ABORT_ERR);
}
ResetFinishedPromise();
DispatchPlaybackEvent(NS_LITERAL_STRING("cancel"));
StickyTimeDuration activeTime = mEffect
? mEffect->GetComputedTiming().mActiveTime
: StickyTimeDuration();
mHoldTime.SetNull();
mStartTime.SetNull();
if (mTimeline) {
mTimeline->RemoveAnimation(this);
}
MaybeQueueCancelEvent(activeTime);
// When an animation is cancelled it no longer needs further ticks from the
// timeline. However, if we queued a cancel event and this was the last
// animation attached to the timeline, the timeline will stop observing the
// refresh driver and there may be no subsequent refresh driver tick for
// dispatching the queued event.
//
// By calling UpdateTiming *after* removing ourselves from our timeline, we
// ensure the timeline will register with the refresh driver for at least one
// more tick.
UpdateTiming(SeekFlag::NoSeek, SyncNotifyFlag::Async);
}
bool
Animation::ShouldBeSynchronizedWithMainThread(
nsCSSPropertyID aProperty,
const nsIFrame* aFrame,
AnimationPerformanceWarning::Type& aPerformanceWarning) const
{
// Only synchronize playing animations
if (!IsPlaying()) {
return false;
}
// Currently only transform animations need to be synchronized
if (aProperty != eCSSProperty_transform) {
return false;
}
KeyframeEffectReadOnly* keyframeEffect = mEffect
? mEffect->AsKeyframeEffect()
: nullptr;
if (!keyframeEffect) {
return false;
}
// Are we starting at the same time as other geometric animations?
// We check this before calling ShouldBlockAsyncTransformAnimations, partly
// because it's cheaper, but also because it's often the most useful thing
// to know when you're debugging performance.
if (mSyncWithGeometricAnimations &&
keyframeEffect->HasAnimationOfProperty(eCSSProperty_transform)) {
aPerformanceWarning = AnimationPerformanceWarning::Type::
TransformWithSyncGeometricAnimations;
return true;
}
return keyframeEffect->
ShouldBlockAsyncTransformAnimations(aFrame, aPerformanceWarning);
}
void
Animation::UpdateRelevance()
{
bool wasRelevant = mIsRelevant;
mIsRelevant = HasCurrentEffect() || IsInEffect();
// Notify animation observers.
if (wasRelevant && !mIsRelevant) {
nsNodeUtils::AnimationRemoved(this);
} else if (!wasRelevant && mIsRelevant) {
nsNodeUtils::AnimationAdded(this);
}
}
bool
Animation::HasLowerCompositeOrderThan(const Animation& aOther) const
{
// 0. Object-equality case
if (&aOther == this) {
return false;
}
// 1. CSS Transitions sort lowest
{
auto asCSSTransitionForSorting =
[] (const Animation& anim) -> const CSSTransition*
{
const CSSTransition* transition = anim.AsCSSTransition();
return transition && transition->IsTiedToMarkup() ?
transition :
nullptr;
};
auto thisTransition = asCSSTransitionForSorting(*this);
auto otherTransition = asCSSTransitionForSorting(aOther);
if (thisTransition && otherTransition) {
return thisTransition->HasLowerCompositeOrderThan(*otherTransition);
}
if (thisTransition || otherTransition) {
// Cancelled transitions no longer have an owning element. To be strictly
// correct we should store a strong reference to the owning element
// so that if we arrive here while sorting cancel events, we can sort
// them in the correct order.
//
// However, given that cancel events are almost always queued
// synchronously in some deterministic manner, we can be fairly sure
// that cancel events will be dispatched in a deterministic order
// (which is our only hard requirement until specs say otherwise).
// Furthermore, we only reach here when we have events with equal
// timestamps so this is an edge case we can probably ignore for now.
return thisTransition;
}
}
// 2. CSS Animations sort next
{
auto asCSSAnimationForSorting =
[] (const Animation& anim) -> const CSSAnimation*
{
const CSSAnimation* animation = anim.AsCSSAnimation();
return animation && animation->IsTiedToMarkup() ? animation : nullptr;
};
auto thisAnimation = asCSSAnimationForSorting(*this);
auto otherAnimation = asCSSAnimationForSorting(aOther);
if (thisAnimation && otherAnimation) {
return thisAnimation->HasLowerCompositeOrderThan(*otherAnimation);
}
if (thisAnimation || otherAnimation) {
return thisAnimation;
}
}
// Subclasses of Animation repurpose mAnimationIndex to implement their
// own brand of composite ordering. However, by this point we should have
// handled any such custom composite ordering so we should now have unique
// animation indices.
MOZ_ASSERT(mAnimationIndex != aOther.mAnimationIndex,
"Animation indices should be unique");
// 3. Finally, generic animations sort by their position in the global
// animation array.
return mAnimationIndex < aOther.mAnimationIndex;
}
void
Animation::WillComposeStyle()
{
mFinishedAtLastComposeStyle = (PlayState() == AnimationPlayState::Finished);
MOZ_ASSERT(mEffect);
KeyframeEffectReadOnly* keyframeEffect = mEffect->AsKeyframeEffect();
if (keyframeEffect) {
keyframeEffect->WillComposeStyle();
}
}
template<typename ComposeAnimationResult>
void
Animation::ComposeStyle(ComposeAnimationResult&& aComposeResult,
const nsCSSPropertyIDSet& aPropertiesToSkip)
{
if (!mEffect) {
return;
}
// In order to prevent flicker, there are a few cases where we want to use
// a different time for rendering that would otherwise be returned by
// GetCurrentTime. These are:
//
// (a) For animations that are pausing but which are still running on the
// compositor. In this case we send a layer transaction that removes the
// animation but which also contains the animation values calculated on
// the main thread. To prevent flicker when this occurs we want to ensure
// the timeline time used to calculate the main thread animation values
// does not lag far behind the time used on the compositor. Ideally we
// would like to use the "animation ready time" calculated at the end of
// the layer transaction as the timeline time but it will be too late to
// update the style rule at that point so instead we just use the current
// wallclock time.
//
// (b) For animations that are pausing that we have already taken off the
// compositor. In this case we record a pending ready time but we don't
// apply it until the next tick. However, while waiting for the next tick,
// we should still use the pending ready time as the timeline time. If we
// use the regular timeline time the animation may appear jump backwards
// if the main thread's timeline time lags behind the compositor.
//
// (c) For animations that are play-pending due to an aborted pause operation
// (i.e. a pause operation that was interrupted before we entered the
// paused state). When we cancel a pending pause we might momentarily take
// the animation off the compositor, only to re-add it moments later. In
// that case the compositor might have been ahead of the main thread so we
// should use the current wallclock time to ensure the animation doesn't
// temporarily jump backwards.
//
// To address each of these cases we temporarily tweak the hold time
// immediately before updating the style rule and then restore it immediately
// afterwards. This is purely to prevent visual flicker. Other behavior
// such as dispatching events continues to rely on the regular timeline time.
AnimationPlayState playState = PlayState();
{
AutoRestore<Nullable<TimeDuration>> restoreHoldTime(mHoldTime);