animation_abort_handle.cc 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Copyright 2021 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/views/animation/animation_abort_handle.h"
  5. #include "ui/compositor/layer.h"
  6. #include "ui/compositor/layer_animator.h"
  7. namespace views {
  8. AnimationAbortHandle::AnimationAbortHandle(AnimationBuilder::Observer* observer)
  9. : observer_(observer) {
  10. observer_->SetAbortHandle(this);
  11. }
  12. AnimationAbortHandle::~AnimationAbortHandle() {
  13. DCHECK_NE(animation_state_, AnimationState::kNotStarted)
  14. << "You can't destroy the handle before the animation starts.";
  15. if (observer_)
  16. observer_->SetAbortHandle(nullptr);
  17. if (animation_state_ != AnimationState::kEnded) {
  18. for (ui::Layer* layer : tracked_layers_) {
  19. if (deleted_layers_.find(layer) != deleted_layers_.end())
  20. continue;
  21. layer->GetAnimator()->AbortAllAnimations();
  22. }
  23. }
  24. // Remove the abort handle itself from the alive tracked layers.
  25. for (ui::Layer* layer : tracked_layers_) {
  26. if (deleted_layers_.find(layer) != deleted_layers_.end())
  27. continue;
  28. layer->RemoveObserver(this);
  29. }
  30. }
  31. void AnimationAbortHandle::OnObserverDeleted() {
  32. observer_ = nullptr;
  33. }
  34. void AnimationAbortHandle::AddLayer(ui::Layer* layer) {
  35. // Do not allow to add the layer that was deleted before.
  36. DCHECK(deleted_layers_.find(layer) == deleted_layers_.end());
  37. bool inserted = tracked_layers_.insert(layer).second;
  38. // In case that one layer is added to the abort handle multiple times.
  39. if (inserted)
  40. layer->AddObserver(this);
  41. }
  42. void AnimationAbortHandle::OnAnimationStarted() {
  43. DCHECK_EQ(animation_state_, AnimationState::kNotStarted);
  44. animation_state_ = AnimationState::kRunning;
  45. }
  46. void AnimationAbortHandle::OnAnimationEnded() {
  47. DCHECK_EQ(animation_state_, AnimationState::kRunning);
  48. animation_state_ = AnimationState::kEnded;
  49. }
  50. void AnimationAbortHandle::LayerDestroyed(ui::Layer* layer) {
  51. layer->RemoveObserver(this);
  52. // NOTE: layer deletion may be caused by animation abortion. In addition,
  53. // aborting an animation may lead to multiple layer deletions (for example, a
  54. // animation abort callback could delete multiple views' layers). Therefore
  55. // the destroyed layer should not be removed from `tracked_layers_` directly.
  56. // Otherwise, iterating `tracked_layers_` in the animation abort handle's
  57. // destructor is risky.
  58. bool inserted = deleted_layers_.insert(layer).second;
  59. DCHECK(inserted);
  60. }
  61. } // namespace views