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