layer_animator.cc 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  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. #include "ui/compositor/layer_animator.h"
  5. #include <stddef.h>
  6. #include <memory>
  7. #include "base/check_op.h"
  8. #include "base/containers/cxx20_erase.h"
  9. #include "base/observer_list.h"
  10. #include "base/trace_event/trace_event.h"
  11. #include "cc/animation/animation.h"
  12. #include "cc/animation/animation_host.h"
  13. #include "cc/animation/animation_id_provider.h"
  14. #include "cc/animation/animation_timeline.h"
  15. #include "cc/animation/element_animations.h"
  16. #include "components/viz/common/frame_sinks/begin_frame_args.h"
  17. #include "ui/compositor/compositor.h"
  18. #include "ui/compositor/layer.h"
  19. #include "ui/compositor/layer_animation_delegate.h"
  20. #include "ui/compositor/layer_animation_observer.h"
  21. #include "ui/compositor/layer_animation_sequence.h"
  22. #include "ui/compositor/layer_animator_collection.h"
  23. #define SAFE_INVOKE_VOID(function, running_anim, ...) \
  24. if (running_anim.is_sequence_alive()) \
  25. function(running_anim.sequence(), ##__VA_ARGS__)
  26. #define SAFE_INVOKE_BOOL(function, running_anim) \
  27. ((running_anim.is_sequence_alive()) \
  28. ? function(running_anim.sequence()) \
  29. : false)
  30. #define SAFE_INVOKE_PTR(function, running_anim) \
  31. ((running_anim.is_sequence_alive()) ? function(running_anim.sequence()) \
  32. : nullptr)
  33. namespace ui {
  34. namespace {
  35. const int kLayerAnimatorDefaultTransitionDurationMs = 120;
  36. } // namespace
  37. // LayerAnimator public --------------------------------------------------------
  38. LayerAnimator::LayerAnimator(base::TimeDelta transition_duration)
  39. : transition_duration_(transition_duration) {
  40. animation_ =
  41. cc::Animation::Create(cc::AnimationIdProvider::NextAnimationId());
  42. }
  43. LayerAnimator::~LayerAnimator() {
  44. for (size_t i = 0; i < running_animations_.size(); ++i) {
  45. if (running_animations_[i].is_sequence_alive())
  46. running_animations_[i].sequence()->OnAnimatorDestroyed();
  47. }
  48. ClearAnimationsInternal();
  49. delegate_ = nullptr;
  50. DCHECK(!animation_->animation_timeline());
  51. }
  52. // static
  53. LayerAnimator* LayerAnimator::CreateDefaultAnimator() {
  54. return new LayerAnimator(base::Milliseconds(0));
  55. }
  56. // static
  57. LayerAnimator* LayerAnimator::CreateImplicitAnimator() {
  58. return new LayerAnimator(
  59. base::Milliseconds(kLayerAnimatorDefaultTransitionDurationMs));
  60. }
  61. // This macro provides the implementation for the setter and getter (well,
  62. // the getter of the target value) for an animated property. For example,
  63. // it is used for the implementations of SetTransform and GetTargetTransform.
  64. // It is worth noting that SetFoo avoids invoking the usual animation machinery
  65. // if the transition duration is zero -- in this case we just set the property
  66. // on the layer animation delegate immediately.
  67. #define ANIMATED_PROPERTY(type, property, name, member_type, member) \
  68. void LayerAnimator::Set##name(type value) { \
  69. base::TimeDelta duration = GetTransitionDuration(); \
  70. if (duration.is_zero() && delegate() && \
  71. (preemption_strategy_ != ENQUEUE_NEW_ANIMATION)) { \
  72. /* Stopping an animation may result in destruction of `this`. */ \
  73. const auto weak_ptr = weak_ptr_factory_.GetWeakPtr(); \
  74. StopAnimatingProperty(LayerAnimationElement::property); \
  75. if (!weak_ptr || !delegate()) \
  76. return; \
  77. delegate()->Set##name##FromAnimation( \
  78. value, PropertyChangeReason::NOT_FROM_ANIMATION); \
  79. return; \
  80. } \
  81. std::unique_ptr<LayerAnimationElement> element = \
  82. LayerAnimationElement::Create##name##Element(value, duration); \
  83. element->set_tween_type(tween_type_); \
  84. StartAnimation(new LayerAnimationSequence(std::move(element))); \
  85. } \
  86. \
  87. member_type LayerAnimator::GetTarget##name() const { \
  88. LayerAnimationElement::TargetValue target(delegate()); \
  89. GetTargetValue(&target); \
  90. return target.member; \
  91. }
  92. ANIMATED_PROPERTY(const gfx::Transform&,
  93. TRANSFORM,
  94. Transform,
  95. gfx::Transform,
  96. transform)
  97. ANIMATED_PROPERTY(const gfx::Rect&, BOUNDS, Bounds, gfx::Rect, bounds)
  98. ANIMATED_PROPERTY(float, OPACITY, Opacity, float, opacity)
  99. ANIMATED_PROPERTY(bool, VISIBILITY, Visibility, bool, visibility)
  100. ANIMATED_PROPERTY(float, BRIGHTNESS, Brightness, float, brightness)
  101. ANIMATED_PROPERTY(float, GRAYSCALE, Grayscale, float, grayscale)
  102. ANIMATED_PROPERTY(SkColor, COLOR, Color, SkColor, color)
  103. ANIMATED_PROPERTY(const gfx::Rect&, CLIP, ClipRect, gfx::Rect, clip_rect)
  104. ANIMATED_PROPERTY(const gfx::RoundedCornersF&,
  105. ROUNDED_CORNERS,
  106. RoundedCorners,
  107. gfx::RoundedCornersF,
  108. rounded_corners)
  109. ANIMATED_PROPERTY(const gfx::LinearGradient&,
  110. GRADIENT_MASK,
  111. GradientMask,
  112. gfx::LinearGradient,
  113. gradient_mask)
  114. #undef ANIMATED_PROPERTY
  115. base::TimeDelta LayerAnimator::GetTransitionDuration() const {
  116. return transition_duration_;
  117. }
  118. void LayerAnimator::SetDelegate(LayerAnimationDelegate* delegate) {
  119. if (delegate_ && is_started_) {
  120. LayerAnimatorCollection* collection = GetLayerAnimatorCollection();
  121. if (collection)
  122. collection->StopAnimator(this);
  123. }
  124. SwitchToLayer(delegate ? delegate->GetCcLayer() : nullptr);
  125. delegate_ = delegate;
  126. if (delegate_ && is_started_) {
  127. LayerAnimatorCollection* collection = GetLayerAnimatorCollection();
  128. if (collection)
  129. collection->StartAnimator(this);
  130. }
  131. }
  132. void LayerAnimator::SwitchToLayer(scoped_refptr<cc::Layer> new_layer) {
  133. if (delegate_)
  134. DetachLayerFromAnimation();
  135. if (new_layer)
  136. AttachLayerToAnimation(new_layer->id());
  137. }
  138. void LayerAnimator::AttachLayerAndTimeline(Compositor* compositor) {
  139. DCHECK(compositor);
  140. cc::AnimationTimeline* timeline = compositor->GetAnimationTimeline();
  141. DCHECK(timeline);
  142. timeline->AttachAnimation(animation_);
  143. DCHECK(delegate_->GetCcLayer());
  144. AttachLayerToAnimation(delegate_->GetCcLayer()->id());
  145. for (auto& layer_animation_sequence : animation_queue_)
  146. layer_animation_sequence->OnAnimatorAttached(delegate());
  147. }
  148. void LayerAnimator::DetachLayerAndTimeline(Compositor* compositor) {
  149. DCHECK(compositor);
  150. cc::AnimationTimeline* timeline = compositor->GetAnimationTimeline();
  151. DCHECK(timeline);
  152. DetachLayerFromAnimation();
  153. timeline->DetachAnimation(animation_);
  154. for (auto& layer_animation_sequence : animation_queue_)
  155. layer_animation_sequence->OnAnimatorDetached();
  156. }
  157. void LayerAnimator::AttachLayerToAnimation(int layer_id) {
  158. // For ui, layer and element ids are equivalent.
  159. cc::ElementId element_id(layer_id);
  160. if (!animation_->element_id())
  161. animation_->AttachElement(element_id);
  162. else
  163. DCHECK_EQ(animation_->element_id(), element_id);
  164. animation_->set_animation_delegate(this);
  165. }
  166. void LayerAnimator::DetachLayerFromAnimation() {
  167. animation_->set_animation_delegate(nullptr);
  168. if (animation_->element_id())
  169. animation_->DetachElement();
  170. }
  171. void LayerAnimator::AddThreadedAnimation(
  172. std::unique_ptr<cc::KeyframeModel> animation) {
  173. animation_->AddKeyframeModel(std::move(animation));
  174. }
  175. void LayerAnimator::RemoveThreadedAnimation(int keyframe_model_id) {
  176. animation_->RemoveKeyframeModel(keyframe_model_id);
  177. }
  178. cc::Animation* LayerAnimator::GetAnimationForTesting() const {
  179. return animation_.get();
  180. }
  181. void LayerAnimator::StartAnimation(LayerAnimationSequence* animation) {
  182. scoped_refptr<LayerAnimator> retain(this);
  183. OnScheduled(animation);
  184. if (!StartSequenceImmediately(animation)) {
  185. // Attempt to preempt a running animation.
  186. switch (preemption_strategy_) {
  187. case IMMEDIATELY_SET_NEW_TARGET:
  188. ImmediatelySetNewTarget(animation);
  189. break;
  190. case IMMEDIATELY_ANIMATE_TO_NEW_TARGET:
  191. ImmediatelyAnimateToNewTarget(animation);
  192. break;
  193. case ENQUEUE_NEW_ANIMATION:
  194. EnqueueNewAnimation(animation);
  195. break;
  196. case REPLACE_QUEUED_ANIMATIONS:
  197. ReplaceQueuedAnimations(animation);
  198. break;
  199. }
  200. }
  201. FinishAnyAnimationWithZeroDuration();
  202. UpdateAnimationState();
  203. }
  204. void LayerAnimator::ScheduleAnimation(LayerAnimationSequence* animation) {
  205. scoped_refptr<LayerAnimator> retain(this);
  206. OnScheduled(animation);
  207. if (is_animating()) {
  208. animation_queue_.push_back(
  209. std::unique_ptr<LayerAnimationSequence>(animation));
  210. ProcessQueue();
  211. } else {
  212. StartSequenceImmediately(animation);
  213. }
  214. UpdateAnimationState();
  215. }
  216. void LayerAnimator::StartTogether(
  217. const std::vector<LayerAnimationSequence*>& animations) {
  218. scoped_refptr<LayerAnimator> retain(this);
  219. if (preemption_strategy_ == IMMEDIATELY_SET_NEW_TARGET) {
  220. std::vector<LayerAnimationSequence*>::const_iterator iter;
  221. for (iter = animations.begin(); iter != animations.end(); ++iter) {
  222. StartAnimation(*iter);
  223. }
  224. return;
  225. }
  226. adding_animations_ = true;
  227. if (!is_animating()) {
  228. LayerAnimatorCollection* collection = GetLayerAnimatorCollection();
  229. if (collection && collection->HasActiveAnimators())
  230. last_step_time_ = collection->last_tick_time();
  231. else
  232. last_step_time_ = base::TimeTicks::Now();
  233. }
  234. // Collect all the affected properties.
  235. LayerAnimationElement::AnimatableProperties animated_properties =
  236. LayerAnimationElement::UNKNOWN;
  237. std::vector<LayerAnimationSequence*>::const_iterator iter;
  238. for (iter = animations.begin(); iter != animations.end(); ++iter)
  239. animated_properties |= (*iter)->properties();
  240. // Starting a zero duration pause that affects all the animated properties
  241. // will prevent any of the sequences from animating until there are no
  242. // running animations that affect any of these properties, as well as
  243. // handle preemption strategy.
  244. StartAnimation(new LayerAnimationSequence(
  245. LayerAnimationElement::CreatePauseElement(animated_properties,
  246. base::TimeDelta())));
  247. bool wait_for_group_start = false;
  248. for (iter = animations.begin(); iter != animations.end(); ++iter)
  249. wait_for_group_start |=
  250. delegate_ && (*iter)->IsFirstElementThreaded(delegate_);
  251. int group_id = cc::AnimationIdProvider::NextGroupId();
  252. // These animations (provided they don't animate any common properties) will
  253. // now animate together if trivially scheduled.
  254. for (iter = animations.begin(); iter != animations.end(); ++iter) {
  255. (*iter)->set_animation_group_id(group_id);
  256. (*iter)->set_waiting_for_group_start(wait_for_group_start);
  257. ScheduleAnimation(*iter);
  258. }
  259. adding_animations_ = false;
  260. UpdateAnimationState();
  261. }
  262. void LayerAnimator::ScheduleTogether(
  263. const std::vector<LayerAnimationSequence*>& animations) {
  264. scoped_refptr<LayerAnimator> retain(this);
  265. // Collect all the affected properties.
  266. LayerAnimationElement::AnimatableProperties animated_properties =
  267. LayerAnimationElement::UNKNOWN;
  268. std::vector<LayerAnimationSequence*>::const_iterator iter;
  269. for (iter = animations.begin(); iter != animations.end(); ++iter)
  270. animated_properties |= (*iter)->properties();
  271. // Scheduling a zero duration pause that affects all the animated properties
  272. // will prevent any of the sequences from animating until there are no
  273. // running animations that affect any of these properties.
  274. ScheduleAnimation(new LayerAnimationSequence(
  275. LayerAnimationElement::CreatePauseElement(animated_properties,
  276. base::TimeDelta())));
  277. bool wait_for_group_start = false;
  278. for (iter = animations.begin(); iter != animations.end(); ++iter)
  279. wait_for_group_start |=
  280. delegate_ && (*iter)->IsFirstElementThreaded(delegate_);
  281. int group_id = cc::AnimationIdProvider::NextGroupId();
  282. // These animations (provided they don't animate any common properties) will
  283. // now animate together if trivially scheduled.
  284. for (iter = animations.begin(); iter != animations.end(); ++iter) {
  285. (*iter)->set_animation_group_id(group_id);
  286. (*iter)->set_waiting_for_group_start(wait_for_group_start);
  287. ScheduleAnimation(*iter);
  288. }
  289. UpdateAnimationState();
  290. }
  291. void LayerAnimator::SchedulePauseForProperties(
  292. base::TimeDelta duration,
  293. LayerAnimationElement::AnimatableProperties properties_to_pause) {
  294. ScheduleAnimation(new ui::LayerAnimationSequence(
  295. ui::LayerAnimationElement::CreatePauseElement(
  296. properties_to_pause, duration)));
  297. }
  298. bool LayerAnimator::IsAnimatingOnePropertyOf(
  299. LayerAnimationElement::AnimatableProperties properties) const {
  300. for (auto& layer_animation_sequence : animation_queue_) {
  301. if (layer_animation_sequence->properties() & properties)
  302. return true;
  303. }
  304. return false;
  305. }
  306. void LayerAnimator::StopAnimatingProperty(
  307. LayerAnimationElement::AnimatableProperty property) {
  308. scoped_refptr<LayerAnimator> retain(this);
  309. while (true) {
  310. // GetRunningAnimation purges deleted animations before searching, so we are
  311. // guaranteed to find a live animation if any is returned at all.
  312. RunningAnimation* running = GetRunningAnimation(property);
  313. if (!running)
  314. break;
  315. // As was mentioned above, this sequence must be alive.
  316. DCHECK(running->is_sequence_alive());
  317. FinishAnimation(running->sequence(), false);
  318. }
  319. }
  320. void LayerAnimator::AddObserver(LayerAnimationObserver* observer) {
  321. if (!observers_.HasObserver(observer)) {
  322. observers_.AddObserver(observer);
  323. for (auto& layer_animation_sequence : animation_queue_)
  324. layer_animation_sequence->AddObserver(observer);
  325. }
  326. }
  327. void LayerAnimator::RemoveObserver(LayerAnimationObserver* observer) {
  328. observers_.RemoveObserver(observer);
  329. // Remove the observer from all sequences as well.
  330. for (AnimationQueue::iterator queue_iter = animation_queue_.begin();
  331. queue_iter != animation_queue_.end(); ++queue_iter) {
  332. (*queue_iter)->RemoveObserver(observer);
  333. }
  334. }
  335. void LayerAnimator::AddOwnedObserver(
  336. std::unique_ptr<ImplicitAnimationObserver> animation_observer) {
  337. owned_observer_list_.push_back(std::move(animation_observer));
  338. }
  339. void LayerAnimator::RemoveAndDestroyOwnedObserver(
  340. ImplicitAnimationObserver* animation_observer) {
  341. base::EraseIf(owned_observer_list_,[animation_observer](
  342. const std::unique_ptr<ImplicitAnimationObserver>& other) {
  343. return other.get() == animation_observer;
  344. });
  345. }
  346. base::CallbackListSubscription LayerAnimator::AddSequenceScheduledCallback(
  347. SequenceScheduledCallback callback) {
  348. return sequence_scheduled_callbacks_.Add(std::move(callback));
  349. }
  350. void LayerAnimator::OnThreadedAnimationStarted(
  351. base::TimeTicks monotonic_time,
  352. cc::TargetProperty::Type target_property,
  353. int group_id) {
  354. LayerAnimationElement::AnimatableProperty property =
  355. LayerAnimationElement::ToAnimatableProperty(target_property);
  356. RunningAnimation* running = GetRunningAnimation(property);
  357. if (!running)
  358. return;
  359. DCHECK(running->is_sequence_alive());
  360. if (running->sequence()->animation_group_id() != group_id)
  361. return;
  362. running->sequence()->OnThreadedAnimationStarted(monotonic_time,
  363. target_property, group_id);
  364. if (!running->sequence()->waiting_for_group_start())
  365. return;
  366. base::TimeTicks start_time = monotonic_time;
  367. running->sequence()->set_waiting_for_group_start(false);
  368. // The call to GetRunningAnimation made above already purged deleted
  369. // animations, so we are guaranteed that all the animations we iterate
  370. // over now are alive.
  371. for (auto iter = running_animations_.begin();
  372. iter != running_animations_.end(); ++iter) {
  373. // Ensure that each sequence is only Started once, regardless of the
  374. // number of sequences in the group that have threaded first elements.
  375. if (((*iter).sequence()->animation_group_id() == group_id) &&
  376. !(*iter).sequence()->IsFirstElementThreaded(delegate_) &&
  377. (*iter).sequence()->waiting_for_group_start()) {
  378. (*iter).sequence()->set_start_time(start_time);
  379. (*iter).sequence()->set_waiting_for_group_start(false);
  380. (*iter).sequence()->Start(delegate());
  381. }
  382. }
  383. }
  384. void LayerAnimator::AddToCollection(LayerAnimatorCollection* collection) {
  385. DCHECK_EQ(collection, GetLayerAnimatorCollection());
  386. if (is_animating() && !is_started_) {
  387. collection->StartAnimator(this);
  388. is_started_ = true;
  389. }
  390. }
  391. void LayerAnimator::RemoveFromCollection(LayerAnimatorCollection* collection) {
  392. DCHECK_EQ(collection, GetLayerAnimatorCollection());
  393. if (is_started_) {
  394. collection->StopAnimator(this);
  395. is_started_ = false;
  396. }
  397. DCHECK(!animation_->element_animations() ||
  398. !animation_->element_animations()->HasTickingKeyframeEffect());
  399. }
  400. // LayerAnimator protected -----------------------------------------------------
  401. void LayerAnimator::ProgressAnimation(LayerAnimationSequence* sequence,
  402. base::TimeTicks now) {
  403. if (!delegate() || sequence->waiting_for_group_start())
  404. return;
  405. sequence->Progress(now, delegate());
  406. }
  407. void LayerAnimator::ProgressAnimationToEnd(LayerAnimationSequence* sequence) {
  408. if (!delegate())
  409. return;
  410. sequence->ProgressToEnd(delegate());
  411. }
  412. bool LayerAnimator::HasAnimation(LayerAnimationSequence* sequence) const {
  413. for (AnimationQueue::const_iterator queue_iter = animation_queue_.begin();
  414. queue_iter != animation_queue_.end(); ++queue_iter) {
  415. if ((*queue_iter).get() == sequence)
  416. return true;
  417. }
  418. return false;
  419. }
  420. // LayerAnimator private -------------------------------------------------------
  421. void LayerAnimator::Step(base::TimeTicks now) {
  422. TRACE_EVENT0("ui", "LayerAnimator::Step");
  423. scoped_refptr<LayerAnimator> retain(this);
  424. last_step_time_ = now;
  425. PurgeDeletedAnimations();
  426. // We need to make a copy of the running animations because progressing them
  427. // and finishing them may indirectly affect the collection of running
  428. // animations.
  429. RunningAnimations running_animations_copy = running_animations_;
  430. for (size_t i = 0; i < running_animations_copy.size(); ++i) {
  431. if (!SAFE_INVOKE_BOOL(HasAnimation, running_animations_copy[i]))
  432. continue;
  433. if (running_animations_copy[i].sequence()->IsFinished(now)) {
  434. SAFE_INVOKE_VOID(FinishAnimation, running_animations_copy[i], false);
  435. } else {
  436. SAFE_INVOKE_VOID(ProgressAnimation, running_animations_copy[i], now);
  437. }
  438. }
  439. }
  440. void LayerAnimator::StopAnimatingInternal(bool abort) {
  441. scoped_refptr<LayerAnimator> retain(this);
  442. while (is_animating() && delegate()) {
  443. // We're going to attempt to finish the first running animation. Let's
  444. // ensure that it's valid.
  445. PurgeDeletedAnimations();
  446. // If we've purged all running animations, attempt to start one up.
  447. if (running_animations_.empty())
  448. ProcessQueue();
  449. DCHECK(!running_animations_.empty());
  450. // Still no luck, let's just bail and clear all animations.
  451. if (running_animations_.empty()) {
  452. ClearAnimationsInternal();
  453. break;
  454. }
  455. SAFE_INVOKE_VOID(FinishAnimation, running_animations_[0], abort);
  456. }
  457. }
  458. void LayerAnimator::UpdateAnimationState() {
  459. if (disable_timer_for_test_)
  460. return;
  461. const bool should_start = is_animating();
  462. LayerAnimatorCollection* collection = GetLayerAnimatorCollection();
  463. if (collection) {
  464. if (should_start && !is_started_)
  465. collection->StartAnimator(this);
  466. else if (!should_start && is_started_)
  467. collection->StopAnimator(this);
  468. is_started_ = should_start;
  469. } else {
  470. is_started_ = false;
  471. }
  472. }
  473. LayerAnimationSequence* LayerAnimator::RemoveAnimation(
  474. LayerAnimationSequence* sequence) {
  475. std::unique_ptr<LayerAnimationSequence> to_return;
  476. bool is_running = false;
  477. // First remove from running animations
  478. for (auto iter = running_animations_.begin();
  479. iter != running_animations_.end(); ++iter) {
  480. if ((*iter).sequence() == sequence) {
  481. running_animations_.erase(iter);
  482. is_running = true;
  483. break;
  484. }
  485. }
  486. // Then remove from the queue
  487. for (AnimationQueue::iterator queue_iter = animation_queue_.begin();
  488. queue_iter != animation_queue_.end(); ++queue_iter) {
  489. if (queue_iter->get() == sequence) {
  490. to_return = std::move(*queue_iter);
  491. animation_queue_.erase(queue_iter);
  492. break;
  493. }
  494. }
  495. // Do not continue and attempt to start other sequences if the delegate is
  496. // nullptr.
  497. // TODO(crbug.com/1247769): Guard other uses of delegate_ in this class.
  498. if (!delegate())
  499. return to_return.release();
  500. if (!to_return.get() || !to_return->waiting_for_group_start() ||
  501. !to_return->IsFirstElementThreaded(delegate_))
  502. return to_return.release();
  503. // The removed sequence may have been responsible for making other sequences
  504. // wait for a group start. If no other sequences in the group have a
  505. // threaded first element, the group no longer needs the additional wait.
  506. bool is_wait_still_needed = false;
  507. int group_id = to_return->animation_group_id();
  508. for (AnimationQueue::iterator queue_iter = animation_queue_.begin();
  509. queue_iter != animation_queue_.end(); ++queue_iter) {
  510. if (((*queue_iter)->animation_group_id() == group_id) &&
  511. (*queue_iter)->IsFirstElementThreaded(delegate_)) {
  512. is_wait_still_needed = true;
  513. break;
  514. }
  515. }
  516. if (is_wait_still_needed)
  517. return to_return.release();
  518. for (AnimationQueue::iterator queue_iter = animation_queue_.begin();
  519. queue_iter != animation_queue_.end(); ++queue_iter) {
  520. if ((*queue_iter)->animation_group_id() == group_id &&
  521. (*queue_iter)->waiting_for_group_start()) {
  522. (*queue_iter)->set_waiting_for_group_start(false);
  523. if (is_running) {
  524. (*queue_iter)->set_start_time(last_step_time_);
  525. (*queue_iter)->Start(delegate());
  526. }
  527. }
  528. }
  529. return to_return.release();
  530. }
  531. void LayerAnimator::FinishAnimation(
  532. LayerAnimationSequence* sequence, bool abort) {
  533. scoped_refptr<LayerAnimator> retain(this);
  534. std::unique_ptr<LayerAnimationSequence> removed(RemoveAnimation(sequence));
  535. if (abort)
  536. sequence->Abort(delegate());
  537. else
  538. ProgressAnimationToEnd(sequence);
  539. if (!delegate())
  540. return;
  541. ProcessQueue();
  542. UpdateAnimationState();
  543. }
  544. void LayerAnimator::FinishAnyAnimationWithZeroDuration() {
  545. scoped_refptr<LayerAnimator> retain(this);
  546. // Special case: if we've started a 0 duration animation, just finish it now
  547. // and get rid of it. We need to make a copy because Progress may indirectly
  548. // cause new animations to start running.
  549. RunningAnimations running_animations_copy = running_animations_;
  550. for (size_t i = 0; i < running_animations_copy.size(); ++i) {
  551. if (!SAFE_INVOKE_BOOL(HasAnimation, running_animations_copy[i]))
  552. continue;
  553. if (running_animations_copy[i].sequence()->IsFinished(
  554. running_animations_copy[i].sequence()->start_time())) {
  555. SAFE_INVOKE_VOID(ProgressAnimationToEnd, running_animations_copy[i]);
  556. std::unique_ptr<LayerAnimationSequence> removed(
  557. SAFE_INVOKE_PTR(RemoveAnimation, running_animations_copy[i]));
  558. }
  559. }
  560. ProcessQueue();
  561. UpdateAnimationState();
  562. }
  563. void LayerAnimator::ClearAnimations() {
  564. scoped_refptr<LayerAnimator> retain(this);
  565. ClearAnimationsInternal();
  566. }
  567. LayerAnimator::RunningAnimation* LayerAnimator::GetRunningAnimation(
  568. LayerAnimationElement::AnimatableProperty property) {
  569. PurgeDeletedAnimations();
  570. for (auto iter = running_animations_.begin();
  571. iter != running_animations_.end(); ++iter) {
  572. if ((*iter).sequence()->properties() & property)
  573. return &(*iter);
  574. }
  575. return nullptr;
  576. }
  577. void LayerAnimator::AddToQueueIfNotPresent(LayerAnimationSequence* animation) {
  578. // If we don't have the animation in the queue yet, add it.
  579. bool found_sequence = false;
  580. for (AnimationQueue::iterator queue_iter = animation_queue_.begin();
  581. queue_iter != animation_queue_.end(); ++queue_iter) {
  582. if (queue_iter->get() == animation) {
  583. found_sequence = true;
  584. break;
  585. }
  586. }
  587. if (!found_sequence) {
  588. animation_queue_.push_front(
  589. std::unique_ptr<LayerAnimationSequence>(animation));
  590. }
  591. }
  592. void LayerAnimator::RemoveAllAnimationsWithACommonProperty(
  593. LayerAnimationSequence* sequence, bool abort) {
  594. // For all the running animations, if they animate the same property,
  595. // progress them to the end and remove them. Note, Aborting or Progressing
  596. // animations may affect the collection of running animations, so we need to
  597. // operate on a copy.
  598. RunningAnimations running_animations_copy = running_animations_;
  599. for (size_t i = 0; i < running_animations_copy.size(); ++i) {
  600. if (!SAFE_INVOKE_BOOL(HasAnimation, running_animations_copy[i]))
  601. continue;
  602. if (running_animations_copy[i].sequence()->HasConflictingProperty(
  603. sequence->properties())) {
  604. std::unique_ptr<LayerAnimationSequence> removed(
  605. SAFE_INVOKE_PTR(RemoveAnimation, running_animations_copy[i]));
  606. if (abort)
  607. running_animations_copy[i].sequence()->Abort(delegate());
  608. else
  609. SAFE_INVOKE_VOID(ProgressAnimationToEnd, running_animations_copy[i]);
  610. }
  611. }
  612. // Same for the queued animations that haven't been started. Again, we'll
  613. // need to operate on a copy.
  614. std::vector<base::WeakPtr<LayerAnimationSequence> > sequences;
  615. for (AnimationQueue::iterator queue_iter = animation_queue_.begin();
  616. queue_iter != animation_queue_.end(); ++queue_iter)
  617. sequences.push_back((*queue_iter)->AsWeakPtr());
  618. for (size_t i = 0; i < sequences.size(); ++i) {
  619. if (!sequences[i].get() || !HasAnimation(sequences[i].get()))
  620. continue;
  621. if (sequences[i]->HasConflictingProperty(sequence->properties())) {
  622. std::unique_ptr<LayerAnimationSequence> removed(
  623. RemoveAnimation(sequences[i].get()));
  624. if (abort)
  625. sequences[i]->Abort(delegate());
  626. else
  627. ProgressAnimationToEnd(sequences[i].get());
  628. }
  629. }
  630. }
  631. void LayerAnimator::ImmediatelySetNewTarget(LayerAnimationSequence* sequence) {
  632. // Need to detect if our sequence gets destroyed.
  633. base::WeakPtr<LayerAnimationSequence> weak_sequence_ptr =
  634. sequence->AsWeakPtr();
  635. const bool abort = false;
  636. RemoveAllAnimationsWithACommonProperty(sequence, abort);
  637. if (!weak_sequence_ptr.get())
  638. return;
  639. LayerAnimationSequence* removed = RemoveAnimation(sequence);
  640. DCHECK(removed == nullptr || removed == sequence);
  641. if (!weak_sequence_ptr.get())
  642. return;
  643. ProgressAnimationToEnd(sequence);
  644. if (!weak_sequence_ptr.get())
  645. return;
  646. delete sequence;
  647. }
  648. void LayerAnimator::ImmediatelyAnimateToNewTarget(
  649. LayerAnimationSequence* sequence) {
  650. // Need to detect if our sequence gets destroyed.
  651. base::WeakPtr<LayerAnimationSequence> weak_sequence_ptr =
  652. sequence->AsWeakPtr();
  653. const bool abort = true;
  654. RemoveAllAnimationsWithACommonProperty(sequence, abort);
  655. if (!weak_sequence_ptr.get())
  656. return;
  657. AddToQueueIfNotPresent(sequence);
  658. if (!weak_sequence_ptr.get())
  659. return;
  660. StartSequenceImmediately(sequence);
  661. }
  662. void LayerAnimator::EnqueueNewAnimation(LayerAnimationSequence* sequence) {
  663. // It is assumed that if there was no conflicting animation, we would
  664. // not have been called. No need to check for a collision; just
  665. // add to the queue.
  666. animation_queue_.push_back(std::unique_ptr<LayerAnimationSequence>(sequence));
  667. ProcessQueue();
  668. }
  669. void LayerAnimator::ReplaceQueuedAnimations(LayerAnimationSequence* sequence) {
  670. // Need to detect if our sequence gets destroyed.
  671. base::WeakPtr<LayerAnimationSequence> weak_sequence_ptr =
  672. sequence->AsWeakPtr();
  673. // Remove all animations that aren't running. Note: at each iteration i is
  674. // incremented or an element is removed from the queue, so
  675. // animation_queue_.size() - i is always decreasing and we are always making
  676. // progress towards the loop terminating.
  677. for (size_t i = 0; i < animation_queue_.size();) {
  678. if (!weak_sequence_ptr.get())
  679. break;
  680. PurgeDeletedAnimations();
  681. bool is_running = false;
  682. for (RunningAnimations::const_iterator iter = running_animations_.begin();
  683. iter != running_animations_.end(); ++iter) {
  684. if ((*iter).sequence() == animation_queue_[i].get()) {
  685. is_running = true;
  686. break;
  687. }
  688. }
  689. if (!is_running)
  690. delete RemoveAnimation(animation_queue_[i].get());
  691. else
  692. ++i;
  693. }
  694. animation_queue_.push_back(std::unique_ptr<LayerAnimationSequence>(sequence));
  695. ProcessQueue();
  696. }
  697. void LayerAnimator::ProcessQueue() {
  698. bool started_sequence = false;
  699. do {
  700. started_sequence = false;
  701. // Build a list of all currently animated properties.
  702. LayerAnimationElement::AnimatableProperties animated =
  703. LayerAnimationElement::UNKNOWN;
  704. for (RunningAnimations::const_iterator iter = running_animations_.begin();
  705. iter != running_animations_.end(); ++iter) {
  706. if (!(*iter).is_sequence_alive())
  707. continue;
  708. animated |= (*iter).sequence()->properties();
  709. }
  710. // Try to find an animation that doesn't conflict with an animated
  711. // property or a property that will be animated before it. Note: starting
  712. // the animation may indirectly cause more animations to be started, so we
  713. // need to operate on a copy.
  714. std::vector<base::WeakPtr<LayerAnimationSequence> > sequences;
  715. for (AnimationQueue::iterator queue_iter = animation_queue_.begin();
  716. queue_iter != animation_queue_.end(); ++queue_iter)
  717. sequences.push_back((*queue_iter)->AsWeakPtr());
  718. for (size_t i = 0; i < sequences.size(); ++i) {
  719. if (!sequences[i].get() || !HasAnimation(sequences[i].get()))
  720. continue;
  721. if (!sequences[i]->HasConflictingProperty(animated)) {
  722. StartSequenceImmediately(sequences[i].get());
  723. started_sequence = true;
  724. break;
  725. }
  726. // Animation couldn't be started. Add its properties to the collection so
  727. // that we don't start a conflicting animation. For example, if our queue
  728. // has the elements { {T,B}, {B} } (that is, an element that animates both
  729. // the transform and the bounds followed by an element that animates the
  730. // bounds), and we're currently animating the transform, we can't start
  731. // the first element because it animates the transform, too. We cannot
  732. // start the second element, either, because the first element animates
  733. // bounds too, and needs to go first.
  734. animated |= sequences[i]->properties();
  735. }
  736. // If we started a sequence, try again. We may be able to start several.
  737. } while (started_sequence);
  738. }
  739. bool LayerAnimator::StartSequenceImmediately(LayerAnimationSequence* sequence) {
  740. PurgeDeletedAnimations();
  741. // Ensure that no one is animating one of the sequence's properties already.
  742. for (RunningAnimations::const_iterator iter = running_animations_.begin();
  743. iter != running_animations_.end(); ++iter) {
  744. if ((*iter).sequence()->HasConflictingProperty(sequence->properties()))
  745. return false;
  746. }
  747. // All clear, actually start the sequence.
  748. // All LayerAnimators share the same LayerAnimatorCollection. Use the
  749. // last_tick_time() from there to ensure animations started during the same
  750. // event complete at the same time.
  751. base::TimeTicks start_time;
  752. LayerAnimatorCollection* collection = GetLayerAnimatorCollection();
  753. if (is_animating() || adding_animations_)
  754. start_time = last_step_time_;
  755. else if (collection && collection->HasActiveAnimators())
  756. start_time = collection->last_tick_time();
  757. else
  758. start_time = base::TimeTicks::Now();
  759. if (!sequence->animation_group_id())
  760. sequence->set_animation_group_id(cc::AnimationIdProvider::NextGroupId());
  761. running_animations_.push_back(
  762. RunningAnimation(sequence->AsWeakPtr()));
  763. // Need to keep a reference to the animation.
  764. AddToQueueIfNotPresent(sequence);
  765. if (!sequence->waiting_for_group_start() ||
  766. sequence->IsFirstElementThreaded(delegate_)) {
  767. sequence->set_start_time(start_time);
  768. sequence->Start(delegate());
  769. }
  770. // Ensure that animations get stepped at their start time.
  771. Step(start_time);
  772. return true;
  773. }
  774. void LayerAnimator::GetTargetValue(
  775. LayerAnimationElement::TargetValue* target) const {
  776. for (AnimationQueue::const_iterator iter = animation_queue_.begin();
  777. iter != animation_queue_.end(); ++iter) {
  778. (*iter)->GetTargetValue(target);
  779. }
  780. }
  781. void LayerAnimator::OnScheduled(LayerAnimationSequence* sequence) {
  782. sequence_scheduled_callbacks_.Notify(sequence);
  783. for (LayerAnimationObserver& observer : observers_)
  784. sequence->AddObserver(&observer);
  785. sequence->OnScheduled();
  786. }
  787. void LayerAnimator::SetTransitionDuration(base::TimeDelta duration) {
  788. if (is_transition_duration_locked_)
  789. return;
  790. transition_duration_ = duration;
  791. }
  792. void LayerAnimator::ClearAnimationsInternal() {
  793. PurgeDeletedAnimations();
  794. // Abort should never affect the set of running animations, but just in case
  795. // clients are badly behaved, we will use a copy of the running animations.
  796. RunningAnimations running_animations_copy = running_animations_;
  797. for (size_t i = 0; i < running_animations_copy.size(); ++i) {
  798. if (!SAFE_INVOKE_BOOL(HasAnimation, running_animations_copy[i]))
  799. continue;
  800. std::unique_ptr<LayerAnimationSequence> removed(
  801. RemoveAnimation(running_animations_copy[i].sequence()));
  802. if (removed.get())
  803. removed->Abort(delegate());
  804. }
  805. // This *should* have cleared the list of running animations.
  806. DCHECK(running_animations_.empty());
  807. running_animations_.clear();
  808. animation_queue_.clear();
  809. UpdateAnimationState();
  810. }
  811. void LayerAnimator::PurgeDeletedAnimations() {
  812. for (size_t i = 0; i < running_animations_.size();) {
  813. if (!running_animations_[i].is_sequence_alive())
  814. running_animations_.erase(running_animations_.begin() + i);
  815. else
  816. i++;
  817. }
  818. }
  819. LayerAnimatorCollection* LayerAnimator::GetLayerAnimatorCollection() {
  820. return delegate_ ? delegate_->GetLayerAnimatorCollection() : nullptr;
  821. }
  822. void LayerAnimator::NotifyAnimationStarted(base::TimeTicks monotonic_time,
  823. int target_property,
  824. int group) {
  825. OnThreadedAnimationStarted(
  826. monotonic_time, static_cast<cc::TargetProperty::Type>(target_property),
  827. group);
  828. }
  829. LayerAnimator::RunningAnimation::RunningAnimation(
  830. const base::WeakPtr<LayerAnimationSequence>& sequence)
  831. : sequence_(sequence) {
  832. }
  833. LayerAnimator::RunningAnimation::RunningAnimation(
  834. const RunningAnimation& other) = default;
  835. LayerAnimator::RunningAnimation::~RunningAnimation() { }
  836. } // namespace ui