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 #include "ash/shell.h"
6 
7 #include <algorithm>
8 #include <memory>
9 #include <string>
10 #include <utility>
11 
12 #include "ash/accelerators/accelerator_controller_impl.h"
13 #include "ash/accelerators/ash_focus_manager_factory.h"
14 #include "ash/accelerators/magnifier_key_scroller.h"
15 #include "ash/accelerators/pre_target_accelerator_handler.h"
16 #include "ash/accelerators/spoken_feedback_toggler.h"
17 #include "ash/accelerometer/accelerometer_reader.h"
18 #include "ash/accessibility/accessibility_controller_impl.h"
19 #include "ash/accessibility/accessibility_delegate.h"
20 #include "ash/accessibility/accessibility_focus_ring_controller_impl.h"
21 #include "ash/accessibility/key_accessibility_enabler.h"
22 #include "ash/ambient/ambient_controller.h"
23 #include "ash/app_list/app_list_controller_impl.h"
24 #include "ash/assistant/assistant_controller_impl.h"
25 #include "ash/autoclick/autoclick_controller.h"
26 #include "ash/bloom/bloom_ui_controller_impl.h"
27 #include "ash/bloom/bloom_ui_delegate_impl.h"
28 #include "ash/capture_mode/capture_mode_controller.h"
29 #include "ash/child_accounts/parent_access_controller_impl.h"
30 #include "ash/clipboard/clipboard_history_controller_impl.h"
31 #include "ash/dbus/ash_dbus_services.h"
32 #include "ash/detachable_base/detachable_base_handler.h"
33 #include "ash/detachable_base/detachable_base_notification_controller.h"
34 #include "ash/display/cros_display_config.h"
35 #include "ash/display/cursor_window_controller.h"
36 #include "ash/display/display_alignment_controller.h"
37 #include "ash/display/display_color_manager.h"
38 #include "ash/display/display_configuration_controller.h"
39 #include "ash/display/display_configuration_observer.h"
40 #include "ash/display/display_error_observer.h"
41 #include "ash/display/display_highlight_controller.h"
42 #include "ash/display/display_prefs.h"
43 #include "ash/display/display_shutdown_observer.h"
44 #include "ash/display/event_transformation_handler.h"
45 #include "ash/display/mouse_cursor_event_filter.h"
46 #include "ash/display/persistent_window_controller.h"
47 #include "ash/display/privacy_screen_controller.h"
48 #include "ash/display/projecting_observer.h"
49 #include "ash/display/resolution_notification_controller.h"
50 #include "ash/display/screen_ash.h"
51 #include "ash/display/screen_orientation_controller.h"
52 #include "ash/display/screen_position_controller.h"
53 #include "ash/display/window_tree_host_manager.h"
54 #include "ash/drag_drop/drag_drop_controller.h"
55 #include "ash/events/event_rewriter_controller_impl.h"
56 #include "ash/fast_ink/laser/laser_pointer_controller.h"
57 #include "ash/focus_cycler.h"
58 #include "ash/frame/non_client_frame_view_ash.h"
59 #include "ash/frame/snap_controller_impl.h"
60 #include "ash/frame_throttler/frame_throttling_controller.h"
61 #include "ash/high_contrast/high_contrast_controller.h"
62 #include "ash/highlighter/highlighter_controller.h"
63 #include "ash/home_screen/home_screen_controller.h"
64 #include "ash/host/ash_window_tree_host_init_params.h"
65 #include "ash/hud_display/hud_display.h"
66 #include "ash/ime/ime_controller_impl.h"
67 #include "ash/in_session_auth/in_session_auth_dialog_controller_impl.h"
68 #include "ash/keyboard/keyboard_controller_impl.h"
69 #include "ash/keyboard/ui/keyboard_ui_factory.h"
70 #include "ash/login/login_screen_controller.h"
71 #include "ash/login_status.h"
72 #include "ash/magnifier/docked_magnifier_controller_impl.h"
73 #include "ash/magnifier/magnification_controller.h"
74 #include "ash/magnifier/partial_magnification_controller.h"
75 #include "ash/media/media_controller_impl.h"
76 #include "ash/media/media_notification_controller_impl.h"
77 #include "ash/multi_device_setup/multi_device_notification_presenter.h"
78 #include "ash/policy/policy_recommendation_restorer.h"
79 #include "ash/power/peripheral_battery_tracker.h"
80 #include "ash/public/cpp/ash_constants.h"
81 #include "ash/public/cpp/ash_features.h"
82 #include "ash/public/cpp/ash_prefs.h"
83 #include "ash/public/cpp/ash_switches.h"
84 #include "ash/public/cpp/holding_space/holding_space_controller.h"
85 #include "ash/public/cpp/nearby_share_delegate.h"
86 #include "ash/public/cpp/shelf_config.h"
87 #include "ash/public/cpp/shelf_model.h"
88 #include "ash/public/cpp/shell_window_ids.h"
89 #include "ash/quick_answers/quick_answers_controller_impl.h"
90 #include "ash/root_window_controller.h"
91 #include "ash/screenshot_delegate.h"
92 #include "ash/session/session_controller_impl.h"
93 #include "ash/shelf/contextual_tooltip.h"
94 #include "ash/shelf/shelf.h"
95 #include "ash/shelf/shelf_controller.h"
96 #include "ash/shelf/shelf_window_watcher.h"
97 #include "ash/shell_delegate.h"
98 #include "ash/shell_init_params.h"
99 #include "ash/shell_observer.h"
100 #include "ash/shell_tab_handler.h"
101 #include "ash/shutdown_controller_impl.h"
102 #include "ash/sticky_keys/sticky_keys_controller.h"
103 #include "ash/style/ash_color_provider.h"
104 #include "ash/system/audio/display_speaker_controller.h"
105 #include "ash/system/bluetooth/bluetooth_notification_controller.h"
106 #include "ash/system/bluetooth/bluetooth_power_controller.h"
107 #include "ash/system/bluetooth/tray_bluetooth_helper_experimental.h"
108 #include "ash/system/bluetooth/tray_bluetooth_helper_legacy.h"
109 #include "ash/system/brightness/brightness_controller_chromeos.h"
110 #include "ash/system/brightness_control_delegate.h"
111 #include "ash/system/caps_lock_notification_controller.h"
112 #include "ash/system/holding_space/holding_space_color_provider_impl.h"
113 #include "ash/system/keyboard_brightness/keyboard_brightness_controller.h"
114 #include "ash/system/keyboard_brightness_control_delegate.h"
115 #include "ash/system/locale/locale_update_controller_impl.h"
116 #include "ash/system/machine_learning/user_settings_event_logger.h"
117 #include "ash/system/message_center/message_center_controller.h"
118 #include "ash/system/model/system_tray_model.h"
119 #include "ash/system/model/virtual_keyboard_model.h"
120 #include "ash/system/nearby_share/nearby_share_controller_impl.h"
121 #include "ash/system/network/sms_observer.h"
122 #include "ash/system/night_light/night_light_controller_impl.h"
123 #include "ash/system/power/backlights_forced_off_setter.h"
124 #include "ash/system/power/peripheral_battery_notifier.h"
125 #include "ash/system/power/power_button_controller.h"
126 #include "ash/system/power/power_event_observer.h"
127 #include "ash/system/power/power_prefs.h"
128 #include "ash/system/power/power_status.h"
129 #include "ash/system/power/video_activity_notifier.h"
130 #include "ash/system/screen_layout_observer.h"
131 #include "ash/system/screen_security/screen_switch_check_controller.h"
132 #include "ash/system/session/logout_confirmation_controller.h"
133 #include "ash/system/status_area_widget.h"
134 #include "ash/system/system_notification_controller.h"
135 #include "ash/system/toast/toast_manager_impl.h"
136 #include "ash/system/tray/system_tray_notifier.h"
137 #include "ash/touch/ash_touch_transform_controller.h"
138 #include "ash/touch/touch_devices_controller.h"
139 #include "ash/tray_action/tray_action.h"
140 #include "ash/utility/screenshot_controller.h"
141 #include "ash/wallpaper/wallpaper_controller_impl.h"
142 #include "ash/wm/ash_focus_rules.h"
143 #include "ash/wm/container_finder.h"
144 #include "ash/wm/cursor_manager_chromeos.h"
145 #include "ash/wm/desks/desks_controller.h"
146 #include "ash/wm/event_client_impl.h"
147 #include "ash/wm/gestures/back_gesture/back_gesture_event_handler.h"
148 #include "ash/wm/immersive_context_ash.h"
149 #include "ash/wm/lock_state_controller.h"
150 #include "ash/wm/mru_window_tracker.h"
151 #include "ash/wm/native_cursor_manager_ash.h"
152 #include "ash/wm/overlay_event_filter.h"
153 #include "ash/wm/overview/overview_controller.h"
154 #include "ash/wm/resize_shadow_controller.h"
155 #include "ash/wm/screen_pinning_controller.h"
156 #include "ash/wm/system_gesture_event_filter.h"
157 #include "ash/wm/system_modal_container_event_filter.h"
158 #include "ash/wm/system_modal_container_layout_manager.h"
159 #include "ash/wm/tablet_mode/tablet_mode_controller.h"
160 #include "ash/wm/tablet_mode/tablet_mode_window_manager.h"
161 #include "ash/wm/toplevel_window_event_handler.h"
162 #include "ash/wm/video_detector.h"
163 #include "ash/wm/window_animations.h"
164 #include "ash/wm/window_cycle_controller.h"
165 #include "ash/wm/window_positioner.h"
166 #include "ash/wm/window_properties.h"
167 #include "ash/wm/window_util.h"
168 #include "ash/wm/wm_shadow_controller_delegate.h"
169 #include "ash/wm/workspace_controller.h"
170 #include "base/bind.h"
171 #include "base/callback_helpers.h"
172 #include "base/check.h"
173 #include "base/command_line.h"
174 #include "base/memory/ptr_util.h"
175 #include "base/notreached.h"
176 #include "base/system/sys_info.h"
177 #include "base/task/post_task.h"
178 #include "base/task/task_traits.h"
179 #include "base/task/thread_pool.h"
180 #include "base/trace_event/trace_event.h"
181 #include "chromeos/components/bloom/public/cpp/bloom_controller.h"
182 #include "chromeos/constants/chromeos_features.h"
183 #include "chromeos/dbus/initialize_dbus_client.h"
184 #include "chromeos/dbus/power/power_policy_controller.h"
185 #include "chromeos/dbus/usb/usbguard_client.h"
186 #include "chromeos/services/assistant/public/cpp/features.h"
187 #include "chromeos/system/devicemode.h"
188 #include "components/prefs/pref_registry_simple.h"
189 #include "components/prefs/pref_service.h"
190 #include "components/viz/host/host_frame_sink_manager.h"
191 #include "dbus/bus.h"
192 #include "media/base/media_switches.h"
193 #include "ui/aura/client/aura_constants.h"
194 #include "ui/aura/env.h"
195 #include "ui/aura/layout_manager.h"
196 #include "ui/aura/window.h"
197 #include "ui/aura/window_event_dispatcher.h"
198 #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h"
199 #include "ui/base/ui_base_features.h"
200 #include "ui/base/ui_base_switches.h"
201 #include "ui/base/user_activity/user_activity_detector.h"
202 #include "ui/chromeos/user_activity_power_manager_notifier.h"
203 #include "ui/compositor/layer.h"
204 #include "ui/compositor/layer_animator.h"
205 #include "ui/display/display.h"
206 #include "ui/display/manager/default_touch_transform_setter.h"
207 #include "ui/display/manager/display_change_observer.h"
208 #include "ui/display/manager/display_configurator.h"
209 #include "ui/display/manager/display_manager.h"
210 #include "ui/display/manager/touch_transform_setter.h"
211 #include "ui/display/screen.h"
212 #include "ui/display/types/native_display_delegate.h"
213 #include "ui/events/event_target_iterator.h"
214 #include "ui/gfx/geometry/insets.h"
215 #include "ui/gfx/image/image_skia.h"
216 #include "ui/message_center/message_center.h"
217 #include "ui/ozone/public/ozone_platform.h"
218 #include "ui/views/corewm/tooltip_aura.h"
219 #include "ui/views/corewm/tooltip_controller.h"
220 #include "ui/views/focus/focus_manager_factory.h"
221 #include "ui/views/widget/native_widget_aura.h"
222 #include "ui/views/widget/widget.h"
223 #include "ui/wm/core/accelerator_filter.h"
224 #include "ui/wm/core/compound_event_filter.h"
225 #include "ui/wm/core/focus_controller.h"
226 #include "ui/wm/core/shadow_controller.h"
227 #include "ui/wm/core/visibility_controller.h"
228 #include "ui/wm/core/window_modality_controller.h"
229 
230 namespace ash {
231 
232 namespace {
233 
234 using aura::Window;
235 using views::Widget;
236 
237 // A Corewm VisibilityController subclass that calls the Ash animation routine
238 // so we can pick up our extended animations. See ash/wm/window_animations.h.
239 class AshVisibilityController : public ::wm::VisibilityController {
240  public:
241   AshVisibilityController() = default;
242   ~AshVisibilityController() override = default;
243 
244  private:
245   // Overridden from ::wm::VisibilityController:
CallAnimateOnChildWindowVisibilityChanged(aura::Window * window,bool visible)246   bool CallAnimateOnChildWindowVisibilityChanged(aura::Window* window,
247                                                  bool visible) override {
248     return AnimateOnChildWindowVisibilityChanged(window, visible);
249   }
250 
251   DISALLOW_COPY_AND_ASSIGN(AshVisibilityController);
252 };
253 
254 }  // namespace
255 
256 // static
257 Shell* Shell::instance_ = nullptr;
258 
259 ////////////////////////////////////////////////////////////////////////////////
260 // Shell, public:
261 
262 // static
CreateInstance(ShellInitParams init_params)263 Shell* Shell::CreateInstance(ShellInitParams init_params) {
264   CHECK(!instance_);
265   instance_ = new Shell(std::move(init_params.delegate));
266   instance_->Init(init_params.context_factory, init_params.local_state,
267                   std::move(init_params.keyboard_ui_factory),
268                   init_params.dbus_bus);
269   return instance_;
270 }
271 
272 // static
Get()273 Shell* Shell::Get() {
274   CHECK(instance_);
275   return instance_;
276 }
277 
278 // static
HasInstance()279 bool Shell::HasInstance() {
280   return !!instance_;
281 }
282 
283 // static
DeleteInstance()284 void Shell::DeleteInstance() {
285   delete instance_;
286 }
287 
288 // static
GetPrimaryRootWindowController()289 RootWindowController* Shell::GetPrimaryRootWindowController() {
290   CHECK(HasInstance());
291   return RootWindowController::ForWindow(GetPrimaryRootWindow());
292 }
293 
294 // static
GetAllRootWindowControllers()295 Shell::RootWindowControllerList Shell::GetAllRootWindowControllers() {
296   CHECK(HasInstance());
297   RootWindowControllerList root_window_controllers;
298   for (aura::Window* root : GetAllRootWindows())
299     root_window_controllers.push_back(RootWindowController::ForWindow(root));
300   return root_window_controllers;
301 }
302 
303 // static
GetRootWindowControllerWithDisplayId(int64_t display_id)304 RootWindowController* Shell::GetRootWindowControllerWithDisplayId(
305     int64_t display_id) {
306   CHECK(HasInstance());
307   aura::Window* root = GetRootWindowForDisplayId(display_id);
308   return root ? RootWindowController::ForWindow(root) : nullptr;
309 }
310 
311 // static
GetRootWindowForDisplayId(int64_t display_id)312 aura::Window* Shell::GetRootWindowForDisplayId(int64_t display_id) {
313   CHECK(HasInstance());
314   return instance_->window_tree_host_manager_->GetRootWindowForDisplayId(
315       display_id);
316 }
317 
318 // static
GetPrimaryRootWindow()319 aura::Window* Shell::GetPrimaryRootWindow() {
320   CHECK(HasInstance());
321   return instance_->window_tree_host_manager_->GetPrimaryRootWindow();
322 }
323 
324 // static
SetRootWindowForNewWindows(aura::Window * root)325 void Shell::SetRootWindowForNewWindows(aura::Window* root) {
326   display::Screen::GetScreen()->SetDisplayForNewWindows(
327       display::Screen::GetScreen()->GetDisplayNearestWindow(root).id());
328 }
329 
330 // static
GetRootWindowForNewWindows()331 aura::Window* Shell::GetRootWindowForNewWindows() {
332   return GetRootWindowForDisplayId(
333       display::Screen::GetScreen()->GetDisplayForNewWindows().id());
334 }
335 
336 // static
GetAllRootWindows()337 aura::Window::Windows Shell::GetAllRootWindows() {
338   CHECK(HasInstance());
339   return instance_->window_tree_host_manager_->GetAllRootWindows();
340 }
341 
342 // static
GetContainer(aura::Window * root_window,int container_id)343 aura::Window* Shell::GetContainer(aura::Window* root_window, int container_id) {
344   return root_window->GetChildById(container_id);
345 }
346 
347 // static
GetContainer(const aura::Window * root_window,int container_id)348 const aura::Window* Shell::GetContainer(const aura::Window* root_window,
349                                         int container_id) {
350   return root_window->GetChildById(container_id);
351 }
352 
353 // static
GetOpenSystemModalWindowContainerId()354 int Shell::GetOpenSystemModalWindowContainerId() {
355   // The test boolean is not static to avoid leaking state between tests.
356   if (Get()->simulate_modal_window_open_for_test_)
357     return kShellWindowId_SystemModalContainer;
358 
359   // Traverse all system modal containers, and find its direct child window
360   // with "SystemModal" setting, and visible.
361   for (aura::Window* root : Shell::GetAllRootWindows()) {
362     for (int modal_window_id : kSystemModalContainerIds) {
363       aura::Window* system_modal = root->GetChildById(modal_window_id);
364       if (!system_modal)
365         continue;
366       for (const aura::Window* child : system_modal->children()) {
367         if (child->GetProperty(aura::client::kModalKey) ==
368                 ui::MODAL_TYPE_SYSTEM &&
369             child->layer()->GetTargetVisibility()) {
370           return modal_window_id;
371         }
372       }
373     }
374   }
375   return -1;
376 }
377 
378 // static
IsSystemModalWindowOpen()379 bool Shell::IsSystemModalWindowOpen() {
380   return GetOpenSystemModalWindowContainerId() >= 0;
381 }
382 
display_configurator()383 display::DisplayConfigurator* Shell::display_configurator() {
384   return display_manager_->configurator();
385 }
386 
TrackInputMethodBounds(ArcInputMethodBoundsTracker * tracker)387 void Shell::TrackInputMethodBounds(ArcInputMethodBoundsTracker* tracker) {
388   system_tray_model()->virtual_keyboard()->SetInputMethodBoundsTrackerObserver(
389       tracker);
390 }
391 
UntrackTrackInputMethodBounds(ArcInputMethodBoundsTracker * tracker)392 void Shell::UntrackTrackInputMethodBounds(
393     ArcInputMethodBoundsTracker* tracker) {
394   system_tray_model()
395       ->virtual_keyboard()
396       ->RemoveInputMethodBoundsTrackerObserver(tracker);
397 }
398 
399 std::unique_ptr<views::NonClientFrameView>
CreateDefaultNonClientFrameView(views::Widget * widget)400 Shell::CreateDefaultNonClientFrameView(views::Widget* widget) {
401   // Use translucent-style window frames for dialogs.
402   return std::make_unique<NonClientFrameViewAsh>(widget);
403 }
404 
SetDisplayWorkAreaInsets(Window * contains,const gfx::Insets & insets)405 void Shell::SetDisplayWorkAreaInsets(Window* contains,
406                                      const gfx::Insets& insets) {
407   window_tree_host_manager_->UpdateWorkAreaOfDisplayNearestWindow(contains,
408                                                                   insets);
409 }
410 
OnCastingSessionStartedOrStopped(bool started)411 void Shell::OnCastingSessionStartedOrStopped(bool started) {
412   for (auto& observer : shell_observers_)
413     observer.OnCastingSessionStartedOrStopped(started);
414 }
415 
OnRootWindowAdded(aura::Window * root_window)416 void Shell::OnRootWindowAdded(aura::Window* root_window) {
417   for (auto& observer : shell_observers_)
418     observer.OnRootWindowAdded(root_window);
419 }
420 
OnDictationStarted()421 void Shell::OnDictationStarted() {
422   for (auto& observer : shell_observers_)
423     observer.OnDictationStarted();
424 }
425 
OnDictationEnded()426 void Shell::OnDictationEnded() {
427   for (auto& observer : shell_observers_)
428     observer.OnDictationEnded();
429 }
430 
IsInTabletMode() const431 bool Shell::IsInTabletMode() const {
432   return tablet_mode_controller()->InTabletMode();
433 }
434 
ShouldSaveDisplaySettings()435 bool Shell::ShouldSaveDisplaySettings() {
436   return !(
437       screen_orientation_controller_->ignore_display_configuration_updates() ||
438       !display_configuration_observer_->save_preference());
439 }
440 
docked_magnifier_controller()441 DockedMagnifierControllerImpl* Shell::docked_magnifier_controller() {
442   return docked_magnifier_controller_.get();
443 }
444 
activation_client()445 ::wm::ActivationClient* Shell::activation_client() {
446   return focus_controller_.get();
447 }
448 
UpdateShelfVisibility()449 void Shell::UpdateShelfVisibility() {
450   for (aura::Window* root : GetAllRootWindows())
451     Shelf::ForWindow(root)->UpdateVisibilityState();
452 }
453 
HasPrimaryStatusArea()454 bool Shell::HasPrimaryStatusArea() {
455   return !!GetPrimaryRootWindowController()->GetStatusAreaWidget();
456 }
457 
SetLargeCursorSizeInDip(int large_cursor_size_in_dip)458 void Shell::SetLargeCursorSizeInDip(int large_cursor_size_in_dip) {
459   window_tree_host_manager_->cursor_window_controller()
460       ->SetLargeCursorSizeInDip(large_cursor_size_in_dip);
461 }
462 
SetCursorColor(SkColor cursor_color)463 void Shell::SetCursorColor(SkColor cursor_color) {
464   window_tree_host_manager_->cursor_window_controller()->SetCursorColor(
465       cursor_color);
466 }
467 
UpdateCursorCompositingEnabled()468 void Shell::UpdateCursorCompositingEnabled() {
469   SetCursorCompositingEnabled(
470       window_tree_host_manager_->cursor_window_controller()
471           ->ShouldEnableCursorCompositing());
472 }
473 
SetCursorCompositingEnabled(bool enabled)474 void Shell::SetCursorCompositingEnabled(bool enabled) {
475   CursorWindowController* cursor_window_controller =
476       window_tree_host_manager_->cursor_window_controller();
477 
478   if (cursor_window_controller->is_cursor_compositing_enabled() == enabled)
479     return;
480   cursor_window_controller->SetCursorCompositingEnabled(enabled);
481   native_cursor_manager_->SetNativeCursorEnabled(!enabled);
482 }
483 
DoInitialWorkspaceAnimation()484 void Shell::DoInitialWorkspaceAnimation() {
485   // Uses the active desk's workspace.
486   auto* workspace = GetActiveWorkspaceController(GetPrimaryRootWindow());
487   DCHECK(workspace);
488   workspace->DoInitialAnimation();
489 }
490 
ShowContextMenu(const gfx::Point & location_in_screen,ui::MenuSourceType source_type)491 void Shell::ShowContextMenu(const gfx::Point& location_in_screen,
492                             ui::MenuSourceType source_type) {
493   // Bail with no active user session, in the lock screen, or in app/kiosk mode.
494   if (session_controller_->NumberOfLoggedInUsers() < 1 ||
495       session_controller_->IsScreenLocked() ||
496       session_controller_->IsRunningInAppMode()) {
497     return;
498   }
499 
500   aura::Window* root = window_util::GetRootWindowAt(location_in_screen);
501   RootWindowController::ForWindow(root)->ShowContextMenu(location_in_screen,
502                                                          source_type);
503 }
504 
AddShellObserver(ShellObserver * observer)505 void Shell::AddShellObserver(ShellObserver* observer) {
506   shell_observers_.AddObserver(observer);
507 }
508 
RemoveShellObserver(ShellObserver * observer)509 void Shell::RemoveShellObserver(ShellObserver* observer) {
510   shell_observers_.RemoveObserver(observer);
511 }
512 
UpdateAfterLoginStatusChange(LoginStatus status)513 void Shell::UpdateAfterLoginStatusChange(LoginStatus status) {
514   for (auto* root_window_controller : GetAllRootWindowControllers())
515     root_window_controller->UpdateAfterLoginStatusChange(status);
516 }
517 
NotifyFullscreenStateChanged(bool is_fullscreen,aura::Window * container)518 void Shell::NotifyFullscreenStateChanged(bool is_fullscreen,
519                                          aura::Window* container) {
520   for (auto& observer : shell_observers_)
521     observer.OnFullscreenStateChanged(is_fullscreen, container);
522 }
523 
NotifyPinnedStateChanged(aura::Window * pinned_window)524 void Shell::NotifyPinnedStateChanged(aura::Window* pinned_window) {
525   for (auto& observer : shell_observers_)
526     observer.OnPinnedStateChanged(pinned_window);
527 }
528 
NotifyUserWorkAreaInsetsChanged(aura::Window * root_window)529 void Shell::NotifyUserWorkAreaInsetsChanged(aura::Window* root_window) {
530   for (auto& observer : shell_observers_)
531     observer.OnUserWorkAreaInsetsChanged(root_window);
532 }
533 
NotifyShelfAlignmentChanged(aura::Window * root_window,ShelfAlignment old_alignment)534 void Shell::NotifyShelfAlignmentChanged(aura::Window* root_window,
535                                         ShelfAlignment old_alignment) {
536   for (auto& observer : shell_observers_)
537     observer.OnShelfAlignmentChanged(root_window, old_alignment);
538 }
539 
NotifyShelfAutoHideBehaviorChanged(aura::Window * root_window)540 void Shell::NotifyShelfAutoHideBehaviorChanged(aura::Window* root_window) {
541   for (auto& observer : shell_observers_)
542     observer.OnShelfAutoHideBehaviorChanged(root_window);
543 }
544 
545 ////////////////////////////////////////////////////////////////////////////////
546 // Shell, private:
547 
Shell(std::unique_ptr<ShellDelegate> shell_delegate)548 Shell::Shell(std::unique_ptr<ShellDelegate> shell_delegate)
549     : brightness_control_delegate_(
550           std::make_unique<system::BrightnessControllerChromeos>()),
551       focus_cycler_(std::make_unique<FocusCycler>()),
552       ime_controller_(std::make_unique<ImeControllerImpl>()),
553       immersive_context_(std::make_unique<ImmersiveContextAsh>()),
554       in_session_auth_dialog_controller_(
555           std::make_unique<InSessionAuthDialogControllerImpl>()),
556       keyboard_brightness_control_delegate_(
557           std::make_unique<KeyboardBrightnessController>()),
558       locale_update_controller_(std::make_unique<LocaleUpdateControllerImpl>()),
559       parent_access_controller_(std::make_unique<ParentAccessControllerImpl>()),
560       session_controller_(std::make_unique<SessionControllerImpl>()),
561       shell_delegate_(std::move(shell_delegate)),
562       shutdown_controller_(std::make_unique<ShutdownControllerImpl>()),
563       system_tray_notifier_(std::make_unique<SystemTrayNotifier>()),
564       window_cycle_controller_(std::make_unique<WindowCycleController>()),
565       native_cursor_manager_(nullptr) {
566   // Ash doesn't properly remove pre-target-handlers.
567   ui::EventHandler::DisableCheckTargets();
568 
569   // AccelerometerReader is important for screen orientation so we need
570   // USER_VISIBLE priority.
571   // Use CONTINUE_ON_SHUTDOWN to avoid blocking shutdown since the data reading
572   // could get blocked on certain devices. See https://crbug.com/1023989.
573   AccelerometerReader::GetInstance()->Initialize(
574       base::ThreadPool::CreateSequencedTaskRunner(
575           {base::MayBlock(), base::TaskPriority::USER_VISIBLE,
576            base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}));
577 
578   login_screen_controller_ =
579       std::make_unique<LoginScreenController>(system_tray_notifier_.get());
580   display_manager_.reset(ScreenAsh::CreateDisplayManager());
581   window_tree_host_manager_ = std::make_unique<WindowTreeHostManager>();
582   user_metrics_recorder_ = std::make_unique<UserMetricsRecorder>();
583   keyboard_controller_ =
584       std::make_unique<KeyboardControllerImpl>(session_controller_.get());
585 
586   if (base::FeatureList::IsEnabled(features::kUseBluetoothSystemInAsh)) {
587     mojo::PendingRemote<device::mojom::BluetoothSystemFactory>
588         bluetooth_system_factory;
589     shell_delegate_->BindBluetoothSystemFactory(
590         bluetooth_system_factory.InitWithNewPipeAndPassReceiver());
591     tray_bluetooth_helper_ = std::make_unique<TrayBluetoothHelperExperimental>(
592         std::move(bluetooth_system_factory));
593   } else {
594     tray_bluetooth_helper_ = std::make_unique<TrayBluetoothHelperLegacy>();
595   }
596 
597   PowerStatus::Initialize();
598 
599   session_controller_->AddObserver(this);
600 }
601 
~Shell()602 Shell::~Shell() {
603   TRACE_EVENT0("shutdown", "ash::Shell::Destructor");
604 
605   hud_display::HUDDisplayView::Destroy();
606 
607   for (auto& observer : shell_observers_)
608     observer.OnShellDestroying();
609 
610   desks_controller_->Shutdown();
611 
612   user_metrics_recorder_->OnShellShuttingDown();
613 
614   cros_display_config_.reset();
615   display_configuration_observer_.reset();
616   display_prefs_.reset();
617   display_alignment_controller_.reset();
618 
619   // Remove the focus from any window. This will prevent overhead and side
620   // effects (e.g. crashes) from changing focus during shutdown.
621   // See bug crbug.com/134502.
622   aura::client::GetFocusClient(GetPrimaryRootWindow())->FocusWindow(nullptr);
623 
624   // Please keep in reverse order as in Init() because it's easy to miss one.
625   if (window_modality_controller_)
626     window_modality_controller_.reset();
627 
628   // We may shutdown while a capture session is active, which is an event
629   // handler that depends on this shell and some of its members. Destroy early.
630   capture_mode_controller_.reset();
631 
632   RemovePreTargetHandler(shell_tab_handler_.get());
633   shell_tab_handler_.reset();
634 
635   RemovePreTargetHandler(magnifier_key_scroll_handler_.get());
636   magnifier_key_scroll_handler_.reset();
637 
638   RemovePreTargetHandler(speech_feedback_handler_.get());
639   speech_feedback_handler_.reset();
640 
641   RemovePreTargetHandler(overlay_filter_.get());
642   overlay_filter_.reset();
643 
644   RemovePreTargetHandler(accelerator_filter_.get());
645   RemovePreTargetHandler(event_transformation_handler_.get());
646   if (back_gesture_event_handler_)
647     RemovePreTargetHandler(back_gesture_event_handler_.get());
648   RemovePreTargetHandler(toplevel_window_event_handler_.get());
649   RemovePostTargetHandler(toplevel_window_event_handler_.get());
650   RemovePreTargetHandler(system_gesture_filter_.get());
651   RemovePreTargetHandler(mouse_cursor_filter_.get());
652   RemovePreTargetHandler(modality_filter_.get());
653   RemovePreTargetHandler(tooltip_controller_.get());
654 
655   event_rewriter_controller_.reset();
656 
657   screen_orientation_controller_.reset();
658   screen_layout_observer_.reset();
659 
660   quick_answers_controller_.reset();
661 
662   // Destroy the virtual keyboard controller before the tablet mode controller
663   // since the latters destructor triggers events that the former is listening
664   // to but no longer cares about.
665   keyboard_controller_->DestroyVirtualKeyboard();
666 
667   // Depends on |tablet_mode_controller_|.
668   shelf_controller_->Shutdown();
669   shelf_config_->Shutdown();
670 
671   // Destroy |home_screen_controller_| before |app_list_controller_| since
672   // the former delegates to the latter.
673   home_screen_controller_.reset();
674 
675   // Destroy |app_list_controller_| earlier than |tablet_mode_controller_| since
676   // the former may use the latter before destruction.
677   app_list_controller_.reset();
678 
679   // Accelerometer file reader stops listening to tablet mode controller.
680   AccelerometerReader::GetInstance()->StopListenToTabletModeController();
681 
682   // Destroy |ambient_controller_| before |assistant_controller_|.
683   ambient_controller_.reset();
684 
685   // Destroy |assistant_controller_| earlier than |tablet_mode_controller_| so
686   // that the former will destroy the Assistant view hierarchy which has a
687   // dependency on the latter.
688   assistant_controller_.reset();
689 
690   // Because this function will call |TabletModeController::RemoveObserver|, do
691   // it before destroying |tablet_mode_controller_|.
692   accessibility_controller_->Shutdown();
693 
694   // Shutdown tablet mode controller early on since it has some observers which
695   // need to be removed. It will be destroyed later after all windows are closed
696   // since it might be accessed during this process.
697   tablet_mode_controller_->Shutdown();
698 
699   // Destroy UserSettingsEventLogger before |system_tray_model_| and
700   // |video_detector_| which it observes.
701   ml::UserSettingsEventLogger::DeleteInstance();
702 
703   toast_manager_.reset();
704 
705   tray_bluetooth_helper_.reset();
706 
707   // Accesses root window containers.
708   logout_confirmation_controller_.reset();
709 
710   // Drag-and-drop must be canceled prior to close all windows.
711   for (aura::Window* root : GetAllRootWindows())
712     aura::client::SetDragDropClient(root, nullptr);
713   drag_drop_controller_.reset();
714 
715   // Controllers who have WindowObserver added must be deleted
716   // before |window_tree_host_manager_| is deleted.
717   persistent_window_controller_.reset();
718 
719   display_highlight_controller_.reset();
720 
721   // VideoActivityNotifier must be deleted before |video_detector_| is
722   // deleted because it's observing video activity through
723   // VideoDetector::Observer interface.
724   video_activity_notifier_.reset();
725   video_detector_.reset();
726   high_contrast_controller_.reset();
727 
728   shadow_controller_.reset();
729   resize_shadow_controller_.reset();
730 
731   // Has to happen before ~MruWindowTracker.
732   window_cycle_controller_.reset();
733   overview_controller_.reset();
734 
735   // Stop dispatching events (e.g. synthesized mouse exits from window close).
736   // https://crbug.com/874156
737   for (RootWindowController* rwc : GetAllRootWindowControllers())
738     rwc->GetHost()->dispatcher()->Shutdown();
739 
740   // Close all widgets (including the shelf) and destroy all window containers.
741   CloseAllRootWindowChildWindows();
742 
743   tablet_mode_controller_.reset();
744   login_screen_controller_.reset();
745   system_notification_controller_.reset();
746   // Should be destroyed after Shelf and |system_notification_controller_|.
747   system_tray_model_.reset();
748 
749   // MruWindowTracker must be destroyed after all windows have been deleted to
750   // avoid a possible crash when Shell is destroyed from a non-normal shutdown
751   // path. (crbug.com/485438).
752   mru_window_tracker_.reset();
753 
754   // These need a valid Shell instance to clean up properly, so explicitly
755   // delete them before invalidating the instance.
756   // Alphabetical. TODO(oshima): sort.
757   autoclick_controller_.reset();
758   magnification_controller_.reset();
759   tooltip_controller_.reset();
760   event_client_.reset();
761   toplevel_window_event_handler_.reset();
762   visibility_controller_.reset();
763   power_prefs_.reset();
764 
765   tray_action_.reset();
766 
767   power_button_controller_.reset();
768   lock_state_controller_.reset();
769   backlights_forced_off_setter_.reset();
770 
771   screen_pinning_controller_.reset();
772 
773   multidevice_notification_presenter_.reset();
774   resolution_notification_controller_.reset();
775   screenshot_controller_.reset();
776   mouse_cursor_filter_.reset();
777   modality_filter_.reset();
778 
779   touch_transformer_controller_.reset();
780   laser_pointer_controller_.reset();
781   partial_magnification_controller_.reset();
782   highlighter_controller_.reset();
783   key_accessibility_enabler_.reset();
784 
785   display_speaker_controller_.reset();
786   screen_switch_check_controller_.reset();
787 
788   ScreenAsh::CreateScreenForShutdown();
789   display_configuration_controller_.reset();
790 
791   // These members access Shell in their destructors.
792   wallpaper_controller_.reset();
793   accessibility_controller_.reset();
794   accessibility_delegate_.reset();
795   accessibility_focus_ring_controller_.reset();
796   policy_recommendation_restorer_.reset();
797   ime_controller_.reset();
798   back_gesture_event_handler_.reset();
799 
800   // Balances the Install() in Initialize().
801   views::FocusManagerFactory::Install(nullptr);
802 
803   // ShelfWindowWatcher has window observers and a pointer to the shelf model.
804   shelf_window_watcher_.reset();
805 
806   // Removes itself as an observer of |pref_service_|.
807   shelf_controller_.reset();
808 
809   // NightLightControllerImpl depends on the PrefService as well as the window
810   // tree host manager, and must be destructed before them. crbug.com/724231.
811   night_light_controller_ = nullptr;
812   // Similarly for DockedMagnifierControllerImpl.
813   docked_magnifier_controller_ = nullptr;
814   // Similarly for PrivacyScreenController.
815   privacy_screen_controller_ = nullptr;
816 
817   // NearbyShareDelegateImpl must be destroyed before SessionController and
818   // NearbyShareControllerImpl.
819   nearby_share_delegate_.reset();
820   nearby_share_controller_.reset();
821 
822   // Stop observing window activation changes before closing all windows.
823   focus_controller_->RemoveObserver(this);
824 
825   // Depends on shelf owned by RootWindowController so destroy this before the
826   // |window_tree_host_manager_|.
827   clipboard_history_controller_.reset();
828 
829   // This also deletes all RootWindows. Note that we invoke Shutdown() on
830   // WindowTreeHostManager before resetting |window_tree_host_manager_|, since
831   // destruction of its owned RootWindowControllers relies on the value.
832   window_tree_host_manager_->Shutdown();
833 
834   // Depends on |focus_controller_|, so must be destroyed before.
835   window_tree_host_manager_.reset();
836 
837   // The desks controller is destroyed after the window tree host manager and
838   // before the focus controller. At this point it is guaranteed that querying
839   // the active desk is no longer needed.
840   desks_controller_.reset();
841 
842   focus_rules_ = nullptr;
843   focus_controller_.reset();
844   screen_position_controller_.reset();
845 
846   display_color_manager_.reset();
847   projecting_observer_.reset();
848 
849   if (display_change_observer_)
850     display_manager_->configurator()->RemoveObserver(
851         display_change_observer_.get());
852   if (display_error_observer_)
853     display_manager_->configurator()->RemoveObserver(
854         display_error_observer_.get());
855   display_change_observer_.reset();
856   display_shutdown_observer_.reset();
857 
858   keyboard_controller_.reset();
859 
860   PowerStatus::Shutdown();
861   // Depends on SessionController.
862   power_event_observer_.reset();
863 
864   session_controller_->RemoveObserver(this);
865   // BluetoothPowerController depends on the PrefService and must be destructed
866   // before it.
867   bluetooth_power_controller_ = nullptr;
868   // TouchDevicesController depends on the PrefService and must be destructed
869   // before it.
870   touch_devices_controller_ = nullptr;
871   // DetachableBaseNotificationController depends on DetachableBaseHandler, and
872   // has to be destructed before it.
873   detachable_base_notification_controller_.reset();
874   // DetachableBaseHandler depends on the PrefService and must be destructed
875   // before it.
876   detachable_base_handler_.reset();
877 
878   // MediaNotificationControllerImpl depends on MessageCenter and must be
879   // destructed before it.
880   media_notification_controller_.reset();
881 
882   // Destroys the MessageCenter singleton, so must happen late.
883   message_center_controller_.reset();
884 
885   // `HoldingSpaceController` observes `SessionController` and must be
886   // destructed before it.
887   holding_space_controller_.reset();
888 
889   ash_color_provider_.reset();
890 
891   shell_delegate_.reset();
892 
893   chromeos::UsbguardClient::Shutdown();
894 
895   // Must be shut down after detachable_base_handler_.
896   chromeos::HammerdClient::Shutdown();
897 
898   for (auto& observer : shell_observers_)
899     observer.OnShellDestroyed();
900 
901   DCHECK(instance_ == this);
902   instance_ = nullptr;
903 }
904 
Init(ui::ContextFactory * context_factory,PrefService * local_state,std::unique_ptr<keyboard::KeyboardUIFactory> keyboard_ui_factory,scoped_refptr<dbus::Bus> dbus_bus)905 void Shell::Init(
906     ui::ContextFactory* context_factory,
907     PrefService* local_state,
908     std::unique_ptr<keyboard::KeyboardUIFactory> keyboard_ui_factory,
909     scoped_refptr<dbus::Bus> dbus_bus) {
910   // Required by DetachableBaseHandler.
911   chromeos::InitializeDBusClient<chromeos::HammerdClient>(dbus_bus.get());
912 
913   chromeos::InitializeDBusClient<chromeos::UsbguardClient>(dbus_bus.get());
914 
915   local_state_ = local_state;
916 
917   // This creates the MessageCenter object which is used by some other objects
918   // initialized here, so it needs to come early.
919   message_center_controller_ = std::make_unique<MessageCenterController>();
920 
921   // These controllers call Shell::Get() in their constructors, so they cannot
922   // be in the member initialization list.
923   touch_devices_controller_ = std::make_unique<TouchDevicesController>();
924   bluetooth_power_controller_ =
925       std::make_unique<BluetoothPowerController>(local_state_);
926   detachable_base_handler_ =
927       std::make_unique<DetachableBaseHandler>(local_state_);
928   detachable_base_notification_controller_ =
929       std::make_unique<DetachableBaseNotificationController>(
930           detachable_base_handler_.get());
931   display_speaker_controller_ = std::make_unique<DisplaySpeakerController>();
932   policy_recommendation_restorer_ =
933       std::make_unique<PolicyRecommendationRestorer>();
934   screen_switch_check_controller_ =
935       std::make_unique<ScreenSwitchCheckController>();
936   multidevice_notification_presenter_ =
937       std::make_unique<MultiDeviceNotificationPresenter>(
938           message_center::MessageCenter::Get());
939   media_controller_ = std::make_unique<MediaControllerImpl>();
940 
941   tablet_mode_controller_ = std::make_unique<TabletModeController>();
942 
943   accessibility_focus_ring_controller_ =
944       std::make_unique<AccessibilityFocusRingControllerImpl>();
945   accessibility_delegate_.reset(shell_delegate_->CreateAccessibilityDelegate());
946   accessibility_controller_ = std::make_unique<AccessibilityControllerImpl>();
947   toast_manager_ = std::make_unique<ToastManagerImpl>();
948 
949   if (features::IsCaptureModeEnabled()) {
950     capture_mode_controller_ = std::make_unique<CaptureModeController>(
951         shell_delegate_->CreateCaptureModeDelegate());
952   }
953 
954   // Accelerometer file reader starts listening to tablet mode controller.
955   AccelerometerReader::GetInstance()->StartListenToTabletModeController();
956 
957   // Install the custom factory early on so that views::FocusManagers for Tray,
958   // Shelf, and WallPaper could be created by the factory.
959   views::FocusManagerFactory::Install(new AshFocusManagerFactory);
960 
961   wallpaper_controller_ =
962       std::make_unique<WallpaperControllerImpl>(local_state_);
963 
964   window_positioner_ = std::make_unique<WindowPositioner>();
965 
966   native_cursor_manager_ = new NativeCursorManagerAsh;
967   cursor_manager_ =
968       std::make_unique<CursorManager>(base::WrapUnique(native_cursor_manager_));
969 
970   InitializeDisplayManager();
971 
972   // RefreshFontParams depends on display prefs.
973   display_manager_->RefreshFontParams();
974 
975   // This will initialize aura::Env which requires |display_manager_| to
976   // be initialized first.
977   aura::Env* env = aura::Env::GetInstance();
978   if (context_factory)
979     env->set_context_factory(context_factory);
980 
981   ash_color_provider_ = std::make_unique<AshColorProvider>();
982 
983   // Night Light depends on the display manager, the display color manager, and
984   // aura::Env, so initialize it after all have been initialized.
985   night_light_controller_ = std::make_unique<NightLightControllerImpl>();
986 
987   // Privacy Screen depends on the display manager, so initialize it after
988   // display manager was properly initialized.
989   privacy_screen_controller_ = std::make_unique<PrivacyScreenController>();
990 
991   // The WindowModalityController needs to be at the front of the input event
992   // pretarget handler list to ensure that it processes input events when modal
993   // windows are active.
994   window_modality_controller_ =
995       std::make_unique<::wm::WindowModalityController>(this, env);
996 
997   event_rewriter_controller_ = std::make_unique<EventRewriterControllerImpl>();
998 
999   env_filter_ = std::make_unique<::wm::CompoundEventFilter>();
1000   AddPreTargetHandler(env_filter_.get());
1001 
1002   // FocusController takes ownership of AshFocusRules.
1003   focus_rules_ = new AshFocusRules();
1004   focus_controller_ = std::make_unique<::wm::FocusController>(focus_rules_);
1005   focus_controller_->AddObserver(this);
1006 
1007   overview_controller_ = std::make_unique<OverviewController>();
1008 
1009   screen_position_controller_ = std::make_unique<ScreenPositionController>();
1010 
1011   window_tree_host_manager_->Start();
1012   AshWindowTreeHostInitParams ash_init_params;
1013   window_tree_host_manager_->CreatePrimaryHost(ash_init_params);
1014 
1015   // Create the desks controller right after the window tree host manager is
1016   // started, and before anything else is created, including the initialization
1017   // of the hosts and the root window controllers. Many things may need to query
1018   // the active desk, even at this early stage. For this the controller must be
1019   // present at all times. The desks controller also depends on the focus
1020   // controller.
1021   desks_controller_ = std::make_unique<DesksController>();
1022 
1023   Shell::SetRootWindowForNewWindows(GetPrimaryRootWindow());
1024 
1025   resolution_notification_controller_ =
1026       std::make_unique<ResolutionNotificationController>();
1027 
1028   cursor_manager_->SetDisplay(
1029       display::Screen::GetScreen()->GetPrimaryDisplay());
1030 
1031   accelerator_controller_ = std::make_unique<AcceleratorControllerImpl>();
1032   if (chromeos::features::IsClipboardHistoryEnabled()) {
1033     clipboard_history_controller_ =
1034         std::make_unique<ClipboardHistoryControllerImpl>();
1035     clipboard_history_controller_->Init();
1036   }
1037 
1038   // `HoldingSpaceController` must be instantiated before the shelf.
1039   if (features::IsTemporaryHoldingSpaceEnabled()) {
1040     holding_space_controller_ = std::make_unique<HoldingSpaceController>(
1041         std::make_unique<HoldingSpaceColorProviderImpl>());
1042   }
1043 
1044   shelf_config_ = std::make_unique<ShelfConfig>();
1045   shelf_controller_ = std::make_unique<ShelfController>();
1046 
1047   shell_tab_handler_ = std::make_unique<ShellTabHandler>(this);
1048   AddPreTargetHandler(shell_tab_handler_.get());
1049   magnifier_key_scroll_handler_ = MagnifierKeyScroller::CreateHandler();
1050   AddPreTargetHandler(magnifier_key_scroll_handler_.get());
1051   speech_feedback_handler_ = SpokenFeedbackToggler::CreateHandler();
1052   AddPreTargetHandler(speech_feedback_handler_.get());
1053 
1054   // The order in which event filters are added is significant.
1055 
1056   // ui::UserActivityDetector passes events to observers, so let them get
1057   // rewritten first.
1058   user_activity_detector_.reset(new ui::UserActivityDetector);
1059 
1060   overlay_filter_.reset(new OverlayEventFilter);
1061   AddPreTargetHandler(overlay_filter_.get());
1062 
1063   accelerator_filter_.reset(new ::wm::AcceleratorFilter(
1064       std::make_unique<PreTargetAcceleratorHandler>(),
1065       accelerator_controller_->accelerator_history()));
1066   AddPreTargetHandler(accelerator_filter_.get());
1067 
1068   event_transformation_handler_.reset(new EventTransformationHandler);
1069   AddPreTargetHandler(event_transformation_handler_.get());
1070 
1071   back_gesture_event_handler_ = std::make_unique<BackGestureEventHandler>();
1072   AddPreTargetHandler(back_gesture_event_handler_.get());
1073 
1074   toplevel_window_event_handler_ =
1075       std::make_unique<ToplevelWindowEventHandler>();
1076 
1077   system_gesture_filter_ = std::make_unique<SystemGestureEventFilter>();
1078   AddPreTargetHandler(system_gesture_filter_.get());
1079 
1080   sticky_keys_controller_.reset(new StickyKeysController);
1081   screen_pinning_controller_ = std::make_unique<ScreenPinningController>();
1082 
1083   power_prefs_ = std::make_unique<PowerPrefs>(
1084       chromeos::PowerPolicyController::Get(),
1085       chromeos::PowerManagerClient::Get(), local_state_);
1086 
1087   backlights_forced_off_setter_ = std::make_unique<BacklightsForcedOffSetter>();
1088 
1089   tray_action_ =
1090       std::make_unique<TrayAction>(backlights_forced_off_setter_.get());
1091 
1092   lock_state_controller_ =
1093       std::make_unique<LockStateController>(shutdown_controller_.get());
1094   power_button_controller_ = std::make_unique<PowerButtonController>(
1095       backlights_forced_off_setter_.get());
1096   // Pass the initial display state to PowerButtonController.
1097   power_button_controller_->OnDisplayModeChanged(
1098       display_configurator()->cached_displays());
1099 
1100   drag_drop_controller_ = std::make_unique<DragDropController>();
1101 
1102   // |screenshot_controller_| needs to be created (and prepended as a
1103   // pre-target handler) at this point, because |mouse_cursor_filter_| needs to
1104   // process mouse events prior to screenshot session.
1105   // See http://crbug.com/459214
1106   screenshot_controller_ = std::make_unique<ScreenshotController>(
1107       shell_delegate_->CreateScreenshotDelegate());
1108   mouse_cursor_filter_ = std::make_unique<MouseCursorEventFilter>();
1109   AddPreTargetHandler(mouse_cursor_filter_.get(),
1110                       ui::EventTarget::Priority::kAccessibility);
1111 
1112   // Create Controllers that may need root window.
1113   // TODO(oshima): Move as many controllers before creating
1114   // RootWindowController as possible.
1115   visibility_controller_.reset(new AshVisibilityController);
1116 
1117   laser_pointer_controller_.reset(new LaserPointerController());
1118   partial_magnification_controller_.reset(new PartialMagnificationController());
1119   highlighter_controller_.reset(new HighlighterController());
1120 
1121   magnification_controller_ = std::make_unique<MagnificationController>();
1122   mru_window_tracker_ = std::make_unique<MruWindowTracker>();
1123   assistant_controller_ = std::make_unique<AssistantControllerImpl>();
1124   if (chromeos::features::IsQuickAnswersEnabled()) {
1125     quick_answers_controller_ = std::make_unique<QuickAnswersControllerImpl>();
1126   }
1127 
1128   // |assistant_controller_| is put before |ambient_controller_| as it will be
1129   // used by the latter.
1130   if (chromeos::features::IsAmbientModeEnabled()) {
1131     mojo::PendingRemote<device::mojom::Fingerprint> fingerprint;
1132     shell_delegate_->BindFingerprint(
1133         fingerprint.InitWithNewPipeAndPassReceiver());
1134     ambient_controller_ =
1135         std::make_unique<AmbientController>(std::move(fingerprint));
1136   }
1137 
1138   if (chromeos::assistant::features::IsBloomEnabled())
1139     bloom_ui_controller_ = std::make_unique<BloomUiControllerImpl>();
1140 
1141   home_screen_controller_ = std::make_unique<HomeScreenController>();
1142 
1143   // |tablet_mode_controller_| |mru_window_tracker_|,
1144   // |assistant_controller_| and |home_screen_controller_| are put before
1145   // |app_list_controller_| as they are used in its constructor.
1146   app_list_controller_ = std::make_unique<AppListControllerImpl>();
1147   home_screen_controller_->SetDelegate(app_list_controller_.get());
1148 
1149   autoclick_controller_ = std::make_unique<AutoclickController>();
1150 
1151   high_contrast_controller_.reset(new HighContrastController);
1152 
1153   docked_magnifier_controller_ =
1154       std::make_unique<DockedMagnifierControllerImpl>();
1155 
1156   video_detector_ = std::make_unique<VideoDetector>();
1157 
1158   tooltip_controller_.reset(new views::corewm::TooltipController(
1159       std::unique_ptr<views::corewm::Tooltip>(new views::corewm::TooltipAura)));
1160   AddPreTargetHandler(tooltip_controller_.get());
1161 
1162   modality_filter_.reset(new SystemModalContainerEventFilter(this));
1163   AddPreTargetHandler(modality_filter_.get());
1164 
1165   event_client_.reset(new EventClientImpl);
1166 
1167   resize_shadow_controller_.reset(new ResizeShadowController());
1168   shadow_controller_ = std::make_unique<::wm::ShadowController>(
1169       focus_controller_.get(), std::make_unique<WmShadowControllerDelegate>(),
1170       env);
1171 
1172   logout_confirmation_controller_ =
1173       std::make_unique<LogoutConfirmationController>();
1174 
1175   // May trigger initialization of the Bluetooth adapter.
1176   tray_bluetooth_helper_->Initialize();
1177 
1178   // Create AshTouchTransformController before
1179   // WindowTreeHostManager::InitDisplays()
1180   // since AshTouchTransformController listens on
1181   // WindowTreeHostManager::Observer::OnDisplaysInitialized().
1182   touch_transformer_controller_ = std::make_unique<AshTouchTransformController>(
1183       display_manager_.get(),
1184       std::make_unique<display::DefaultTouchTransformSetter>());
1185 
1186   // |system_tray_model_| should be available before
1187   // |system_notification_controller_| is initialized and Shelf is created by
1188   // WindowTreeHostManager::InitHosts.
1189   system_tray_model_ = std::make_unique<SystemTrayModel>();
1190 
1191   // The |shelf_config_| needs |app_list_controller_| and |system_tray_model_|
1192   // to initialize itself.
1193   shelf_config_->Init();
1194 
1195   nearby_share_controller_ = std::make_unique<NearbyShareControllerImpl>();
1196   nearby_share_delegate_ = shell_delegate_->CreateNearbyShareDelegate(
1197       nearby_share_controller_.get());
1198 
1199   system_notification_controller_ =
1200       std::make_unique<SystemNotificationController>();
1201 
1202   window_tree_host_manager_->InitHosts();
1203 
1204   // Create virtual keyboard after WindowTreeHostManager::InitHosts() since
1205   // it may enable the virtual keyboard immediately, which requires a
1206   // WindowTreeHostManager to host the keyboard window.
1207   keyboard_controller_->CreateVirtualKeyboard(std::move(keyboard_ui_factory));
1208 
1209   cursor_manager_->HideCursor();  // Hide the mouse cursor on startup.
1210   cursor_manager_->SetCursor(ui::mojom::CursorType::kPointer);
1211 
1212   peripheral_battery_notifier_ = std::make_unique<PeripheralBatteryNotifier>();
1213   if (base::FeatureList::IsEnabled(
1214           chromeos::features::kShowBluetoothDeviceBattery)) {
1215     peripheral_battery_tracker_ = std::make_unique<PeripheralBatteryTracker>();
1216   }
1217   power_event_observer_.reset(new PowerEventObserver());
1218 
1219   mojo::PendingRemote<device::mojom::Fingerprint> fingerprint;
1220   shell_delegate_->BindFingerprint(
1221       fingerprint.InitWithNewPipeAndPassReceiver());
1222   user_activity_notifier_ =
1223       std::make_unique<ui::UserActivityPowerManagerNotifier>(
1224           user_activity_detector_.get(), std::move(fingerprint));
1225   video_activity_notifier_.reset(
1226       new VideoActivityNotifier(video_detector_.get()));
1227   bluetooth_notification_controller_ =
1228       std::make_unique<BluetoothNotificationController>(
1229           message_center::MessageCenter::Get());
1230   screen_orientation_controller_ =
1231       std::make_unique<ScreenOrientationController>();
1232 
1233   cros_display_config_ = std::make_unique<CrosDisplayConfig>();
1234 
1235   screen_layout_observer_.reset(new ScreenLayoutObserver());
1236   sms_observer_.reset(new SmsObserver());
1237   snap_controller_ = std::make_unique<SnapControllerImpl>();
1238   key_accessibility_enabler_ = std::make_unique<KeyAccessibilityEnabler>();
1239   frame_throttling_controller_ =
1240       std::make_unique<FrameThrottlingController>(context_factory);
1241 
1242   // Create UserSettingsEventLogger after |system_tray_model_| and
1243   // |video_detector_| which it observes.
1244   ml::UserSettingsEventLogger::CreateInstance();
1245 
1246   // The compositor thread and main message loop have to be running in
1247   // order to create mirror window. Run it after the main message loop
1248   // is started.
1249   display_manager_->CreateMirrorWindowAsyncIfAny();
1250 
1251   if (base::FeatureList::IsEnabled(features::kMediaSessionNotification) &&
1252       !base::FeatureList::IsEnabled(media::kGlobalMediaControlsForChromeOS)) {
1253     media_notification_controller_ =
1254         std::make_unique<MediaNotificationControllerImpl>();
1255   }
1256 
1257   // TODO(1091497): Consider combining DisplayHighlightController and
1258   // DisplayAlignmentController.
1259   if (features::IsDisplayIdentificationEnabled()) {
1260     display_highlight_controller_ =
1261         std::make_unique<DisplayHighlightController>();
1262   }
1263 
1264   if (features::IsDisplayAlignmentAssistanceEnabled()) {
1265     display_alignment_controller_ =
1266         std::make_unique<DisplayAlignmentController>();
1267   }
1268 
1269   for (auto& observer : shell_observers_)
1270     observer.OnShellInitialized();
1271 
1272   user_metrics_recorder_->OnShellInitialized();
1273 
1274   // Initialize the D-Bus bus and services for ash.
1275   dbus_bus_ = dbus_bus;
1276   ash_dbus_services_ = std::make_unique<AshDBusServices>(dbus_bus.get());
1277 
1278   // By this point ash shell should have initialized its D-Bus signal
1279   // listeners, so inform the session manager that Ash is initialized.
1280   session_controller_->EmitAshInitialized();
1281 }
1282 
InitializeDisplayManager()1283 void Shell::InitializeDisplayManager() {
1284   display_manager_->InitConfigurator(
1285       ui::OzonePlatform::GetInstance()->CreateNativeDisplayDelegate());
1286   display_configuration_controller_ =
1287       std::make_unique<DisplayConfigurationController>(
1288           display_manager_.get(), window_tree_host_manager_.get());
1289   display_configuration_observer_ =
1290       std::make_unique<DisplayConfigurationObserver>();
1291 
1292   persistent_window_controller_ =
1293       std::make_unique<PersistentWindowController>();
1294 
1295   projecting_observer_ =
1296       std::make_unique<ProjectingObserver>(display_manager_->configurator());
1297 
1298   display_prefs_ = std::make_unique<DisplayPrefs>(local_state_);
1299 
1300   bool display_initialized = display_manager_->InitFromCommandLine();
1301 
1302   if (!display_initialized) {
1303     if (chromeos::IsRunningAsSystemCompositor()) {
1304       display_change_observer_ =
1305           std::make_unique<display::DisplayChangeObserver>(
1306               display_manager_.get());
1307 
1308       display_error_observer_ = std::make_unique<DisplayErrorObserver>();
1309       display_shutdown_observer_ = std::make_unique<DisplayShutdownObserver>(
1310           display_manager_->configurator());
1311 
1312       display_manager_->ForceInitialConfigureWithObservers(
1313           display_change_observer_.get(), display_error_observer_.get());
1314       display_initialized = true;
1315     }
1316   }
1317 
1318   display_color_manager_ = std::make_unique<DisplayColorManager>(
1319       display_manager_->configurator(), display::Screen::GetScreen());
1320 
1321   if (!display_initialized)
1322     display_manager_->InitDefaultDisplay();
1323 }
1324 
InitRootWindow(aura::Window * root_window)1325 void Shell::InitRootWindow(aura::Window* root_window) {
1326   DCHECK(focus_controller_);
1327   DCHECK(visibility_controller_.get());
1328 
1329   aura::client::SetFocusClient(root_window, focus_controller_.get());
1330   ::wm::SetActivationClient(root_window, focus_controller_.get());
1331   root_window->AddPreTargetHandler(focus_controller_.get());
1332   aura::client::SetVisibilityClient(root_window, visibility_controller_.get());
1333   aura::client::SetDragDropClient(root_window, drag_drop_controller_.get());
1334   aura::client::SetScreenPositionClient(root_window,
1335                                         screen_position_controller_.get());
1336   aura::client::SetCursorClient(root_window, cursor_manager_.get());
1337   ::wm::SetTooltipClient(root_window, tooltip_controller_.get());
1338   aura::client::SetEventClient(root_window, event_client_.get());
1339 
1340   ::wm::SetWindowMoveClient(root_window, toplevel_window_event_handler_.get());
1341   root_window->AddPreTargetHandler(toplevel_window_event_handler_.get());
1342   root_window->AddPostTargetHandler(toplevel_window_event_handler_.get());
1343 }
1344 
CloseAllRootWindowChildWindows()1345 void Shell::CloseAllRootWindowChildWindows() {
1346   for (aura::Window* root : GetAllRootWindows()) {
1347     RootWindowController* controller = RootWindowController::ForWindow(root);
1348     if (controller) {
1349       controller->CloseChildWindows();
1350     } else {
1351       while (!root->children().empty()) {
1352         aura::Window* child = root->children()[0];
1353         delete child;
1354       }
1355     }
1356   }
1357 }
1358 
CanWindowReceiveEvents(aura::Window * window)1359 bool Shell::CanWindowReceiveEvents(aura::Window* window) {
1360   RootWindowControllerList controllers = GetAllRootWindowControllers();
1361   for (RootWindowController* controller : controllers) {
1362     if (controller->CanWindowReceiveEvents(window))
1363       return true;
1364   }
1365   return false;
1366 }
1367 
1368 ////////////////////////////////////////////////////////////////////////////////
1369 // Shell, ui::EventTarget overrides:
1370 
CanAcceptEvent(const ui::Event & event)1371 bool Shell::CanAcceptEvent(const ui::Event& event) {
1372   return true;
1373 }
1374 
GetParentTarget()1375 ui::EventTarget* Shell::GetParentTarget() {
1376   return aura::Env::GetInstance();
1377 }
1378 
GetChildIterator() const1379 std::unique_ptr<ui::EventTargetIterator> Shell::GetChildIterator() const {
1380   return std::unique_ptr<ui::EventTargetIterator>();
1381 }
1382 
GetEventTargeter()1383 ui::EventTargeter* Shell::GetEventTargeter() {
1384   NOTREACHED();
1385   return nullptr;
1386 }
1387 
OnWindowActivated(::wm::ActivationChangeObserver::ActivationReason reason,aura::Window * gained_active,aura::Window * lost_active)1388 void Shell::OnWindowActivated(
1389     ::wm::ActivationChangeObserver::ActivationReason reason,
1390     aura::Window* gained_active,
1391     aura::Window* lost_active) {
1392   if (!gained_active)
1393     return;
1394 
1395   Shell::SetRootWindowForNewWindows(gained_active->GetRootWindow());
1396 }
1397 
OnFirstSessionStarted()1398 void Shell::OnFirstSessionStarted() {
1399   // Enable magnifier scroll keys as there may be no mouse cursor in kiosk mode.
1400   MagnifierKeyScroller::SetEnabled(session_controller_->IsRunningInAppMode());
1401 
1402   // Enable long press action to toggle spoken feedback with hotrod remote
1403   // which can't handle shortcuts.
1404   SpokenFeedbackToggler::SetEnabled(session_controller_->IsRunningInAppMode());
1405 
1406   // Reset user prefs related to contextual tooltips.
1407   if (switches::ContextualNudgesResetShownCount())
1408     contextual_tooltip::ClearPrefs();
1409 }
1410 
OnSessionStateChanged(session_manager::SessionState state)1411 void Shell::OnSessionStateChanged(session_manager::SessionState state) {
1412   const bool is_session_active = state == session_manager::SessionState::ACTIVE;
1413   // Initialize the |shelf_window_watcher_| when a session becomes active.
1414   // Shelf itself is initialized in RootWindowController.
1415   if (is_session_active && !shelf_window_watcher_) {
1416     shelf_window_watcher_ =
1417         std::make_unique<ShelfWindowWatcher>(shelf_controller()->model());
1418   }
1419 
1420   // Disable drag-and-drop during OOBE and GAIA login screens by only enabling
1421   // the controller when the session is active. https://crbug.com/464118
1422   drag_drop_controller_->set_enabled(is_session_active);
1423 }
1424 
OnLoginStatusChanged(LoginStatus login_status)1425 void Shell::OnLoginStatusChanged(LoginStatus login_status) {
1426   UpdateAfterLoginStatusChange(login_status);
1427 }
1428 
OnLockStateChanged(bool locked)1429 void Shell::OnLockStateChanged(bool locked) {
1430 #ifndef NDEBUG
1431   // Make sure that there is no system modal in Lock layer when unlocked.
1432   if (!locked) {
1433     aura::Window::Windows containers = GetContainersForAllRootWindows(
1434         kShellWindowId_LockSystemModalContainer, GetPrimaryRootWindow());
1435     for (aura::Window* container : containers)
1436       DCHECK(container->children().empty());
1437   }
1438 #endif
1439 }
1440 
1441 }  // namespace ash
1442