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