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
;
33 class MicroTaskRunnable
;
37 class AnimationEffect
;
38 class AsyncFinishNotification
;
44 class Animation
: public DOMEventTargetHelper
,
45 public LinkedListElement
<Animation
> {
50 explicit Animation(nsIGlobalObject
* aGlobal
);
52 // Constructs a copy of |aOther| with a new effect and timeline.
53 // This is only intended to be used while making a static clone of a document
54 // during printing, and does not assume that |aOther| is in the same document
55 // as any of the other arguments.
56 static already_AddRefed
<Animation
> ClonePausedAnimation(
57 nsIGlobalObject
* aGlobal
, const Animation
& aOther
,
58 AnimationEffect
& aEffect
, AnimationTimeline
& aTimeline
);
60 NS_DECL_ISUPPORTS_INHERITED
61 NS_DECL_CYCLE_COLLECTION_CLASS_INHERITED(Animation
, DOMEventTargetHelper
)
63 nsIGlobalObject
* GetParentObject() const { return GetOwnerGlobal(); }
66 * Utility function to get the target (pseudo-)element associated with an
69 NonOwningAnimationTarget
GetTargetForAnimation() const;
71 virtual JSObject
* WrapObject(JSContext
* aCx
,
72 JS::Handle
<JSObject
*> aGivenProto
) override
;
74 virtual CSSAnimation
* AsCSSAnimation() { return nullptr; }
75 virtual const CSSAnimation
* AsCSSAnimation() const { return nullptr; }
76 virtual CSSTransition
* AsCSSTransition() { return nullptr; }
77 virtual const CSSTransition
* AsCSSTransition() const { return nullptr; }
80 * Flag to pass to Play to indicate whether or not it should automatically
81 * rewind the current time to the start point if the animation is finished.
82 * For regular calls to play() from script we should do this, but when a CSS
83 * animation's animation-play-state changes we shouldn't rewind the animation.
85 enum class LimitBehavior
{ AutoRewind
, Continue
};
87 // Animation interface methods
88 static already_AddRefed
<Animation
> Constructor(
89 const GlobalObject
& aGlobal
, AnimationEffect
* aEffect
,
90 const Optional
<AnimationTimeline
*>& aTimeline
, ErrorResult
& aRv
);
92 void GetId(nsAString
& aResult
) const { aResult
= mId
; }
93 void SetId(const nsAString
& aId
);
95 AnimationEffect
* GetEffect() const { return mEffect
; }
96 virtual void SetEffect(AnimationEffect
* aEffect
);
97 void SetEffectNoUpdate(AnimationEffect
* aEffect
);
99 // FIXME: Bug 1676794. This is a tentative solution before we implement
100 // ScrollTimeline interface. If the timeline is scroll/view timeline, we
101 // return null. Once we implement ScrollTimeline interface, we can drop this.
102 already_AddRefed
<AnimationTimeline
> GetTimelineFromJS() const {
103 return mTimeline
&& mTimeline
->IsScrollTimeline() ? nullptr
104 : do_AddRef(mTimeline
);
106 void SetTimelineFromJS(AnimationTimeline
* aTimeline
) {
107 SetTimeline(aTimeline
);
110 AnimationTimeline
* GetTimeline() const { return mTimeline
; }
111 void SetTimeline(AnimationTimeline
* aTimeline
);
112 void SetTimelineNoUpdate(AnimationTimeline
* aTimeline
);
114 Nullable
<TimeDuration
> GetStartTime() const { return mStartTime
; }
115 Nullable
<double> GetStartTimeAsDouble() const;
116 void SetStartTime(const Nullable
<TimeDuration
>& aNewStartTime
);
117 void SetPendingReadyTime(const TimeStamp
& aReadyTime
) {
118 mPendingReadyTime
= aReadyTime
;
120 virtual void SetStartTimeAsDouble(const Nullable
<double>& aStartTime
);
122 // This is deliberately _not_ called GetCurrentTime since that would clash
123 // with a macro defined in winbase.h
124 Nullable
<TimeDuration
> GetCurrentTimeAsDuration() const {
125 return GetCurrentTimeForHoldTime(mHoldTime
);
127 Nullable
<double> GetCurrentTimeAsDouble() const;
128 void SetCurrentTime(const TimeDuration
& aSeekTime
);
129 void SetCurrentTimeNoUpdate(const TimeDuration
& aSeekTime
);
130 void SetCurrentTimeAsDouble(const Nullable
<double>& aCurrentTime
,
133 double PlaybackRate() const { return mPlaybackRate
; }
134 void SetPlaybackRate(double aPlaybackRate
);
136 AnimationPlayState
PlayState() const;
137 virtual AnimationPlayState
PlayStateFromJS() const { return PlayState(); }
139 bool Pending() const { return mPendingState
!= PendingState::NotPending
; }
140 virtual bool PendingFromJS() const { return Pending(); }
141 AnimationReplaceState
ReplaceState() const { return mReplaceState
; }
143 virtual Promise
* GetReady(ErrorResult
& aRv
);
144 Promise
* GetFinished(ErrorResult
& aRv
);
146 IMPL_EVENT_HANDLER(finish
);
147 IMPL_EVENT_HANDLER(cancel
);
148 IMPL_EVENT_HANDLER(remove
);
150 void Cancel(PostRestyleMode aPostRestyle
= PostRestyleMode::IfNeeded
);
152 void Finish(ErrorResult
& aRv
);
154 void Play(ErrorResult
& aRv
, LimitBehavior aLimitBehavior
);
155 virtual void PlayFromJS(ErrorResult
& aRv
) {
156 Play(aRv
, LimitBehavior::AutoRewind
);
159 void Pause(ErrorResult
& aRv
);
160 virtual void PauseFromJS(ErrorResult
& aRv
) { Pause(aRv
); }
162 void UpdatePlaybackRate(double aPlaybackRate
);
163 virtual void Reverse(ErrorResult
& aRv
);
166 MOZ_CAN_RUN_SCRIPT
void CommitStyles(ErrorResult
& aRv
);
168 bool IsRunningOnCompositor() const;
170 using TickState
= AnimationTimeline::TickState
;
171 virtual void Tick(TickState
&);
172 bool NeedsTicks() const {
174 (PlayState() == AnimationPlayState::Running
&&
175 // An animation with a zero playback rate doesn't need ticks even if
176 // it is running since it effectively behaves as if it is paused.
178 // It's important we return false in this case since a zero playback
179 // rate animation in the before or after phase that doesn't fill
180 // won't be relevant and hence won't be returned by GetAnimations().
181 // We don't want its timeline to keep it alive (which would happen
182 // if we return true) since otherwise it will effectively be leaked.
183 PlaybackRate() != 0.0) ||
184 // Always return true for not idle animations attached to not
185 // monotonically increasing timelines even if the animation is
186 // finished. This is required to accommodate cases where timeline
187 // ticks back in time.
188 (mTimeline
&& !mTimeline
->IsMonotonicallyIncreasing() &&
189 PlayState() != AnimationPlayState::Idle
);
192 * For the monotonically increasing timeline, we use this only for testing:
193 * Start or pause a pending animation using the current timeline time. This
194 * is used to support existing tests that expect animations to begin
195 * immediately. Ideally we would rewrite the those tests and get rid of this
196 * method, but there are a lot of them.
198 bool TryTriggerNow();
200 * As with the start time, we should use the pending playback rate when
201 * producing layer animations.
203 double CurrentOrPendingPlaybackRate() const {
204 return mPendingPlaybackRate
.valueOr(mPlaybackRate
);
206 bool HasPendingPlaybackRate() const { return mPendingPlaybackRate
.isSome(); }
209 * The following relationship from the definition of the 'current time' is
210 * re-used in many algorithms so we extract it here into a static method that
213 * current time = (timeline time - start time) * playback rate
215 * As per https://drafts.csswg.org/web-animations-1/#current-time
217 static TimeDuration
CurrentTimeFromTimelineTime(
218 const TimeDuration
& aTimelineTime
, const TimeDuration
& aStartTime
,
219 float aPlaybackRate
) {
220 return (aTimelineTime
- aStartTime
).MultDouble(aPlaybackRate
);
224 * As with calculating the current time, we often need to calculate a start
225 * time from a current time. The following method simply inverts the current
228 * In each case where this is used, the desired behavior for playbackRate ==
229 * 0 is to return the specified timeline time (often referred to as the ready
232 static TimeDuration
StartTimeFromTimelineTime(
233 const TimeDuration
& aTimelineTime
, const TimeDuration
& aCurrentTime
,
234 float aPlaybackRate
) {
235 TimeDuration result
= aTimelineTime
;
236 if (aPlaybackRate
== 0) {
240 result
-= aCurrentTime
.MultDouble(1.0 / aPlaybackRate
);
245 * Converts a time in the timescale of this Animation's currentTime, to a
246 * TimeStamp. Returns a null TimeStamp if the conversion cannot be performed
247 * because of the current state of this Animation (e.g. it has no timeline, a
248 * zero playbackRate, an unresolved start time etc.) or the value of the time
249 * passed-in (e.g. an infinite time).
251 TimeStamp
AnimationTimeToTimeStamp(const StickyTimeDuration
& aTime
) const;
253 // Converts an AnimationEvent's elapsedTime value to an equivalent TimeStamp
254 // that can be used to sort events by when they occurred.
255 TimeStamp
ElapsedTimeToTimeStamp(
256 const StickyTimeDuration
& aElapsedTime
) const;
258 bool IsPausedOrPausing() const {
259 return PlayState() == AnimationPlayState::Paused
;
262 bool HasCurrentEffect() const;
263 bool IsInEffect() const;
265 bool IsPlaying() const {
266 return mPlaybackRate
!= 0.0 && mTimeline
&&
267 !mTimeline
->GetCurrentTimeAsDuration().IsNull() &&
268 PlayState() == AnimationPlayState::Running
;
271 bool ShouldBeSynchronizedWithMainThread(
272 const nsCSSPropertyIDSet
& aPropertySet
, const nsIFrame
* aFrame
,
273 AnimationPerformanceWarning::Type
& aPerformanceWarning
/* out */) const;
275 bool IsRelevant() const { return mIsRelevant
; }
276 void UpdateRelevance();
278 // https://drafts.csswg.org/web-animations-1/#replaceable-animation
279 bool IsReplaceable() const;
282 * Returns true if this Animation satisfies the requirements for being
283 * removed when it is replaced.
285 * Returning true does not imply this animation _should_ be removed.
286 * Determining that depends on the other effects in the same EffectSet to
287 * which this animation's effect, if any, contributes.
289 bool IsRemovable() const;
292 * Make this animation's target effect no-longer part of the effect stack
293 * while preserving its timing information.
298 * Returns true if this Animation has a lower composite order than aOther.
300 bool HasLowerCompositeOrderThan(const Animation
& aOther
) const;
303 * Returns the level at which the effect(s) associated with this Animation
304 * are applied to the CSS cascade.
306 virtual EffectCompositor::CascadeLevel
CascadeLevel() const {
307 return EffectCompositor::CascadeLevel::Animations
;
311 * Returns true if this animation does not currently need to update
312 * style on the main thread (e.g. because it is empty, or is
313 * running on the compositor).
315 bool CanThrottle() const;
318 * Updates various bits of state that we need to update as the result of
319 * running ComposeStyle().
320 * See the comment of KeyframeEffect::WillComposeStyle for more detail.
322 void WillComposeStyle();
325 * Updates |aComposeResult| with the animation values of this animation's
327 * Any properties contained in |aPropertiesToSkip| will not be added or
328 * updated in |aComposeResult|.
330 void ComposeStyle(StyleAnimationValueMap
& aComposeResult
,
331 const nsCSSPropertyIDSet
& aPropertiesToSkip
);
333 void NotifyEffectTimingUpdated();
334 void NotifyEffectPropertiesUpdated();
335 void NotifyEffectTargetUpdated();
338 * Used by subclasses to synchronously queue a cancel event in situations
339 * where the Animation may have been cancelled.
341 * We need to do this synchronously because after a CSS animation/transition
342 * is canceled, it will be released by its owning element and may not still
343 * exist when we would normally go to queue events on the next tick.
345 virtual void MaybeQueueCancelEvent(const StickyTimeDuration
& aActiveTime
){};
347 Maybe
<uint32_t>& CachedChildIndexRef() { return mCachedChildIndex
; }
349 void SetPartialPrerendered(uint64_t aIdOnCompositor
) {
350 mIdOnCompositor
= aIdOnCompositor
;
351 mIsPartialPrerendered
= true;
353 bool IsPartialPrerendered() const { return mIsPartialPrerendered
; }
354 uint64_t IdOnCompositor() const { return mIdOnCompositor
; }
356 * Needs to be called when the pre-rendered animation is going to no longer
357 * run on the compositor.
359 void ResetPartialPrerendered() {
360 MOZ_ASSERT(mIsPartialPrerendered
);
361 mIsPartialPrerendered
= false;
365 * Called via NotifyJankedAnimations IPC call from the compositor to update
366 * pre-rendered area on the main-thread.
368 void UpdatePartialPrerendered() {
369 ResetPartialPrerendered();
373 bool UsingScrollTimeline() const {
374 return mTimeline
&& mTimeline
->IsScrollTimeline();
378 * Returns true if this is at the progress timeline boundary.
379 * https://drafts.csswg.org/web-animations-2/#at-progress-timeline-boundary
381 enum class ProgressTimelinePosition
: uint8_t { Boundary
, NotBoundary
};
382 static ProgressTimelinePosition
AtProgressTimelineBoundary(
383 const Nullable
<TimeDuration
>& aTimelineDuration
,
384 const Nullable
<TimeDuration
>& aCurrentTime
,
385 const TimeDuration
& aEffectStartTime
, const double aPlaybackRate
);
386 ProgressTimelinePosition
AtProgressTimelineBoundary() const {
387 Nullable
<TimeDuration
> currentTime
= GetUnconstrainedCurrentTime();
388 return AtProgressTimelineBoundary(
389 mTimeline
? mTimeline
->TimelineDuration() : nullptr,
390 // Set unlimited current time based on the first matching condition:
391 // 1. start time is resolved:
392 // (timeline time - start time) × playback rate
394 // animation’s current time
395 !currentTime
.IsNull() ? currentTime
: GetCurrentTimeAsDuration(),
396 mStartTime
.IsNull() ? TimeDuration() : mStartTime
.Value(),
400 void SetHiddenByContentVisibility(bool hidden
);
401 bool IsHiddenByContentVisibility() const {
402 return mHiddenByContentVisibility
;
404 void UpdateHiddenByContentVisibility();
406 DocGroup
* GetDocGroup();
409 void SilentlySetCurrentTime(const TimeDuration
& aNewCurrentTime
);
410 void CancelNoUpdate();
411 void PlayNoUpdate(ErrorResult
& aRv
, LimitBehavior aLimitBehavior
);
412 void ResumeAt(const TimeDuration
& aReadyTime
);
413 void PauseAt(const TimeDuration
& aReadyTime
);
414 void FinishPendingAt(const TimeDuration
& aReadyTime
) {
415 if (mPendingState
== PendingState::PlayPending
) {
416 ResumeAt(aReadyTime
);
417 } else if (mPendingState
== PendingState::PausePending
) {
420 MOZ_ASSERT_UNREACHABLE(
421 "Can't finish pending if we're not in a pending state");
424 void ApplyPendingPlaybackRate() {
425 if (mPendingPlaybackRate
) {
426 mPlaybackRate
= mPendingPlaybackRate
.extract();
431 * Finishing behavior depends on if changes to timing occurred due
432 * to a seek or regular playback.
434 enum class SeekFlag
{ NoSeek
, DidSeek
};
436 enum class SyncNotifyFlag
{ Sync
, Async
};
438 virtual void UpdateTiming(SeekFlag aSeekFlag
, SyncNotifyFlag aSyncNotifyFlag
);
439 void UpdateFinishedState(SeekFlag aSeekFlag
, SyncNotifyFlag aSyncNotifyFlag
);
440 void UpdateEffect(PostRestyleMode aPostRestyle
);
442 * Flush all pending styles other than throttled animation styles (e.g.
443 * animations running on the compositor).
445 void FlushUnanimatedStyle() const;
447 void ResetFinishedPromise();
448 void MaybeResolveFinishedPromise();
449 void DoFinishNotification(SyncNotifyFlag aSyncNotifyFlag
);
450 friend class AsyncFinishNotification
;
451 void DoFinishNotificationImmediately(MicroTaskRunnable
* aAsync
= nullptr);
452 void QueuePlaybackEvent(const nsAString
& aName
,
453 TimeStamp
&& aScheduledEventTime
);
456 * Remove this animation from the pending animation tracker and reset
457 * mPendingState as necessary. The caller is responsible for resolving or
458 * aborting the mReady promise as necessary.
460 void CancelPendingTasks();
463 * Performs the same steps as CancelPendingTasks and also rejects and
464 * recreates the ready promise if the animation was pending.
466 void ResetPendingTasks();
467 StickyTimeDuration
EffectEnd() const;
469 Nullable
<TimeDuration
> GetCurrentTimeForHoldTime(
470 const Nullable
<TimeDuration
>& aHoldTime
) const;
471 Nullable
<TimeDuration
> GetUnconstrainedCurrentTime() const {
472 return GetCurrentTimeForHoldTime(Nullable
<TimeDuration
>());
475 void ScheduleReplacementCheck();
476 void MaybeScheduleReplacementCheck();
478 // Earlier side of the elapsed time range reported in CSS Animations and CSS
479 // Transitions events.
481 // https://drafts.csswg.org/css-animations-2/#interval-start
482 // https://drafts.csswg.org/css-transitions-2/#interval-start
483 StickyTimeDuration
IntervalStartTime(
484 const StickyTimeDuration
& aActiveDuration
) const;
486 // Later side of the elapsed time range reported in CSS Animations and CSS
487 // Transitions events.
489 // https://drafts.csswg.org/css-animations-2/#interval-end
490 // https://drafts.csswg.org/css-transitions-2/#interval-end
491 StickyTimeDuration
IntervalEndTime(
492 const StickyTimeDuration
& aActiveDuration
) const;
494 TimeStamp
GetTimelineCurrentTimeAsTimeStamp() const {
495 return mTimeline
? mTimeline
->GetCurrentTimeAsTimeStamp() : TimeStamp();
498 Document
* GetRenderedDocument() const;
499 Document
* GetTimelineDocument() const;
501 bool HasFiniteTimeline() const {
502 return mTimeline
&& !mTimeline
->IsMonotonicallyIncreasing();
505 void UpdateScrollTimelineAnimationTracker(AnimationTimeline
* aOldTimeline
,
506 AnimationTimeline
* aNewTimeline
);
508 RefPtr
<AnimationTimeline
> mTimeline
;
509 RefPtr
<AnimationEffect
> mEffect
;
510 // The beginning of the delay period.
511 Nullable
<TimeDuration
> mStartTime
; // Timeline timescale
512 Nullable
<TimeDuration
> mHoldTime
; // Animation timescale
513 Nullable
<TimeDuration
> mPreviousCurrentTime
; // Animation timescale
514 double mPlaybackRate
= 1.0;
515 Maybe
<double> mPendingPlaybackRate
;
517 // A Promise that is replaced on each call to Play()
518 // and fulfilled when Play() is successfully completed.
519 // This object is lazily created by GetReady.
520 // See http://drafts.csswg.org/web-animations/#current-ready-promise
521 RefPtr
<Promise
> mReady
;
523 // A Promise that is resolved when we reach the end of the effect, or
524 // 0 when playing backwards. The Promise is replaced if the animation is
525 // finished but then a state change makes it not finished.
526 // This object is lazily created by GetFinished.
527 // See http://drafts.csswg.org/web-animations/#current-finished-promise
528 RefPtr
<Promise
> mFinished
;
530 static uint64_t sNextAnimationIndex
;
532 // The relative position of this animation within the global animation list.
534 // Note that subclasses such as CSSTransition and CSSAnimation may repurpose
535 // this member to implement their own brand of sorting. As a result, it is
536 // possible for two different objects to have the same index.
537 uint64_t mAnimationIndex
;
539 // While ordering Animation objects for event dispatch, the index of the
540 // target node in its parent may be cached in mCachedChildIndex.
541 Maybe
<uint32_t> mCachedChildIndex
;
543 // Indicates if the animation is in the pending state (and what state it is
544 // waiting to enter when it finished pending).
545 enum class PendingState
: uint8_t { NotPending
, PlayPending
, PausePending
};
546 PendingState mPendingState
= PendingState::NotPending
;
548 // Handling of this animation's target effect when filling while finished.
549 AnimationReplaceState mReplaceState
= AnimationReplaceState::Active
;
551 bool mFinishedAtLastComposeStyle
= false;
552 bool mWasReplaceableAtLastTick
= false;
553 // When we create a new pending animation, this tracks whether we've seen at
554 // least one refresh driver tick. This is used to guarantee that a whole tick
555 // has run before triggering the animation, which guarantees (for most pages)
556 // that we've actually painted.
557 bool mSawTickWhilePending
= false;
559 bool mHiddenByContentVisibility
= false;
561 // Indicates that the animation should be exposed in an element's
562 // getAnimations() list.
563 bool mIsRelevant
= false;
565 // True if mFinished is resolved or would be resolved if mFinished has
566 // yet to be created. This is not set when mFinished is rejected since
567 // in that case mFinished is immediately reset to represent a new current
569 bool mFinishedIsResolved
= false;
571 RefPtr
<MicroTaskRunnable
> mFinishNotificationTask
;
575 bool mResetCurrentTimeOnResume
= false;
577 // Whether the Animation is System, ResistFingerprinting, or neither
578 RTPCallerType mRTPCallerType
;
580 // The time at which our animation should be ready.
581 TimeStamp mPendingReadyTime
;
584 // The id for this animation on the compositor.
585 uint64_t mIdOnCompositor
= 0;
586 bool mIsPartialPrerendered
= false;
590 } // namespace mozilla
592 #endif // mozilla_dom_Animation_h