File: user_switch_animator.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (382 lines) | stat: -rw-r--r-- 14,608 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/multi_user/user_switch_animator.h"

#include <algorithm>
#include <memory>

#include "ash/multi_user/multi_user_window_manager_impl.h"
#include "ash/public/cpp/multi_user_window_manager_delegate.h"
#include "ash/shell.h"
#include "ash/wallpaper/wallpaper_controller_impl.h"
#include "ash/wm/desks/desks_controller.h"
#include "ash/wm/mru_window_tracker.h"
#include "ash/wm/overview/overview_controller.h"
#include "ash/wm/window_positioner.h"
#include "base/containers/contains.h"
#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/base/mojom/window_show_state.mojom.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_animation_observer.h"
#include "ui/compositor/layer_tree_owner.h"
#include "ui/compositor/scoped_layer_animation_settings.h"
#include "ui/display/display.h"
#include "ui/wm/core/window_util.h"
#include "ui/wm/public/activation_client.h"

namespace ash {
namespace {

// The minimal possible animation time for animations which should happen
// "instantly".
constexpr base::TimeDelta kMinimalAnimationTime = base::Milliseconds(1);

// logic while the user gets switched.
class UserChangeActionDisabler {
 public:
  UserChangeActionDisabler() {
    window_positioner::DisableAutoPositioning(true);
    Shell::Get()->mru_window_tracker()->SetIgnoreActivations(true);
  }

  UserChangeActionDisabler(const UserChangeActionDisabler&) = delete;
  UserChangeActionDisabler& operator=(const UserChangeActionDisabler&) = delete;

  ~UserChangeActionDisabler() {
    window_positioner::DisableAutoPositioning(false);
    Shell::Get()->mru_window_tracker()->SetIgnoreActivations(false);
  }
};

// Defines an animation watcher for the 'hide' animation of the first maximized
// window we encounter while looping through the old user's windows. This is
// to observe the end of the animation so that we can destruct the old detached
// layer of the window.
class MaximizedWindowAnimationWatcher : public ui::ImplicitAnimationObserver {
 public:
  explicit MaximizedWindowAnimationWatcher(
      std::unique_ptr<ui::LayerTreeOwner> old_layer)
      : old_layer_(std::move(old_layer)) {}

  MaximizedWindowAnimationWatcher(const MaximizedWindowAnimationWatcher&) =
      delete;
  MaximizedWindowAnimationWatcher& operator=(
      const MaximizedWindowAnimationWatcher&) = delete;

  // ui::ImplicitAnimationObserver:
  void OnImplicitAnimationsCompleted() override { delete this; }

 private:
  std::unique_ptr<ui::LayerTreeOwner> old_layer_;
};

// Modifies the given |window_list| such that the most-recently used window (if
// any, and if it exists in |window_list|) will be the last window in the list.
void PutMruWindowLast(
    std::vector<raw_ptr<aura::Window, VectorExperimental>>* window_list) {
  DCHECK(window_list);
  auto it = std::ranges::find_if(*window_list, &wm::IsActiveWindow);
  if (it == window_list->end())
    return;
  // Move the active window to the end of the list.
  aura::Window* active_window = *it;
  window_list->erase(it);
  window_list->push_back(active_window);
}

}  // namespace

UserSwitchAnimator::UserSwitchAnimator(MultiUserWindowManagerImpl* owner,
                                       const AccountId& new_account_id,
                                       base::TimeDelta animation_speed)
    : owner_(owner),
      new_account_id_(new_account_id),
      animation_speed_(animation_speed),
      animation_step_(ANIMATION_STEP_HIDE_OLD_USER),
      screen_cover_(GetScreenCover(NULL)),
      windows_by_account_id_() {
  Shell::Get()->overview_controller()->EndOverview(
      OverviewEndAction::kUserSwitch);
  BuildUserToWindowsListMap();
  AdvanceUserTransitionAnimation();

  if (animation_speed_.is_zero()) {
    FinalizeAnimation();
  } else {
    user_changed_animation_timer_ = std::make_unique<base::RepeatingTimer>();
    user_changed_animation_timer_->Start(
        FROM_HERE, animation_speed_,
        base::BindRepeating(&UserSwitchAnimator::AdvanceUserTransitionAnimation,
                            base::Unretained(this)));
  }
}

UserSwitchAnimator::~UserSwitchAnimator() {
  FinalizeAnimation();
}

// static
bool UserSwitchAnimator::CoversScreen(aura::Window* window) {
  // Full screen covers the screen naturally. Since a normal window can have the
  // same size as the work area, we only compare the bounds against the work
  // area.
  if (wm::WindowStateIs(window, ui::mojom::WindowShowState::kFullscreen)) {
    return true;
  }
  gfx::Rect bounds = window->GetBoundsInScreen();
  gfx::Rect work_area =
      display::Screen::GetScreen()->GetDisplayNearestWindow(window).work_area();
  bounds.Intersect(work_area);
  return work_area == bounds;
}

void UserSwitchAnimator::AdvanceUserTransitionAnimation() {
  DCHECK_NE(animation_step_, ANIMATION_STEP_ENDED);

  TransitionWallpaper(animation_step_);
  TransitionUserShelf(animation_step_);
  TransitionWindows(animation_step_);

  // Advance to the next step.
  switch (animation_step_) {
    case ANIMATION_STEP_HIDE_OLD_USER:
      animation_step_ = ANIMATION_STEP_SHOW_NEW_USER;
      break;
    case ANIMATION_STEP_SHOW_NEW_USER:
      animation_step_ = ANIMATION_STEP_FINALIZE;
      break;
    case ANIMATION_STEP_FINALIZE:
      user_changed_animation_timer_.reset();
      animation_step_ = ANIMATION_STEP_ENDED;
      break;
    case ANIMATION_STEP_ENDED:
      NOTREACHED();
  }
}

void UserSwitchAnimator::CancelAnimation() {
  animation_step_ = ANIMATION_STEP_ENDED;
}

void UserSwitchAnimator::FinalizeAnimation() {
  user_changed_animation_timer_.reset();
  while (ANIMATION_STEP_ENDED != animation_step_)
    AdvanceUserTransitionAnimation();
}

void UserSwitchAnimator::TransitionWallpaper(AnimationStep animation_step) {
  auto* wallpaper_controller = Shell::Get()->wallpaper_controller();

  // Handle the wallpaper switch.
  if (animation_step == ANIMATION_STEP_HIDE_OLD_USER) {
    // Set the wallpaper cross dissolve animation duration to our complete
    // animation cycle for a fade in and fade out.
    base::TimeDelta duration =
        animation_speed_ * (NO_USER_COVERS_SCREEN == screen_cover_ ? 2 : 0);
    wallpaper_controller->SetAnimationDuration(
        duration > kMinimalAnimationTime ? duration : kMinimalAnimationTime);
    if (screen_cover_ != NEW_USER_COVERS_SCREEN) {
      wallpaper_controller->ShowUserWallpaper(new_account_id_);
      wallpaper_user_id_for_test_ =
          (NO_USER_COVERS_SCREEN == screen_cover_ ? "->" : "") +
          new_account_id_.Serialize();
    }
  } else if (animation_step == ANIMATION_STEP_FINALIZE) {
    // Revert the wallpaper cross dissolve animation duration back to the
    // default.
    if (screen_cover_ == NEW_USER_COVERS_SCREEN)
      wallpaper_controller->ShowUserWallpaper(new_account_id_);

    // Coming here the wallpaper user id is the final result. No matter how we
    // got here.
    wallpaper_user_id_for_test_ = new_account_id_.Serialize();
    wallpaper_controller->SetAnimationDuration(base::TimeDelta());
  }
}

void UserSwitchAnimator::TransitionUserShelf(AnimationStep animation_step) {
  if (animation_step != ANIMATION_STEP_SHOW_NEW_USER)
    return;

  owner_->delegate_->OnTransitionUserShelfToNewAccount();
}

void UserSwitchAnimator::TransitionWindows(AnimationStep animation_step) {
  // Disable the window position manager and the MRU window tracker temporarily.
  UserChangeActionDisabler disabler;

  // Animation duration.
  base::TimeDelta duration =
      base::Milliseconds(std::max(kMinimalAnimationTime.InMilliseconds(),
                                  2 * animation_speed_.InMilliseconds()));

  switch (animation_step) {
    case ANIMATION_STEP_HIDE_OLD_USER: {
      // Hide the old users.
      for (auto& user_pair : windows_by_account_id_) {
        auto& show_for_account_id = user_pair.first;
        if (show_for_account_id == new_account_id_) {
          continue;
        }

        bool found_foreground_maximized_window = false;

        // We hide the windows such that the MRU window is the last one to be
        // hidden, at which point all other windows have already been hidden,
        // and hence the FocusController will not be able to find a next
        // activateable window to restore focus to, and so we don't change
        // window order (crbug.com/424307).
        PutMruWindowLast(&(user_pair.second));
        for (aura::Window* window : user_pair.second) {
          // Minimized visiting windows (minimized windows with an owner
          // different than that of the for_show_account_id) should return to
          // their
          // original owners' desktops.
          MultiUserWindowManagerImpl::WindowToEntryMap::const_iterator itr =
              owner_->window_to_entry().find(window);
          DCHECK(itr != owner_->window_to_entry().end());
          if (show_for_account_id != itr->second->owner() &&
              wm::WindowStateIs(window,
                                ui::mojom::WindowShowState::kMinimized)) {
            owner_->ShowWindowForUserIntern(window, itr->second->owner());
            wm::Unminimize(window);
            continue;
          }

          if (!found_foreground_maximized_window && CoversScreen(window) &&
              screen_cover_ == BOTH_USERS_COVER_SCREEN) {
            // Maximized windows should be hidden, but visually kept visible
            // in order to prevent showing the background while the animation is
            // in progress. Therefore we detach the old layer and recreate fresh
            // ones. The old layers will be destructed at the animation step
            // |ANIMATION_STEP_FINALIZE|.
            // old_layers_.push_back(wm::RecreateLayers(window));
            // We only want to do this for the first (foreground) maximized
            // window we encounter.
            found_foreground_maximized_window = true;
            std::unique_ptr<ui::LayerTreeOwner> old_layer =
                wm::RecreateLayers(window);
            window->layer()->parent()->StackAtBottom(old_layer->root());
            ui::ScopedLayerAnimationSettings settings(
                window->layer()->GetAnimator());
            settings.AddObserver(
                new MaximizedWindowAnimationWatcher(std::move(old_layer)));
            // Call SetWindowVisibility() within the scope of |settings| so that
            // MaximizedWindowAnimationWatcher is notified when the animation
            // completes.
            owner_->SetWindowVisibility(window, false, duration);
          } else {
            owner_->SetWindowVisibility(window, false, duration);
          }
        }
      }

      // Show new user.
      auto new_user_itr = windows_by_account_id_.find(new_account_id_);
      auto* desks_controller = Shell::Get()->desks_controller();
      if (new_user_itr == windows_by_account_id_.end()) {
        // Despite no new windows being shown, we still need to call
        // DesksController::OnNewUserShown() to properly restack visible on all
        // desks windows.
        desks_controller->OnNewUserShown();
        return;
      }

      for (aura::Window* window : new_user_itr->second) {
        auto entry = owner_->window_to_entry().find(window);
        DCHECK(entry != owner_->window_to_entry().end());

        if (entry->second->show()) {
          owner_->SetWindowVisibility(window, true, duration);
        }
      }
      desks_controller->OnNewUserShown();

      break;
    }

    case ANIMATION_STEP_SHOW_NEW_USER: {
      // In order to make the animation look better, we had to move the code
      // that shows the new user to the previous step. Hence, we do nothing
      // here.
      break;
    }
    case ANIMATION_STEP_FINALIZE: {
      // Reactivate the MRU window of the new user.
      aura::Window::Windows mru_list =
          Shell::Get()->mru_window_tracker()->BuildMruWindowList(kActiveDesk);
      if (!mru_list.empty()) {
        aura::Window* window = mru_list[0];
        if (owner_->IsWindowOnDesktopOfUser(window, new_account_id_) &&
            !wm::WindowStateIs(window,
                               ui::mojom::WindowShowState::kMinimized)) {
          // Several unit tests come here without an activation client.
          wm::ActivationClient* client =
              wm::GetActivationClient(window->GetRootWindow());
          if (client) {
            client->ActivateWindow(window);
          }
        }
      }

      break;
    }
    case ANIMATION_STEP_ENDED:
      NOTREACHED();
  }
}

UserSwitchAnimator::TransitioningScreenCover UserSwitchAnimator::GetScreenCover(
    aura::Window* root_window) {
  TransitioningScreenCover cover = NO_USER_COVERS_SCREEN;
  for (auto& pair : owner_->window_to_entry()) {
    aura::Window* window = pair.first;
    if (root_window && window->GetRootWindow() != root_window)
      continue;
    if (window->IsVisible() && CoversScreen(window)) {
      if (cover == NEW_USER_COVERS_SCREEN)
        return BOTH_USERS_COVER_SCREEN;
      else
        cover = OLD_USER_COVERS_SCREEN;
    } else if (owner_->IsWindowOnDesktopOfUser(window, new_account_id_) &&
               CoversScreen(window)) {
      if (cover == OLD_USER_COVERS_SCREEN)
        return BOTH_USERS_COVER_SCREEN;
      else
        cover = NEW_USER_COVERS_SCREEN;
    }
  }
  return cover;
}

void UserSwitchAnimator::BuildUserToWindowsListMap() {
  // This is to be called only at the time this animation is constructed.
  DCHECK(windows_by_account_id_.empty());

  // For each unique parent window, we enumerate its children windows, and
  // for each child if it's in the |window_to_entry()| map, we add it to the
  // |windows_by_account_id_| map.
  // This gives us a list of windows per each user that is in the same order
  // they were created in their parent windows.
  std::set<aura::Window*> parent_windows;
  auto& window_to_entry_map = owner_->window_to_entry();
  for (auto& window_entry_pair : window_to_entry_map) {
    aura::Window* parent_window = window_entry_pair.first->parent();
    if (!base::Contains(parent_windows, parent_window)) {
      parent_windows.insert(parent_window);
      for (aura::Window* child_window : parent_window->children()) {
        auto itr = window_to_entry_map.find(child_window);
        if (itr != window_to_entry_map.end()) {
          windows_by_account_id_[itr->second->show_for_user()].push_back(
              child_window);
        }
      }
    }
  }
}

}  // namespace ash