Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / ash / shell.cc
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "ash/shell.h"
6
7 #include <algorithm>
8 #include <string>
9
10 #include "ash/accelerators/accelerator_controller.h"
11 #include "ash/accelerators/accelerator_filter.h"
12 #include "ash/accelerators/focus_manager_factory.h"
13 #include "ash/accelerators/nested_dispatcher_controller.h"
14 #include "ash/ash_switches.h"
15 #include "ash/autoclick/autoclick_controller.h"
16 #include "ash/caps_lock_delegate.h"
17 #include "ash/desktop_background/desktop_background_controller.h"
18 #include "ash/desktop_background/desktop_background_view.h"
19 #include "ash/desktop_background/user_wallpaper_delegate.h"
20 #include "ash/display/cursor_window_controller.h"
21 #include "ash/display/display_controller.h"
22 #include "ash/display/display_manager.h"
23 #include "ash/display/event_transformation_handler.h"
24 #include "ash/display/mouse_cursor_event_filter.h"
25 #include "ash/display/screen_position_controller.h"
26 #include "ash/display/virtual_keyboard_window_controller.h"
27 #include "ash/drag_drop/drag_drop_controller.h"
28 #include "ash/first_run/first_run_helper_impl.h"
29 #include "ash/focus_cycler.h"
30 #include "ash/gpu_support.h"
31 #include "ash/high_contrast/high_contrast_controller.h"
32 #include "ash/host/window_tree_host_factory.h"
33 #include "ash/keyboard_uma_event_filter.h"
34 #include "ash/magnifier/magnification_controller.h"
35 #include "ash/magnifier/partial_magnification_controller.h"
36 #include "ash/media_delegate.h"
37 #include "ash/new_window_delegate.h"
38 #include "ash/root_window_controller.h"
39 #include "ash/session_state_delegate.h"
40 #include "ash/shelf/app_list_shelf_item_delegate.h"
41 #include "ash/shelf/shelf_delegate.h"
42 #include "ash/shelf/shelf_item_delegate.h"
43 #include "ash/shelf/shelf_item_delegate_manager.h"
44 #include "ash/shelf/shelf_layout_manager.h"
45 #include "ash/shelf/shelf_model.h"
46 #include "ash/shelf/shelf_widget.h"
47 #include "ash/shelf/shelf_window_watcher.h"
48 #include "ash/shell_delegate.h"
49 #include "ash/shell_factory.h"
50 #include "ash/shell_window_ids.h"
51 #include "ash/system/locale/locale_notification_controller.h"
52 #include "ash/system/status_area_widget.h"
53 #include "ash/system/tray/system_tray_delegate.h"
54 #include "ash/system/tray/system_tray_notifier.h"
55 #include "ash/wm/app_list_controller.h"
56 #include "ash/wm/ash_focus_rules.h"
57 #include "ash/wm/ash_native_cursor_manager.h"
58 #include "ash/wm/coordinate_conversion.h"
59 #include "ash/wm/custom_frame_view_ash.h"
60 #include "ash/wm/event_client_impl.h"
61 #include "ash/wm/lock_state_controller.h"
62 #include "ash/wm/mru_window_tracker.h"
63 #include "ash/wm/overlay_event_filter.h"
64 #include "ash/wm/overview/window_selector_controller.h"
65 #include "ash/wm/power_button_controller.h"
66 #include "ash/wm/resize_shadow_controller.h"
67 #include "ash/wm/root_window_layout_manager.h"
68 #include "ash/wm/screen_dimmer.h"
69 #include "ash/wm/system_gesture_event_filter.h"
70 #include "ash/wm/system_modal_container_event_filter.h"
71 #include "ash/wm/system_modal_container_layout_manager.h"
72 #include "ash/wm/toplevel_window_event_handler.h"
73 #include "ash/wm/user_activity_detector.h"
74 #include "ash/wm/video_detector.h"
75 #include "ash/wm/window_animations.h"
76 #include "ash/wm/window_cycle_controller.h"
77 #include "ash/wm/window_positioner.h"
78 #include "ash/wm/window_properties.h"
79 #include "ash/wm/window_util.h"
80 #include "ash/wm/workspace_controller.h"
81 #include "base/bind.h"
82 #include "base/command_line.h"
83 #include "base/debug/trace_event.h"
84 #include "ui/aura/client/aura_constants.h"
85 #include "ui/aura/client/user_action_client.h"
86 #include "ui/aura/env.h"
87 #include "ui/aura/layout_manager.h"
88 #include "ui/aura/root_window.h"
89 #include "ui/aura/window.h"
90 #include "ui/base/ui_base_switches.h"
91 #include "ui/compositor/layer.h"
92 #include "ui/compositor/layer_animator.h"
93 #include "ui/events/event_target_iterator.h"
94 #include "ui/gfx/display.h"
95 #include "ui/gfx/image/image_skia.h"
96 #include "ui/gfx/screen.h"
97 #include "ui/gfx/size.h"
98 #include "ui/keyboard/keyboard.h"
99 #include "ui/keyboard/keyboard_controller.h"
100 #include "ui/keyboard/keyboard_switches.h"
101 #include "ui/keyboard/keyboard_util.h"
102 #include "ui/message_center/message_center.h"
103 #include "ui/views/corewm/compound_event_filter.h"
104 #include "ui/views/corewm/corewm_switches.h"
105 #include "ui/views/corewm/focus_controller.h"
106 #include "ui/views/corewm/input_method_event_filter.h"
107 #include "ui/views/corewm/shadow_controller.h"
108 #include "ui/views/corewm/tooltip_aura.h"
109 #include "ui/views/corewm/tooltip_controller.h"
110 #include "ui/views/corewm/visibility_controller.h"
111 #include "ui/views/corewm/window_modality_controller.h"
112 #include "ui/views/focus/focus_manager_factory.h"
113 #include "ui/views/widget/native_widget_aura.h"
114 #include "ui/views/widget/widget.h"
115
116 #if defined(OS_CHROMEOS)
117 #if defined(USE_X11)
118 #include "ash/accelerators/magnifier_key_scroller.h"
119 #include "ash/accelerators/spoken_feedback_toggler.h"
120 #include "ash/ash_constants.h"
121 #include "ash/display/display_change_observer_chromeos.h"
122 #include "ash/display/display_error_observer_chromeos.h"
123 #include "ash/display/output_configurator_animation.h"
124 #include "ash/display/projecting_observer_chromeos.h"
125 #include "base/message_loop/message_pump_x11.h"
126 #include "base/sys_info.h"
127 #include "chromeos/display/output_configurator.h"
128 #endif  // defined(USE_X11)
129 #include "ash/display/resolution_notification_controller.h"
130 #include "ash/sticky_keys/sticky_keys_controller.h"
131 #include "ash/system/chromeos/brightness/brightness_controller_chromeos.h"
132 #include "ash/system/chromeos/power/power_event_observer.h"
133 #include "ash/system/chromeos/power/power_status.h"
134 #include "ash/system/chromeos/power/user_activity_notifier.h"
135 #include "ash/system/chromeos/power/video_activity_notifier.h"
136 #endif  // defined(OS_CHROMEOS)
137
138 namespace ash {
139
140 namespace {
141
142 using aura::Window;
143 using views::Widget;
144
145 // A Corewm VisibilityController subclass that calls the Ash animation routine
146 // so we can pick up our extended animations. See ash/wm/window_animations.h.
147 class AshVisibilityController : public views::corewm::VisibilityController {
148  public:
149   AshVisibilityController() {}
150   virtual ~AshVisibilityController() {}
151
152  private:
153   // Overridden from views::corewm::VisibilityController:
154   virtual bool CallAnimateOnChildWindowVisibilityChanged(
155       aura::Window* window,
156       bool visible) OVERRIDE {
157     return AnimateOnChildWindowVisibilityChanged(window, visible);
158   }
159
160   DISALLOW_COPY_AND_ASSIGN(AshVisibilityController);
161 };
162
163 }  // namespace
164
165 // static
166 Shell* Shell::instance_ = NULL;
167 // static
168 bool Shell::initially_hide_cursor_ = false;
169
170 ////////////////////////////////////////////////////////////////////////////////
171 // Shell, public:
172
173 // static
174 Shell* Shell::CreateInstance(ShellDelegate* delegate) {
175   CHECK(!instance_);
176   instance_ = new Shell(delegate);
177   instance_->Init();
178   return instance_;
179 }
180
181 // static
182 Shell* Shell::GetInstance() {
183   DCHECK(instance_);
184   return instance_;
185 }
186
187 // static
188 bool Shell::HasInstance() {
189   return !!instance_;
190 }
191
192 // static
193 void Shell::DeleteInstance() {
194   delete instance_;
195   instance_ = NULL;
196 }
197
198 // static
199 internal::RootWindowController* Shell::GetPrimaryRootWindowController() {
200   return internal::GetRootWindowController(GetPrimaryRootWindow());
201 }
202
203 // static
204 Shell::RootWindowControllerList Shell::GetAllRootWindowControllers() {
205   return Shell::GetInstance()->display_controller()->
206       GetAllRootWindowControllers();
207 }
208
209 // static
210 aura::Window* Shell::GetPrimaryRootWindow() {
211   return GetInstance()->display_controller()->GetPrimaryRootWindow();
212 }
213
214 // static
215 aura::Window* Shell::GetTargetRootWindow() {
216   Shell* shell = GetInstance();
217   if (shell->scoped_target_root_window_)
218     return shell->scoped_target_root_window_;
219   return shell->target_root_window_;
220 }
221
222 // static
223 gfx::Screen* Shell::GetScreen() {
224   return gfx::Screen::GetScreenByType(gfx::SCREEN_TYPE_ALTERNATE);
225 }
226
227 // static
228 aura::Window::Windows Shell::GetAllRootWindows() {
229   return Shell::GetInstance()->display_controller()->
230       GetAllRootWindows();
231 }
232
233 // static
234 aura::Window* Shell::GetContainer(aura::Window* root_window,
235                                   int container_id) {
236   return root_window->GetChildById(container_id);
237 }
238
239 // static
240 const aura::Window* Shell::GetContainer(const aura::Window* root_window,
241                                         int container_id) {
242   return root_window->GetChildById(container_id);
243 }
244
245 // static
246 std::vector<aura::Window*> Shell::GetContainersFromAllRootWindows(
247     int container_id,
248     aura::Window* priority_root) {
249   std::vector<aura::Window*> containers;
250   aura::Window::Windows root_windows = GetAllRootWindows();
251   for (aura::Window::Windows::const_iterator it = root_windows.begin();
252        it != root_windows.end(); ++it) {
253     aura::Window* container = (*it)->GetChildById(container_id);
254     if (container) {
255       if (priority_root && priority_root->Contains(container))
256         containers.insert(containers.begin(), container);
257       else
258         containers.push_back(container);
259     }
260   }
261   return containers;
262 }
263
264 void Shell::ShowContextMenu(const gfx::Point& location_in_screen,
265                             ui::MenuSourceType source_type) {
266   // No context menus if there is no session with an active user.
267   if (!session_state_delegate_->NumberOfLoggedInUsers())
268     return;
269   // No context menus when screen is locked.
270   if (session_state_delegate_->IsScreenLocked())
271     return;
272
273   aura::Window* root =
274       wm::GetRootWindowMatching(gfx::Rect(location_in_screen, gfx::Size()));
275   internal::GetRootWindowController(root)->
276       ShowContextMenu(location_in_screen, source_type);
277 }
278
279 void Shell::ToggleAppList(aura::Window* window) {
280   // If the context window is not given, show it on the target root window.
281   if (!window)
282     window = GetTargetRootWindow();
283   if (!app_list_controller_)
284     app_list_controller_.reset(new internal::AppListController);
285   app_list_controller_->SetVisible(!app_list_controller_->IsVisible(), window);
286 }
287
288 bool Shell::GetAppListTargetVisibility() const {
289   return app_list_controller_.get() &&
290       app_list_controller_->GetTargetVisibility();
291 }
292
293 aura::Window* Shell::GetAppListWindow() {
294   return app_list_controller_.get() ? app_list_controller_->GetWindow() : NULL;
295 }
296
297 app_list::AppListView* Shell::GetAppListView() {
298   return app_list_controller_.get() ? app_list_controller_->GetView() : NULL;
299 }
300
301 bool Shell::IsSystemModalWindowOpen() const {
302   if (simulate_modal_window_open_for_testing_)
303     return true;
304   const std::vector<aura::Window*> containers = GetContainersFromAllRootWindows(
305       internal::kShellWindowId_SystemModalContainer, NULL);
306   for (std::vector<aura::Window*>::const_iterator cit = containers.begin();
307        cit != containers.end(); ++cit) {
308     for (aura::Window::Windows::const_iterator wit = (*cit)->children().begin();
309          wit != (*cit)->children().end(); ++wit) {
310       if ((*wit)->GetProperty(aura::client::kModalKey) ==
311           ui::MODAL_TYPE_SYSTEM && (*wit)->TargetVisibility()) {
312         return true;
313       }
314     }
315   }
316   return false;
317 }
318
319 views::NonClientFrameView* Shell::CreateDefaultNonClientFrameView(
320     views::Widget* widget) {
321   // Use translucent-style window frames for dialogs.
322   return new CustomFrameViewAsh(widget);
323 }
324
325 void Shell::RotateFocus(Direction direction) {
326   focus_cycler_->RotateFocus(
327       direction == FORWARD ? internal::FocusCycler::FORWARD :
328                              internal::FocusCycler::BACKWARD);
329 }
330
331 void Shell::SetDisplayWorkAreaInsets(Window* contains,
332                                      const gfx::Insets& insets) {
333   if (!display_controller_->UpdateWorkAreaOfDisplayNearestWindow(
334           contains, insets)) {
335     return;
336   }
337   FOR_EACH_OBSERVER(ShellObserver, observers_,
338                     OnDisplayWorkAreaInsetsChanged());
339 }
340
341 void Shell::OnLoginStateChanged(user::LoginStatus status) {
342   FOR_EACH_OBSERVER(ShellObserver, observers_, OnLoginStateChanged(status));
343 }
344
345 void Shell::OnLoginUserProfilePrepared() {
346   CreateShelf();
347   CreateKeyboard();
348 }
349
350 void Shell::UpdateAfterLoginStatusChange(user::LoginStatus status) {
351   RootWindowControllerList controllers = GetAllRootWindowControllers();
352   for (RootWindowControllerList::iterator iter = controllers.begin();
353        iter != controllers.end(); ++iter)
354     (*iter)->UpdateAfterLoginStatusChange(status);
355 }
356
357 void Shell::OnAppTerminating() {
358   FOR_EACH_OBSERVER(ShellObserver, observers_, OnAppTerminating());
359 }
360
361 void Shell::OnLockStateChanged(bool locked) {
362   FOR_EACH_OBSERVER(ShellObserver, observers_, OnLockStateChanged(locked));
363 #ifndef NDEBUG
364   // Make sure that there is no system modal in Lock layer when unlocked.
365   if (!locked) {
366     std::vector<aura::Window*> containers = GetContainersFromAllRootWindows(
367         internal::kShellWindowId_LockSystemModalContainer,
368         GetPrimaryRootWindow());
369     for (std::vector<aura::Window*>::const_iterator iter = containers.begin();
370          iter != containers.end(); ++iter) {
371       DCHECK_EQ(0u, (*iter)->children().size());
372     }
373   }
374 #endif
375 }
376
377 void Shell::OnCastingSessionStartedOrStopped(bool started) {
378 #if defined(OS_CHROMEOS) && defined(USE_X11)
379   if (projecting_observer_)
380     projecting_observer_->OnCastingSessionStartedOrStopped(started);
381 #endif
382 }
383
384 void Shell::CreateShelf() {
385   RootWindowControllerList controllers = GetAllRootWindowControllers();
386   for (RootWindowControllerList::iterator iter = controllers.begin();
387        iter != controllers.end(); ++iter)
388     (*iter)->shelf()->CreateShelf();
389 }
390
391 void Shell::CreateKeyboard() {
392   // TODO(bshe): Primary root window controller may not be the controller to
393   // attach virtual keyboard. See http://crbug.com/303429
394   InitKeyboard();
395   if (keyboard::IsKeyboardUsabilityExperimentEnabled()) {
396     display_controller()->virtual_keyboard_window_controller()->
397         ActivateKeyboard(keyboard_controller_.get());
398   } else {
399     GetPrimaryRootWindowController()->
400         ActivateKeyboard(keyboard_controller_.get());
401   }
402 }
403
404 void Shell::DeactivateKeyboard() {
405   if (keyboard_controller_.get()) {
406     RootWindowControllerList controllers = GetAllRootWindowControllers();
407     for (RootWindowControllerList::iterator iter = controllers.begin();
408         iter != controllers.end(); ++iter) {
409       (*iter)->DeactivateKeyboard(keyboard_controller_.get());
410     }
411   }
412   keyboard_controller_.reset();
413 }
414
415 void Shell::ShowShelf() {
416   RootWindowControllerList controllers = GetAllRootWindowControllers();
417   for (RootWindowControllerList::iterator iter = controllers.begin();
418        iter != controllers.end(); ++iter)
419     (*iter)->ShowShelf();
420 }
421
422 void Shell::AddShellObserver(ShellObserver* observer) {
423   observers_.AddObserver(observer);
424 }
425
426 void Shell::RemoveShellObserver(ShellObserver* observer) {
427   observers_.RemoveObserver(observer);
428 }
429
430 void Shell::UpdateShelfVisibility() {
431   RootWindowControllerList controllers = GetAllRootWindowControllers();
432   for (RootWindowControllerList::iterator iter = controllers.begin();
433        iter != controllers.end(); ++iter)
434     if ((*iter)->shelf())
435       (*iter)->UpdateShelfVisibility();
436 }
437
438 void Shell::SetShelfAutoHideBehavior(ShelfAutoHideBehavior behavior,
439                                      aura::Window* root_window) {
440   ash::internal::ShelfLayoutManager::ForShelf(root_window)->
441       SetAutoHideBehavior(behavior);
442 }
443
444 ShelfAutoHideBehavior Shell::GetShelfAutoHideBehavior(
445     aura::Window* root_window) const {
446   return ash::internal::ShelfLayoutManager::ForShelf(root_window)->
447       auto_hide_behavior();
448 }
449
450 void Shell::SetShelfAlignment(ShelfAlignment alignment,
451                               aura::Window* root_window) {
452   if (ash::internal::ShelfLayoutManager::ForShelf(root_window)->
453       SetAlignment(alignment)) {
454     FOR_EACH_OBSERVER(
455         ShellObserver, observers_, OnShelfAlignmentChanged(root_window));
456   }
457 }
458
459 ShelfAlignment Shell::GetShelfAlignment(aura::Window* root_window) {
460   return internal::GetRootWindowController(root_window)->
461       GetShelfLayoutManager()->GetAlignment();
462 }
463
464 void Shell::SetDimming(bool should_dim) {
465   RootWindowControllerList controllers = GetAllRootWindowControllers();
466   for (RootWindowControllerList::iterator iter = controllers.begin();
467        iter != controllers.end(); ++iter)
468     (*iter)->screen_dimmer()->SetDimming(should_dim);
469 }
470
471 void Shell::NotifyFullscreenStateChange(bool is_fullscreen,
472                                         aura::Window* root_window) {
473   FOR_EACH_OBSERVER(ShellObserver, observers_, OnFullscreenStateChanged(
474       is_fullscreen, root_window));
475 }
476
477 void Shell::CreateModalBackground(aura::Window* window) {
478   if (!modality_filter_) {
479     modality_filter_.reset(new internal::SystemModalContainerEventFilter(this));
480     AddPreTargetHandler(modality_filter_.get());
481   }
482   RootWindowControllerList controllers = GetAllRootWindowControllers();
483   for (RootWindowControllerList::iterator iter = controllers.begin();
484        iter != controllers.end(); ++iter)
485     (*iter)->GetSystemModalLayoutManager(window)->CreateModalBackground();
486 }
487
488 void Shell::OnModalWindowRemoved(aura::Window* removed) {
489   RootWindowControllerList controllers = GetAllRootWindowControllers();
490   bool activated = false;
491   for (RootWindowControllerList::iterator iter = controllers.begin();
492        iter != controllers.end() && !activated; ++iter) {
493     activated = (*iter)->GetSystemModalLayoutManager(removed)->
494         ActivateNextModalWindow();
495   }
496   if (!activated) {
497     RemovePreTargetHandler(modality_filter_.get());
498     modality_filter_.reset();
499     for (RootWindowControllerList::iterator iter = controllers.begin();
500          iter != controllers.end(); ++iter)
501       (*iter)->GetSystemModalLayoutManager(removed)->DestroyModalBackground();
502   }
503 }
504
505 WebNotificationTray* Shell::GetWebNotificationTray() {
506   return GetPrimaryRootWindowController()->shelf()->
507       status_area_widget()->web_notification_tray();
508 }
509
510 bool Shell::HasPrimaryStatusArea() {
511   ShelfWidget* shelf = GetPrimaryRootWindowController()->shelf();
512   return shelf && shelf->status_area_widget();
513 }
514
515 SystemTray* Shell::GetPrimarySystemTray() {
516   return GetPrimaryRootWindowController()->GetSystemTray();
517 }
518
519 ShelfDelegate* Shell::GetShelfDelegate() {
520   if (!shelf_delegate_) {
521     shelf_model_.reset(new ShelfModel);
522     // Creates ShelfItemDelegateManager before ShelfDelegate.
523     shelf_item_delegate_manager_.reset(
524         new ShelfItemDelegateManager(shelf_model_.get()));
525
526     shelf_delegate_.reset(delegate_->CreateShelfDelegate(shelf_model_.get()));
527     scoped_ptr<ShelfItemDelegate> controller(
528         new internal::AppListShelfItemDelegate);
529
530     // Finding the shelf model's location of the app list and setting its
531     // ShelfItemDelegate.
532     int app_list_index = shelf_model_->GetItemIndexForType(TYPE_APP_LIST);
533     DCHECK_GE(app_list_index, 0);
534     ShelfID app_list_id = shelf_model_->items()[app_list_index].id;
535     DCHECK(app_list_id);
536     shelf_item_delegate_manager_->SetShelfItemDelegate(app_list_id,
537                                                        controller.Pass());
538     shelf_window_watcher_.reset(new internal::ShelfWindowWatcher(
539                                         shelf_model_.get(),
540                                         shelf_item_delegate_manager_.get()));
541   }
542   return shelf_delegate_.get();
543 }
544
545 void Shell::SetTouchHudProjectionEnabled(bool enabled) {
546   if (is_touch_hud_projection_enabled_ == enabled)
547     return;
548
549   is_touch_hud_projection_enabled_ = enabled;
550   FOR_EACH_OBSERVER(ShellObserver, observers_,
551                     OnTouchHudProjectionToggled(enabled));
552 }
553
554 #if defined(OS_CHROMEOS)
555 ash::FirstRunHelper* Shell::CreateFirstRunHelper() {
556   return new ash::FirstRunHelperImpl;
557 }
558
559 void Shell::SetCursorCompositingEnabled(bool enabled) {
560   display_controller_->cursor_window_controller()->SetCursorCompositingEnabled(
561       enabled);
562   native_cursor_manager_->SetNativeCursorEnabled(!enabled);
563 }
564 #endif  // defined(OS_CHROMEOS)
565
566 void Shell::DoInitialWorkspaceAnimation() {
567   return GetPrimaryRootWindowController()->workspace_controller()->
568       DoInitialAnimation();
569 }
570
571 ////////////////////////////////////////////////////////////////////////////////
572 // Shell, private:
573
574 Shell::Shell(ShellDelegate* delegate)
575     : target_root_window_(NULL),
576       scoped_target_root_window_(NULL),
577       delegate_(delegate),
578       window_positioner_(new WindowPositioner),
579       activation_client_(NULL),
580 #if defined(OS_CHROMEOS) && defined(USE_X11)
581       output_configurator_(new chromeos::OutputConfigurator()),
582 #endif  // defined(OS_CHROMEOS) && defined(USE_X11)
583       native_cursor_manager_(new AshNativeCursorManager),
584       cursor_manager_(scoped_ptr<views::corewm::NativeCursorManager>(
585           native_cursor_manager_)),
586       simulate_modal_window_open_for_testing_(false),
587       is_touch_hud_projection_enabled_(false) {
588   DCHECK(delegate_.get());
589   gpu_support_.reset(delegate_->CreateGPUSupport());
590   display_manager_.reset(new internal::DisplayManager);
591   display_controller_.reset(new DisplayController);
592 #if defined(OS_CHROMEOS) && defined(USE_X11)
593   // TODO: Move this initialization into Shell::Init().
594   output_configurator_->Init(!gpu_support_->IsPanelFittingDisabled());
595   user_metrics_recorder_.reset(new UserMetricsRecorder);
596
597   base::MessagePumpX11::Current()->AddDispatcherForRootWindow(
598       output_configurator());
599   // We can't do this with a root window listener because XI_HierarchyChanged
600   // messages don't have a target window.
601   base::MessagePumpX11::Current()->AddObserver(output_configurator());
602 #endif  // defined(OS_CHROMEOS)
603
604 #if defined(OS_CHROMEOS)
605   internal::PowerStatus::Initialize();
606 #endif
607 }
608
609 Shell::~Shell() {
610   TRACE_EVENT0("shutdown", "ash::Shell::Destructor");
611
612   views::FocusManagerFactory::Install(NULL);
613
614   // Remove the focus from any window. This will prevent overhead and side
615   // effects (e.g. crashes) from changing focus during shutdown.
616   // See bug crbug.com/134502.
617   aura::client::GetFocusClient(GetPrimaryRootWindow())->FocusWindow(NULL);
618
619   // Please keep in same order as in Init() because it's easy to miss one.
620   if (window_modality_controller_)
621     window_modality_controller_.reset();
622 #if defined(OS_CHROMEOS) && defined(USE_X11)
623   RemovePreTargetHandler(magnifier_key_scroll_handler_.get());
624   magnifier_key_scroll_handler_.reset();
625
626   RemovePreTargetHandler(speech_feedback_handler_.get());
627   speech_feedback_handler_.reset();
628 #endif
629   RemovePreTargetHandler(user_activity_detector_.get());
630   RemovePreTargetHandler(overlay_filter_.get());
631   RemovePreTargetHandler(input_method_filter_.get());
632   RemovePreTargetHandler(accelerator_filter_.get());
633   RemovePreTargetHandler(event_transformation_handler_.get());
634   RemovePreTargetHandler(toplevel_window_event_handler_.get());
635   RemovePostTargetHandler(toplevel_window_event_handler_.get());
636   RemovePreTargetHandler(system_gesture_filter_.get());
637   RemovePreTargetHandler(keyboard_metrics_filter_.get());
638   if (mouse_cursor_filter_)
639     RemovePreTargetHandler(mouse_cursor_filter_.get());
640
641   // TooltipController is deleted with the Shell so removing its references.
642   RemovePreTargetHandler(tooltip_controller_.get());
643
644   // AppList needs to be released before shelf layout manager, which is
645   // destroyed with shelf container in the loop below. However, app list
646   // container is now on top of shelf container and released after it.
647   // TODO(xiyuan): Move it back when app list container is no longer needed.
648   app_list_controller_.reset();
649
650   // Destroy SystemTrayDelegate before destroying the status area(s).
651   system_tray_delegate_->Shutdown();
652   system_tray_delegate_.reset();
653
654   locale_notification_controller_.reset();
655
656   // Drag-and-drop must be canceled prior to close all windows.
657   drag_drop_controller_.reset();
658
659   // Controllers who have WindowObserver added must be deleted
660   // before |display_controller_| is deleted.
661
662 #if defined(OS_CHROMEOS)
663   // VideoActivityNotifier must be deleted before |video_detector_| is
664   // deleted because it's observing video activity through
665   // VideoDetectorObserver interface.
666   video_activity_notifier_.reset();
667 #endif  // defined(OS_CHROMEOS)
668   video_detector_.reset();
669
670   shadow_controller_.reset();
671   resize_shadow_controller_.reset();
672
673   window_selector_controller_.reset();
674   window_cycle_controller_.reset();
675   mru_window_tracker_.reset();
676
677   // |shelf_window_watcher_| has a weak pointer to |shelf_Model_|
678   // and has window observers.
679   shelf_window_watcher_.reset();
680
681   // Destroy all child windows including widgets.
682   display_controller_->CloseChildWindows();
683   display_controller_->CloseNonDesktopDisplay();
684
685   // Chrome implementation of shelf delegate depends on FocusClient,
686   // so must be deleted before |focus_client_|.
687   shelf_delegate_.reset();
688   focus_client_.reset();
689
690   // Destroy SystemTrayNotifier after destroying SystemTray as TrayItems
691   // needs to remove observers from it.
692   system_tray_notifier_.reset();
693
694   // These need a valid Shell instance to clean up properly, so explicitly
695   // delete them before invalidating the instance.
696   // Alphabetical. TODO(oshima): sort.
697   magnification_controller_.reset();
698   partial_magnification_controller_.reset();
699   tooltip_controller_.reset();
700   event_client_.reset();
701   nested_dispatcher_controller_.reset();
702   toplevel_window_event_handler_.reset();
703   user_action_client_.reset();
704   visibility_controller_.reset();
705   // |shelf_item_delegate_manager_| observes |shelf_model_|. It must be
706   // destroyed before |shelf_model_| is destroyed.
707   shelf_item_delegate_manager_.reset();
708   shelf_model_.reset();
709
710   power_button_controller_.reset();
711   lock_state_controller_.reset();
712
713 #if defined(OS_CHROMEOS)
714   resolution_notification_controller_.reset();
715 #endif
716   desktop_background_controller_.reset();
717
718   // This also deletes all RootWindows. Note that we invoke Shutdown() on
719   // DisplayController before resetting |display_controller_|, since destruction
720   // of its owned RootWindowControllers relies on the value.
721   display_manager_->CreateScreenForShutdown();
722   display_controller_->Shutdown();
723   display_controller_.reset();
724   screen_position_controller_.reset();
725
726   keyboard_controller_.reset();
727   accessibility_delegate_.reset();
728   new_window_delegate_.reset();
729   media_delegate_.reset();
730
731 #if defined(OS_CHROMEOS) && defined(USE_X11)
732   if (display_change_observer_)
733     output_configurator_->RemoveObserver(display_change_observer_.get());
734   if (output_configurator_animation_)
735     output_configurator_->RemoveObserver(output_configurator_animation_.get());
736   if (display_error_observer_)
737     output_configurator_->RemoveObserver(display_error_observer_.get());
738   if (projecting_observer_)
739     output_configurator_->RemoveObserver(projecting_observer_.get());
740   base::MessagePumpX11::Current()->RemoveDispatcherForRootWindow(
741       output_configurator());
742   base::MessagePumpX11::Current()->RemoveObserver(output_configurator());
743   display_change_observer_.reset();
744 #endif  // defined(OS_CHROMEOS)
745
746 #if defined(OS_CHROMEOS)
747   internal::PowerStatus::Shutdown();
748 #endif
749
750   DCHECK(instance_ == this);
751   instance_ = NULL;
752 }
753
754 void Shell::Init() {
755   CommandLine* command_line = CommandLine::ForCurrentProcess();
756
757   delegate_->PreInit();
758   if (keyboard::IsKeyboardUsabilityExperimentEnabled()) {
759     display_manager_->SetSecondDisplayMode(
760         internal::DisplayManager::VIRTUAL_KEYBOARD);
761   }
762   bool display_initialized = display_manager_->InitFromCommandLine();
763 #if defined(OS_CHROMEOS) && defined(USE_X11)
764   output_configurator_animation_.reset(
765       new internal::OutputConfiguratorAnimation());
766   output_configurator_->AddObserver(output_configurator_animation_.get());
767
768   projecting_observer_.reset(new internal::ProjectingObserver());
769   output_configurator_->AddObserver(projecting_observer_.get());
770
771   if (!display_initialized && base::SysInfo::IsRunningOnChromeOS()) {
772     display_change_observer_.reset(new internal::DisplayChangeObserver);
773     // Register |display_change_observer_| first so that the rest of
774     // observer gets invoked after the root windows are configured.
775     output_configurator_->AddObserver(display_change_observer_.get());
776     display_error_observer_.reset(new internal::DisplayErrorObserver());
777     output_configurator_->AddObserver(display_error_observer_.get());
778     output_configurator_->set_state_controller(display_change_observer_.get());
779     output_configurator_->set_mirroring_controller(display_manager_.get());
780     output_configurator_->Start(
781         delegate_->IsFirstRunAfterBoot() ? kChromeOsBootColor : 0);
782     display_initialized = true;
783   }
784 #endif  // defined(OS_CHROMEOS) && defined(USE_X11)
785   if (!display_initialized)
786     display_manager_->InitDefaultDisplay();
787
788   // Install the custom factory first so that views::FocusManagers for Tray,
789   // Shelf, and WallPaper could be created by the factory.
790   views::FocusManagerFactory::Install(new AshFocusManagerFactory);
791
792   // Env creates the compositor. Historically it seems to have been implicitly
793   // initialized first by the ActivationController, but now that FocusController
794   // no longer does this we need to do it explicitly.
795   aura::Env::CreateInstance();
796
797   // The WindowModalityController needs to be at the front of the input event
798   // pretarget handler list to ensure that it processes input events when modal
799   // windows are active.
800   window_modality_controller_.reset(
801       new views::corewm::WindowModalityController(this));
802
803   AddPreTargetHandler(this);
804
805   env_filter_.reset(new views::corewm::CompoundEventFilter);
806   AddPreTargetHandler(env_filter_.get());
807
808   views::corewm::FocusController* focus_controller =
809       new views::corewm::FocusController(new wm::AshFocusRules);
810   focus_client_.reset(focus_controller);
811   activation_client_ = focus_controller;
812   activation_client_->AddObserver(this);
813   focus_cycler_.reset(new internal::FocusCycler());
814
815   screen_position_controller_.reset(new internal::ScreenPositionController);
816   window_tree_host_factory_.reset(delegate_->CreateWindowTreeHostFactory());
817
818   display_controller_->Start();
819   display_controller_->InitPrimaryDisplay();
820   aura::Window* root_window = display_controller_->GetPrimaryRootWindow();
821   target_root_window_ = root_window;
822
823 #if defined(OS_CHROMEOS)
824   resolution_notification_controller_.reset(
825       new internal::ResolutionNotificationController);
826 #endif
827
828   cursor_manager_.SetDisplay(GetScreen()->GetPrimaryDisplay());
829
830   nested_dispatcher_controller_.reset(new NestedDispatcherController);
831   accelerator_controller_.reset(new AcceleratorController);
832
833 #if defined(OS_CHROMEOS) && defined(USE_X11)
834   magnifier_key_scroll_handler_ = MagnifierKeyScroller::CreateHandler().Pass();
835   AddPreTargetHandler(magnifier_key_scroll_handler_.get());
836   speech_feedback_handler_ = SpokenFeedbackToggler::CreateHandler().Pass();
837   AddPreTargetHandler(speech_feedback_handler_.get());
838 #endif
839
840   // The order in which event filters are added is significant.
841
842 #if defined(OS_CHROMEOS)
843   // The StickyKeysController also rewrites events and must be added
844   // before observers, but after the EventRewriterEventFilter.
845   sticky_keys_controller_.reset(new StickyKeysController);
846   AddPreTargetHandler(sticky_keys_controller_.get());
847 #endif
848
849   // UserActivityDetector passes events to observers, so let them get
850   // rewritten first.
851   user_activity_detector_.reset(new UserActivityDetector);
852   AddPreTargetHandler(user_activity_detector_.get());
853
854   overlay_filter_.reset(new internal::OverlayEventFilter);
855   AddPreTargetHandler(overlay_filter_.get());
856   AddShellObserver(overlay_filter_.get());
857
858   input_method_filter_.reset(new views::corewm::InputMethodEventFilter(
859       root_window->GetDispatcher()->host()->GetAcceleratedWidget()));
860   AddPreTargetHandler(input_method_filter_.get());
861
862   accelerator_filter_.reset(new internal::AcceleratorFilter);
863   AddPreTargetHandler(accelerator_filter_.get());
864
865   event_transformation_handler_.reset(new internal::EventTransformationHandler);
866   AddPreTargetHandler(event_transformation_handler_.get());
867
868   toplevel_window_event_handler_.reset(new ToplevelWindowEventHandler);
869
870   system_gesture_filter_.reset(new internal::SystemGestureEventFilter);
871   AddPreTargetHandler(system_gesture_filter_.get());
872
873   keyboard_metrics_filter_.reset(new internal::KeyboardUMAEventFilter);
874   AddPreTargetHandler(keyboard_metrics_filter_.get());
875
876   // The keyboard system must be initialized before the RootWindowController is
877   // created.
878 #if defined(OS_CHROMEOS)
879     keyboard::InitializeKeyboard();
880 #endif
881
882   lock_state_controller_.reset(new LockStateController);
883   power_button_controller_.reset(new PowerButtonController(
884       lock_state_controller_.get()));
885   AddShellObserver(lock_state_controller_.get());
886
887   drag_drop_controller_.reset(new internal::DragDropController);
888   mouse_cursor_filter_.reset(new internal::MouseCursorEventFilter());
889   PrependPreTargetHandler(mouse_cursor_filter_.get());
890
891   // Create Controllers that may need root window.
892   // TODO(oshima): Move as many controllers before creating
893   // RootWindowController as possible.
894   visibility_controller_.reset(new AshVisibilityController);
895   user_action_client_.reset(delegate_->CreateUserActionClient());
896
897   magnification_controller_.reset(
898       MagnificationController::CreateInstance());
899   mru_window_tracker_.reset(new MruWindowTracker(activation_client_));
900
901   partial_magnification_controller_.reset(
902       new PartialMagnificationController());
903
904   autoclick_controller_.reset(AutoclickController::CreateInstance());
905
906   high_contrast_controller_.reset(new HighContrastController);
907   video_detector_.reset(new VideoDetector);
908   window_cycle_controller_.reset(new WindowCycleController());
909   window_selector_controller_.reset(new WindowSelectorController());
910
911   tooltip_controller_.reset(
912       new views::corewm::TooltipController(
913           scoped_ptr<views::corewm::Tooltip>(
914               new views::corewm::TooltipAura(gfx::SCREEN_TYPE_ALTERNATE))));
915   AddPreTargetHandler(tooltip_controller_.get());
916
917   event_client_.reset(new internal::EventClientImpl);
918
919   // This controller needs to be set before SetupManagedWindowMode.
920   desktop_background_controller_.reset(new DesktopBackgroundController());
921   user_wallpaper_delegate_.reset(delegate_->CreateUserWallpaperDelegate());
922
923   // StatusAreaWidget uses Shell's CapsLockDelegate.
924   caps_lock_delegate_.reset(delegate_->CreateCapsLockDelegate());
925
926   session_state_delegate_.reset(delegate_->CreateSessionStateDelegate());
927   accessibility_delegate_.reset(delegate_->CreateAccessibilityDelegate());
928   new_window_delegate_.reset(delegate_->CreateNewWindowDelegate());
929   media_delegate_.reset(delegate_->CreateMediaDelegate());
930
931   if (!command_line->HasSwitch(views::corewm::switches::kNoDropShadows)) {
932     resize_shadow_controller_.reset(new internal::ResizeShadowController());
933     shadow_controller_.reset(
934         new views::corewm::ShadowController(activation_client_));
935   }
936
937   // Create system_tray_notifier_ before the delegate.
938   system_tray_notifier_.reset(new ash::SystemTrayNotifier());
939
940   // Initialize system_tray_delegate_ before initializing StatusAreaWidget.
941   system_tray_delegate_.reset(delegate()->CreateSystemTrayDelegate());
942   DCHECK(system_tray_delegate_.get());
943
944   locale_notification_controller_.reset(
945       new internal::LocaleNotificationController);
946
947   // Initialize system_tray_delegate_ after StatusAreaWidget is created.
948   system_tray_delegate_->Initialize();
949
950   // TODO(oshima): Initialize all RootWindowControllers once, and
951   // initialize controller/delegates above when initializing the
952   // primary root window controller.
953   internal::RootWindowController::CreateForPrimaryDisplay(
954       root_window->GetDispatcher());
955
956   display_controller_->InitSecondaryDisplays();
957
958   // It needs to be created after RootWindowController has been created
959   // (which calls OnWindowResized has been called, otherwise the
960   // widget will not paint when restoring after a browser crash.  Also it needs
961   // to be created after InitSecondaryDisplays() to initialize the wallpapers in
962   // the correct size.
963   user_wallpaper_delegate_->InitializeWallpaper();
964
965   if (initially_hide_cursor_)
966     cursor_manager_.HideCursor();
967   cursor_manager_.SetCursor(ui::kCursorPointer);
968
969 #if defined(OS_CHROMEOS)
970   // Set accelerator controller delegates.
971   accelerator_controller_->SetBrightnessControlDelegate(
972       scoped_ptr<ash::BrightnessControlDelegate>(
973           new ash::system::BrightnessControllerChromeos).Pass());
974
975   power_event_observer_.reset(new internal::PowerEventObserver());
976   user_activity_notifier_.reset(
977       new internal::UserActivityNotifier(user_activity_detector_.get()));
978   video_activity_notifier_.reset(
979       new internal::VideoActivityNotifier(video_detector_.get()));
980 #endif
981
982   weak_display_manager_factory_.reset(
983       new base::WeakPtrFactory<internal::DisplayManager>(
984           display_manager_.get()));
985   // The compositor thread and main message loop have to be running in
986   // order to create mirror window. Run it after the main message loop
987   // is started.
988   base::MessageLoopForUI::current()->PostTask(
989       FROM_HERE,
990       base::Bind(&internal::DisplayManager::CreateMirrorWindowIfAny,
991                  weak_display_manager_factory_->GetWeakPtr()));
992 }
993
994 void Shell::InitKeyboard() {
995   if (keyboard::IsKeyboardEnabled()) {
996     if (keyboard_controller_.get()) {
997       RootWindowControllerList controllers = GetAllRootWindowControllers();
998       for (RootWindowControllerList::iterator iter = controllers.begin();
999            iter != controllers.end(); ++iter) {
1000         (*iter)->DeactivateKeyboard(keyboard_controller_.get());
1001       }
1002     }
1003     keyboard::KeyboardControllerProxy* proxy =
1004         delegate_->CreateKeyboardControllerProxy();
1005     keyboard_controller_.reset(
1006         new keyboard::KeyboardController(proxy));
1007   }
1008 }
1009
1010 void Shell::InitRootWindow(aura::Window* root_window) {
1011   DCHECK(activation_client_);
1012   DCHECK(visibility_controller_.get());
1013   DCHECK(drag_drop_controller_.get());
1014   DCHECK(window_cycle_controller_.get());
1015
1016   aura::client::SetFocusClient(root_window, focus_client_.get());
1017   input_method_filter_->SetInputMethodPropertyInRootWindow(root_window);
1018   aura::client::SetActivationClient(root_window, activation_client_);
1019   views::corewm::FocusController* focus_controller =
1020       static_cast<views::corewm::FocusController*>(activation_client_);
1021   root_window->AddPreTargetHandler(focus_controller);
1022   aura::client::SetVisibilityClient(root_window, visibility_controller_.get());
1023   aura::client::SetDragDropClient(root_window, drag_drop_controller_.get());
1024   aura::client::SetScreenPositionClient(root_window,
1025                                         screen_position_controller_.get());
1026   aura::client::SetCursorClient(root_window, &cursor_manager_);
1027   aura::client::SetTooltipClient(root_window, tooltip_controller_.get());
1028   aura::client::SetEventClient(root_window, event_client_.get());
1029
1030   aura::client::SetWindowMoveClient(root_window,
1031       toplevel_window_event_handler_.get());
1032   root_window->AddPreTargetHandler(toplevel_window_event_handler_.get());
1033   root_window->AddPostTargetHandler(toplevel_window_event_handler_.get());
1034
1035   if (nested_dispatcher_controller_) {
1036     aura::client::SetDispatcherClient(root_window,
1037                                       nested_dispatcher_controller_.get());
1038   }
1039   if (user_action_client_)
1040     aura::client::SetUserActionClient(root_window, user_action_client_.get());
1041 }
1042
1043 bool Shell::CanWindowReceiveEvents(aura::Window* window) {
1044   RootWindowControllerList controllers = GetAllRootWindowControllers();
1045   for (RootWindowControllerList::iterator iter = controllers.begin();
1046        iter != controllers.end(); ++iter) {
1047     internal::SystemModalContainerLayoutManager* layout_manager =
1048         (*iter)->GetSystemModalLayoutManager(window);
1049     if (layout_manager && layout_manager->CanWindowReceiveEvents(window))
1050       return true;
1051   }
1052   return false;
1053 }
1054
1055 ////////////////////////////////////////////////////////////////////////////////
1056 // Shell, ui::EventTarget overrides:
1057
1058 bool Shell::CanAcceptEvent(const ui::Event& event) {
1059   return true;
1060 }
1061
1062 ui::EventTarget* Shell::GetParentTarget() {
1063   return aura::Env::GetInstance();
1064 }
1065
1066 scoped_ptr<ui::EventTargetIterator> Shell::GetChildIterator() const {
1067   return scoped_ptr<ui::EventTargetIterator>();
1068 }
1069
1070 ui::EventTargeter* Shell::GetEventTargeter() {
1071   NOTREACHED();
1072   return NULL;
1073 }
1074
1075 void Shell::OnEvent(ui::Event* event) {
1076 }
1077
1078 ////////////////////////////////////////////////////////////////////////////////
1079 // Shell, aura::client::ActivationChangeObserver implementation:
1080
1081 void Shell::OnWindowActivated(aura::Window* gained_active,
1082                               aura::Window* lost_active) {
1083   if (gained_active)
1084     target_root_window_ = gained_active->GetRootWindow();
1085 }
1086
1087 }  // namespace ash