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