[M120 Migration][MM] Fix EME AD insert issue
[platform/framework/web/chromium-efl.git] / ash / shell.cc
1 // Copyright 2012 The Chromium Authors
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 <iterator>
9 #include <memory>
10 #include <string>
11 #include <utility>
12
13 #include "ash/accelerators/accelerator_controller_impl.h"
14 #include "ash/accelerators/accelerator_prefs.h"
15 #include "ash/accelerators/accelerator_tracker.h"
16 #include "ash/accelerators/ash_accelerator_configuration.h"
17 #include "ash/accelerators/ash_focus_manager_factory.h"
18 #include "ash/accelerators/magnifier_key_scroller.h"
19 #include "ash/accelerators/pre_target_accelerator_handler.h"
20 #include "ash/accelerators/shortcut_input_handler.h"
21 #include "ash/accelerators/spoken_feedback_toggler.h"
22 #include "ash/accelerometer/accelerometer_reader.h"
23 #include "ash/accessibility/accessibility_controller_impl.h"
24 #include "ash/accessibility/accessibility_delegate.h"
25 #include "ash/accessibility/autoclick/autoclick_controller.h"
26 #include "ash/accessibility/chromevox/key_accessibility_enabler.h"
27 #include "ash/accessibility/magnifier/docked_magnifier_controller.h"
28 #include "ash/accessibility/magnifier/fullscreen_magnifier_controller.h"
29 #include "ash/accessibility/magnifier/partial_magnifier_controller.h"
30 #include "ash/accessibility/sticky_keys/sticky_keys_controller.h"
31 #include "ash/accessibility/ui/accessibility_focus_ring_controller_impl.h"
32 #include "ash/ambient/ambient_controller.h"
33 #include "ash/app_list/app_list_controller_impl.h"
34 #include "ash/app_list/app_list_feature_usage_metrics.h"
35 #include "ash/assistant/assistant_controller_impl.h"
36 #include "ash/booting/booting_animation_controller.h"
37 #include "ash/calendar/calendar_controller.h"
38 #include "ash/capture_mode/capture_mode_controller.h"
39 #include "ash/child_accounts/parent_access_controller_impl.h"
40 #include "ash/clipboard/clipboard_history_controller_delegate.h"
41 #include "ash/clipboard/clipboard_history_controller_impl.h"
42 #include "ash/clipboard/clipboard_history_util.h"
43 #include "ash/clipboard/control_v_histogram_recorder.h"
44 #include "ash/color_enhancement/color_enhancement_controller.h"
45 #include "ash/constants/ash_features.h"
46 #include "ash/constants/ash_switches.h"
47 #include "ash/controls/contextual_tooltip.h"
48 #include "ash/curtain/security_curtain_controller_impl.h"
49 #include "ash/dbus/ash_dbus_services.h"
50 #include "ash/detachable_base/detachable_base_handler.h"
51 #include "ash/detachable_base/detachable_base_notification_controller.h"
52 #include "ash/display/cros_display_config.h"
53 #include "ash/display/cursor_window_controller.h"
54 #include "ash/display/display_alignment_controller.h"
55 #include "ash/display/display_color_manager.h"
56 #include "ash/display/display_configuration_controller.h"
57 #include "ash/display/display_configuration_observer.h"
58 #include "ash/display/display_error_observer.h"
59 #include "ash/display/display_highlight_controller.h"
60 #include "ash/display/display_prefs.h"
61 #include "ash/display/display_shutdown_observer.h"
62 #include "ash/display/event_transformation_handler.h"
63 #include "ash/display/mouse_cursor_event_filter.h"
64 #include "ash/display/privacy_screen_controller.h"
65 #include "ash/display/projecting_observer.h"
66 #include "ash/display/resolution_notification_controller.h"
67 #include "ash/display/screen_ash.h"
68 #include "ash/display/screen_orientation_controller.h"
69 #include "ash/display/screen_position_controller.h"
70 #include "ash/display/window_tree_host_manager.h"
71 #include "ash/drag_drop/drag_drop_controller.h"
72 #include "ash/events/event_rewriter_controller_impl.h"
73 #include "ash/fast_ink/laser/laser_pointer_controller.h"
74 #include "ash/focus_cycler.h"
75 #include "ash/frame/non_client_frame_view_ash.h"
76 #include "ash/frame/snap_controller_impl.h"
77 #include "ash/frame_throttler/frame_throttling_controller.h"
78 #include "ash/game_dashboard/game_dashboard_controller.h"
79 #include "ash/glanceables/glanceables_controller.h"
80 #include "ash/glanceables/post_login_glanceables_metrics_recorder.h"
81 #include "ash/host/ash_window_tree_host_init_params.h"
82 #include "ash/hud_display/hud_display.h"
83 #include "ash/ime/ime_controller_impl.h"
84 #include "ash/in_session_auth/in_session_auth_dialog_controller_impl.h"
85 #include "ash/in_session_auth/webauthn_dialog_controller_impl.h"
86 #include "ash/keyboard/keyboard_controller_impl.h"
87 #include "ash/keyboard/ui/keyboard_ui_factory.h"
88 #include "ash/login/login_screen_controller.h"
89 #include "ash/login/ui/local_authentication_request_controller_impl.h"
90 #include "ash/login_status.h"
91 #include "ash/media/media_controller_impl.h"
92 #include "ash/metrics/feature_discovery_duration_reporter_impl.h"
93 #include "ash/metrics/login_unlock_throughput_recorder.h"
94 #include "ash/metrics/user_metrics_recorder.h"
95 #include "ash/multi_capture/multi_capture_service_client.h"
96 #include "ash/multi_device_setup/multi_device_notification_presenter.h"
97 #include "ash/policy/policy_recommendation_restorer.h"
98 #include "ash/projector/projector_controller_impl.h"
99 #include "ash/public/cpp/accelerator_keycode_lookup_cache.h"
100 #include "ash/public/cpp/ash_prefs.h"
101 #include "ash/public/cpp/holding_space/holding_space_controller.h"
102 #include "ash/public/cpp/login/local_authentication_request_controller.h"
103 #include "ash/public/cpp/nearby_share_delegate.h"
104 #include "ash/public/cpp/saved_desk_delegate.h"
105 #include "ash/public/cpp/shelf_config.h"
106 #include "ash/public/cpp/shelf_model.h"
107 #include "ash/public/cpp/shell_window_ids.h"
108 #include "ash/public/cpp/system_sounds_delegate.h"
109 #include "ash/public/cpp/tab_cluster/tab_cluster_ui_controller.h"
110 #include "ash/public/cpp/views_text_services_context_menu_ash.h"
111 #include "ash/quick_pair/keyed_service/quick_pair_mediator.h"
112 #include "ash/rgb_keyboard/rgb_keyboard_manager.h"
113 #include "ash/root_window_controller.h"
114 #include "ash/session/session_controller_impl.h"
115 #include "ash/shelf/shelf_controller.h"
116 #include "ash/shelf/shelf_window_watcher.h"
117 #include "ash/shell_delegate.h"
118 #include "ash/shell_init_params.h"
119 #include "ash/shell_observer.h"
120 #include "ash/shell_tab_handler.h"
121 #include "ash/shutdown_controller_impl.h"
122 #include "ash/style/ash_color_mixer.h"
123 #include "ash/style/ash_color_provider.h"
124 #include "ash/style/color_palette_controller.h"
125 #include "ash/style/dark_light_mode_controller_impl.h"
126 #include "ash/style/style_util.h"
127 #include "ash/system/audio/audio_effects_controller.h"
128 #include "ash/system/audio/display_speaker_controller.h"
129 #include "ash/system/bluetooth/bluetooth_device_status_ui_handler.h"
130 #include "ash/system/bluetooth/bluetooth_notification_controller.h"
131 #include "ash/system/bluetooth/bluetooth_state_cache.h"
132 #include "ash/system/brightness/brightness_controller_chromeos.h"
133 #include "ash/system/brightness_control_delegate.h"
134 #include "ash/system/camera/autozoom_controller_impl.h"
135 #include "ash/system/camera/camera_effects_controller.h"
136 #include "ash/system/caps_lock_notification_controller.h"
137 #include "ash/system/diagnostics/diagnostics_log_controller.h"
138 #include "ash/system/federated/federated_service_controller_impl.h"
139 #include "ash/system/firmware_update/firmware_update_notification_controller.h"
140 #include "ash/system/focus_mode/focus_mode_controller.h"
141 #include "ash/system/geolocation/geolocation_controller.h"
142 #include "ash/system/hotspot/hotspot_icon_animation.h"
143 #include "ash/system/hotspot/hotspot_info_cache.h"
144 #include "ash/system/human_presence/human_presence_orientation_controller.h"
145 #include "ash/system/human_presence/snooping_protection_controller.h"
146 #include "ash/system/input_device_settings/input_device_key_alias_manager.h"
147 #include "ash/system/input_device_settings/input_device_settings_controller_impl.h"
148 #include "ash/system/input_device_settings/input_device_settings_dispatcher.h"
149 #include "ash/system/input_device_settings/input_device_tracker.h"
150 #include "ash/system/input_device_settings/keyboard_modifier_metrics_recorder.h"
151 #include "ash/system/keyboard_brightness/keyboard_backlight_color_controller.h"
152 #include "ash/system/keyboard_brightness/keyboard_brightness_controller.h"
153 #include "ash/system/keyboard_brightness_control_delegate.h"
154 #include "ash/system/locale/locale_update_controller_impl.h"
155 #include "ash/system/media/media_notification_provider.h"
156 #include "ash/system/message_center/message_center_ash_impl.h"
157 #include "ash/system/message_center/message_center_controller.h"
158 #include "ash/system/model/system_tray_model.h"
159 #include "ash/system/model/virtual_keyboard_model.h"
160 #include "ash/system/nearby_share/nearby_share_controller_impl.h"
161 #include "ash/system/network/sms_observer.h"
162 #include "ash/system/night_light/night_light_controller_impl.h"
163 #include "ash/system/pcie_peripheral/pcie_peripheral_notification_controller.h"
164 #include "ash/system/power/adaptive_charging_controller.h"
165 #include "ash/system/power/backlights_forced_off_setter.h"
166 #include "ash/system/power/battery_saver_controller.h"
167 #include "ash/system/power/peripheral_battery_notifier.h"
168 #include "ash/system/power/power_button_controller.h"
169 #include "ash/system/power/power_event_observer.h"
170 #include "ash/system/power/power_prefs.h"
171 #include "ash/system/power/power_status.h"
172 #include "ash/system/power/video_activity_notifier.h"
173 #include "ash/system/privacy/screen_switch_check_controller.h"
174 #include "ash/system/privacy_hub/privacy_hub_controller.h"
175 #include "ash/system/screen_layout_observer.h"
176 #include "ash/system/session/logout_confirmation_controller.h"
177 #include "ash/system/status_area_widget.h"
178 #include "ash/system/system_notification_controller.h"
179 #include "ash/system/toast/anchored_nudge_manager_impl.h"
180 #include "ash/system/toast/system_nudge_pause_manager_impl.h"
181 #include "ash/system/toast/toast_manager_impl.h"
182 #include "ash/system/tray/system_tray_notifier.h"
183 #include "ash/system/usb_peripheral/usb_peripheral_notification_controller.h"
184 #include "ash/system/video_conference/fake_video_conference_tray_controller.h"
185 #include "ash/touch/ash_touch_transform_controller.h"
186 #include "ash/touch/touch_devices_controller.h"
187 #include "ash/tray_action/tray_action.h"
188 #include "ash/user_education/user_education_controller.h"
189 #include "ash/user_education/user_education_delegate.h"
190 #include "ash/utility/occlusion_tracker_pauser.h"
191 #include "ash/wallpaper/wallpaper_controller_impl.h"
192 #include "ash/wm/ash_focus_rules.h"
193 #include "ash/wm/container_finder.h"
194 #include "ash/wm/coral/coral_controller.h"
195 #include "ash/wm/cursor_manager_chromeos.h"
196 #include "ash/wm/desks/desks_controller.h"
197 #include "ash/wm/desks/templates/saved_desk_controller.h"
198 #include "ash/wm/event_client_impl.h"
199 #include "ash/wm/float/float_controller.h"
200 #include "ash/wm/gestures/back_gesture/back_gesture_event_handler.h"
201 #include "ash/wm/immersive_context_ash.h"
202 #include "ash/wm/lock_state_controller.h"
203 #include "ash/wm/mru_window_tracker.h"
204 #include "ash/wm/multi_display/multi_display_metrics_controller.h"
205 #include "ash/wm/multi_display/persistent_window_controller.h"
206 #include "ash/wm/multitask_menu_nudge_delegate_ash.h"
207 #include "ash/wm/native_cursor_manager_ash.h"
208 #include "ash/wm/overview/overview_controller.h"
209 #include "ash/wm/pip/pip_controller.h"
210 #include "ash/wm/raster_scale/raster_scale_controller.h"
211 #include "ash/wm/resize_shadow_controller.h"
212 #include "ash/wm/screen_pinning_controller.h"
213 #include "ash/wm/snap_group/snap_group_controller.h"
214 #include "ash/wm/system_gesture_event_filter.h"
215 #include "ash/wm/system_modal_container_event_filter.h"
216 #include "ash/wm/system_modal_container_layout_manager.h"
217 #include "ash/wm/tablet_mode/tablet_mode_controller.h"
218 #include "ash/wm/tablet_mode/tablet_mode_window_manager.h"
219 #include "ash/wm/toplevel_window_event_handler.h"
220 #include "ash/wm/video_detector.h"
221 #include "ash/wm/window_animations.h"
222 #include "ash/wm/window_cycle/window_cycle_controller.h"
223 #include "ash/wm/window_properties.h"
224 #include "ash/wm/window_restore/window_restore_controller.h"
225 #include "ash/wm/window_util.h"
226 #include "ash/wm/wm_shadow_controller_delegate.h"
227 #include "ash/wm/workspace_controller.h"
228 #include "ash/wm_mode/wm_mode_controller.h"
229 #include "base/check.h"
230 #include "base/command_line.h"
231 #include "base/functional/bind.h"
232 #include "base/functional/callback_helpers.h"
233 #include "base/memory/ptr_util.h"
234 #include "base/notreached.h"
235 #include "base/ranges/algorithm.h"
236 #include "base/system/sys_info.h"
237 #include "base/trace_event/trace_event.h"
238 #include "chromeos/ash/components/dbus/fwupd/fwupd_client.h"
239 #include "chromeos/ash/components/dbus/typecd/typecd_client.h"
240 #include "chromeos/ash/components/dbus/usb/usbguard_client.h"
241 #include "chromeos/ash/components/fwupd/firmware_update_manager.h"
242 #include "chromeos/ash/components/peripheral_notification/peripheral_notification_manager.h"
243 #include "chromeos/ash/services/assistant/public/cpp/features.h"
244 #include "chromeos/dbus/init/initialize_dbus_client.h"
245 #include "chromeos/dbus/power/power_policy_controller.h"
246 #include "chromeos/ui/clipboard_history/clipboard_history_util.h"
247 #include "components/prefs/pref_registry_simple.h"
248 #include "components/prefs/pref_service.h"
249 #include "components/viz/host/host_frame_sink_manager.h"
250 #include "dbus/bus.h"
251 #include "media/capture/video/chromeos/video_capture_features_chromeos.h"
252 #include "services/video_capture/public/mojom/multi_capture_service.mojom.h"
253 #include "ui/aura/client/aura_constants.h"
254 #include "ui/aura/env.h"
255 #include "ui/aura/layout_manager.h"
256 #include "ui/aura/window.h"
257 #include "ui/aura/window_event_dispatcher.h"
258 #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h"
259 #include "ui/base/ui_base_features.h"
260 #include "ui/base/user_activity/user_activity_detector.h"
261 #include "ui/chromeos/user_activity_power_manager_notifier.h"
262 #include "ui/color/color_provider_manager.h"
263 #include "ui/compositor/layer.h"
264 #include "ui/compositor/layer_animator.h"
265 #include "ui/display/display.h"
266 #include "ui/display/manager/default_touch_transform_setter.h"
267 #include "ui/display/manager/display_change_observer.h"
268 #include "ui/display/manager/display_configurator.h"
269 #include "ui/display/manager/display_manager.h"
270 #include "ui/display/manager/display_port_observer.h"
271 #include "ui/display/manager/touch_transform_setter.h"
272 #include "ui/display/screen.h"
273 #include "ui/display/types/native_display_delegate.h"
274 #include "ui/events/ash/keyboard_capability.h"
275 #include "ui/events/event_target_iterator.h"
276 #include "ui/gfx/geometry/insets.h"
277 #include "ui/gfx/image/image_skia.h"
278 #include "ui/message_center/message_center.h"
279 #include "ui/ozone/public/ozone_platform.h"
280 #include "ui/views/controls/views_text_services_context_menu_chromeos.h"
281 #include "ui/views/corewm/tooltip_aura.h"
282 #include "ui/views/corewm/tooltip_controller.h"
283 #include "ui/views/focus/focus_manager_factory.h"
284 #include "ui/views/widget/native_widget_aura.h"
285 #include "ui/views/widget/widget.h"
286 #include "ui/wm/core/accelerator_filter.h"
287 #include "ui/wm/core/capture_controller.h"
288 #include "ui/wm/core/compound_event_filter.h"
289 #include "ui/wm/core/focus_controller.h"
290 #include "ui/wm/core/shadow_controller.h"
291 #include "ui/wm/core/visibility_controller.h"
292 #include "ui/wm/core/window_modality_controller.h"
293
294 namespace ash {
295
296 namespace {
297
298 using aura::Window;
299 using views::Widget;
300
301 // A Corewm VisibilityController subclass that calls the Ash animation routine
302 // so we can pick up our extended animations. See ash/wm/window_animations.h.
303 class AshVisibilityController : public ::wm::VisibilityController {
304  public:
305   AshVisibilityController() = default;
306
307   AshVisibilityController(const AshVisibilityController&) = delete;
308   AshVisibilityController& operator=(const AshVisibilityController&) = delete;
309
310   ~AshVisibilityController() override = default;
311
312  private:
313   // Overridden from ::wm::VisibilityController:
314   bool CallAnimateOnChildWindowVisibilityChanged(aura::Window* window,
315                                                  bool visible) override {
316     return AnimateOnChildWindowVisibilityChanged(window, visible);
317   }
318 };
319
320 }  // namespace
321
322 // static
323 Shell* Shell::instance_ = nullptr;
324
325 ////////////////////////////////////////////////////////////////////////////////
326 // Shell, public:
327
328 // static
329 Shell* Shell::CreateInstance(ShellInitParams init_params) {
330   CHECK(!instance_);
331   instance_ = new Shell(std::move(init_params.delegate));
332   instance_->Init(init_params.context_factory, init_params.local_state,
333                   std::move(init_params.keyboard_ui_factory),
334                   std::move(init_params.quick_pair_mediator_factory),
335                   init_params.dbus_bus,
336                   std::move(init_params.native_display_delegate));
337   return instance_;
338 }
339
340 // static
341 Shell* Shell::Get() {
342   CHECK(instance_);
343   return instance_;
344 }
345
346 // static
347 bool Shell::HasInstance() {
348   return !!instance_;
349 }
350
351 // static
352 void Shell::DeleteInstance() {
353   delete instance_;
354 }
355
356 // static
357 RootWindowController* Shell::GetPrimaryRootWindowController() {
358   CHECK(HasInstance());
359   return RootWindowController::ForWindow(GetPrimaryRootWindow());
360 }
361
362 // static
363 Shell::RootWindowControllerList Shell::GetAllRootWindowControllers() {
364   CHECK(HasInstance());
365   RootWindowControllerList root_window_controllers;
366   for (aura::Window* root : GetAllRootWindows()) {
367     root_window_controllers.push_back(RootWindowController::ForWindow(root));
368   }
369   return root_window_controllers;
370 }
371
372 // static
373 RootWindowController* Shell::GetRootWindowControllerWithDisplayId(
374     int64_t display_id) {
375   CHECK(HasInstance());
376   aura::Window* root = GetRootWindowForDisplayId(display_id);
377   return root ? RootWindowController::ForWindow(root) : nullptr;
378 }
379
380 // static
381 aura::Window* Shell::GetRootWindowForDisplayId(int64_t display_id) {
382   CHECK(HasInstance());
383   return instance_->window_tree_host_manager_->GetRootWindowForDisplayId(
384       display_id);
385 }
386
387 // static
388 aura::Window* Shell::GetPrimaryRootWindow() {
389   CHECK(HasInstance());
390   return instance_->window_tree_host_manager_->GetPrimaryRootWindow();
391 }
392
393 // static
394 void Shell::SetRootWindowForNewWindows(aura::Window* root) {
395   display::Screen::GetScreen()->SetDisplayForNewWindows(
396       display::Screen::GetScreen()->GetDisplayNearestWindow(root).id());
397 }
398
399 // static
400 aura::Window* Shell::GetRootWindowForNewWindows() {
401   return GetRootWindowForDisplayId(
402       display::Screen::GetScreen()->GetDisplayForNewWindows().id());
403 }
404
405 // static
406 aura::Window::Windows Shell::GetAllRootWindows() {
407   CHECK(HasInstance());
408   return instance_->window_tree_host_manager_->GetAllRootWindows();
409 }
410
411 // static
412 aura::Window* Shell::GetContainer(aura::Window* root_window, int container_id) {
413   return root_window->GetChildById(container_id);
414 }
415
416 // static
417 const aura::Window* Shell::GetContainer(const aura::Window* root_window,
418                                         int container_id) {
419   return root_window->GetChildById(container_id);
420 }
421
422 // static
423 int Shell::GetOpenSystemModalWindowContainerId() {
424   // The test boolean is not static to avoid leaking state between tests.
425   if (Get()->simulate_modal_window_open_for_test_) {
426     return kShellWindowId_SystemModalContainer;
427   }
428
429   // Traverse all system modal containers, and find its direct child window
430   // with "SystemModal" setting, and visible.
431   for (aura::Window* root : Shell::GetAllRootWindows()) {
432     for (int modal_window_id : kSystemModalContainerIds) {
433       aura::Window* system_modal = root->GetChildById(modal_window_id);
434       if (!system_modal) {
435         continue;
436       }
437       for (const aura::Window* child : system_modal->children()) {
438         if (child->GetProperty(aura::client::kModalKey) ==
439                 ui::MODAL_TYPE_SYSTEM &&
440             child->layer()->GetTargetVisibility()) {
441           return modal_window_id;
442         }
443       }
444     }
445   }
446   return -1;
447 }
448
449 // static
450 bool Shell::IsSystemModalWindowOpen() {
451   return GetOpenSystemModalWindowContainerId() >= 0;
452 }
453
454 display::DisplayConfigurator* Shell::display_configurator() {
455   return display_manager_->configurator();
456 }
457
458 void Shell::TrackInputMethodBounds(ArcInputMethodBoundsTracker* tracker) {
459   system_tray_model()->virtual_keyboard()->SetInputMethodBoundsTrackerObserver(
460       tracker);
461 }
462
463 void Shell::UntrackTrackInputMethodBounds(
464     ArcInputMethodBoundsTracker* tracker) {
465   system_tray_model()
466       ->virtual_keyboard()
467       ->RemoveInputMethodBoundsTrackerObserver(tracker);
468 }
469
470 std::unique_ptr<views::NonClientFrameView>
471 Shell::CreateDefaultNonClientFrameView(views::Widget* widget) {
472   // Use translucent-style window frames for dialogs.
473   return std::make_unique<NonClientFrameViewAsh>(widget);
474 }
475
476 void Shell::OnCastingSessionStartedOrStopped(bool started) {
477   for (auto& observer : shell_observers_) {
478     observer.OnCastingSessionStartedOrStopped(started);
479   }
480 }
481
482 void Shell::OnRootWindowAdded(aura::Window* root_window) {
483   for (auto& observer : shell_observers_) {
484     observer.OnRootWindowAdded(root_window);
485   }
486 }
487
488 void Shell::OnRootWindowWillShutdown(aura::Window* root_window) {
489   DCHECK(toplevel_window_event_handler_);
490   root_window->RemovePreTargetHandler(toplevel_window_event_handler_.get());
491   root_window->RemovePostTargetHandler(toplevel_window_event_handler_.get());
492
493   for (auto& observer : shell_observers_) {
494     observer.OnRootWindowWillShutdown(root_window);
495   }
496 }
497
498 void Shell::OnDictationStarted() {
499   for (auto& observer : shell_observers_) {
500     observer.OnDictationStarted();
501   }
502 }
503
504 void Shell::OnDictationEnded() {
505   for (auto& observer : shell_observers_) {
506     observer.OnDictationEnded();
507   }
508 }
509
510 bool Shell::IsInTabletMode() const {
511   return tablet_mode_controller()->InTabletMode();
512 }
513
514 bool Shell::ShouldSaveDisplaySettings() {
515   return !(
516       screen_orientation_controller_->ignore_display_configuration_updates() ||
517       // Save display settings if we don't need to show the display change
518       // dialog.
519       resolution_notification_controller_->ShouldShowDisplayChangeDialog());
520 }
521
522 ::wm::ActivationClient* Shell::activation_client() {
523   return focus_controller_.get();
524 }
525
526 bool Shell::HasPrimaryStatusArea() {
527   return !!GetPrimaryRootWindowController()->GetStatusAreaWidget();
528 }
529
530 void Shell::SetLargeCursorSizeInDip(int large_cursor_size_in_dip) {
531   window_tree_host_manager_->cursor_window_controller()
532       ->SetLargeCursorSizeInDip(large_cursor_size_in_dip);
533 }
534
535 void Shell::SetCursorColor(SkColor cursor_color) {
536   window_tree_host_manager_->cursor_window_controller()->SetCursorColor(
537       cursor_color);
538 }
539
540 void Shell::UpdateCursorCompositingEnabled() {
541   SetCursorCompositingEnabled(
542       window_tree_host_manager_->cursor_window_controller()
543           ->ShouldEnableCursorCompositing());
544 }
545
546 void Shell::SetCursorCompositingEnabled(bool enabled) {
547   CursorWindowController* cursor_window_controller =
548       window_tree_host_manager_->cursor_window_controller();
549
550   if (cursor_window_controller->is_cursor_compositing_enabled() == enabled) {
551     return;
552   }
553   cursor_window_controller->SetCursorCompositingEnabled(enabled);
554   native_cursor_manager_->SetNativeCursorEnabled(!enabled);
555 }
556
557 void Shell::DoInitialWorkspaceAnimation() {
558   // Uses the active desk's workspace.
559   auto* workspace = GetActiveWorkspaceController(GetPrimaryRootWindow());
560   DCHECK(workspace);
561   workspace->DoInitialAnimation();
562 }
563
564 void Shell::ShowContextMenu(const gfx::Point& location_in_screen,
565                             ui::MenuSourceType source_type) {
566   // Bail with no active user session, in the lock screen, or in app/kiosk mode.
567   if (session_controller_->NumberOfLoggedInUsers() < 1 ||
568       session_controller_->IsScreenLocked() ||
569       session_controller_->IsRunningInAppMode()) {
570     return;
571   }
572
573   aura::Window* root = window_util::GetRootWindowAt(location_in_screen);
574   RootWindowController::ForWindow(root)->ShowContextMenu(location_in_screen,
575                                                          source_type);
576 }
577
578 void Shell::AddShellObserver(ShellObserver* observer) {
579   shell_observers_.AddObserver(observer);
580 }
581
582 void Shell::RemoveShellObserver(ShellObserver* observer) {
583   shell_observers_.RemoveObserver(observer);
584 }
585
586 void Shell::ShutdownEventDispatch() {
587   for (aura::Window* root : GetAllRootWindows()) {
588     aura::client::SetDragDropClient(root, nullptr);
589   }
590
591   // Stop dispatching events (e.g. synthesized mouse exits from window close).
592   // https://crbug.com/874156
593   for (RootWindowController* rwc : GetAllRootWindowControllers()) {
594     rwc->GetHost()->dispatcher()->Shutdown();
595   }
596 }
597
598 void Shell::UpdateAfterLoginStatusChange(LoginStatus status) {
599   for (auto* root_window_controller : GetAllRootWindowControllers()) {
600     root_window_controller->UpdateAfterLoginStatusChange(status);
601   }
602 }
603
604 void Shell::NotifyFullscreenStateChanged(bool is_fullscreen,
605                                          aura::Window* container) {
606   for (auto& observer : shell_observers_) {
607     observer.OnFullscreenStateChanged(is_fullscreen, container);
608   }
609 }
610
611 void Shell::NotifyPinnedStateChanged(aura::Window* pinned_window) {
612   for (auto& observer : shell_observers_) {
613     observer.OnPinnedStateChanged(pinned_window);
614   }
615 }
616
617 void Shell::NotifyUserWorkAreaInsetsChanged(aura::Window* root_window) {
618   for (auto& observer : shell_observers_) {
619     observer.OnUserWorkAreaInsetsChanged(root_window);
620   }
621 }
622
623 void Shell::NotifyShelfAlignmentChanged(aura::Window* root_window,
624                                         ShelfAlignment old_alignment) {
625   for (auto& observer : shell_observers_) {
626     observer.OnShelfAlignmentChanged(root_window, old_alignment);
627   }
628 }
629
630 void Shell::NotifyDisplayForNewWindowsChanged() {
631   for (auto& observer : shell_observers_) {
632     observer.OnDisplayForNewWindowsChanged();
633   }
634 }
635
636 void Shell::AddAccessibilityEventHandler(
637     ui::EventHandler* handler,
638     AccessibilityEventHandlerManager::HandlerType type) {
639   if (!accessibility_event_handler_manager_) {
640     accessibility_event_handler_manager_ =
641         std::make_unique<AccessibilityEventHandlerManager>();
642   }
643
644   accessibility_event_handler_manager_->AddAccessibilityEventHandler(handler,
645                                                                      type);
646 }
647 void Shell::RemoveAccessibilityEventHandler(ui::EventHandler* handler) {
648   accessibility_event_handler_manager_->RemoveAccessibilityEventHandler(
649       handler);
650 }
651
652 ////////////////////////////////////////////////////////////////////////////////
653 // Shell, private:
654
655 Shell::Shell(std::unique_ptr<ShellDelegate> shell_delegate)
656     : brightness_control_delegate_(
657           std::make_unique<system::BrightnessControllerChromeos>()),
658       focus_cycler_(std::make_unique<FocusCycler>()),
659       ime_controller_(std::make_unique<ImeControllerImpl>()),
660       immersive_context_(std::make_unique<ImmersiveContextAsh>()),
661       webauthn_dialog_controller_(
662           std::make_unique<WebAuthNDialogControllerImpl>()),
663       in_session_auth_dialog_controller_(
664           std::make_unique<InSessionAuthDialogControllerImpl>()),
665       keyboard_brightness_control_delegate_(
666           std::make_unique<KeyboardBrightnessController>()),
667       locale_update_controller_(std::make_unique<LocaleUpdateControllerImpl>()),
668       parent_access_controller_(std::make_unique<ParentAccessControllerImpl>()),
669       local_authentication_request_controller_(
670           std::make_unique<LocalAuthenticationRequestControllerImpl>()),
671       session_controller_(std::make_unique<SessionControllerImpl>()),
672       feature_discover_reporter_(
673           std::make_unique<FeatureDiscoveryDurationReporterImpl>(
674               session_controller_.get())),
675       shell_delegate_(std::move(shell_delegate)),
676       shutdown_controller_(std::make_unique<ShutdownControllerImpl>()),
677       system_tray_notifier_(std::make_unique<SystemTrayNotifier>()),
678       native_cursor_manager_(nullptr) {
679   AccelerometerReader::GetInstance()->Initialize();
680
681   login_screen_controller_ =
682       std::make_unique<LoginScreenController>(system_tray_notifier_.get());
683   display_manager_ = ScreenAsh::CreateDisplayManager();
684   window_tree_host_manager_ = std::make_unique<WindowTreeHostManager>();
685   user_metrics_recorder_ = std::make_unique<UserMetricsRecorder>();
686   keyboard_controller_ =
687       std::make_unique<KeyboardControllerImpl>(session_controller_.get());
688
689   PowerStatus::Initialize();
690
691   session_controller_->AddObserver(this);
692 }
693
694 Shell::~Shell() {
695   TRACE_EVENT0("shutdown", "ash::Shell::Destructor");
696 #if DCHECK_IS_ON()
697   // All WindowEventDispatchers should be shutdown before the Shell is
698   // destroyed.
699   for (RootWindowController* rwc : GetAllRootWindowControllers()) {
700     DCHECK(rwc->GetHost()->dispatcher()->in_shutdown());
701   }
702 #endif
703   booting_animation_controller_.reset();
704   login_unlock_throughput_recorder_.reset();
705
706   hud_display::HUDDisplayView::Destroy();
707
708   // Observes `SessionController` and must be destroyed before it.
709   privacy_hub_controller_.reset();
710
711   for (auto& observer : shell_observers_) {
712     observer.OnShellDestroying();
713   }
714
715   ash_dbus_services_.reset();
716
717   saved_desk_controller_.reset();
718   saved_desk_delegate_.reset();
719   desks_controller_->Shutdown();
720
721   user_metrics_recorder_->OnShellShuttingDown();
722
723   cros_display_config_.reset();
724   display_configuration_observer_.reset();
725   display_prefs_.reset();
726   display_alignment_controller_.reset();
727
728   // Remove the focus from any window. This will prevent overhead and side
729   // effects (e.g. crashes) from changing focus during shutdown.
730   // See bug crbug.com/134502.
731   aura::client::GetFocusClient(GetPrimaryRootWindow())->FocusWindow(nullptr);
732
733   // Please keep in reverse order as in Init() because it's easy to miss one.
734   if (window_modality_controller_) {
735     window_modality_controller_.reset();
736   }
737
738   RemovePreTargetHandler(shell_tab_handler_.get());
739   shell_tab_handler_.reset();
740
741   RemovePreTargetHandler(magnifier_key_scroll_handler_.get());
742   magnifier_key_scroll_handler_.reset();
743
744   RemovePreTargetHandler(speech_feedback_handler_.get());
745   speech_feedback_handler_.reset();
746
747   RemovePreTargetHandler(control_v_histogram_recorder_.get());
748   RemovePreTargetHandler(accelerator_tracker_.get());
749   RemovePreTargetHandler(accelerator_filter_.get());
750   RemovePreTargetHandler(event_transformation_handler_.get());
751   if (back_gesture_event_handler_) {
752     RemovePreTargetHandler(back_gesture_event_handler_.get());
753   }
754   RemovePreTargetHandler(system_gesture_filter_.get());
755   RemoveAccessibilityEventHandler(mouse_cursor_filter_.get());
756   if (features::IsPeripheralCustomizationEnabled()) {
757     RemovePreTargetHandler(shortcut_input_handler_.get());
758   }
759   RemovePreTargetHandler(modality_filter_.get());
760   RemovePreTargetHandler(tooltip_controller_.get());
761
762   // Resets the implementation of clipboard history utility functions.
763   chromeos::clipboard_history::SetQueryItemDescriptorsImpl(
764       base::NullCallback());
765   chromeos::clipboard_history::SetPasteClipboardItemByIdImpl(
766       base::NullCallback());
767
768   // Resets the text context menu implementation factory.
769   views::ViewsTextServicesContextMenuChromeos::SetImplFactory(
770       base::NullCallback());
771
772   wm_mode_controller_.reset();
773
774   event_rewriter_controller_.reset();
775   keyboard_modifier_metrics_recorder_.reset();
776   input_device_settings_dispatcher_.reset();
777   input_device_tracker_.reset();
778   input_device_settings_controller_.reset();
779   input_device_key_alias_manager_.reset();
780   shortcut_input_handler_.reset();
781
782   screen_orientation_controller_.reset();
783   screen_layout_observer_.reset();
784
785   // Destroy the virtual keyboard controller before the tablet mode controller
786   // since the latters destructor triggers events that the former is listening
787   // to but no longer cares about.
788   keyboard_controller_->DestroyVirtualKeyboard();
789
790   // Depends on |tablet_mode_controller_|.
791   window_restore_controller_.reset();
792   shelf_controller_->Shutdown();
793   shelf_config_->Shutdown();
794
795   // Depends on `app_list_controller_` and `tablet_mode_controller_`.
796   app_list_feature_usage_metrics_.reset();
797
798   // Destroy |app_list_controller_| earlier than |tablet_mode_controller_| since
799   // the former may use the latter before destruction.
800   app_list_controller_.reset();
801
802   // Accelerometer file reader stops listening to tablet mode controller.
803   AccelerometerReader::GetInstance()->StopListenToTabletModeController();
804
805   // Destroy |ambient_controller_| before |assistant_controller_|.
806   ambient_controller_.reset();
807
808   // Destroy |assistant_controller_| earlier than |tablet_mode_controller_| so
809   // that the former will destroy the Assistant view hierarchy which has a
810   // dependency on the latter.
811   assistant_controller_.reset();
812
813   // Because this function will call |TabletModeController::RemoveObserver|, do
814   // it before destroying |tablet_mode_controller_|.
815   accessibility_controller_->Shutdown();
816
817   // Must be destructed before human_presence_orientation_controller_.
818   power_prefs_.reset();
819
820   // Must be destructed before the tablet mode and message center controllers,
821   // both of which these rely on.
822   snooping_protection_controller_.reset();
823   human_presence_orientation_controller_.reset();
824
825   snap_group_controller_.reset();
826
827   // Shutdown tablet mode controller early on since it has some observers which
828   // need to be removed. It will be destroyed later after all windows are closed
829   // since it might be accessed during this process.
830   tablet_mode_controller_->Shutdown();
831
832   // Shutdown the clipboard history controller to clean up the child windows and
833   // widgets that may be animating out.
834   clipboard_history_controller_->Shutdown();
835
836   toast_manager_.reset();
837   anchored_nudge_manager_.reset();
838
839   // Accesses root window containers.
840   logout_confirmation_controller_.reset();
841
842   adaptive_charging_controller_.reset();
843
844   // Drag-and-drop must be canceled prior to close all windows.
845   drag_drop_controller_.reset();
846
847   // Controllers who have WindowObserver added must be deleted
848   // before |window_tree_host_manager_| is deleted.
849   persistent_window_controller_.reset();
850
851   display_highlight_controller_.reset();
852
853   // VideoActivityNotifier must be deleted before |video_detector_| is
854   // deleted because it's observing video activity through
855   // VideoDetector::Observer interface.
856   video_activity_notifier_.reset();
857   video_detector_.reset();
858   color_enhancement_controller_.reset();
859
860   shadow_controller_.reset();
861   resize_shadow_controller_.reset();
862   raster_scale_controller_.reset();
863
864   // Has to happen before ~MruWindowTracker.
865   window_cycle_controller_.reset();
866
867   // As clients of `capture_mode_controller_`, `projector_controller_` and
868   // `game_dashboard_controller_` need to be destroyed before
869   // `capture_mode_controller_`.
870   projector_controller_.reset();
871   game_dashboard_controller_.reset();
872
873   // This must be called before `capture_mode_controller_` is destroyed. Note
874   // that 'capture' in `CaptureModeController` means 'screenshot capture, while
875   // 'capture' in `wm::CaptureController` means 'input capture'. Some windows
876   // like popup windows close themselves when losing 'input capture' but if
877   // 'screenshot capture' is in progress, they do not close themselves. For this
878   // reason, change of 'input capture' can cause a call to
879   // `CaptureModeController::Get()`. By calling `PrepareForShutdown()` here, it
880   // prevents `CaptureModeController::Get()` from being called after the object
881   // is destroyed.
882   wm::CaptureController::Get()->PrepareForShutdown();
883
884   // This must be destroyed before deleting all the windows below in
885   // `CloseAllRootWindowChildWindows()`, since shutting down the session will
886   // need to access those windows and it will be a UAF.
887   // https://crbug.com/1350711.
888   capture_mode_controller_.reset();
889
890   // Relies on `overview_controller`.
891   post_login_glanceables_metrics_reporter_.reset();
892
893   // Has to happen before `~MruWindowTracker` and after
894   // `~GameDashboardController`.
895   overview_controller_.reset();
896
897   // This must be called before deleting all the windows below in
898   // `CloseAllRootWindowChildWindows()` since host_windows(which gets destroyed)
899   // are needed for proper deletion of RoundedDisplayProviders.
900   window_tree_host_manager_->ShutdownRoundedDisplays();
901
902   // Close all widgets (including the shelf) and destroy all window containers.
903   CloseAllRootWindowChildWindows();
904
905   glanceables_controller_.reset();
906
907   multitask_menu_nudge_delegate_.reset();
908   tablet_mode_controller_.reset();
909   login_screen_controller_.reset();
910
911   // This must be destroyed before `message_center_controller_` in order to
912   // restore the original settings if a focus session was active. Also, this
913   // should be destroyed before `system_notification_controller_`, which could
914   // be indirectly called by `focus_mode_controller_` to update the DND
915   // notification.
916   focus_mode_controller_.reset();
917
918   system_notification_controller_.reset();
919   // Should be destroyed after Shelf and |system_notification_controller_|.
920   system_tray_model_.reset();
921   system_sounds_delegate_.reset();
922
923   // MultiDisplayMetricsController has a dependency on `mru_window_tracker_`.
924   multi_display_metrics_controller_.reset();
925
926   // MruWindowTracker must be destroyed after all windows have been deleted to
927   // avoid a possible crash when Shell is destroyed from a non-normal shutdown
928   // path. (crbug.com/485438).
929   mru_window_tracker_.reset();
930
931   // These need a valid Shell instance to clean up properly, so explicitly
932   // delete them before invalidating the instance.
933   // Alphabetical. TODO(oshima): sort.
934   autoclick_controller_.reset();
935   fullscreen_magnifier_controller_.reset();
936   tooltip_controller_.reset();
937   event_client_.reset();
938   toplevel_window_event_handler_.reset();
939   visibility_controller_.reset();
940
941   tray_action_.reset();
942
943   power_button_controller_.reset();
944   lock_state_controller_.reset();
945   backlights_forced_off_setter_.reset();
946
947   float_controller_.reset();
948   pip_controller_.reset();
949   screen_pinning_controller_.reset();
950
951   multidevice_notification_presenter_.reset();
952   resolution_notification_controller_.reset();
953   mouse_cursor_filter_.reset();
954   modality_filter_.reset();
955
956   touch_transformer_controller_.reset();
957   key_accessibility_enabler_.reset();
958
959   display_speaker_controller_.reset();
960   screen_switch_check_controller_.reset();
961
962   ScreenAsh::CreateScreenForShutdown();
963   display_configuration_controller_.reset();
964
965   // Needs to be destructed before `ime_controler_`.
966   keyboard_backlight_color_controller_.reset();
967   rgb_keyboard_manager_.reset();
968
969   ash_color_provider_.reset();
970
971   // Depends on `dark_light_mode_controller_` and `wallpaper_controller_` so it
972   // should be destroyed first.
973   color_palette_controller_.reset();
974
975   // Depends on `geolocation_controller_` and `wallpaper_controller_`, so it
976   // must be destructed before the geolocation controller and wallpaper
977   // controller.
978   dark_light_mode_controller_.reset();
979
980   // These members access Shell in their destructors.
981   wallpaper_controller_.reset();
982   accessibility_controller_.reset();
983   accessibility_delegate_.reset();
984   accessibility_focus_ring_controller_.reset();
985   policy_recommendation_restorer_.reset();
986   ime_controller_.reset();
987   back_gesture_event_handler_.reset();
988
989   // Balances the Install() in Initialize().
990   views::FocusManagerFactory::Install(nullptr);
991
992   // ShelfWindowWatcher has window observers and a pointer to the shelf model.
993   shelf_window_watcher_.reset();
994
995   // Removes itself as an observer of |pref_service_|.
996   shelf_controller_.reset();
997
998   // `CameraEffectsController` depends on `AutozoomController`, so it must be
999   // destructed before it.
1000   camera_effects_controller_.reset();
1001
1002   // NightLightControllerImpl depends on the PrefService, the window tree host
1003   // manager, and `geolocation_controller_`, so it must be destructed before
1004   // them. crbug.com/724231.
1005   night_light_controller_ = nullptr;
1006   // Similarly for DockedMagnifierController.
1007   docked_magnifier_controller_ = nullptr;
1008   // Similarly for PrivacyScreenController.
1009   privacy_screen_controller_ = nullptr;
1010   // Similarly for AutozoomControllerImpl
1011   autozoom_controller_ = nullptr;
1012
1013   geolocation_controller_.reset();
1014
1015   // NearbyShareDelegateImpl must be destroyed before SessionController and
1016   // NearbyShareControllerImpl.
1017   nearby_share_delegate_.reset();
1018   nearby_share_controller_.reset();
1019
1020   // Stop observing window activation changes before closing all windows.
1021   focus_controller_->RemoveObserver(this);
1022
1023   // Depends on shelf owned by RootWindowController so destroy this before the
1024   // |window_tree_host_manager_|.
1025   clipboard_history_controller_.reset();
1026
1027   // Should be destroyed after `clipbaord_history_controller_` and
1028   // `autozoom_controller_` since they will destruct `SystemNudgeController`.
1029   system_nudge_pause_manager_.reset();
1030
1031   // This also deletes all RootWindows. Note that we invoke Shutdown() on
1032   // WindowTreeHostManager before resetting |window_tree_host_manager_|, since
1033   // destruction of its owned RootWindowControllers relies on the value.
1034   window_tree_host_manager_->Shutdown();
1035
1036   // Depends on |focus_controller_|, so must be destroyed before.
1037   window_tree_host_manager_.reset();
1038
1039   // The desks controller is destroyed after the window tree host manager and
1040   // before the focus controller. At this point it is guaranteed that querying
1041   // the active desk is no longer needed.
1042   desks_controller_.reset();
1043
1044   tab_cluster_ui_controller_.reset();
1045
1046   focus_rules_ = nullptr;
1047   focus_controller_.reset();
1048   screen_position_controller_.reset();
1049
1050   display_color_manager_.reset();
1051   projecting_observer_.reset();
1052
1053   partial_magnifier_controller_.reset();
1054
1055   laser_pointer_controller_.reset();
1056
1057   if (display_change_observer_) {
1058     display_manager_->configurator()->RemoveObserver(
1059         display_change_observer_.get());
1060   }
1061   if (display_error_observer_) {
1062     display_manager_->configurator()->RemoveObserver(
1063         display_error_observer_.get());
1064   }
1065   display_change_observer_.reset();
1066   display_shutdown_observer_.reset();
1067
1068   display_port_observer_.reset();
1069
1070   keyboard_controller_.reset();
1071
1072   // Depends on PowerStatus.
1073   battery_saver_controller_.reset();
1074
1075   PowerStatus::Shutdown();
1076   // Depends on SessionController.
1077   power_event_observer_.reset();
1078
1079   session_controller_->RemoveObserver(this);
1080   // TouchDevicesController depends on the PrefService and must be destructed
1081   // before it.
1082   touch_devices_controller_ = nullptr;
1083   // DetachableBaseNotificationController depends on DetachableBaseHandler, and
1084   // has to be destructed before it.
1085   detachable_base_notification_controller_.reset();
1086   // DetachableBaseHandler depends on the PrefService and must be destructed
1087   // before it.
1088   detachable_base_handler_.reset();
1089
1090   diagnostics_log_controller_.reset();
1091
1092   firmware_update_notification_controller_.reset();
1093
1094   firmware_update_manager_.reset();
1095
1096   pcie_peripheral_notification_controller_.reset();
1097
1098   usb_peripheral_notification_controller_.reset();
1099
1100   keyboard_capability_.reset();
1101
1102   message_center_ash_impl_.reset();
1103
1104   // Destroys the MessageCenter singleton, so must happen late.
1105   message_center_controller_.reset();
1106
1107   // `HoldingSpaceController` observes `SessionController` and must be
1108   // destructed before it.
1109   holding_space_controller_.reset();
1110
1111   // `CalendarController` observes `SessionController` and must be destructed
1112   // before it.
1113   calendar_controller_.reset();
1114
1115   audio_effects_controller_.reset();
1116
1117   shell_delegate_.reset();
1118
1119   multi_capture_service_client_.reset();
1120
1121   // Observes `SessionController` and must be destroyed before it.
1122   federated_service_controller_.reset();
1123
1124   UsbguardClient::Shutdown();
1125
1126   // Must be shut down after detachable_base_handler_.
1127   HammerdClient::Shutdown();
1128
1129   if (FwupdClient::Get()) {
1130     FwupdClient::Shutdown();
1131   }
1132
1133   for (auto& observer : shell_observers_) {
1134     observer.OnShellDestroyed();
1135   }
1136
1137   DCHECK(instance_ == this);
1138   instance_ = nullptr;
1139 }
1140
1141 void Shell::Init(
1142     ui::ContextFactory* context_factory,
1143     PrefService* local_state,
1144     std::unique_ptr<keyboard::KeyboardUIFactory> keyboard_ui_factory,
1145     std::unique_ptr<ash::quick_pair::Mediator::Factory>
1146         quick_pair_mediator_factory,
1147     scoped_refptr<dbus::Bus> dbus_bus,
1148     std::unique_ptr<display::NativeDisplayDelegate> native_display_delegate) {
1149   native_display_delegate_ = std::move(native_display_delegate);
1150   login_unlock_throughput_recorder_ =
1151       std::make_unique<LoginUnlockThroughputRecorder>();
1152
1153   // Required by DetachableBaseHandler.
1154   chromeos::InitializeDBusClient<HammerdClient>(dbus_bus.get());
1155
1156   chromeos::InitializeDBusClient<UsbguardClient>(dbus_bus.get());
1157
1158   local_state_ = local_state;
1159
1160   if (local_state_ != nullptr) {
1161     // Only construct BatterySaverController if prefs exists. It uses prefs to
1162     // store the battery saver state, so testing its functionality without
1163     // prefs doesn't make sense.
1164     if (features::IsBatterySaverAvailable()) {
1165       battery_saver_controller_ =
1166           std::make_unique<BatterySaverController>(local_state_);
1167     } else {
1168       // It's possible that we have a new Chrome without battery saver mode
1169       // available, but still have battery saver running because the previous
1170       // chrome did. So unconditionally reset battery saver state.
1171       BatterySaverController::ResetState(local_state_);
1172     }
1173   }
1174
1175   // This creates the MessageCenter object which is used by some other objects
1176   // initialized here, so it needs to come early.
1177   message_center_controller_ = std::make_unique<MessageCenterController>();
1178
1179   message_center_ash_impl_ = std::make_unique<MessageCenterAshImpl>();
1180
1181   // Initialized early since it is used by some other objects.
1182   keyboard_capability_ = std::make_unique<ui::KeyboardCapability>();
1183
1184   // These controllers call Shell::Get() in their constructors, so they cannot
1185   // be in the member initialization list.
1186   touch_devices_controller_ = std::make_unique<TouchDevicesController>();
1187   detachable_base_handler_ =
1188       std::make_unique<DetachableBaseHandler>(local_state_);
1189   detachable_base_notification_controller_ =
1190       std::make_unique<DetachableBaseNotificationController>(
1191           detachable_base_handler_.get());
1192   display_speaker_controller_ = std::make_unique<DisplaySpeakerController>();
1193   policy_recommendation_restorer_ =
1194       std::make_unique<PolicyRecommendationRestorer>();
1195   screen_switch_check_controller_ =
1196       std::make_unique<ScreenSwitchCheckController>();
1197   multidevice_notification_presenter_ =
1198       std::make_unique<MultiDeviceNotificationPresenter>(
1199           message_center::MessageCenter::Get());
1200   media_controller_ = std::make_unique<MediaControllerImpl>();
1201   media_notification_provider_ =
1202       shell_delegate_->CreateMediaNotificationProvider();
1203
1204   tablet_mode_controller_ = std::make_unique<TabletModeController>();
1205
1206   rgb_keyboard_manager_ =
1207       std::make_unique<RgbKeyboardManager>(ime_controller_.get());
1208
1209   // Observes the tablet mode controller if any hps feature is enabled.
1210   if (features::IsSnoopingProtectionEnabled() ||
1211       features::IsQuickDimEnabled()) {
1212     human_presence_orientation_controller_ =
1213         std::make_unique<HumanPresenceOrientationController>();
1214   }
1215
1216   // Construct SnoopingProtectionController, must be constructed after
1217   // HumanPresenceOrientationController.
1218   if (features::IsSnoopingProtectionEnabled()) {
1219     snooping_protection_controller_ =
1220         std::make_unique<SnoopingProtectionController>();
1221   }
1222
1223   // Manages lifetime of DiagnosticApp logs.
1224   diagnostics_log_controller_ =
1225       std::make_unique<diagnostics::DiagnosticsLogController>();
1226
1227   pcie_peripheral_notification_controller_ =
1228       std::make_unique<PciePeripheralNotificationController>(
1229           message_center::MessageCenter::Get());
1230
1231   usb_peripheral_notification_controller_ =
1232       std::make_unique<UsbPeripheralNotificationController>(
1233           message_center::MessageCenter::Get());
1234
1235   accessibility_focus_ring_controller_ =
1236       std::make_unique<AccessibilityFocusRingControllerImpl>();
1237   accessibility_delegate_.reset(shell_delegate_->CreateAccessibilityDelegate());
1238   accessibility_controller_ = std::make_unique<AccessibilityControllerImpl>();
1239   toast_manager_ = std::make_unique<ToastManagerImpl>();
1240   if (features::IsSystemNudgeV2Enabled()) {
1241     anchored_nudge_manager_ = std::make_unique<AnchoredNudgeManagerImpl>();
1242   }
1243   system_nudge_pause_manager_ = std::make_unique<SystemNudgePauseManagerImpl>();
1244
1245   peripheral_battery_listener_ = std::make_unique<PeripheralBatteryListener>();
1246
1247   peripheral_battery_notifier_ = std::make_unique<PeripheralBatteryNotifier>(
1248       peripheral_battery_listener_.get());
1249   power_event_observer_ = std::make_unique<PowerEventObserver>();
1250   window_cycle_controller_ = std::make_unique<WindowCycleController>();
1251
1252   capture_mode_controller_ = std::make_unique<CaptureModeController>(
1253       shell_delegate_->CreateCaptureModeDelegate());
1254
1255   // Accelerometer file reader starts listening to tablet mode controller.
1256   AccelerometerReader::GetInstance()->StartListenToTabletModeController();
1257
1258   // Install the custom factory early on so that views::FocusManagers for Tray,
1259   // Shelf, and WallPaper could be created by the factory.
1260   views::FocusManagerFactory::Install(new AshFocusManagerFactory);
1261
1262   wallpaper_controller_ = WallpaperControllerImpl::Create(local_state_);
1263
1264   // Initialized after |rgb_keyboard_manager_| to observe the state of rgb
1265   // keyboard and |wallpaper_controller_| because we will need to observe when
1266   // the extracted wallpaper color changes.
1267   keyboard_backlight_color_controller_ =
1268       std::make_unique<KeyboardBacklightColorController>(local_state_);
1269
1270   native_cursor_manager_ = new NativeCursorManagerAsh;
1271   cursor_manager_ = std::make_unique<CursorManager>(
1272       base::WrapUnique(native_cursor_manager_.get()));
1273
1274   InitializeDisplayManager();
1275
1276   // RefreshFontParams depends on display prefs.
1277   display_manager_->RefreshFontParams();
1278
1279   // This will initialize aura::Env which requires |display_manager_| to
1280   // be initialized first.
1281   aura::Env* env = aura::Env::GetInstance();
1282   if (context_factory) {
1283     env->set_context_factory(context_factory);
1284   }
1285
1286   ash_color_provider_ = std::make_unique<AshColorProvider>();
1287   ui::ColorProviderManager::Get().AppendColorProviderInitializer(
1288       base::BindRepeating(AddCrosStylesColorMixer));
1289   ui::ColorProviderManager::Get().AppendColorProviderInitializer(
1290       base::BindRepeating(AddAshColorMixer));
1291
1292   // Geolocation controller needs to be created before any `ScheduledFeature`
1293   // subclasses such as night light and dark mode controllers because
1294   // `ScheduledFeature` ctor will access `geolocation_controller_` from
1295   // `Shell`.
1296   geolocation_controller_ = std::make_unique<GeolocationController>(
1297       shell_delegate_->GetGeolocationUrlLoaderFactory());
1298
1299   // Night Light depends on the display manager, the display color manager,
1300   // aura::Env, and geolocation controller, so initialize it after all have
1301   // been initialized.
1302   night_light_controller_ = std::make_unique<NightLightControllerImpl>();
1303
1304   dark_light_mode_controller_ = std::make_unique<DarkLightModeControllerImpl>();
1305
1306   color_palette_controller_ =
1307       ColorPaletteController::Create(dark_light_mode_controller_.get(),
1308                                      wallpaper_controller_.get(), local_state_);
1309
1310   // Privacy Screen depends on the display manager, so initialize it after
1311   // display manager was properly initialized.
1312   privacy_screen_controller_ = std::make_unique<PrivacyScreenController>();
1313
1314   if (media::ShouldEnableAutoFraming()) {
1315     autozoom_controller_ = std::make_unique<AutozoomControllerImpl>();
1316   }
1317
1318   // Fast Pair depends on the display manager, so initialize it after
1319   // display manager was properly initialized.
1320   if (base::FeatureList::IsEnabled(features::kFastPair) &&
1321       quick_pair_mediator_factory) {
1322     quick_pair_mediator_ = quick_pair_mediator_factory->BuildInstance();
1323   }
1324
1325   // The WindowModalityController needs to be at the front of the input event
1326   // pretarget handler list to ensure that it processes input events when modal
1327   // windows are active.
1328   window_modality_controller_ =
1329       std::make_unique<::wm::WindowModalityController>(this, env);
1330
1331   input_device_key_alias_manager_ =
1332       std::make_unique<InputDeviceKeyAliasManager>();
1333
1334   // The `InputDeviceSettingsController` is a dependency of the following so it
1335   // must be initialized first:
1336   //  - `EventRewriterController`
1337   //  - `InputDeviceTracker`
1338   //  - `KeyboardModifierMetricsRecorder`
1339   //  - `InputDeviceSettingsDispatcher`
1340   input_device_settings_controller_ =
1341       std::make_unique<InputDeviceSettingsControllerImpl>(local_state_);
1342   input_device_tracker_ = std::make_unique<InputDeviceTracker>();
1343   input_device_settings_dispatcher_ =
1344       std::make_unique<InputDeviceSettingsDispatcher>(
1345           ui::OzonePlatform::GetInstance()->GetInputController());
1346   keyboard_modifier_metrics_recorder_ =
1347       std::make_unique<KeyboardModifierMetricsRecorder>();
1348   event_rewriter_controller_ = std::make_unique<EventRewriterControllerImpl>();
1349
1350   env_filter_ = std::make_unique<::wm::CompoundEventFilter>();
1351   AddPreTargetHandler(env_filter_.get());
1352
1353   // FocusController takes ownership of AshFocusRules.
1354   focus_rules_ = new AshFocusRules();
1355   focus_controller_ = std::make_unique<::wm::FocusController>(focus_rules_);
1356   focus_controller_->AddObserver(this);
1357
1358   overview_controller_ = std::make_unique<OverviewController>();
1359
1360   // `GameDashboardController` has dependencies on `OverviewController` and
1361   // `CaptureModeController`.
1362   if (features::IsGameDashboardEnabled()) {
1363     game_dashboard_controller_ = std::make_unique<GameDashboardController>(
1364         shell_delegate_->CreateGameDashboardDelegate());
1365   }
1366
1367   // `SnapGroupController` has dependencies on `OverviweController` and
1368   // `TabletModeController`.
1369   if (features::IsSnapGroupEnabled()) {
1370     snap_group_controller_ = std::make_unique<SnapGroupController>();
1371   }
1372
1373   screen_position_controller_ = std::make_unique<ScreenPositionController>();
1374
1375   frame_throttling_controller_ = std::make_unique<FrameThrottlingController>(
1376       context_factory->GetHostFrameSinkManager());
1377
1378   if (features::IsTabClusterUIEnabled()) {
1379     tab_cluster_ui_controller_ = std::make_unique<TabClusterUIController>();
1380   }
1381
1382   window_tree_host_manager_->Start();
1383   AshWindowTreeHostInitParams ash_init_params;
1384   window_tree_host_manager_->CreatePrimaryHost(ash_init_params);
1385
1386   // Create the desks controller right after the window tree host manager is
1387   // started, and before anything else is created, including the initialization
1388   // of the hosts and the root window controllers. Many things may need to query
1389   // the active desk, even at this early stage. For this the controller must be
1390   // present at all times. The desks controller also depends on the focus
1391   // controller.
1392   desks_controller_ = std::make_unique<DesksController>();
1393   saved_desk_delegate_ = shell_delegate_->CreateSavedDeskDelegate();
1394   // Initialized here since it depends on desks.
1395   if (base::FeatureList::IsEnabled(features::kAppLaunchAutomation)) {
1396     saved_desk_controller_ = std::make_unique<SavedDeskController>();
1397   }
1398
1399   Shell::SetRootWindowForNewWindows(GetPrimaryRootWindow());
1400
1401   resolution_notification_controller_ =
1402       std::make_unique<ResolutionNotificationController>();
1403
1404   cursor_manager_->SetDisplay(
1405       display::Screen::GetScreen()->GetPrimaryDisplay());
1406
1407   // Initialize before AcceleratorController and AshAcceleratorConfiguration.
1408   accelerator_prefs_ = std::make_unique<AcceleratorPrefs>(
1409       shell_delegate_->CreateAcceleratorPrefsDelegate());
1410
1411   // Must be initialized after InputMethodManager.
1412   accelerator_keycode_lookup_cache_ =
1413       std::make_unique<AcceleratorKeycodeLookupCache>();
1414   ash_accelerator_configuration_ =
1415       std::make_unique<AshAcceleratorConfiguration>();
1416   ash_accelerator_configuration_->Initialize();
1417   accelerator_controller_ = std::make_unique<AcceleratorControllerImpl>(
1418       ash_accelerator_configuration_.get());
1419
1420   clipboard_history_controller_ =
1421       std::make_unique<ClipboardHistoryControllerImpl>(
1422           shell_delegate_->CreateClipboardHistoryControllerDelegate());
1423
1424   // `HoldingSpaceController` must be instantiated before the shelf.
1425   holding_space_controller_ = std::make_unique<HoldingSpaceController>();
1426
1427   calendar_controller_ = std::make_unique<CalendarController>();
1428
1429   if (features::IsVideoConferenceEnabled()) {
1430     camera_effects_controller_ = std::make_unique<CameraEffectsController>();
1431     audio_effects_controller_ = std::make_unique<AudioEffectsController>();
1432   }
1433
1434   shelf_config_ = std::make_unique<ShelfConfig>();
1435   shelf_controller_ = std::make_unique<ShelfController>();
1436
1437   shell_tab_handler_ = std::make_unique<ShellTabHandler>(this);
1438   AddPreTargetHandler(shell_tab_handler_.get());
1439   magnifier_key_scroll_handler_ = MagnifierKeyScroller::CreateHandler();
1440   AddPreTargetHandler(magnifier_key_scroll_handler_.get());
1441   speech_feedback_handler_ = SpokenFeedbackToggler::CreateHandler();
1442   AddPreTargetHandler(speech_feedback_handler_.get());
1443
1444   // The order in which event filters are added is significant.
1445
1446   // ui::UserActivityDetector passes events to observers, so let them get
1447   // rewritten first.
1448   user_activity_detector_ = std::make_unique<ui::UserActivityDetector>();
1449
1450   control_v_histogram_recorder_ = std::make_unique<ControlVHistogramRecorder>();
1451   AddPreTargetHandler(control_v_histogram_recorder_.get(),
1452                       ui::EventTarget::Priority::kAccessibility);
1453
1454   // AcceleratorTracker should be placed before AcceleratorFilter to make sure
1455   // the accelerators won't be filtered out before getting AcceleratorTracker.
1456   accelerator_tracker_ = std::make_unique<AcceleratorTracker>(
1457       base::make_span(kAcceleratorTrackerList, kAcceleratorTrackerListLength));
1458   AddPreTargetHandler(accelerator_tracker_.get());
1459
1460   accelerator_filter_ = std::make_unique<::wm::AcceleratorFilter>(
1461       std::make_unique<PreTargetAcceleratorHandler>());
1462   AddPreTargetHandler(accelerator_filter_.get());
1463
1464   event_transformation_handler_ =
1465       std::make_unique<EventTransformationHandler>();
1466   AddPreTargetHandler(event_transformation_handler_.get());
1467
1468   back_gesture_event_handler_ = std::make_unique<BackGestureEventHandler>();
1469   AddPreTargetHandler(back_gesture_event_handler_.get());
1470
1471   toplevel_window_event_handler_ =
1472       std::make_unique<ToplevelWindowEventHandler>();
1473
1474   system_gesture_filter_ = std::make_unique<SystemGestureEventFilter>();
1475   AddPreTargetHandler(system_gesture_filter_.get());
1476
1477   sticky_keys_controller_ = std::make_unique<StickyKeysController>();
1478   screen_pinning_controller_ = std::make_unique<ScreenPinningController>();
1479
1480   power_prefs_ = std::make_unique<PowerPrefs>(
1481       chromeos::PowerPolicyController::Get(),
1482       chromeos::PowerManagerClient::Get(), local_state_);
1483
1484   backlights_forced_off_setter_ = std::make_unique<BacklightsForcedOffSetter>();
1485
1486   tray_action_ =
1487       std::make_unique<TrayAction>(backlights_forced_off_setter_.get());
1488
1489   lock_state_controller_ = std::make_unique<LockStateController>(
1490       shutdown_controller_.get(), local_state_);
1491   power_button_controller_ = std::make_unique<PowerButtonController>(
1492       backlights_forced_off_setter_.get());
1493   // Pass the initial display state to PowerButtonController.
1494   power_button_controller_->OnDisplayModeChanged(
1495       display_configurator()->cached_displays());
1496
1497   drag_drop_controller_ = std::make_unique<DragDropController>();
1498
1499   mouse_cursor_filter_ = std::make_unique<MouseCursorEventFilter>();
1500   AddAccessibilityEventHandler(
1501       mouse_cursor_filter_.get(),
1502       AccessibilityEventHandlerManager::HandlerType::kCursor);
1503
1504   if (features::IsAdaptiveChargingEnabled()) {
1505     adaptive_charging_controller_ =
1506         std::make_unique<AdaptiveChargingController>();
1507   }
1508
1509   // Create Controllers that may need root window.
1510   // TODO(oshima): Move as many controllers before creating
1511   // RootWindowController as possible.
1512   visibility_controller_ = std::make_unique<AshVisibilityController>();
1513
1514   laser_pointer_controller_ = std::make_unique<LaserPointerController>();
1515   partial_magnifier_controller_ =
1516       std::make_unique<PartialMagnifierController>();
1517
1518   fullscreen_magnifier_controller_ =
1519       std::make_unique<FullscreenMagnifierController>();
1520   mru_window_tracker_ = std::make_unique<MruWindowTracker>();
1521   assistant_controller_ = std::make_unique<AssistantControllerImpl>();
1522
1523   // MultiDisplayMetricsController has a dependency on `mru_window_tracker_`.
1524   multi_display_metrics_controller_ =
1525       std::make_unique<MultiDisplayMetricsController>();
1526
1527   mojo::PendingRemote<device::mojom::Fingerprint> ambient_fingerprint;
1528   shell_delegate_->BindFingerprint(
1529       ambient_fingerprint.InitWithNewPipeAndPassReceiver());
1530   ambient_controller_ =
1531       std::make_unique<AmbientController>(std::move(ambient_fingerprint));
1532
1533   mojo::PendingRemote<video_capture::mojom::MultiCaptureService>
1534       multi_capture_service;
1535   shell_delegate_->BindMultiCaptureService(
1536       multi_capture_service.InitWithNewPipeAndPassReceiver());
1537   multi_capture_service_client_ = std::make_unique<MultiCaptureServiceClient>(
1538       std::move(multi_capture_service));
1539
1540   // |tablet_mode_controller_| |mru_window_tracker_|, and
1541   // |assistant_controller_| are put before |app_list_controller_| as they are
1542   // used in its constructor.
1543   app_list_controller_ = std::make_unique<AppListControllerImpl>();
1544
1545   autoclick_controller_ = std::make_unique<AutoclickController>();
1546
1547   color_enhancement_controller_ =
1548       std::make_unique<ColorEnhancementController>();
1549
1550   security_curtain_controller_ =
1551       std::make_unique<curtain::SecurityCurtainControllerImpl>(this);
1552
1553   docked_magnifier_controller_ = std::make_unique<DockedMagnifierController>();
1554
1555   video_detector_ = std::make_unique<VideoDetector>();
1556
1557   tooltip_controller_ = std::make_unique<views::corewm::TooltipController>(
1558       std::make_unique<views::corewm::TooltipAura>(
1559           base::BindRepeating(&StyleUtil::CreateAshStyleTooltipView)),
1560       activation_client());
1561   AddPreTargetHandler(tooltip_controller_.get());
1562
1563   modality_filter_ = std::make_unique<SystemModalContainerEventFilter>(this);
1564   AddPreTargetHandler(modality_filter_.get());
1565
1566   if (features::IsPeripheralCustomizationEnabled()) {
1567     shortcut_input_handler_ = std::make_unique<ShortcutInputHandler>();
1568     AddPreTargetHandler(shortcut_input_handler_.get());
1569   }
1570
1571   event_client_ = std::make_unique<EventClientImpl>();
1572
1573   resize_shadow_controller_ = std::make_unique<ResizeShadowController>();
1574   raster_scale_controller_ = std::make_unique<RasterScaleController>();
1575   shadow_controller_ = std::make_unique<::wm::ShadowController>(
1576       focus_controller_.get(), std::make_unique<WmShadowControllerDelegate>(),
1577       env);
1578
1579   logout_confirmation_controller_ =
1580       std::make_unique<LogoutConfirmationController>();
1581
1582   // Create AshTouchTransformController before
1583   // WindowTreeHostManager::InitDisplays()
1584   // since AshTouchTransformController listens on
1585   // WindowTreeHostManager::Observer::OnDisplaysInitialized().
1586   touch_transformer_controller_ = std::make_unique<AshTouchTransformController>(
1587       display_manager_.get(),
1588       std::make_unique<display::DefaultTouchTransformSetter>());
1589
1590   // |system_tray_model_| should be available before
1591   // |system_notification_controller_| is initialized and Shelf is created by
1592   // WindowTreeHostManager::InitHosts.
1593   system_tray_model_ = std::make_unique<SystemTrayModel>();
1594
1595   // The |shelf_config_| needs |app_list_controller_| and |system_tray_model_|
1596   // to initialize itself.
1597   shelf_config_->Init();
1598
1599   // The `shelf_controller_` needs `app_list_controller_` to initialize
1600   // launcher_nudge_controller_.
1601   shelf_controller_->Init();
1602
1603   nearby_share_controller_ = std::make_unique<NearbyShareControllerImpl>();
1604   nearby_share_delegate_ = shell_delegate_->CreateNearbyShareDelegate(
1605       nearby_share_controller_.get());
1606
1607   // System sounds delegate should be initialized before
1608   // `SystemNotificationController` is created, because
1609   // `SystemNotificationController` ctor will creat an instance of
1610   // `PowerSoundsController`, which will access and play the initialized sounds.
1611   if (features::AreSystemSoundsEnabled()) {
1612     system_sounds_delegate_ = shell_delegate_->CreateSystemSoundsDelegate();
1613     system_sounds_delegate_->Init();
1614   }
1615
1616   privacy_hub_controller_ = PrivacyHubController::CreatePrivacyHubController();
1617
1618   // One of the subcontrollers accesses the SystemNotificationController.
1619   system_notification_controller_ =
1620       std::make_unique<SystemNotificationController>();
1621
1622   if (features::IsFocusModeEnabled()) {
1623     focus_mode_controller_ = std::make_unique<FocusModeController>();
1624   }
1625
1626   // WmModeController should be created before initializing the window tree
1627   // hosts, since the latter will initialize the shelf on each display, which
1628   // hosts the WM mode tray button.
1629   if (features::IsWmModeEnabled()) {
1630     wm_mode_controller_ = std::make_unique<WmModeController>();
1631   }
1632
1633   if (features::IsHotspotEnabled()) {
1634     hotspot_icon_animation_ = std::make_unique<HotspotIconAnimation>();
1635     hotspot_info_cache_ = std::make_unique<HotspotInfoCache>();
1636   }
1637
1638   window_tree_host_manager_->InitHosts();
1639
1640   if (ash::features::IsOobeSimonEnabled()) {
1641     booting_animation_controller_ =
1642         std::make_unique<BootingAnimationController>();
1643   }
1644
1645   // Create virtual keyboard after WindowTreeHostManager::InitHosts() since
1646   // it may enable the virtual keyboard immediately, which requires a
1647   // WindowTreeHostManager to host the keyboard window.
1648   keyboard_controller_->CreateVirtualKeyboard(std::move(keyboard_ui_factory));
1649
1650   // Create window restore controller after `WindowTreeHostManager::InitHosts()`
1651   // since it may need to add observers to root windows.
1652   window_restore_controller_ = std::make_unique<WindowRestoreController>();
1653
1654   static_cast<CursorManager*>(cursor_manager_.get())->Init();
1655
1656   mojo::PendingRemote<device::mojom::Fingerprint> fingerprint;
1657   shell_delegate_->BindFingerprint(
1658       fingerprint.InitWithNewPipeAndPassReceiver());
1659   user_activity_notifier_ =
1660       std::make_unique<ui::UserActivityPowerManagerNotifier>(
1661           user_activity_detector_.get(), std::move(fingerprint));
1662   video_activity_notifier_ =
1663       std::make_unique<VideoActivityNotifier>(video_detector_.get());
1664   bluetooth_state_cache_ = std::make_unique<BluetoothStateCache>();
1665   bluetooth_device_status_ui_handler_ =
1666       std::make_unique<BluetoothDeviceStatusUiHandler>();
1667   bluetooth_notification_controller_ =
1668       std::make_unique<BluetoothNotificationController>(
1669           message_center::MessageCenter::Get());
1670   screen_orientation_controller_ =
1671       std::make_unique<ScreenOrientationController>();
1672
1673   cros_display_config_ = std::make_unique<CrosDisplayConfig>();
1674
1675   screen_layout_observer_ = std::make_unique<ScreenLayoutObserver>();
1676   sms_observer_ = std::make_unique<SmsObserver>();
1677   snap_controller_ = std::make_unique<SnapControllerImpl>();
1678   key_accessibility_enabler_ = std::make_unique<KeyAccessibilityEnabler>();
1679
1680   // The compositor thread and main message loop have to be running in
1681   // order to create mirror window. Run it after the main message loop
1682   // is started.
1683   display_manager_->CreateMirrorWindowAsyncIfAny();
1684
1685   // TODO(1091497): Consider combining DisplayHighlightController and
1686   // DisplayAlignmentController.
1687   display_highlight_controller_ =
1688       std::make_unique<DisplayHighlightController>();
1689
1690   if (features::IsDisplayAlignmentAssistanceEnabled()) {
1691     display_alignment_controller_ =
1692         std::make_unique<DisplayAlignmentController>();
1693   }
1694
1695   if (features::AreGlanceablesV2Enabled() ||
1696       features::AreGlanceablesV2EnabledForTrustedTesters()) {
1697     glanceables_controller_ = std::make_unique<GlanceablesController>();
1698   }
1699   post_login_glanceables_metrics_reporter_ =
1700       std::make_unique<PostLoginGlanceablesMetricsRecorder>();
1701
1702   projector_controller_ = std::make_unique<ProjectorControllerImpl>();
1703
1704   float_controller_ = std::make_unique<FloatController>();
1705   pip_controller_ = std::make_unique<PipController>();
1706
1707   multitask_menu_nudge_delegate_ =
1708       std::make_unique<MultitaskMenuNudgeDelegateAsh>();
1709
1710   if (features::IsFederatedServiceEnabled()) {
1711     federated_service_controller_ =
1712         std::make_unique<federated::FederatedServiceControllerImpl>();
1713   }
1714
1715   if (features::IsUserEducationEnabled()) {
1716     user_education_controller_ = std::make_unique<UserEducationController>(
1717         shell_delegate_->CreateUserEducationDelegate());
1718   }
1719
1720   if (features::IsCoralFeatureEnabled() &&
1721       CoralController::IsSecretKeyMatched()) {
1722     coral_controller_ = std::make_unique<CoralController>();
1723   }
1724
1725   // Injects the factory which fulfills the implementation of the text context
1726   // menu exclusive to CrOS.
1727   views::ViewsTextServicesContextMenuChromeos::SetImplFactory(
1728       base::BindRepeating(
1729           [](ui::SimpleMenuModel* menu_model, views::Textfield* textfield)
1730               -> std::unique_ptr<views::ViewsTextServicesContextMenu> {
1731             return std::make_unique<ViewsTextServicesContextMenuAsh>(menu_model,
1732                                                                      textfield);
1733           }));
1734
1735   // Sets the implementation of clipboard history utility functions.
1736   // It is safe to pass `clipboard_history_controller_` raw pointer here.
1737   // Because the function implementation is reset before
1738   // `clipboard_history_controller_` is destroyed.
1739   chromeos::clipboard_history::SetQueryItemDescriptorsImpl(base::BindRepeating(
1740       [](ClipboardHistoryControllerImpl* controller) {
1741         std::vector<crosapi::mojom::ClipboardHistoryItemDescriptor> descriptors;
1742         if (clipboard_history_util::IsEnabledInCurrentMode()) {
1743           const auto& items = controller->history()->GetItems();
1744           descriptors.reserve(items.size());
1745           base::ranges::transform(items, std::back_inserter(descriptors),
1746                                   &clipboard_history_util::ItemToDescriptor);
1747         }
1748         return descriptors;
1749       },
1750       clipboard_history_controller_.get()));
1751   chromeos::clipboard_history::SetPasteClipboardItemByIdImpl(
1752       base::BindRepeating(
1753           [](const base::UnguessableToken& id, int event_flags,
1754              crosapi::mojom::ClipboardHistoryControllerShowSource show_source) {
1755             ClipboardHistoryController::Get()->PasteClipboardItemById(
1756                 id.ToString(), event_flags, show_source);
1757           }));
1758
1759   for (auto& observer : shell_observers_) {
1760     observer.OnShellInitialized();
1761   }
1762
1763   user_metrics_recorder_->OnShellInitialized();
1764
1765   occlusion_tracker_pauser_ = std::make_unique<OcclusionTrackerPauser>();
1766
1767   // Initialize the D-Bus bus and services for ash.
1768   dbus_bus_ = dbus_bus;
1769   ash_dbus_services_ = std::make_unique<AshDBusServices>(dbus_bus.get());
1770 }
1771
1772 void Shell::InitializeDisplayManager() {
1773   if (!native_display_delegate_) {
1774     native_display_delegate_ =
1775         ui::OzonePlatform::GetInstance()->CreateNativeDisplayDelegate();
1776   }
1777   display_manager_->InitConfigurator(std::move(native_display_delegate_));
1778   display_configuration_controller_ =
1779       std::make_unique<DisplayConfigurationController>(
1780           display_manager_.get(), window_tree_host_manager_.get());
1781   display_configuration_observer_ =
1782       std::make_unique<DisplayConfigurationObserver>();
1783
1784   persistent_window_controller_ =
1785       std::make_unique<PersistentWindowController>();
1786
1787   projecting_observer_ =
1788       std::make_unique<ProjectingObserver>(display_manager_->configurator());
1789
1790   display_prefs_ = std::make_unique<DisplayPrefs>(local_state_);
1791
1792   bool display_initialized = display_manager_->InitFromCommandLine();
1793
1794   if (!display_initialized) {
1795     if (base::SysInfo::IsRunningOnChromeOS()) {
1796       display_change_observer_ =
1797           std::make_unique<display::DisplayChangeObserver>(
1798               display_manager_.get());
1799
1800       display_error_observer_ = std::make_unique<DisplayErrorObserver>();
1801       display_shutdown_observer_ = std::make_unique<DisplayShutdownObserver>(
1802           display_manager_->configurator());
1803
1804       display_manager_->ForceInitialConfigureWithObservers(
1805           display_change_observer_.get(), display_error_observer_.get());
1806       display_initialized = true;
1807     }
1808   }
1809
1810   display_color_manager_ =
1811       std::make_unique<DisplayColorManager>(display_manager_->configurator());
1812
1813   display_port_observer_ = std::make_unique<display::DisplayPortObserver>(
1814       display_manager_->configurator(),
1815       base::BindRepeating([](const std::vector<uint32_t>& port_nums) {
1816         TypecdClient::Get()->SetTypeCPortsUsingDisplays(port_nums);
1817       }));
1818
1819   if (!display_initialized) {
1820     display_manager_->InitDefaultDisplay();
1821   }
1822 }
1823
1824 void Shell::InitRootWindow(aura::Window* root_window) {
1825   DCHECK(focus_controller_);
1826   DCHECK(visibility_controller_.get());
1827
1828   aura::client::SetFocusClient(root_window, focus_controller_.get());
1829   ::wm::SetActivationClient(root_window, focus_controller_.get());
1830   root_window->AddPreTargetHandler(focus_controller_.get());
1831   aura::client::SetVisibilityClient(root_window, visibility_controller_.get());
1832   aura::client::SetDragDropClient(root_window, drag_drop_controller_.get());
1833   aura::client::SetScreenPositionClient(root_window,
1834                                         screen_position_controller_.get());
1835   aura::client::SetCursorClient(root_window, cursor_manager_.get());
1836   ::wm::SetTooltipClient(root_window, tooltip_controller_.get());
1837   aura::client::SetEventClient(root_window, event_client_.get());
1838
1839   ::wm::SetWindowMoveClient(root_window, toplevel_window_event_handler_.get());
1840   root_window->AddPreTargetHandler(toplevel_window_event_handler_.get());
1841   root_window->AddPostTargetHandler(toplevel_window_event_handler_.get());
1842 }
1843
1844 void Shell::CloseAllRootWindowChildWindows() {
1845   for (aura::Window* root : GetAllRootWindows()) {
1846     RootWindowController* controller = RootWindowController::ForWindow(root);
1847     if (controller) {
1848       controller->CloseChildWindows();
1849     } else {
1850       while (!root->children().empty()) {
1851         aura::Window* child = root->children()[0];
1852         delete child;
1853       }
1854     }
1855   }
1856 }
1857
1858 bool Shell::CanWindowReceiveEvents(aura::Window* window) {
1859   RootWindowControllerList controllers = GetAllRootWindowControllers();
1860   for (RootWindowController* controller : controllers) {
1861     if (controller->CanWindowReceiveEvents(window)) {
1862       return true;
1863     }
1864   }
1865   return false;
1866 }
1867
1868 ////////////////////////////////////////////////////////////////////////////////
1869 // Shell, ui::EventTarget overrides:
1870
1871 bool Shell::CanAcceptEvent(const ui::Event& event) {
1872   return true;
1873 }
1874
1875 ui::EventTarget* Shell::GetParentTarget() {
1876   return aura::Env::GetInstance();
1877 }
1878
1879 std::unique_ptr<ui::EventTargetIterator> Shell::GetChildIterator() const {
1880   return nullptr;
1881 }
1882
1883 ui::EventTargeter* Shell::GetEventTargeter() {
1884   NOTREACHED();
1885   return nullptr;
1886 }
1887
1888 void Shell::OnWindowActivated(
1889     ::wm::ActivationChangeObserver::ActivationReason reason,
1890     aura::Window* gained_active,
1891     aura::Window* lost_active) {
1892   if (!gained_active) {
1893     return;
1894   }
1895
1896   Shell::SetRootWindowForNewWindows(gained_active->GetRootWindow());
1897 }
1898
1899 void Shell::OnFirstSessionStarted() {
1900   // Enable magnifier scroll keys as there may be no mouse cursor in kiosk mode.
1901   MagnifierKeyScroller::SetEnabled(session_controller_->IsRunningInAppMode());
1902
1903   // Enable long press action to toggle spoken feedback with hotrod remote
1904   // which can't handle shortcuts.
1905   SpokenFeedbackToggler::SetEnabled(session_controller_->IsRunningInAppMode());
1906
1907   // Reset user prefs related to contextual tooltips.
1908   if (switches::ContextualNudgesResetShownCount()) {
1909     contextual_tooltip::ClearPrefs();
1910   }
1911
1912   // The launcher is not available before login, so start tracking usage after
1913   // the session starts.
1914   app_list_feature_usage_metrics_ =
1915       std::make_unique<AppListFeatureUsageMetrics>();
1916 }
1917
1918 void Shell::OnSessionStateChanged(session_manager::SessionState state) {
1919   const bool is_session_active = state == session_manager::SessionState::ACTIVE;
1920   // Initialize the |shelf_window_watcher_| when a session becomes active.
1921   // Shelf itself is initialized in RootWindowController.
1922   if (is_session_active && !shelf_window_watcher_) {
1923     shelf_window_watcher_ =
1924         std::make_unique<ShelfWindowWatcher>(shelf_controller()->model());
1925   }
1926
1927   // Initialize the fwupd (firmware updater) DBus client only when the user
1928   // session is active. Since the fwupd service is only relevant during an
1929   // active user session, this prevents a bug in which the service would start
1930   // up earlier than expected and causes a delay during boot.
1931   // See b/250002264 for more details.
1932   if (is_session_active && !FwupdClient::Get() &&
1933       !firmware_update_notification_controller_ &&
1934       !features::IsBlockFwupdClientEnabled()) {
1935     chromeos::InitializeDBusClient<FwupdClient>(dbus_bus_.get());
1936     firmware_update_manager_ = std::make_unique<FirmwareUpdateManager>();
1937     // The notification controller is registered as an observer before
1938     // requesting updates to allow a notification to be shown if a critical
1939     // firmware update is found.
1940     firmware_update_notification_controller_ =
1941         std::make_unique<FirmwareUpdateNotificationController>(
1942             message_center::MessageCenter::Get());
1943     firmware_update_manager_->RequestAllUpdates();
1944   }
1945
1946   // Disable drag-and-drop during OOBE and GAIA login screens by only enabling
1947   // the controller when the session is active. https://crbug.com/464118
1948   drag_drop_controller_->set_enabled(is_session_active);
1949 }
1950
1951 void Shell::OnLoginStatusChanged(LoginStatus login_status) {
1952   UpdateAfterLoginStatusChange(login_status);
1953 }
1954
1955 void Shell::OnLockStateChanged(bool locked) {
1956 #ifndef NDEBUG
1957   // Make sure that there is no system modal in Lock layer when unlocked.
1958   if (!locked) {
1959     aura::Window::Windows containers = GetContainersForAllRootWindows(
1960         kShellWindowId_LockSystemModalContainer, GetPrimaryRootWindow());
1961     for (aura::Window* container : containers) {
1962       DCHECK(container->children().empty());
1963     }
1964   }
1965 #endif
1966 }
1967
1968 }  // namespace ash