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