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/BasePrincipal.h"
15 #include "mozilla/DOMEventTargetHelper.h"
16 #include "mozilla/EffectCompositor.h" // For EffectCompositor::CascadeLevel
17 #include "mozilla/LinkedList.h"
18 #include "mozilla/Maybe.h"
19 #include "mozilla/PostRestyleMode.h"
20 #include "mozilla/StickyTimeDuration.h"
21 #include "mozilla/TimeStamp.h" // for TimeStamp, TimeDuration
22 #include "mozilla/dom/AnimationBinding.h" // for AnimationPlayState
23 #include "mozilla/dom/AnimationTimeline.h"
26 class nsCSSPropertyIDSet
;
28 class nsIGlobalObject
;
34 class MicroTaskRunnable
;
38 class AnimationEffect
;
39 class AsyncFinishNotification
;
45 class Animation
: public DOMEventTargetHelper
,
46 public LinkedListElement
<Animation
> {
51 explicit Animation(nsIGlobalObject
* aGlobal
);
53 // Constructs a copy of |aOther| with a new effect and timeline.
54 // This is only intended to be used while making a static clone of a document
55 // during printing, and does not assume that |aOther| is in the same document
56 // as any of the other arguments.
57 static already_AddRefed
<Animation
> ClonePausedAnimation(
58 nsIGlobalObject
* aGlobal
, const Animation
& aOther
,
59 AnimationEffect
& aEffect
, AnimationTimeline
& aTimeline
);
61 NS_DECL_ISUPPORTS_INHERITED
62 NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(Animation
, DOMEventTargetHelper
)
64 nsIGlobalObject
* GetParentObject() const { return GetOwnerGlobal(); }
67 * Utility function to get the target (pseudo-)element associated with an
70 NonOwningAnimationTarget
GetTargetForAnimation() const;
72 virtual JSObject
* WrapObject(JSContext
* aCx
,
73 JS::Handle
<JSObject
*> aGivenProto
) override
;
75 virtual CSSAnimation
* AsCSSAnimation() { return nullptr; }
76 virtual const CSSAnimation
* AsCSSAnimation() const { return nullptr; }
77 virtual CSSTransition
* AsCSSTransition() { return nullptr; }
78 virtual const CSSTransition
* AsCSSTransition() const { return nullptr; }
81 * Flag to pass to Play to indicate whether or not it should automatically
82 * rewind the current time to the start point if the animation is finished.
83 * For regular calls to play() from script we should do this, but when a CSS
84 * animation's animation-play-state changes we shouldn't rewind the animation.
86 enum class LimitBehavior
{ AutoRewind
, Continue
};
88 // Animation interface methods
89 static already_AddRefed
<Animation
> Constructor(
90 const GlobalObject
& aGlobal
, AnimationEffect
* aEffect
,
91 const Optional
<AnimationTimeline
*>& aTimeline
, ErrorResult
& aRv
);
93 void GetId(nsAString
& aResult
) const { aResult
= mId
; }
94 void SetId(const nsAString
& aId
);
96 AnimationEffect
* GetEffect() const { return mEffect
; }
97 virtual void SetEffect(AnimationEffect
* aEffect
);
98 void SetEffectNoUpdate(AnimationEffect
* aEffect
);
100 // FIXME: Bug 1676794. This is a tentative solution before we implement
101 // ScrollTimeline interface. If the timeline is scroll/view timeline, we
102 // return null. Once we implement ScrollTimeline interface, we can drop this.
103 already_AddRefed
<AnimationTimeline
> GetTimelineFromJS() const {
104 return mTimeline
&& mTimeline
->IsScrollTimeline() ? nullptr
105 : do_AddRef(mTimeline
);
107 void SetTimelineFromJS(AnimationTimeline
* aTimeline
) {
108 SetTimeline(aTimeline
);
111 AnimationTimeline
* GetTimeline() const { return mTimeline
; }
112 void SetTimeline(AnimationTimeline
* aTimeline
);
113 void SetTimelineNoUpdate(AnimationTimeline
* aTimeline
);
115 Nullable
<TimeDuration
> GetStartTime() const { return mStartTime
; }
116 Nullable
<double> GetStartTimeAsDouble() const;
117 void SetStartTime(const Nullable
<TimeDuration
>& aNewStartTime
);
118 const TimeStamp
& GetPendingReadyTime() const { return mPendingReadyTime
; }
119 void SetPendingReadyTime(const TimeStamp
& aReadyTime
) {
120 mPendingReadyTime
= aReadyTime
;
122 virtual void SetStartTimeAsDouble(const Nullable
<double>& aStartTime
);
124 // This is deliberately _not_ called GetCurrentTime since that would clash
125 // with a macro defined in winbase.h
126 Nullable
<TimeDuration
> GetCurrentTimeAsDuration() const {
127 return GetCurrentTimeForHoldTime(mHoldTime
);
129 Nullable
<double> GetCurrentTimeAsDouble() const;
130 void SetCurrentTime(const TimeDuration
& aSeekTime
);
131 void SetCurrentTimeNoUpdate(const TimeDuration
& aSeekTime
);
132 void SetCurrentTimeAsDouble(const Nullable
<double>& aCurrentTime
,
135 double PlaybackRate() const { return mPlaybackRate
; }
136 void SetPlaybackRate(double aPlaybackRate
);
138 AnimationPlayState
PlayState() const;
139 virtual AnimationPlayState
PlayStateFromJS() const { return PlayState(); }
141 bool Pending() const { return mPendingState
!= PendingState::NotPending
; }
142 virtual bool PendingFromJS() const { return Pending(); }
143 AnimationReplaceState
ReplaceState() const { return mReplaceState
; }
145 virtual Promise
* GetReady(ErrorResult
& aRv
);
146 Promise
* GetFinished(ErrorResult
& aRv
);
148 IMPL_EVENT_HANDLER(finish
);
149 IMPL_EVENT_HANDLER(cancel
);
150 IMPL_EVENT_HANDLER(remove
);
152 void Cancel(PostRestyleMode aPostRestyle
= PostRestyleMode::IfNeeded
);
154 void Finish(ErrorResult
& aRv
);
156 void Play(ErrorResult
& aRv
, LimitBehavior aLimitBehavior
);
157 virtual void PlayFromJS(ErrorResult
& aRv
) {
158 Play(aRv
, LimitBehavior::AutoRewind
);
161 void Pause(ErrorResult
& aRv
);
162 virtual void PauseFromJS(ErrorResult
& aRv
) { Pause(aRv
); }
164 void UpdatePlaybackRate(double aPlaybackRate
);
165 virtual void Reverse(ErrorResult
& aRv
);
168 MOZ_CAN_RUN_SCRIPT
void CommitStyles(ErrorResult
& aRv
);
170 bool IsRunningOnCompositor() const;
172 using TickState
= AnimationTimeline::TickState
;
173 virtual void Tick(TickState
&);
174 bool NeedsTicks() const {
176 (PlayState() == AnimationPlayState::Running
&&
177 // An animation with a zero playback rate doesn't need ticks even if
178 // it is running since it effectively behaves as if it is paused.
180 // It's important we return false in this case since a zero playback
181 // rate animation in the before or after phase that doesn't fill
182 // won't be relevant and hence won't be returned by GetAnimations().
183 // We don't want its timeline to keep it alive (which would happen
184 // if we return true) since otherwise it will effectively be leaked.
185 PlaybackRate() != 0.0) ||
186 // Always return true for not idle animations attached to not
187 // monotonically increasing timelines even if the animation is
188 // finished. This is required to accommodate cases where timeline
189 // ticks back in time.
190 (mTimeline
&& !mTimeline
->IsMonotonicallyIncreasing() &&
191 PlayState() != AnimationPlayState::Idle
);
194 * For the monotonically increasing timeline, we use this only for testing:
195 * Start or pause a pending animation using the current timeline time. This
196 * is used to support existing tests that expect animations to begin
197 * immediately. Ideally we would rewrite the those tests and get rid of this
198 * method, but there are a lot of them.
200 bool TryTriggerNow();
202 * As with the start time, we should use the pending playback rate when
203 * producing layer animations.
205 double CurrentOrPendingPlaybackRate() const {
206 return mPendingPlaybackRate
.valueOr(mPlaybackRate
);
208 bool HasPendingPlaybackRate() const { return mPendingPlaybackRate
.isSome(); }
211 * The following relationship from the definition of the 'current time' is
212 * re-used in many algorithms so we extract it here into a static method that
215 * current time = (timeline time - start time) * playback rate
217 * As per https://drafts.csswg.org/web-animations-1/#current-time
219 static TimeDuration
CurrentTimeFromTimelineTime(
220 const TimeDuration
& aTimelineTime
, const TimeDuration
& aStartTime
,
221 float aPlaybackRate
) {
222 return (aTimelineTime
- aStartTime
).MultDouble(aPlaybackRate
);
226 * As with calculating the current time, we often need to calculate a start
227 * time from a current time. The following method simply inverts the current
230 * In each case where this is used, the desired behavior for playbackRate ==
231 * 0 is to return the specified timeline time (often referred to as the ready
234 static TimeDuration
StartTimeFromTimelineTime(
235 const TimeDuration
& aTimelineTime
, const TimeDuration
& aCurrentTime
,
236 float aPlaybackRate
) {
237 TimeDuration result
= aTimelineTime
;
238 if (aPlaybackRate
== 0) {
242 result
-= aCurrentTime
.MultDouble(1.0 / aPlaybackRate
);
247 * Converts a time in the timescale of this Animation's currentTime, to a
248 * TimeStamp. Returns a null TimeStamp if the conversion cannot be performed
249 * because of the current state of this Animation (e.g. it has no timeline, a
250 * zero playbackRate, an unresolved start time etc.) or the value of the time
251 * passed-in (e.g. an infinite time).
253 TimeStamp
AnimationTimeToTimeStamp(const StickyTimeDuration
& aTime
) const;
255 // Converts an AnimationEvent's elapsedTime value to an equivalent TimeStamp
256 // that can be used to sort events by when they occurred.
257 TimeStamp
ElapsedTimeToTimeStamp(
258 const StickyTimeDuration
& aElapsedTime
) const;
260 bool IsPausedOrPausing() const {
261 return PlayState() == AnimationPlayState::Paused
;
264 bool HasCurrentEffect() const;
265 bool IsInEffect() const;
267 bool IsPlaying() const {
268 return mPlaybackRate
!= 0.0 && mTimeline
&&
269 !mTimeline
->GetCurrentTimeAsDuration().IsNull() &&
270 PlayState() == AnimationPlayState::Running
;
273 bool ShouldBeSynchronizedWithMainThread(
274 const nsCSSPropertyIDSet
& aPropertySet
, const nsIFrame
* aFrame
,
275 AnimationPerformanceWarning::Type
& aPerformanceWarning
/* out */) const;
277 bool IsRelevant() const { return mIsRelevant
; }
278 void UpdateRelevance();
280 // https://drafts.csswg.org/web-animations-1/#replaceable-animation
281 bool IsReplaceable() const;
284 * Returns true if this Animation satisfies the requirements for being
285 * removed when it is replaced.
287 * Returning true does not imply this animation _should_ be removed.
288 * Determining that depends on the other effects in the same EffectSet to
289 * which this animation's effect, if any, contributes.
291 bool IsRemovable() const;
294 * Make this animation's target effect no-longer part of the effect stack
295 * while preserving its timing information.
300 * Returns true if this Animation has a lower composite order than aOther.
302 bool HasLowerCompositeOrderThan(const Animation
& aOther
) const;
305 * Returns the level at which the effect(s) associated with this Animation
306 * are applied to the CSS cascade.
308 virtual EffectCompositor::CascadeLevel
CascadeLevel() const {
309 return EffectCompositor::CascadeLevel::Animations
;
313 * Returns true if this animation does not currently need to update
314 * style on the main thread (e.g. because it is empty, or is
315 * running on the compositor).
317 bool CanThrottle() const;
320 * Updates various bits of state that we need to update as the result of
321 * running ComposeStyle().
322 * See the comment of KeyframeEffect::WillComposeStyle for more detail.
324 void WillComposeStyle();
327 * Updates |aComposeResult| with the animation values of this animation's
329 * Any properties contained in |aPropertiesToSkip| will not be added or
330 * updated in |aComposeResult|.
332 void ComposeStyle(StyleAnimationValueMap
& aComposeResult
,
333 const nsCSSPropertyIDSet
& aPropertiesToSkip
);
335 void NotifyEffectTimingUpdated();
336 void NotifyEffectPropertiesUpdated();
337 void NotifyEffectTargetUpdated();
340 * Used by subclasses to synchronously queue a cancel event in situations
341 * where the Animation may have been cancelled.
343 * We need to do this synchronously because after a CSS animation/transition
344 * is canceled, it will be released by its owning element and may not still
345 * exist when we would normally go to queue events on the next tick.
347 virtual void MaybeQueueCancelEvent(const StickyTimeDuration
& aActiveTime
){};
349 Maybe
<uint32_t>& CachedChildIndexRef() { return mCachedChildIndex
; }
351 void SetPartialPrerendered(uint64_t aIdOnCompositor
) {
352 mIdOnCompositor
= aIdOnCompositor
;
353 mIsPartialPrerendered
= true;
355 bool IsPartialPrerendered() const { return mIsPartialPrerendered
; }
356 uint64_t IdOnCompositor() const { return mIdOnCompositor
; }
358 * Needs to be called when the pre-rendered animation is going to no longer
359 * run on the compositor.
361 void ResetPartialPrerendered() {
362 MOZ_ASSERT(mIsPartialPrerendered
);
363 mIsPartialPrerendered
= false;
367 * Called via NotifyJankedAnimations IPC call from the compositor to update
368 * pre-rendered area on the main-thread.
370 void UpdatePartialPrerendered() {
371 ResetPartialPrerendered();
375 bool UsingScrollTimeline() const {
376 return mTimeline
&& mTimeline
->IsScrollTimeline();
380 * Returns true if this is at the progress timeline boundary.
381 * https://drafts.csswg.org/web-animations-2/#at-progress-timeline-boundary
383 enum class ProgressTimelinePosition
: uint8_t { Boundary
, NotBoundary
};
384 static ProgressTimelinePosition
AtProgressTimelineBoundary(
385 const Nullable
<TimeDuration
>& aTimelineDuration
,
386 const Nullable
<TimeDuration
>& aCurrentTime
,
387 const TimeDuration
& aEffectStartTime
, const double aPlaybackRate
);
388 ProgressTimelinePosition
AtProgressTimelineBoundary() const {
389 Nullable
<TimeDuration
> currentTime
= GetUnconstrainedCurrentTime();
390 return AtProgressTimelineBoundary(
391 mTimeline
? mTimeline
->TimelineDuration() : nullptr,
392 // Set unlimited current time based on the first matching condition:
393 // 1. start time is resolved:
394 // (timeline time - start time) × playback rate
396 // animation’s current time
397 !currentTime
.IsNull() ? currentTime
: GetCurrentTimeAsDuration(),
398 mStartTime
.IsNull() ? TimeDuration() : mStartTime
.Value(),
402 void SetHiddenByContentVisibility(bool hidden
);
403 bool IsHiddenByContentVisibility() const {
404 return mHiddenByContentVisibility
;
406 void UpdateHiddenByContentVisibility();
408 DocGroup
* GetDocGroup();
411 void SilentlySetCurrentTime(const TimeDuration
& aNewCurrentTime
);
412 void CancelNoUpdate();
413 void PlayNoUpdate(ErrorResult
& aRv
, LimitBehavior aLimitBehavior
);
414 void ResumeAt(const TimeDuration
& aReadyTime
);
415 void PauseAt(const TimeDuration
& aReadyTime
);
416 void FinishPendingAt(const TimeDuration
& aReadyTime
) {
417 if (mPendingState
== PendingState::PlayPending
) {
418 ResumeAt(aReadyTime
);
419 } else if (mPendingState
== PendingState::PausePending
) {
422 MOZ_ASSERT_UNREACHABLE(
423 "Can't finish pending if we're not in a pending state");
426 void ApplyPendingPlaybackRate() {
427 if (mPendingPlaybackRate
) {
428 mPlaybackRate
= mPendingPlaybackRate
.extract();
433 * Finishing behavior depends on if changes to timing occurred due
434 * to a seek or regular playback.
436 enum class SeekFlag
{ NoSeek
, DidSeek
};
438 enum class SyncNotifyFlag
{ Sync
, Async
};
440 virtual void UpdateTiming(SeekFlag aSeekFlag
, SyncNotifyFlag aSyncNotifyFlag
);
441 void UpdateFinishedState(SeekFlag aSeekFlag
, SyncNotifyFlag aSyncNotifyFlag
);
442 void UpdateEffect(PostRestyleMode aPostRestyle
);
444 * Flush all pending styles other than throttled animation styles (e.g.
445 * animations running on the compositor).
447 void FlushUnanimatedStyle() const;
449 void ResetFinishedPromise();
450 void MaybeResolveFinishedPromise();
451 void DoFinishNotification(SyncNotifyFlag aSyncNotifyFlag
);
452 friend class AsyncFinishNotification
;
453 void DoFinishNotificationImmediately(MicroTaskRunnable
* aAsync
= nullptr);
454 void QueuePlaybackEvent(nsAtom
* aOnEvent
, TimeStamp
&& aScheduledEventTime
);
457 * Remove this animation from the pending animation tracker and reset
458 * mPendingState as necessary. The caller is responsible for resolving or
459 * aborting the mReady promise as necessary.
461 void CancelPendingTasks();
464 * Performs the same steps as CancelPendingTasks and also rejects and
465 * recreates the ready promise if the animation was pending.
467 void ResetPendingTasks();
468 StickyTimeDuration
EffectEnd() const;
470 Nullable
<TimeDuration
> GetCurrentTimeForHoldTime(
471 const Nullable
<TimeDuration
>& aHoldTime
) const;
472 Nullable
<TimeDuration
> GetUnconstrainedCurrentTime() const {
473 return GetCurrentTimeForHoldTime(Nullable
<TimeDuration
>());
476 void ScheduleReplacementCheck();
477 void MaybeScheduleReplacementCheck();
479 // Earlier side of the elapsed time range reported in CSS Animations and CSS
480 // Transitions events.
482 // https://drafts.csswg.org/css-animations-2/#interval-start
483 // https://drafts.csswg.org/css-transitions-2/#interval-start
484 StickyTimeDuration
IntervalStartTime(
485 const StickyTimeDuration
& aActiveDuration
) const;
487 // Later side of the elapsed time range reported in CSS Animations and CSS
488 // Transitions events.
490 // https://drafts.csswg.org/css-animations-2/#interval-end
491 // https://drafts.csswg.org/css-transitions-2/#interval-end
492 StickyTimeDuration
IntervalEndTime(
493 const StickyTimeDuration
& aActiveDuration
) const;
495 TimeStamp
GetTimelineCurrentTimeAsTimeStamp() const {
496 return mTimeline
? mTimeline
->GetCurrentTimeAsTimeStamp() : TimeStamp();
499 Document
* GetRenderedDocument() const;
500 Document
* GetTimelineDocument() const;
502 bool HasFiniteTimeline() const {
503 return mTimeline
&& !mTimeline
->IsMonotonicallyIncreasing();
506 void UpdateScrollTimelineAnimationTracker(AnimationTimeline
* aOldTimeline
,
507 AnimationTimeline
* aNewTimeline
);
509 RefPtr
<AnimationTimeline
> mTimeline
;
510 RefPtr
<AnimationEffect
> mEffect
;
511 // The beginning of the delay period.
512 Nullable
<TimeDuration
> mStartTime
; // Timeline timescale
513 Nullable
<TimeDuration
> mHoldTime
; // Animation timescale
514 Nullable
<TimeDuration
> mPreviousCurrentTime
; // Animation timescale
515 double mPlaybackRate
= 1.0;
516 Maybe
<double> mPendingPlaybackRate
;
518 // A Promise that is replaced on each call to Play()
519 // and fulfilled when Play() is successfully completed.
520 // This object is lazily created by GetReady.
521 // See http://drafts.csswg.org/web-animations/#current-ready-promise
522 RefPtr
<Promise
> mReady
;
524 // A Promise that is resolved when we reach the end of the effect, or
525 // 0 when playing backwards. The Promise is replaced if the animation is
526 // finished but then a state change makes it not finished.
527 // This object is lazily created by GetFinished.
528 // See http://drafts.csswg.org/web-animations/#current-finished-promise
529 RefPtr
<Promise
> mFinished
;
531 static uint64_t sNextAnimationIndex
;
533 // The relative position of this animation within the global animation list.
535 // Note that subclasses such as CSSTransition and CSSAnimation may repurpose
536 // this member to implement their own brand of sorting. As a result, it is
537 // possible for two different objects to have the same index.
538 uint64_t mAnimationIndex
;
540 // While ordering Animation objects for event dispatch, the index of the
541 // target node in its parent may be cached in mCachedChildIndex.
542 Maybe
<uint32_t> mCachedChildIndex
;
544 // Indicates if the animation is in the pending state (and what state it is
545 // waiting to enter when it finished pending).
546 enum class PendingState
: uint8_t { NotPending
, PlayPending
, PausePending
};
547 PendingState mPendingState
= PendingState::NotPending
;
549 // Handling of this animation's target effect when filling while finished.
550 AnimationReplaceState mReplaceState
= AnimationReplaceState::Active
;
552 bool mFinishedAtLastComposeStyle
= false;
553 bool mWasReplaceableAtLastTick
= false;
555 bool mHiddenByContentVisibility
= false;
557 // Indicates that the animation should be exposed in an element's
558 // getAnimations() list.
559 bool mIsRelevant
= false;
561 // True if mFinished is resolved or would be resolved if mFinished has
562 // yet to be created. This is not set when mFinished is rejected since
563 // in that case mFinished is immediately reset to represent a new current
565 bool mFinishedIsResolved
= false;
567 RefPtr
<MicroTaskRunnable
> mFinishNotificationTask
;
571 bool mResetCurrentTimeOnResume
= false;
573 // Whether the Animation is System, ResistFingerprinting, or neither
574 RTPCallerType mRTPCallerType
;
576 // The time at which our animation should be ready.
577 TimeStamp mPendingReadyTime
;
580 // The id for this animation on the compositor.
581 uint64_t mIdOnCompositor
= 0;
582 bool mIsPartialPrerendered
= false;
586 } // namespace mozilla
588 #endif // mozilla_dom_Animation_h