layer_animator.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef UI_COMPOSITOR_LAYER_ANIMATOR_H_
  5. #define UI_COMPOSITOR_LAYER_ANIMATOR_H_
  6. #include <vector>
  7. #include "base/callback.h"
  8. #include "base/callback_list.h"
  9. #include "base/containers/circular_deque.h"
  10. #include "base/gtest_prod_util.h"
  11. #include "base/memory/raw_ptr.h"
  12. #include "base/memory/ref_counted.h"
  13. #include "base/memory/weak_ptr.h"
  14. #include "base/observer_list.h"
  15. #include "base/time/time.h"
  16. #include "cc/animation/animation_delegate.h"
  17. #include "cc/trees/target_property.h"
  18. #include "ui/compositor/compositor_export.h"
  19. #include "ui/compositor/layer_animation_element.h"
  20. #include "ui/compositor/layer_threaded_animation_delegate.h"
  21. #include "ui/gfx/animation/tween.h"
  22. #include "ui/gfx/geometry/linear_gradient.h"
  23. namespace cc {
  24. class Animation;
  25. class AnimationTimeline;
  26. class Layer;
  27. }
  28. namespace gfx {
  29. class Animation;
  30. class AnimationCurve;
  31. class Rect;
  32. class Transform;
  33. }
  34. namespace ui {
  35. class Compositor;
  36. class ImplicitAnimationObserver;
  37. class Layer;
  38. class LayerAnimationSequence;
  39. class LayerAnimationDelegate;
  40. class LayerAnimationObserver;
  41. class LayerAnimatorCollection;
  42. class ScopedLayerAnimationSettings;
  43. // When a property of layer needs to be changed it is set by way of
  44. // LayerAnimator. This enables LayerAnimator to animate property changes.
  45. // NB: during many tests, set_disable_animations_for_test is used and causes
  46. // all animations to complete immediately. The layer animation is ref counted
  47. // so that if its owning layer is deleted (and the owning layer is only other
  48. // class that should ever hold a ref ptr to a LayerAnimator), the animator can
  49. // ensure that it is not disposed of until it finishes executing. It does this
  50. // by holding a reference to itself for the duration of methods for which it
  51. // must guarantee that |this| is valid.
  52. class COMPOSITOR_EXPORT LayerAnimator : public base::RefCounted<LayerAnimator>,
  53. public LayerThreadedAnimationDelegate,
  54. public cc::AnimationDelegate {
  55. public:
  56. enum PreemptionStrategy {
  57. IMMEDIATELY_SET_NEW_TARGET,
  58. IMMEDIATELY_ANIMATE_TO_NEW_TARGET,
  59. ENQUEUE_NEW_ANIMATION,
  60. REPLACE_QUEUED_ANIMATIONS
  61. };
  62. using SequenceScheduledCallbacks =
  63. base::RepeatingCallbackList<void(LayerAnimationSequence*)>;
  64. using SequenceScheduledCallback = SequenceScheduledCallbacks::CallbackType;
  65. explicit LayerAnimator(base::TimeDelta transition_duration);
  66. LayerAnimator(const LayerAnimator&) = delete;
  67. LayerAnimator& operator=(const LayerAnimator&) = delete;
  68. // No implicit animations when properties are set.
  69. static LayerAnimator* CreateDefaultAnimator();
  70. // Implicitly animates when properties are set.
  71. static LayerAnimator* CreateImplicitAnimator();
  72. // Sets the transform on the delegate. May cause an implicit animation.
  73. virtual void SetTransform(const gfx::Transform& transform);
  74. gfx::Transform GetTargetTransform() const;
  75. // Sets the bounds on the delegate. May cause an implicit animation.
  76. virtual void SetBounds(const gfx::Rect& bounds);
  77. gfx::Rect GetTargetBounds() const;
  78. // Sets the opacity on the delegate. May cause an implicit animation.
  79. virtual void SetOpacity(float opacity);
  80. float GetTargetOpacity() const;
  81. // Sets the visibility of the delegate. May cause an implicit animation.
  82. virtual void SetVisibility(bool visibility);
  83. bool GetTargetVisibility() const;
  84. // Sets the brightness on the delegate. May cause an implicit animation.
  85. virtual void SetBrightness(float brightness);
  86. float GetTargetBrightness() const;
  87. // Sets the grayscale on the delegate. May cause an implicit animation.
  88. virtual void SetGrayscale(float grayscale);
  89. float GetTargetGrayscale() const;
  90. // Sets the color on the delegate. May cause an implicit animation.
  91. virtual void SetColor(SkColor color);
  92. SkColor GetTargetColor() const;
  93. // Sets the clip rect on the delegate. May cause an implicit animation.
  94. virtual void SetClipRect(const gfx::Rect& clip_rect);
  95. gfx::Rect GetTargetClipRect() const;
  96. // Sets the rounded corners on the delegate. May cause an implicit animation.
  97. virtual void SetRoundedCorners(const gfx::RoundedCornersF& rounded_corners);
  98. gfx::RoundedCornersF GetTargetRoundedCorners() const;
  99. // Sets the linear gradient mask on the delegate. Requires that the bounds are
  100. // set by SetRoundedCorners. May cause an implicit animation.
  101. virtual void SetGradientMask(const gfx::LinearGradient& linear_gradient);
  102. gfx::LinearGradient GetTargetGradientMask() const;
  103. // Returns the default length of animations, including adjustment for slow
  104. // animation mode if set.
  105. base::TimeDelta GetTransitionDuration() const;
  106. // Sets the layer animation delegate the animator is associated with. The
  107. // animator does not own the delegate. The layer animator expects a non-NULL
  108. // delegate for most of its operations, so do not call any methods without
  109. // a valid delegate installed.
  110. void SetDelegate(LayerAnimationDelegate* delegate);
  111. // Unsubscribe from |cc_layer_| and subscribe to |new_layer|.
  112. void SwitchToLayer(scoped_refptr<cc::Layer> new_layer);
  113. // Attach Animation to Layer and AnimationTimeline
  114. void AttachLayerAndTimeline(Compositor* compositor);
  115. // Detach Animation from Layer and AnimationTimeline
  116. void DetachLayerAndTimeline(Compositor* compositor);
  117. cc::Animation* GetAnimationForTesting() const;
  118. // Sets the animation preemption strategy. This determines the behaviour if
  119. // a property is set during an animation. The default is
  120. // IMMEDIATELY_SET_NEW_TARGET (see ImmediatelySetNewTarget below).
  121. void set_preemption_strategy(PreemptionStrategy strategy) {
  122. preemption_strategy_ = strategy;
  123. }
  124. PreemptionStrategy preemption_strategy() const {
  125. return preemption_strategy_;
  126. }
  127. // Start an animation sequence. If an animation for the same property is in
  128. // progress, it needs to be interrupted with the new animation. The animator
  129. // takes ownership of this animation sequence.
  130. void StartAnimation(LayerAnimationSequence* animation);
  131. // Schedule an animation to be run when possible. The animator takes ownership
  132. // of this animation sequence.
  133. void ScheduleAnimation(LayerAnimationSequence* animation);
  134. // Starts the animations to be run together, ensuring that the first elements
  135. // in these sequences have the same effective start time even when some of
  136. // them start on the compositor thread (but there is no such guarantee for
  137. // the effective start time of subsequent elements). Obviously will not work
  138. // if they animate any common properties. The animator takes ownership of the
  139. // animation sequences. Takes PreemptionStrategy into account.
  140. void StartTogether(const std::vector<LayerAnimationSequence*>& animations);
  141. // Schedules the animations to be run together, ensuring that the first
  142. // elements in these sequences have the same effective start time even when
  143. // some of them start on the compositor thread (but there is no such guarantee
  144. // for the effective start time of subsequent elements). Obviously will not
  145. // work if they animate any common properties. The animator takes ownership
  146. // of the animation sequences.
  147. void ScheduleTogether(const std::vector<LayerAnimationSequence*>& animations);
  148. // Schedules a pause for length |duration| of all the specified properties.
  149. // End the list with -1.
  150. void SchedulePauseForProperties(
  151. base::TimeDelta duration,
  152. LayerAnimationElement::AnimatableProperties properties_to_pause);
  153. // Returns true if there is an animation in the queue (animations remain in
  154. // the queue until they complete, so this includes running animations).
  155. bool is_animating() const { return !animation_queue_.empty(); }
  156. // Returns true if there is an animation in the queue that animates the given
  157. // property (animations remain in the queue until they complete, so this
  158. // includes running animations).
  159. bool IsAnimatingProperty(
  160. LayerAnimationElement::AnimatableProperty property) const {
  161. return IsAnimatingOnePropertyOf(property);
  162. }
  163. // Returns true if there is an animation in the queue that animates at least
  164. // one of the given property (animations remain in the queue until they
  165. // complete, so this includes running animations).
  166. bool IsAnimatingOnePropertyOf(
  167. LayerAnimationElement::AnimatableProperties properties) const;
  168. // Stops animating the given property. No effect if there is no running
  169. // animation for the given property. Skips to the final state of the
  170. // animation.
  171. void StopAnimatingProperty(
  172. LayerAnimationElement::AnimatableProperty property);
  173. // Stops all animation and clears any queued animations. This call progresses
  174. // animations to their end points and notifies all observers.
  175. void StopAnimating() { StopAnimatingInternal(false); }
  176. // This is similar to StopAnimating, but aborts rather than finishes the
  177. // animations and notifies all observers.
  178. void AbortAllAnimations() { StopAnimatingInternal(true); }
  179. // Adds/remove |observer| from the observer list. Observers are notified when
  180. // animations are scheduled, start, end or are aborted. They may also be
  181. // notified when they're attached/detached from a LayerAnimationSequence (see
  182. // LayerAnimationObserver).
  183. void AddObserver(LayerAnimationObserver* observer);
  184. void RemoveObserver(LayerAnimationObserver* observer);
  185. void AddOwnedObserver(
  186. std::unique_ptr<ImplicitAnimationObserver> animation_observer);
  187. void RemoveAndDestroyOwnedObserver(
  188. ImplicitAnimationObserver* animation_observer);
  189. // Adds callback to list which is invoked when a new sequence is scheduled.
  190. // Prefer using this callback to better managed LayerAnimationObservers.
  191. // Caller must retain the result for as long as the callback needs to remain
  192. // active. Clearing the result (add_sequence_subscription.reset()) will also
  193. // remove the subscription.
  194. [[nodiscard]] base::CallbackListSubscription AddSequenceScheduledCallback(
  195. SequenceScheduledCallback callback);
  196. // Called when a threaded animation is actually started.
  197. void OnThreadedAnimationStarted(base::TimeTicks monotonic_time,
  198. cc::TargetProperty::Type target_property,
  199. int group_id);
  200. // This determines how implicit animations will be tweened. This has no
  201. // effect on animations that are explicitly started or scheduled. The default
  202. // is Tween::LINEAR.
  203. void set_tween_type(gfx::Tween::Type tween_type) { tween_type_ = tween_type; }
  204. gfx::Tween::Type tween_type() const { return tween_type_; }
  205. // For testing purposes only.
  206. void set_disable_timer_for_test(bool disable_timer) {
  207. disable_timer_for_test_ = disable_timer;
  208. }
  209. void set_last_step_time(base::TimeTicks time) {
  210. last_step_time_ = time;
  211. }
  212. base::TimeTicks last_step_time() const { return last_step_time_; }
  213. void Step(base::TimeTicks time_now);
  214. void AddToCollection(LayerAnimatorCollection* collection);
  215. void RemoveFromCollection(LayerAnimatorCollection* collection);
  216. protected:
  217. ~LayerAnimator() override;
  218. LayerAnimationDelegate* delegate() { return delegate_; }
  219. const LayerAnimationDelegate* delegate() const { return delegate_; }
  220. // Virtual for testing.
  221. virtual void ProgressAnimation(LayerAnimationSequence* sequence,
  222. base::TimeTicks now);
  223. void ProgressAnimationToEnd(LayerAnimationSequence* sequence);
  224. // Returns true if the sequence is owned by this animator.
  225. bool HasAnimation(LayerAnimationSequence* sequence) const;
  226. private:
  227. friend class base::RefCounted<LayerAnimator>;
  228. friend class ScopedLayerAnimationSettings;
  229. friend class LayerAnimatorTestController;
  230. friend class AnimationThroughputReporter;
  231. FRIEND_TEST_ALL_PREFIXES(LayerAnimatorTest, AnimatorStartedCorrectly);
  232. FRIEND_TEST_ALL_PREFIXES(LayerAnimatorTest,
  233. AnimatorRemovedFromCollectionWhenLayerIsDestroyed);
  234. class RunningAnimation {
  235. public:
  236. RunningAnimation(const base::WeakPtr<LayerAnimationSequence>& sequence);
  237. RunningAnimation(const RunningAnimation& other);
  238. ~RunningAnimation();
  239. bool is_sequence_alive() const { return !!sequence_.get(); }
  240. LayerAnimationSequence* sequence() const { return sequence_.get(); }
  241. private:
  242. base::WeakPtr<LayerAnimationSequence> sequence_;
  243. // Copy and assign are allowed.
  244. };
  245. using RunningAnimations = std::vector<RunningAnimation>;
  246. using AnimationQueue =
  247. base::circular_deque<std::unique_ptr<LayerAnimationSequence>>;
  248. // Finishes all animations by either advancing them to their final state or by
  249. // aborting them.
  250. void StopAnimatingInternal(bool abort);
  251. // Starts or stops stepping depending on whether thare are running animations.
  252. void UpdateAnimationState();
  253. // Removes the sequences from both the running animations and the queue.
  254. // Returns a pointer to the removed animation, if any. NOTE: the caller is
  255. // responsible for deleting the returned pointer.
  256. [[nodiscard]] LayerAnimationSequence* RemoveAnimation(
  257. LayerAnimationSequence* sequence);
  258. // Progresses to the end of the sequence before removing it.
  259. void FinishAnimation(LayerAnimationSequence* sequence, bool abort);
  260. // Finishes any running animation with zero duration.
  261. void FinishAnyAnimationWithZeroDuration();
  262. // Clears the running animations and the queue. No sequences are progressed.
  263. void ClearAnimations();
  264. // Returns the running animation animating the given property, if any.
  265. RunningAnimation* GetRunningAnimation(
  266. LayerAnimationElement::AnimatableProperty property);
  267. // Checks if the sequence has already been added to the queue and adds it
  268. // to the front if note.
  269. void AddToQueueIfNotPresent(LayerAnimationSequence* sequence);
  270. // Any running or queued animation that affects a property in common with
  271. // |sequence| is either finished or aborted depending on |abort|.
  272. void RemoveAllAnimationsWithACommonProperty(LayerAnimationSequence* sequence,
  273. bool abort);
  274. // Preempts a running animation by progressing both the running animation and
  275. // the given sequence to the end.
  276. void ImmediatelySetNewTarget(LayerAnimationSequence* sequence);
  277. // Preempts by aborting the running animation, and starts the given animation.
  278. void ImmediatelyAnimateToNewTarget(LayerAnimationSequence* sequence);
  279. // Preempts by adding the new animation to the queue.
  280. void EnqueueNewAnimation(LayerAnimationSequence* sequence);
  281. // Preempts by wiping out any unstarted animation in the queue and then
  282. // enqueuing this animation.
  283. void ReplaceQueuedAnimations(LayerAnimationSequence* sequence);
  284. // If there's an animation in the queue that doesn't animate the same property
  285. // as a running animation, or an animation schedule to run before it, start it
  286. // up. Repeat until there are no such animations.
  287. void ProcessQueue();
  288. // Attempts to add the sequence to the list of running animations. Returns
  289. // false if there is an animation running that already animates one of the
  290. // properties affected by |sequence|.
  291. bool StartSequenceImmediately(LayerAnimationSequence* sequence);
  292. // Sets the value of target as if all the running and queued animations were
  293. // allowed to finish.
  294. void GetTargetValue(LayerAnimationElement::TargetValue* target) const;
  295. // Called whenever an animation is added to the animation queue. Either by
  296. // starting the animation or adding to the queue.
  297. void OnScheduled(LayerAnimationSequence* sequence);
  298. // Sets |transition_duration_| unless |is_transition_duration_locked_| is set.
  299. void SetTransitionDuration(base::TimeDelta duration);
  300. // Clears the animation queues and notifies any running animations that they
  301. // have been aborted.
  302. void ClearAnimationsInternal();
  303. // Cleans up any running animations that may have been deleted.
  304. void PurgeDeletedAnimations();
  305. LayerAnimatorCollection* GetLayerAnimatorCollection();
  306. // cc::AnimationDelegate implementation.
  307. void NotifyAnimationStarted(base::TimeTicks monotonic_time,
  308. int target_property,
  309. int group_id) override;
  310. void NotifyAnimationFinished(base::TimeTicks monotonic_time,
  311. int target_property,
  312. int group_id) override {}
  313. void NotifyAnimationAborted(base::TimeTicks monotonic_time,
  314. int target_property,
  315. int group_id) override {}
  316. void NotifyAnimationTakeover(
  317. base::TimeTicks monotonic_time,
  318. int target_property,
  319. base::TimeTicks animation_start_time,
  320. std::unique_ptr<gfx::AnimationCurve> curve) override {}
  321. void NotifyLocalTimeUpdated(
  322. absl::optional<base::TimeDelta> local_time) override {}
  323. // Implementation of LayerThreadedAnimationDelegate.
  324. void AddThreadedAnimation(
  325. std::unique_ptr<cc::KeyframeModel> keyframe_model) override;
  326. void RemoveThreadedAnimation(int keyframe_model_id) override;
  327. void AttachLayerToAnimation(int layer_id);
  328. void DetachLayerFromAnimation();
  329. // This is the queue of animations to run.
  330. AnimationQueue animation_queue_;
  331. // The target of all layer animations.
  332. raw_ptr<LayerAnimationDelegate> delegate_ = nullptr;
  333. // Plays CC animations.
  334. scoped_refptr<cc::Animation> animation_;
  335. // The currently running animations.
  336. RunningAnimations running_animations_;
  337. // Determines how animations are replaced.
  338. PreemptionStrategy preemption_strategy_ = IMMEDIATELY_SET_NEW_TARGET;
  339. // Whether the length of animations is locked. While it is locked
  340. // SetTransitionDuration does not set |transition_duration_|.
  341. bool is_transition_duration_locked_ = false;
  342. // The default length of animations.
  343. base::TimeDelta transition_duration_;
  344. // The default tween type for implicit transitions
  345. gfx::Tween::Type tween_type_ = gfx::Tween::LINEAR;
  346. // Used for coordinating the starting of animations.
  347. base::TimeTicks last_step_time_;
  348. // True if we are being stepped by our container.
  349. bool is_started_ = false;
  350. // This prevents the animator from automatically stepping through animations
  351. // and allows for manual stepping.
  352. bool disable_timer_for_test_ = false;
  353. // Prevents timer adjustments in case when we start multiple animations
  354. // with preemption strategies that discard previous animations.
  355. bool adding_animations_ = false;
  356. // Observers are notified when layer animations end, are scheduled or are
  357. // aborted.
  358. // TODO(crbug.com/1248132): Once all references to Add/RemoveObserver
  359. // functions are removed, delete these, the associated methods other internal
  360. // related code.
  361. base::ObserverList<LayerAnimationObserver>::Unchecked observers_;
  362. std::vector<std::unique_ptr<ImplicitAnimationObserver>> owned_observer_list_;
  363. SequenceScheduledCallbacks sequence_scheduled_callbacks_;
  364. base::WeakPtrFactory<LayerAnimator> weak_ptr_factory_{this};
  365. };
  366. } // namespace ui
  367. #endif // UI_COMPOSITOR_LAYER_ANIMATOR_H_