Backed out 8 changesets (bug 1873776) for causing vendor failures. CLOSED TREE
[gecko.git] / dom / animation / Animation.h
blob56c0f86d5087fe7e8b49e815884c89eaec123256
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"
25 struct JSContext;
26 class nsCSSPropertyIDSet;
27 class nsIFrame;
28 class nsIGlobalObject;
30 namespace mozilla {
32 struct AnimationRule;
33 class MicroTaskRunnable;
35 namespace dom {
37 class AnimationEffect;
38 class AsyncFinishNotification;
39 class CSSAnimation;
40 class CSSTransition;
41 class Document;
42 class Promise;
44 class Animation : public DOMEventTargetHelper,
45 public LinkedListElement<Animation> {
46 protected:
47 virtual ~Animation();
49 public:
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(); }
65 /**
66 * Utility function to get the target (pseudo-)element associated with an
67 * animation.
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; }
79 /**
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 virtual void SetStartTimeAsDouble(const Nullable<double>& aStartTime);
119 // This is deliberately _not_ called GetCurrentTime since that would clash
120 // with a macro defined in winbase.h
121 Nullable<TimeDuration> GetCurrentTimeAsDuration() const {
122 return GetCurrentTimeForHoldTime(mHoldTime);
124 Nullable<double> GetCurrentTimeAsDouble() const;
125 void SetCurrentTime(const TimeDuration& aSeekTime);
126 void SetCurrentTimeNoUpdate(const TimeDuration& aSeekTime);
127 void SetCurrentTimeAsDouble(const Nullable<double>& aCurrentTime,
128 ErrorResult& aRv);
130 double PlaybackRate() const { return mPlaybackRate; }
131 void SetPlaybackRate(double aPlaybackRate);
133 AnimationPlayState PlayState() const;
134 virtual AnimationPlayState PlayStateFromJS() const { return PlayState(); }
136 bool Pending() const { return mPendingState != PendingState::NotPending; }
137 virtual bool PendingFromJS() const { return Pending(); }
138 AnimationReplaceState ReplaceState() const { return mReplaceState; }
140 virtual Promise* GetReady(ErrorResult& aRv);
141 Promise* GetFinished(ErrorResult& aRv);
143 IMPL_EVENT_HANDLER(finish);
144 IMPL_EVENT_HANDLER(cancel);
145 IMPL_EVENT_HANDLER(remove);
147 void Cancel(PostRestyleMode aPostRestyle = PostRestyleMode::IfNeeded);
149 void Finish(ErrorResult& aRv);
151 void Play(ErrorResult& aRv, LimitBehavior aLimitBehavior);
152 virtual void PlayFromJS(ErrorResult& aRv) {
153 Play(aRv, LimitBehavior::AutoRewind);
156 void Pause(ErrorResult& aRv);
157 virtual void PauseFromJS(ErrorResult& aRv) { Pause(aRv); }
159 void UpdatePlaybackRate(double aPlaybackRate);
160 virtual void Reverse(ErrorResult& aRv);
162 void Persist();
163 MOZ_CAN_RUN_SCRIPT void CommitStyles(ErrorResult& aRv);
165 bool IsRunningOnCompositor() const;
167 using TickState = AnimationTimeline::TickState;
168 virtual void Tick(TickState&);
169 bool NeedsTicks() const {
170 return Pending() ||
171 (PlayState() == AnimationPlayState::Running &&
172 // An animation with a zero playback rate doesn't need ticks even if
173 // it is running since it effectively behaves as if it is paused.
175 // It's important we return false in this case since a zero playback
176 // rate animation in the before or after phase that doesn't fill
177 // won't be relevant and hence won't be returned by GetAnimations().
178 // We don't want its timeline to keep it alive (which would happen
179 // if we return true) since otherwise it will effectively be leaked.
180 PlaybackRate() != 0.0) ||
181 // Always return true for not idle animations attached to not
182 // monotonically increasing timelines even if the animation is
183 // finished. This is required to accommodate cases where timeline
184 // ticks back in time.
185 (mTimeline && !mTimeline->IsMonotonicallyIncreasing() &&
186 PlayState() != AnimationPlayState::Idle);
189 * For the monotonically increasing timeline, we use this only for testing:
190 * Start or pause a pending animation using the current timeline time. This
191 * is used to support existing tests that expect animations to begin
192 * immediately. Ideally we would rewrite the those tests and get rid of this
193 * method, but there are a lot of them.
195 bool TryTriggerNow();
197 * As with the start time, we should use the pending playback rate when
198 * producing layer animations.
200 double CurrentOrPendingPlaybackRate() const {
201 return mPendingPlaybackRate.valueOr(mPlaybackRate);
203 bool HasPendingPlaybackRate() const { return mPendingPlaybackRate.isSome(); }
206 * The following relationship from the definition of the 'current time' is
207 * re-used in many algorithms so we extract it here into a static method that
208 * can be re-used:
210 * current time = (timeline time - start time) * playback rate
212 * As per https://drafts.csswg.org/web-animations-1/#current-time
214 static TimeDuration CurrentTimeFromTimelineTime(
215 const TimeDuration& aTimelineTime, const TimeDuration& aStartTime,
216 float aPlaybackRate) {
217 return (aTimelineTime - aStartTime).MultDouble(aPlaybackRate);
221 * As with calculating the current time, we often need to calculate a start
222 * time from a current time. The following method simply inverts the current
223 * time relationship.
225 * In each case where this is used, the desired behavior for playbackRate ==
226 * 0 is to return the specified timeline time (often referred to as the ready
227 * time).
229 static TimeDuration StartTimeFromTimelineTime(
230 const TimeDuration& aTimelineTime, const TimeDuration& aCurrentTime,
231 float aPlaybackRate) {
232 TimeDuration result = aTimelineTime;
233 if (aPlaybackRate == 0) {
234 return result;
237 result -= aCurrentTime.MultDouble(1.0 / aPlaybackRate);
238 return result;
242 * Converts a time in the timescale of this Animation's currentTime, to a
243 * TimeStamp. Returns a null TimeStamp if the conversion cannot be performed
244 * because of the current state of this Animation (e.g. it has no timeline, a
245 * zero playbackRate, an unresolved start time etc.) or the value of the time
246 * passed-in (e.g. an infinite time).
248 TimeStamp AnimationTimeToTimeStamp(const StickyTimeDuration& aTime) const;
250 // Converts an AnimationEvent's elapsedTime value to an equivalent TimeStamp
251 // that can be used to sort events by when they occurred.
252 TimeStamp ElapsedTimeToTimeStamp(
253 const StickyTimeDuration& aElapsedTime) const;
255 bool IsPausedOrPausing() const {
256 return PlayState() == AnimationPlayState::Paused;
259 bool HasCurrentEffect() const;
260 bool IsInEffect() const;
262 bool IsPlaying() const {
263 return mPlaybackRate != 0.0 && mTimeline &&
264 !mTimeline->GetCurrentTimeAsDuration().IsNull() &&
265 PlayState() == AnimationPlayState::Running;
268 bool ShouldBeSynchronizedWithMainThread(
269 const nsCSSPropertyIDSet& aPropertySet, const nsIFrame* aFrame,
270 AnimationPerformanceWarning::Type& aPerformanceWarning /* out */) const;
272 bool IsRelevant() const { return mIsRelevant; }
273 void UpdateRelevance();
275 // https://drafts.csswg.org/web-animations-1/#replaceable-animation
276 bool IsReplaceable() const;
279 * Returns true if this Animation satisfies the requirements for being
280 * removed when it is replaced.
282 * Returning true does not imply this animation _should_ be removed.
283 * Determining that depends on the other effects in the same EffectSet to
284 * which this animation's effect, if any, contributes.
286 bool IsRemovable() const;
289 * Make this animation's target effect no-longer part of the effect stack
290 * while preserving its timing information.
292 void Remove();
295 * Returns true if this Animation has a lower composite order than aOther.
297 bool HasLowerCompositeOrderThan(const Animation& aOther) const;
300 * Returns the level at which the effect(s) associated with this Animation
301 * are applied to the CSS cascade.
303 virtual EffectCompositor::CascadeLevel CascadeLevel() const {
304 return EffectCompositor::CascadeLevel::Animations;
308 * Returns true if this animation does not currently need to update
309 * style on the main thread (e.g. because it is empty, or is
310 * running on the compositor).
312 bool CanThrottle() const;
315 * Updates various bits of state that we need to update as the result of
316 * running ComposeStyle().
317 * See the comment of KeyframeEffect::WillComposeStyle for more detail.
319 void WillComposeStyle();
322 * Updates |aComposeResult| with the animation values of this animation's
323 * effect, if any.
324 * Any properties contained in |aPropertiesToSkip| will not be added or
325 * updated in |aComposeResult|.
327 void ComposeStyle(StyleAnimationValueMap& aComposeResult,
328 const nsCSSPropertyIDSet& aPropertiesToSkip);
330 void NotifyEffectTimingUpdated();
331 void NotifyEffectPropertiesUpdated();
332 void NotifyEffectTargetUpdated();
333 void NotifyGeometricAnimationsStartingThisFrame();
336 * Used by subclasses to synchronously queue a cancel event in situations
337 * where the Animation may have been cancelled.
339 * We need to do this synchronously because after a CSS animation/transition
340 * is canceled, it will be released by its owning element and may not still
341 * exist when we would normally go to queue events on the next tick.
343 virtual void MaybeQueueCancelEvent(const StickyTimeDuration& aActiveTime){};
345 Maybe<uint32_t>& CachedChildIndexRef() { return mCachedChildIndex; }
347 void SetPartialPrerendered(uint64_t aIdOnCompositor) {
348 mIdOnCompositor = aIdOnCompositor;
349 mIsPartialPrerendered = true;
351 bool IsPartialPrerendered() const { return mIsPartialPrerendered; }
352 uint64_t IdOnCompositor() const { return mIdOnCompositor; }
354 * Needs to be called when the pre-rendered animation is going to no longer
355 * run on the compositor.
357 void ResetPartialPrerendered() {
358 MOZ_ASSERT(mIsPartialPrerendered);
359 mIsPartialPrerendered = false;
360 mIdOnCompositor = 0;
363 * Called via NotifyJankedAnimations IPC call from the compositor to update
364 * pre-rendered area on the main-thread.
366 void UpdatePartialPrerendered() {
367 ResetPartialPrerendered();
368 PostUpdate();
371 bool UsingScrollTimeline() const {
372 return mTimeline && mTimeline->IsScrollTimeline();
376 * Returns true if this is at the progress timeline boundary.
377 * https://drafts.csswg.org/web-animations-2/#at-progress-timeline-boundary
379 enum class ProgressTimelinePosition : uint8_t { Boundary, NotBoundary };
380 static ProgressTimelinePosition AtProgressTimelineBoundary(
381 const Nullable<TimeDuration>& aTimelineDuration,
382 const Nullable<TimeDuration>& aCurrentTime,
383 const TimeDuration& aEffectStartTime, const double aPlaybackRate);
384 ProgressTimelinePosition AtProgressTimelineBoundary() const {
385 Nullable<TimeDuration> currentTime = GetUnconstrainedCurrentTime();
386 return AtProgressTimelineBoundary(
387 mTimeline ? mTimeline->TimelineDuration() : nullptr,
388 // Set unlimited current time based on the first matching condition:
389 // 1. start time is resolved:
390 // (timeline time - start time) × playback rate
391 // 2. Otherwise:
392 // animation’s current time
393 !currentTime.IsNull() ? currentTime : GetCurrentTimeAsDuration(),
394 mStartTime.IsNull() ? TimeDuration() : mStartTime.Value(),
395 mPlaybackRate);
398 void SetHiddenByContentVisibility(bool hidden);
399 bool IsHiddenByContentVisibility() const {
400 return mHiddenByContentVisibility;
402 void UpdateHiddenByContentVisibility();
404 DocGroup* GetDocGroup();
405 void SetSyncWithGeometricAnimations() { mSyncWithGeometricAnimations = true; }
407 protected:
408 void SilentlySetCurrentTime(const TimeDuration& aNewCurrentTime);
409 void CancelNoUpdate();
410 void PlayNoUpdate(ErrorResult& aRv, LimitBehavior aLimitBehavior);
411 void ResumeAt(const TimeDuration& aReadyTime);
412 void PauseAt(const TimeDuration& aReadyTime);
413 void FinishPendingAt(const TimeDuration& aReadyTime) {
414 if (mPendingState == PendingState::PlayPending) {
415 ResumeAt(aReadyTime);
416 } else if (mPendingState == PendingState::PausePending) {
417 PauseAt(aReadyTime);
418 } else {
419 MOZ_ASSERT_UNREACHABLE(
420 "Can't finish pending if we're not in a pending state");
423 void ApplyPendingPlaybackRate() {
424 if (mPendingPlaybackRate) {
425 mPlaybackRate = mPendingPlaybackRate.extract();
430 * Finishing behavior depends on if changes to timing occurred due
431 * to a seek or regular playback.
433 enum class SeekFlag { NoSeek, DidSeek };
435 enum class SyncNotifyFlag { Sync, Async };
437 virtual void UpdateTiming(SeekFlag aSeekFlag, SyncNotifyFlag aSyncNotifyFlag);
438 void UpdateFinishedState(SeekFlag aSeekFlag, SyncNotifyFlag aSyncNotifyFlag);
439 void UpdateEffect(PostRestyleMode aPostRestyle);
441 * Flush all pending styles other than throttled animation styles (e.g.
442 * animations running on the compositor).
444 void FlushUnanimatedStyle() const;
445 void PostUpdate();
446 void ResetFinishedPromise();
447 void MaybeResolveFinishedPromise();
448 void DoFinishNotification(SyncNotifyFlag aSyncNotifyFlag);
449 friend class AsyncFinishNotification;
450 void DoFinishNotificationImmediately(MicroTaskRunnable* aAsync = nullptr);
451 void QueuePlaybackEvent(const nsAString& aName,
452 TimeStamp&& aScheduledEventTime);
455 * Remove this animation from the pending animation tracker and reset
456 * mPendingState as necessary. The caller is responsible for resolving or
457 * aborting the mReady promise as necessary.
459 void CancelPendingTasks();
462 * Performs the same steps as CancelPendingTasks and also rejects and
463 * recreates the ready promise if the animation was pending.
465 void ResetPendingTasks();
466 StickyTimeDuration EffectEnd() const;
468 Nullable<TimeDuration> GetCurrentTimeForHoldTime(
469 const Nullable<TimeDuration>& aHoldTime) const;
470 Nullable<TimeDuration> GetUnconstrainedCurrentTime() const {
471 return GetCurrentTimeForHoldTime(Nullable<TimeDuration>());
474 void ScheduleReplacementCheck();
475 void MaybeScheduleReplacementCheck();
477 // Earlier side of the elapsed time range reported in CSS Animations and CSS
478 // Transitions events.
480 // https://drafts.csswg.org/css-animations-2/#interval-start
481 // https://drafts.csswg.org/css-transitions-2/#interval-start
482 StickyTimeDuration IntervalStartTime(
483 const StickyTimeDuration& aActiveDuration) const;
485 // Later side of the elapsed time range reported in CSS Animations and CSS
486 // Transitions events.
488 // https://drafts.csswg.org/css-animations-2/#interval-end
489 // https://drafts.csswg.org/css-transitions-2/#interval-end
490 StickyTimeDuration IntervalEndTime(
491 const StickyTimeDuration& aActiveDuration) const;
493 TimeStamp GetTimelineCurrentTimeAsTimeStamp() const {
494 return mTimeline ? mTimeline->GetCurrentTimeAsTimeStamp() : TimeStamp();
497 Document* GetRenderedDocument() const;
498 Document* GetTimelineDocument() const;
500 bool HasFiniteTimeline() const {
501 return mTimeline && !mTimeline->IsMonotonicallyIncreasing();
504 void UpdateScrollTimelineAnimationTracker(AnimationTimeline* aOldTimeline,
505 AnimationTimeline* aNewTimeline);
507 RefPtr<AnimationTimeline> mTimeline;
508 RefPtr<AnimationEffect> mEffect;
509 // The beginning of the delay period.
510 Nullable<TimeDuration> mStartTime; // Timeline timescale
511 Nullable<TimeDuration> mHoldTime; // Animation timescale
512 Nullable<TimeDuration> mPreviousCurrentTime; // Animation timescale
513 double mPlaybackRate = 1.0;
514 Maybe<double> mPendingPlaybackRate;
516 // A Promise that is replaced on each call to Play()
517 // and fulfilled when Play() is successfully completed.
518 // This object is lazily created by GetReady.
519 // See http://drafts.csswg.org/web-animations/#current-ready-promise
520 RefPtr<Promise> mReady;
522 // A Promise that is resolved when we reach the end of the effect, or
523 // 0 when playing backwards. The Promise is replaced if the animation is
524 // finished but then a state change makes it not finished.
525 // This object is lazily created by GetFinished.
526 // See http://drafts.csswg.org/web-animations/#current-finished-promise
527 RefPtr<Promise> mFinished;
529 static uint64_t sNextAnimationIndex;
531 // The relative position of this animation within the global animation list.
533 // Note that subclasses such as CSSTransition and CSSAnimation may repurpose
534 // this member to implement their own brand of sorting. As a result, it is
535 // possible for two different objects to have the same index.
536 uint64_t mAnimationIndex;
538 // While ordering Animation objects for event dispatch, the index of the
539 // target node in its parent may be cached in mCachedChildIndex.
540 Maybe<uint32_t> mCachedChildIndex;
542 // Indicates if the animation is in the pending state (and what state it is
543 // waiting to enter when it finished pending).
544 enum class PendingState : uint8_t { NotPending, PlayPending, PausePending };
545 PendingState mPendingState = PendingState::NotPending;
547 // Handling of this animation's target effect when filling while finished.
548 AnimationReplaceState mReplaceState = AnimationReplaceState::Active;
550 bool mFinishedAtLastComposeStyle = false;
551 bool mWasReplaceableAtLastTick = false;
552 // When we create a new pending animation, this tracks whether we've seen at
553 // least one refresh driver tick. This is used to guarantee that a whole tick
554 // has run before triggering the animation, which guarantees (for most pages)
555 // that we've actually painted.
556 bool mSawTickWhilePending = false;
558 bool mHiddenByContentVisibility = false;
560 // Indicates that the animation should be exposed in an element's
561 // getAnimations() list.
562 bool mIsRelevant = false;
564 // True if mFinished is resolved or would be resolved if mFinished has
565 // yet to be created. This is not set when mFinished is rejected since
566 // in that case mFinished is immediately reset to represent a new current
567 // finished promise.
568 bool mFinishedIsResolved = false;
570 // True if this animation was triggered at the same time as one or more
571 // geometric animations and hence we should run any transform animations on
572 // the main thread.
573 bool mSyncWithGeometricAnimations = false;
575 RefPtr<MicroTaskRunnable> mFinishNotificationTask;
577 nsString mId;
579 bool mResetCurrentTimeOnResume = false;
581 // Whether the Animation is System, ResistFingerprinting, or neither
582 RTPCallerType mRTPCallerType;
584 private:
585 // The id for this animation on the compositor.
586 uint64_t mIdOnCompositor = 0;
587 bool mIsPartialPrerendered = false;
590 } // namespace dom
591 } // namespace mozilla
593 #endif // mozilla_dom_Animation_h