1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #ifndef mozilla_dom_Animation_h
8 #define mozilla_dom_Animation_h
10 #include "X11UndefineNone.h"
11 #include "nsCycleCollectionParticipant.h"
12 #include "mozilla/AnimationPerformanceWarning.h"
13 #include "mozilla/Attributes.h"
14 #include "mozilla/DOMEventTargetHelper.h"
15 #include "mozilla/EffectCompositor.h" // For EffectCompositor::CascadeLevel
16 #include "mozilla/LinkedList.h"
17 #include "mozilla/Maybe.h"
18 #include "mozilla/PostRestyleMode.h"
19 #include "mozilla/StickyTimeDuration.h"
20 #include "mozilla/TimeStamp.h" // for TimeStamp, TimeDuration
21 #include "mozilla/dom/AnimationBinding.h" // for AnimationPlayState
22 #include "mozilla/dom/AnimationTimeline.h"
25 class nsCSSPropertyIDSet
;
27 class nsIGlobalObject
;
32 class MicroTaskRunnable
;
36 class AnimationEffect
;
37 class AsyncFinishNotification
;
43 class Animation
: public DOMEventTargetHelper
,
44 public LinkedListElement
<Animation
> {
49 explicit Animation(nsIGlobalObject
* aGlobal
);
51 // Constructs a copy of |aOther| with a new effect and timeline.
52 // This is only intended to be used while making a static clone of a document
53 // during printing, and does not assume that |aOther| is in the same document
54 // as any of the other arguments.
55 static already_AddRefed
<Animation
> ClonePausedAnimation(
56 nsIGlobalObject
* aGlobal
, const Animation
& aOther
,
57 AnimationEffect
& aEffect
, AnimationTimeline
& aTimeline
);
59 NS_DECL_ISUPPORTS_INHERITED
60 NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(Animation
, DOMEventTargetHelper
)
62 nsIGlobalObject
* GetParentObject() const { return GetOwnerGlobal(); }
65 * Utility function to get the target (pseudo-)element associated with an
68 NonOwningAnimationTarget
GetTargetForAnimation() const;
70 virtual JSObject
* WrapObject(JSContext
* aCx
,
71 JS::Handle
<JSObject
*> aGivenProto
) override
;
73 virtual CSSAnimation
* AsCSSAnimation() { return nullptr; }
74 virtual const CSSAnimation
* AsCSSAnimation() const { return nullptr; }
75 virtual CSSTransition
* AsCSSTransition() { return nullptr; }
76 virtual const CSSTransition
* AsCSSTransition() const { return nullptr; }
79 * Flag to pass to Play to indicate whether or not it should automatically
80 * rewind the current time to the start point if the animation is finished.
81 * For regular calls to play() from script we should do this, but when a CSS
82 * animation's animation-play-state changes we shouldn't rewind the animation.
84 enum class LimitBehavior
{ AutoRewind
, Continue
};
86 // Animation interface methods
87 static already_AddRefed
<Animation
> Constructor(
88 const GlobalObject
& aGlobal
, AnimationEffect
* aEffect
,
89 const Optional
<AnimationTimeline
*>& aTimeline
, ErrorResult
& aRv
);
91 void GetId(nsAString
& aResult
) const { aResult
= mId
; }
92 void SetId(const nsAString
& aId
);
94 AnimationEffect
* GetEffect() const { return mEffect
; }
95 virtual void SetEffect(AnimationEffect
* aEffect
);
96 void SetEffectNoUpdate(AnimationEffect
* aEffect
);
98 AnimationTimeline
* GetTimeline() const { return mTimeline
; }
99 // Animation.timeline setter is supported only on Nightly.
100 void SetTimeline(AnimationTimeline
* aTimeline
);
101 void SetTimelineNoUpdate(AnimationTimeline
* aTimeline
);
103 Nullable
<TimeDuration
> GetStartTime() const { return mStartTime
; }
104 Nullable
<double> GetStartTimeAsDouble() const;
105 void SetStartTime(const Nullable
<TimeDuration
>& aNewStartTime
);
106 virtual void SetStartTimeAsDouble(const Nullable
<double>& aStartTime
);
108 // This is deliberately _not_ called GetCurrentTime since that would clash
109 // with a macro defined in winbase.h
110 Nullable
<TimeDuration
> GetCurrentTimeAsDuration() const {
111 return GetCurrentTimeForHoldTime(mHoldTime
);
113 Nullable
<double> GetCurrentTimeAsDouble() const;
114 void SetCurrentTime(const TimeDuration
& aNewCurrentTime
);
115 void SetCurrentTimeAsDouble(const Nullable
<double>& aCurrentTime
,
118 double PlaybackRate() const { return mPlaybackRate
; }
119 void SetPlaybackRate(double aPlaybackRate
);
121 AnimationPlayState
PlayState() const;
122 virtual AnimationPlayState
PlayStateFromJS() const { return PlayState(); }
124 bool Pending() const { return mPendingState
!= PendingState::NotPending
; }
125 virtual bool PendingFromJS() const { return Pending(); }
126 AnimationReplaceState
ReplaceState() const { return mReplaceState
; }
128 virtual Promise
* GetReady(ErrorResult
& aRv
);
129 Promise
* GetFinished(ErrorResult
& aRv
);
131 IMPL_EVENT_HANDLER(finish
);
132 IMPL_EVENT_HANDLER(cancel
);
133 IMPL_EVENT_HANDLER(remove
);
135 void Cancel(PostRestyleMode aPostRestyle
= PostRestyleMode::IfNeeded
);
137 void Finish(ErrorResult
& aRv
);
139 void Play(ErrorResult
& aRv
, LimitBehavior aLimitBehavior
);
140 virtual void PlayFromJS(ErrorResult
& aRv
) {
141 Play(aRv
, LimitBehavior::AutoRewind
);
144 void Pause(ErrorResult
& aRv
);
145 virtual void PauseFromJS(ErrorResult
& aRv
) { Pause(aRv
); }
147 void UpdatePlaybackRate(double aPlaybackRate
);
148 virtual void Reverse(ErrorResult
& aRv
);
151 MOZ_CAN_RUN_SCRIPT
void CommitStyles(ErrorResult
& aRv
);
153 bool IsRunningOnCompositor() const;
156 bool NeedsTicks() const {
158 (PlayState() == AnimationPlayState::Running
&&
159 // An animation with a zero playback rate doesn't need ticks even if
160 // it is running since it effectively behaves as if it is paused.
162 // It's important we return false in this case since a zero playback
163 // rate animation in the before or after phase that doesn't fill
164 // won't be relevant and hence won't be returned by GetAnimations().
165 // We don't want its timeline to keep it alive (which would happen
166 // if we return true) since otherwise it will effectively be leaked.
167 PlaybackRate() != 0.0);
171 * Set the time to use for starting or pausing a pending animation.
173 * Typically, when an animation is played, it does not start immediately but
174 * is added to a table of pending animations on the document of its effect.
175 * In the meantime it sets its hold time to the time from which playback
178 * When the document finishes painting, any pending animations in its table
179 * are marked as being ready to start by calling TriggerOnNextTick.
180 * The moment when the paint completed is also recorded, converted to a
181 * timeline time, and passed to StartOnTick. This is so that when these
182 * animations do start, they can be timed from the point when painting
185 * After calling TriggerOnNextTick, animations remain in the pending state
186 * until the next refresh driver tick. At that time they transition out of
187 * the pending state using the time passed to TriggerOnNextTick as the
188 * effective time at which they resumed.
190 * This approach means that any setup time required for performing the
191 * initial paint of an animation such as layerization is not deducted from
192 * the running time of the animation. Without this we can easily drop the
193 * first few frames of an animation, or, on slower devices, the whole
198 * - Starting the animation immediately when painting finishes is problematic
199 * because the start time of the animation will be ahead of its timeline
200 * (since the timeline time is based on the refresh driver time).
201 * That's a problem because the animation is playing but its timing
202 * suggests it starts in the future. We could update the timeline to match
203 * the start time of the animation but then we'd also have to update the
204 * timing and style of all animations connected to that timeline or else be
205 * stuck in an inconsistent state until the next refresh driver tick.
207 * - If we simply use the refresh driver time on its next tick, the lag
208 * between triggering an animation and its effective start is unacceptably
211 * For pausing, we apply the same asynchronous approach. This is so that we
212 * synchronize with animations that are running on the compositor. Otherwise
213 * if the main thread lags behind the compositor there will be a noticeable
214 * jump backwards when the main thread takes over. Even though main thread
215 * animations could be paused immediately, we do it asynchronously for
216 * consistency and so that animations paused together end up in step.
218 * Note that the caller of this method is responsible for removing the
219 * animation from any PendingAnimationTracker it may have been added to.
221 void TriggerOnNextTick(const Nullable
<TimeDuration
>& aReadyTime
);
223 * Testing only: Start or pause a pending animation using the current
224 * timeline time. This is used to support existing tests that expect
225 * animations to begin immediately. Ideally we would rewrite the those tests
226 * and get rid of this method, but there are a lot of them.
228 * As with TriggerOnNextTick, the caller of this method is responsible for
229 * removing the animation from any PendingAnimationTracker it may have been
234 * When TriggerOnNextTick is called, we store the ready time but we don't
235 * apply it until the next tick. In the meantime, GetStartTime() will return
238 * However, if we build layer animations again before the next tick, we
239 * should initialize them with the start time that GetStartTime() will return
242 * If we were to simply set the start time of layer animations to null, their
243 * start time would be updated to the current wallclock time when rendering
244 * finishes, thus making them out of sync with the start time stored here.
245 * This, in turn, will make the animation jump backwards when we build
246 * animations on the next tick and apply the start time stored here.
248 * This method returns the start time, if resolved. Otherwise, if we have
249 * a pending ready time, it returns the corresponding start time. If neither
250 * of those are available, it returns null.
252 Nullable
<TimeDuration
> GetCurrentOrPendingStartTime() const;
255 * As with the start time, we should use the pending playback rate when
256 * producing layer animations.
258 double CurrentOrPendingPlaybackRate() const {
259 return mPendingPlaybackRate
.valueOr(mPlaybackRate
);
261 bool HasPendingPlaybackRate() const { return mPendingPlaybackRate
.isSome(); }
264 * The following relationship from the definition of the 'current time' is
265 * re-used in many algorithms so we extract it here into a static method that
268 * current time = (timeline time - start time) * playback rate
270 * As per https://drafts.csswg.org/web-animations-1/#current-time
272 static TimeDuration
CurrentTimeFromTimelineTime(
273 const TimeDuration
& aTimelineTime
, const TimeDuration
& aStartTime
,
274 float aPlaybackRate
) {
275 return (aTimelineTime
- aStartTime
).MultDouble(aPlaybackRate
);
279 * As with calculating the current time, we often need to calculate a start
280 * time from a current time. The following method simply inverts the current
283 * In each case where this is used, the desired behavior for playbackRate ==
284 * 0 is to return the specified timeline time (often referred to as the ready
287 static TimeDuration
StartTimeFromTimelineTime(
288 const TimeDuration
& aTimelineTime
, const TimeDuration
& aCurrentTime
,
289 float aPlaybackRate
) {
290 TimeDuration result
= aTimelineTime
;
291 if (aPlaybackRate
== 0) {
295 result
-= aCurrentTime
.MultDouble(1.0 / aPlaybackRate
);
300 * Converts a time in the timescale of this Animation's currentTime, to a
301 * TimeStamp. Returns a null TimeStamp if the conversion cannot be performed
302 * because of the current state of this Animation (e.g. it has no timeline, a
303 * zero playbackRate, an unresolved start time etc.) or the value of the time
304 * passed-in (e.g. an infinite time).
306 TimeStamp
AnimationTimeToTimeStamp(const StickyTimeDuration
& aTime
) const;
308 // Converts an AnimationEvent's elapsedTime value to an equivalent TimeStamp
309 // that can be used to sort events by when they occurred.
310 TimeStamp
ElapsedTimeToTimeStamp(
311 const StickyTimeDuration
& aElapsedTime
) const;
313 bool IsPausedOrPausing() const {
314 return PlayState() == AnimationPlayState::Paused
;
317 bool HasCurrentEffect() const;
318 bool IsInEffect() const;
320 bool IsPlaying() const {
321 return mPlaybackRate
!= 0.0 && mTimeline
&&
322 !mTimeline
->GetCurrentTimeAsDuration().IsNull() &&
323 PlayState() == AnimationPlayState::Running
;
326 bool ShouldBeSynchronizedWithMainThread(
327 const nsCSSPropertyIDSet
& aPropertySet
, const nsIFrame
* aFrame
,
328 AnimationPerformanceWarning::Type
& aPerformanceWarning
/* out */) const;
330 bool IsRelevant() const { return mIsRelevant
; }
331 void UpdateRelevance();
333 // https://drafts.csswg.org/web-animations-1/#replaceable-animation
334 bool IsReplaceable() const;
337 * Returns true if this Animation satisfies the requirements for being
338 * removed when it is replaced.
340 * Returning true does not imply this animation _should_ be removed.
341 * Determining that depends on the other effects in the same EffectSet to
342 * which this animation's effect, if any, contributes.
344 bool IsRemovable() const;
347 * Make this animation's target effect no-longer part of the effect stack
348 * while preserving its timing information.
353 * Returns true if this Animation has a lower composite order than aOther.
355 bool HasLowerCompositeOrderThan(const Animation
& aOther
) const;
358 * Returns the level at which the effect(s) associated with this Animation
359 * are applied to the CSS cascade.
361 virtual EffectCompositor::CascadeLevel
CascadeLevel() const {
362 return EffectCompositor::CascadeLevel::Animations
;
366 * Returns true if this animation does not currently need to update
367 * style on the main thread (e.g. because it is empty, or is
368 * running on the compositor).
370 bool CanThrottle() const;
373 * Updates various bits of state that we need to update as the result of
374 * running ComposeStyle().
375 * See the comment of KeyframeEffect::WillComposeStyle for more detail.
377 void WillComposeStyle();
380 * Updates |aComposeResult| with the animation values of this animation's
382 * Any properties contained in |aPropertiesToSkip| will not be added or
383 * updated in |aComposeResult|.
385 void ComposeStyle(RawServoAnimationValueMap
& aComposeResult
,
386 const nsCSSPropertyIDSet
& aPropertiesToSkip
);
388 void NotifyEffectTimingUpdated();
389 void NotifyEffectPropertiesUpdated();
390 void NotifyEffectTargetUpdated();
391 void NotifyGeometricAnimationsStartingThisFrame();
394 * Reschedule pending pause or pending play tasks when updating the target
397 * If we are pending, we will either be registered in the pending animation
398 * tracker and have a null pending ready time, or, after our effect has been
399 * painted, we will be removed from the tracker and assigned a pending ready
402 * When the target effect is updated, we'll typically need to repaint so for
403 * the latter case where we already have a pending ready time, clear it and
404 * put ourselves back in the pending animation tracker.
406 void ReschedulePendingTasks();
409 * Used by subclasses to synchronously queue a cancel event in situations
410 * where the Animation may have been cancelled.
412 * We need to do this synchronously because after a CSS animation/transition
413 * is canceled, it will be released by its owning element and may not still
414 * exist when we would normally go to queue events on the next tick.
416 virtual void MaybeQueueCancelEvent(const StickyTimeDuration
& aActiveTime
){};
418 int32_t& CachedChildIndexRef() { return mCachedChildIndex
; }
420 void SetPartialPrerendered(uint64_t aIdOnCompositor
) {
421 mIdOnCompositor
= aIdOnCompositor
;
422 mIsPartialPrerendered
= true;
424 bool IsPartialPrerendered() const { return mIsPartialPrerendered
; }
425 uint64_t IdOnCompositor() const { return mIdOnCompositor
; }
427 * Needs to be called when the pre-rendered animation is going to no longer
428 * run on the compositor.
430 void ResetPartialPrerendered() {
431 MOZ_ASSERT(mIsPartialPrerendered
);
432 mIsPartialPrerendered
= false;
436 * Called via NotifyJankedAnimations IPC call from the compositor to update
437 * pre-rendered area on the main-thread.
439 void UpdatePartialPrerendered() {
440 ResetPartialPrerendered();
445 void SilentlySetCurrentTime(const TimeDuration
& aNewCurrentTime
);
446 void CancelNoUpdate();
447 void PlayNoUpdate(ErrorResult
& aRv
, LimitBehavior aLimitBehavior
);
448 void ResumeAt(const TimeDuration
& aReadyTime
);
449 void PauseAt(const TimeDuration
& aReadyTime
);
450 void FinishPendingAt(const TimeDuration
& aReadyTime
) {
451 if (mPendingState
== PendingState::PlayPending
) {
452 ResumeAt(aReadyTime
);
453 } else if (mPendingState
== PendingState::PausePending
) {
456 MOZ_ASSERT_UNREACHABLE(
457 "Can't finish pending if we're not in a pending state");
460 void ApplyPendingPlaybackRate() {
461 if (mPendingPlaybackRate
) {
462 mPlaybackRate
= *mPendingPlaybackRate
;
463 mPendingPlaybackRate
.reset();
468 * Finishing behavior depends on if changes to timing occurred due
469 * to a seek or regular playback.
471 enum class SeekFlag
{ NoSeek
, DidSeek
};
473 enum class SyncNotifyFlag
{ Sync
, Async
};
475 virtual void UpdateTiming(SeekFlag aSeekFlag
, SyncNotifyFlag aSyncNotifyFlag
);
476 void UpdateFinishedState(SeekFlag aSeekFlag
, SyncNotifyFlag aSyncNotifyFlag
);
477 void UpdateEffect(PostRestyleMode aPostRestyle
);
479 * Flush all pending styles other than throttled animation styles (e.g.
480 * animations running on the compositor).
482 void FlushUnanimatedStyle() const;
484 void ResetFinishedPromise();
485 void MaybeResolveFinishedPromise();
486 void DoFinishNotification(SyncNotifyFlag aSyncNotifyFlag
);
487 friend class AsyncFinishNotification
;
488 void DoFinishNotificationImmediately(MicroTaskRunnable
* aAsync
= nullptr);
489 void QueuePlaybackEvent(const nsAString
& aName
,
490 TimeStamp
&& aScheduledEventTime
);
493 * Remove this animation from the pending animation tracker and reset
494 * mPendingState as necessary. The caller is responsible for resolving or
495 * aborting the mReady promise as necessary.
497 void CancelPendingTasks();
500 * Performs the same steps as CancelPendingTasks and also rejects and
501 * recreates the ready promise if the animation was pending.
503 void ResetPendingTasks();
506 * Returns true if this animation is not only play-pending, but has
507 * yet to be given a pending ready time. This roughly corresponds to
508 * animations that are waiting to be painted (since we set the pending
509 * ready time at the end of painting). Identifying such animations is
510 * useful because in some cases animations that are painted together
511 * may need to be synchronized.
513 * We don't, however, want to include animations with a fixed start time such
514 * as animations that are simply having their playbackRate updated or which
515 * are resuming from an aborted pause.
517 bool IsNewlyStarted() const {
518 return mPendingState
== PendingState::PlayPending
&&
519 mPendingReadyTime
.IsNull() && mStartTime
.IsNull();
521 bool IsPossiblyOrphanedPendingAnimation() const;
522 StickyTimeDuration
EffectEnd() const;
524 Nullable
<TimeDuration
> GetCurrentTimeForHoldTime(
525 const Nullable
<TimeDuration
>& aHoldTime
) const;
526 Nullable
<TimeDuration
> GetUnconstrainedCurrentTime() const {
527 return GetCurrentTimeForHoldTime(Nullable
<TimeDuration
>());
530 void ScheduleReplacementCheck();
531 void MaybeScheduleReplacementCheck();
533 // Earlier side of the elapsed time range reported in CSS Animations and CSS
534 // Transitions events.
536 // https://drafts.csswg.org/css-animations-2/#interval-start
537 // https://drafts.csswg.org/css-transitions-2/#interval-start
538 StickyTimeDuration
IntervalStartTime(
539 const StickyTimeDuration
& aActiveDuration
) const;
541 // Later side of the elapsed time range reported in CSS Animations and CSS
542 // Transitions events.
544 // https://drafts.csswg.org/css-animations-2/#interval-end
545 // https://drafts.csswg.org/css-transitions-2/#interval-end
546 StickyTimeDuration
IntervalEndTime(
547 const StickyTimeDuration
& aActiveDuration
) const;
549 TimeStamp
GetTimelineCurrentTimeAsTimeStamp() const {
550 return mTimeline
? mTimeline
->GetCurrentTimeAsTimeStamp() : TimeStamp();
553 Document
* GetRenderedDocument() const;
554 Document
* GetTimelineDocument() const;
556 RefPtr
<AnimationTimeline
> mTimeline
;
557 RefPtr
<AnimationEffect
> mEffect
;
558 // The beginning of the delay period.
559 Nullable
<TimeDuration
> mStartTime
; // Timeline timescale
560 Nullable
<TimeDuration
> mHoldTime
; // Animation timescale
561 Nullable
<TimeDuration
> mPendingReadyTime
; // Timeline timescale
562 Nullable
<TimeDuration
> mPreviousCurrentTime
; // Animation timescale
563 double mPlaybackRate
= 1.0;
564 Maybe
<double> mPendingPlaybackRate
;
566 // A Promise that is replaced on each call to Play()
567 // and fulfilled when Play() is successfully completed.
568 // This object is lazily created by GetReady.
569 // See http://drafts.csswg.org/web-animations/#current-ready-promise
570 RefPtr
<Promise
> mReady
;
572 // A Promise that is resolved when we reach the end of the effect, or
573 // 0 when playing backwards. The Promise is replaced if the animation is
574 // finished but then a state change makes it not finished.
575 // This object is lazily created by GetFinished.
576 // See http://drafts.csswg.org/web-animations/#current-finished-promise
577 RefPtr
<Promise
> mFinished
;
579 static uint64_t sNextAnimationIndex
;
581 // The relative position of this animation within the global animation list.
583 // Note that subclasses such as CSSTransition and CSSAnimation may repurpose
584 // this member to implement their own brand of sorting. As a result, it is
585 // possible for two different objects to have the same index.
586 uint64_t mAnimationIndex
;
588 // While ordering Animation objects for event dispatch, the index of the
589 // target node in its parent may be cached in mCachedChildIndex.
590 int32_t mCachedChildIndex
= -1;
592 // Indicates if the animation is in the pending state (and what state it is
593 // waiting to enter when it finished pending). We use this rather than
594 // checking if this animation is tracked by a PendingAnimationTracker because
595 // the animation will continue to be pending even after it has been removed
596 // from the PendingAnimationTracker while it is waiting for the next tick
597 // (see TriggerOnNextTick for details).
598 enum class PendingState
: uint8_t { NotPending
, PlayPending
, PausePending
};
599 PendingState mPendingState
= PendingState::NotPending
;
601 // Handling of this animation's target effect when filling while finished.
602 AnimationReplaceState mReplaceState
= AnimationReplaceState::Active
;
604 bool mFinishedAtLastComposeStyle
= false;
605 bool mWasReplaceableAtLastTick
= false;
607 // Indicates that the animation should be exposed in an element's
608 // getAnimations() list.
609 bool mIsRelevant
= false;
611 // True if mFinished is resolved or would be resolved if mFinished has
612 // yet to be created. This is not set when mFinished is rejected since
613 // in that case mFinished is immediately reset to represent a new current
615 bool mFinishedIsResolved
= false;
617 // True if this animation was triggered at the same time as one or more
618 // geometric animations and hence we should run any transform animations on
620 bool mSyncWithGeometricAnimations
= false;
622 RefPtr
<MicroTaskRunnable
> mFinishNotificationTask
;
627 // The id for this animaiton on the compositor.
628 uint64_t mIdOnCompositor
= 0;
629 bool mIsPartialPrerendered
= false;
633 } // namespace mozilla
635 #endif // mozilla_dom_Animation_h