shell.cc revision 4e180b6a0b4720a9b8e9e959a882386f690f08ff
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/focus_cycler.h"
28#include "ash/high_contrast/high_contrast_controller.h"
29#include "ash/host/root_window_host_factory.h"
30#include "ash/keyboard_uma_event_filter.h"
31#include "ash/launcher/launcher_delegate.h"
32#include "ash/launcher/launcher_item_delegate.h"
33#include "ash/launcher/launcher_item_delegate_manager.h"
34#include "ash/launcher/launcher_model.h"
35#include "ash/magnifier/magnification_controller.h"
36#include "ash/magnifier/partial_magnification_controller.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_layout_manager.h"
42#include "ash/shelf/shelf_util.h"
43#include "ash/shelf/shelf_widget.h"
44#include "ash/shell_delegate.h"
45#include "ash/shell_factory.h"
46#include "ash/shell_window_ids.h"
47#include "ash/system/locale/locale_notification_controller.h"
48#include "ash/system/status_area_widget.h"
49#include "ash/system/tray/system_tray_delegate.h"
50#include "ash/system/tray/system_tray_notifier.h"
51#include "ash/wm/app_list_controller.h"
52#include "ash/wm/ash_focus_rules.h"
53#include "ash/wm/ash_native_cursor_manager.h"
54#include "ash/wm/base_layout_manager.h"
55#include "ash/wm/coordinate_conversion.h"
56#include "ash/wm/custom_frame_view_ash.h"
57#include "ash/wm/event_client_impl.h"
58#include "ash/wm/event_rewriter_event_filter.h"
59#include "ash/wm/lock_state_controller.h"
60#include "ash/wm/mru_window_tracker.h"
61#include "ash/wm/overlay_event_filter.h"
62#include "ash/wm/overview/window_selector_controller.h"
63#include "ash/wm/power_button_controller.h"
64#include "ash/wm/resize_shadow_controller.h"
65#include "ash/wm/root_window_layout_manager.h"
66#include "ash/wm/screen_dimmer.h"
67#include "ash/wm/system_gesture_event_filter.h"
68#include "ash/wm/system_modal_container_event_filter.h"
69#include "ash/wm/system_modal_container_layout_manager.h"
70#include "ash/wm/user_activity_detector.h"
71#include "ash/wm/video_detector.h"
72#include "ash/wm/window_animations.h"
73#include "ash/wm/window_cycle_controller.h"
74#include "ash/wm/window_positioner.h"
75#include "ash/wm/window_properties.h"
76#include "ash/wm/window_util.h"
77#include "ash/wm/workspace_controller.h"
78#include "base/bind.h"
79#include "base/command_line.h"
80#include "base/debug/leak_annotations.h"
81#include "base/debug/trace_event.h"
82#include "ui/aura/client/aura_constants.h"
83#include "ui/aura/client/user_action_client.h"
84#include "ui/aura/env.h"
85#include "ui/aura/focus_manager.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  // TODO(oshima): The root and root window controller shouldn't be
270  // NULL even for the out-of-bounds |location_in_screen| (It should
271  // return the primary root). Investigate why/how this is
272  // happening. crbug.com/165214.
273  internal::RootWindowController* rwc = internal::GetRootWindowController(root);
274  CHECK(rwc) << "root=" << root
275             << ", location:" << location_in_screen.ToString();
276  if (rwc)
277    rwc->ShowContextMenu(location_in_screen, source_type);
278}
279
280void 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
289bool Shell::GetAppListTargetVisibility() const {
290  return app_list_controller_.get() &&
291      app_list_controller_->GetTargetVisibility();
292}
293
294aura::Window* Shell::GetAppListWindow() {
295  return app_list_controller_.get() ? app_list_controller_->GetWindow() : NULL;
296}
297
298bool Shell::IsSystemModalWindowOpen() const {
299  if (simulate_modal_window_open_for_testing_)
300    return true;
301  const std::vector<aura::Window*> containers = GetContainersFromAllRootWindows(
302      internal::kShellWindowId_SystemModalContainer, NULL);
303  for (std::vector<aura::Window*>::const_iterator cit = containers.begin();
304       cit != containers.end(); ++cit) {
305    for (aura::Window::Windows::const_iterator wit = (*cit)->children().begin();
306         wit != (*cit)->children().end(); ++wit) {
307      if ((*wit)->GetProperty(aura::client::kModalKey) ==
308          ui::MODAL_TYPE_SYSTEM && (*wit)->TargetVisibility()) {
309        return true;
310      }
311    }
312  }
313  return false;
314}
315
316views::NonClientFrameView* Shell::CreateDefaultNonClientFrameView(
317    views::Widget* widget) {
318  // Use translucent-style window frames for dialogs.
319  CustomFrameViewAsh* frame_view = new CustomFrameViewAsh;
320  frame_view->Init(widget);
321  return frame_view;
322}
323
324void Shell::RotateFocus(Direction direction) {
325  focus_cycler_->RotateFocus(
326      direction == FORWARD ? internal::FocusCycler::FORWARD :
327                             internal::FocusCycler::BACKWARD);
328}
329
330void Shell::SetDisplayWorkAreaInsets(Window* contains,
331                                     const gfx::Insets& insets) {
332  if (!display_controller_->UpdateWorkAreaOfDisplayNearestWindow(
333          contains, insets)) {
334    return;
335  }
336  FOR_EACH_OBSERVER(ShellObserver, observers_,
337                    OnDisplayWorkAreaInsetsChanged());
338}
339
340void Shell::OnLoginStateChanged(user::LoginStatus status) {
341  if (status != user::LOGGED_IN_NONE) {
342    // TODO(bshe): Primary root window controller may not be the controller to
343    // attach virtual keyboard. See http://crbug.com/303429
344    InitKeyboard(GetPrimaryRootWindowController());
345  }
346  FOR_EACH_OBSERVER(ShellObserver, observers_, OnLoginStateChanged(status));
347}
348
349void Shell::UpdateAfterLoginStatusChange(user::LoginStatus status) {
350  RootWindowControllerList controllers = GetAllRootWindowControllers();
351  for (RootWindowControllerList::iterator iter = controllers.begin();
352       iter != controllers.end(); ++iter)
353    (*iter)->UpdateAfterLoginStatusChange(status);
354}
355
356void Shell::OnAppTerminating() {
357  FOR_EACH_OBSERVER(ShellObserver, observers_, OnAppTerminating());
358}
359
360void Shell::OnLockStateChanged(bool locked) {
361  FOR_EACH_OBSERVER(ShellObserver, observers_, OnLockStateChanged(locked));
362#ifndef NDEBUG
363  // Make sure that there is no system modal in Lock layer when unlocked.
364  if (!locked) {
365    std::vector<aura::Window*> containers = GetContainersFromAllRootWindows(
366        internal::kShellWindowId_LockSystemModalContainer,
367        GetPrimaryRootWindow());
368    for (std::vector<aura::Window*>::const_iterator iter = containers.begin();
369         iter != containers.end(); ++iter) {
370      DCHECK_EQ(0u, (*iter)->children().size());
371    }
372  }
373#endif
374}
375
376void Shell::CreateLauncher() {
377  RootWindowControllerList controllers = GetAllRootWindowControllers();
378  for (RootWindowControllerList::iterator iter = controllers.begin();
379       iter != controllers.end(); ++iter)
380    (*iter)->shelf()->CreateLauncher();
381}
382
383void Shell::ShowLauncher() {
384  RootWindowControllerList controllers = GetAllRootWindowControllers();
385  for (RootWindowControllerList::iterator iter = controllers.begin();
386       iter != controllers.end(); ++iter)
387    (*iter)->ShowLauncher();
388}
389
390void Shell::AddShellObserver(ShellObserver* observer) {
391  observers_.AddObserver(observer);
392}
393
394void Shell::RemoveShellObserver(ShellObserver* observer) {
395  observers_.RemoveObserver(observer);
396}
397
398void Shell::UpdateShelfVisibility() {
399  RootWindowControllerList controllers = GetAllRootWindowControllers();
400  for (RootWindowControllerList::iterator iter = controllers.begin();
401       iter != controllers.end(); ++iter)
402    if ((*iter)->shelf())
403      (*iter)->UpdateShelfVisibility();
404}
405
406void Shell::SetShelfAutoHideBehavior(ShelfAutoHideBehavior behavior,
407                                     aura::RootWindow* root_window) {
408  ash::internal::ShelfLayoutManager::ForLauncher(root_window)->
409      SetAutoHideBehavior(behavior);
410}
411
412ShelfAutoHideBehavior Shell::GetShelfAutoHideBehavior(
413    aura::RootWindow* root_window) const {
414  return ash::internal::ShelfLayoutManager::ForLauncher(root_window)->
415      auto_hide_behavior();
416}
417
418void Shell::SetShelfAlignment(ShelfAlignment alignment,
419                              aura::RootWindow* root_window) {
420  if (ash::internal::ShelfLayoutManager::ForLauncher(root_window)->
421      SetAlignment(alignment)) {
422    FOR_EACH_OBSERVER(
423        ShellObserver, observers_, OnShelfAlignmentChanged(root_window));
424  }
425}
426
427ShelfAlignment Shell::GetShelfAlignment(aura::RootWindow* root_window) {
428  return internal::GetRootWindowController(root_window)->
429      GetShelfLayoutManager()->GetAlignment();
430}
431
432void Shell::SetDimming(bool should_dim) {
433  RootWindowControllerList controllers = GetAllRootWindowControllers();
434  for (RootWindowControllerList::iterator iter = controllers.begin();
435       iter != controllers.end(); ++iter)
436    (*iter)->screen_dimmer()->SetDimming(should_dim);
437}
438
439void Shell::NotifyFullscreenStateChange(bool is_fullscreen,
440                                        aura::RootWindow* root_window) {
441  FOR_EACH_OBSERVER(ShellObserver, observers_, OnFullscreenStateChanged(
442      is_fullscreen, root_window));
443}
444
445void Shell::CreateModalBackground(aura::Window* window) {
446  if (!modality_filter_) {
447    modality_filter_.reset(new internal::SystemModalContainerEventFilter(this));
448    AddPreTargetHandler(modality_filter_.get());
449  }
450  RootWindowControllerList controllers = GetAllRootWindowControllers();
451  for (RootWindowControllerList::iterator iter = controllers.begin();
452       iter != controllers.end(); ++iter)
453    (*iter)->GetSystemModalLayoutManager(window)->CreateModalBackground();
454}
455
456void Shell::OnModalWindowRemoved(aura::Window* removed) {
457  RootWindowControllerList controllers = GetAllRootWindowControllers();
458  bool activated = false;
459  for (RootWindowControllerList::iterator iter = controllers.begin();
460       iter != controllers.end() && !activated; ++iter) {
461    activated = (*iter)->GetSystemModalLayoutManager(removed)->
462        ActivateNextModalWindow();
463  }
464  if (!activated) {
465    RemovePreTargetHandler(modality_filter_.get());
466    modality_filter_.reset();
467    for (RootWindowControllerList::iterator iter = controllers.begin();
468         iter != controllers.end(); ++iter)
469      (*iter)->GetSystemModalLayoutManager(removed)->DestroyModalBackground();
470  }
471}
472
473WebNotificationTray* Shell::GetWebNotificationTray() {
474  return GetPrimaryRootWindowController()->shelf()->
475      status_area_widget()->web_notification_tray();
476}
477
478bool Shell::HasPrimaryStatusArea() {
479  ShelfWidget* shelf = GetPrimaryRootWindowController()->shelf();
480  return shelf && shelf->status_area_widget();
481}
482
483SystemTray* Shell::GetPrimarySystemTray() {
484  return GetPrimaryRootWindowController()->GetSystemTray();
485}
486
487LauncherDelegate* Shell::GetLauncherDelegate() {
488  if (!launcher_delegate_) {
489    launcher_model_.reset(new LauncherModel);
490    // Creates LauncherItemDelegateManager before LauncherDelegate.
491    launcher_item_delegate_manager_.reset(
492        new LauncherItemDelegateManager(launcher_model_.get()));
493
494    launcher_delegate_.reset(
495        delegate_->CreateLauncherDelegate(launcher_model_.get()));
496    scoped_ptr<LauncherItemDelegate> controller(
497        new internal::AppListShelfItemDelegate);
498
499    ash::LauncherID app_list_id = 0;
500    // TODO(simon.hong81): Make function for this in shelf_util.h
501    // Finding the launcher model's location of the app list and setting its
502    // LauncherItemDelegate.
503    for (size_t i = 0; i < launcher_model_->items().size(); ++i) {
504      if (launcher_model_->items()[i].type == ash::TYPE_APP_LIST) {
505        app_list_id = launcher_model_->items()[i].id;
506        break;
507      }
508    }
509    DCHECK(app_list_id);
510    launcher_item_delegate_manager_->SetLauncherItemDelegate(
511        app_list_id,
512        controller.Pass());
513  }
514  return launcher_delegate_.get();
515}
516
517void Shell::SetTouchHudProjectionEnabled(bool enabled) {
518  if (is_touch_hud_projection_enabled_ == enabled)
519    return;
520
521  is_touch_hud_projection_enabled_ = enabled;
522  FOR_EACH_OBSERVER(ShellObserver, observers_,
523                    OnTouchHudProjectionToggled(enabled));
524}
525
526void Shell::InitRootWindowForSecondaryDisplay(aura::RootWindow* root) {
527  internal::RootWindowController* controller =
528      new internal::RootWindowController(root);
529  // Pass false for the |is_first_run_after_boot| parameter so we'll show a
530  // black background on this display instead of trying to mimic the boot splash
531  // screen.
532  InitRootWindowController(controller, false);
533
534  controller->root_window_layout()->OnWindowResized();
535  desktop_background_controller_->OnRootWindowAdded(root);
536  high_contrast_controller_->OnRootWindowAdded(root);
537  root->ShowRootWindow();
538  // Activate new root for testing.
539  // TODO(oshima): remove this.
540  target_root_window_ = root;
541
542  // Create a launcher if a user is already logged.
543  if (Shell::GetInstance()->session_state_delegate()->NumberOfLoggedInUsers())
544    controller->shelf()->CreateLauncher();
545}
546
547void Shell::DoInitialWorkspaceAnimation() {
548  return GetPrimaryRootWindowController()->workspace_controller()->
549      DoInitialAnimation();
550}
551
552////////////////////////////////////////////////////////////////////////////////
553// Shell, private:
554
555Shell::Shell(ShellDelegate* delegate)
556    : screen_(new ScreenAsh),
557      target_root_window_(NULL),
558      scoped_target_root_window_(NULL),
559      delegate_(delegate),
560      window_positioner_(new WindowPositioner),
561      activation_client_(NULL),
562#if defined(OS_CHROMEOS) && defined(USE_X11)
563      output_configurator_(new chromeos::OutputConfigurator()),
564#endif  // defined(OS_CHROMEOS) && defined(USE_X11)
565      native_cursor_manager_(new AshNativeCursorManager),
566      cursor_manager_(scoped_ptr<views::corewm::NativeCursorManager>(
567          native_cursor_manager_)),
568      browser_context_(NULL),
569      simulate_modal_window_open_for_testing_(false),
570      is_touch_hud_projection_enabled_(false) {
571  DCHECK(delegate_.get());
572  display_manager_.reset(new internal::DisplayManager);
573
574  ANNOTATE_LEAKING_OBJECT_PTR(screen_);  // see crbug.com/156466
575  gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_ALTERNATE, screen_);
576  if (!gfx::Screen::GetScreenByType(gfx::SCREEN_TYPE_NATIVE))
577    gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, screen_);
578  display_controller_.reset(new DisplayController);
579#if defined(OS_CHROMEOS) && defined(USE_X11)
580  bool is_panel_fitting_disabled =
581      content::GpuDataManager::GetInstance()->IsFeatureBlacklisted(
582          gpu::GPU_FEATURE_TYPE_PANEL_FITTING);
583
584  output_configurator_->Init(!is_panel_fitting_disabled);
585
586  base::MessagePumpX11::Current()->AddDispatcherForRootWindow(
587      output_configurator());
588  // We can't do this with a root window listener because XI_HierarchyChanged
589  // messages don't have a target window.
590  base::MessagePumpX11::Current()->AddObserver(output_configurator());
591#endif  // defined(OS_CHROMEOS)
592
593#if defined(OS_CHROMEOS)
594  internal::PowerStatus::Initialize();
595#endif
596}
597
598Shell::~Shell() {
599  TRACE_EVENT0("shutdown", "ash::Shell::Destructor");
600
601  views::FocusManagerFactory::Install(NULL);
602
603  // Remove the focus from any window. This will prevent overhead and side
604  // effects (e.g. crashes) from changing focus during shutdown.
605  // See bug crbug.com/134502.
606  aura::client::GetFocusClient(GetPrimaryRootWindow())->FocusWindow(NULL);
607
608  // Please keep in same order as in Init() because it's easy to miss one.
609  if (window_modality_controller_)
610    window_modality_controller_.reset();
611  RemovePreTargetHandler(event_rewriter_filter_.get());
612  RemovePreTargetHandler(user_activity_detector_.get());
613  RemovePreTargetHandler(overlay_filter_.get());
614  RemovePreTargetHandler(input_method_filter_.get());
615  if (mouse_cursor_filter_)
616    RemovePreTargetHandler(mouse_cursor_filter_.get());
617  RemovePreTargetHandler(system_gesture_filter_.get());
618  RemovePreTargetHandler(keyboard_metrics_filter_.get());
619  RemovePreTargetHandler(event_transformation_handler_.get());
620  RemovePreTargetHandler(accelerator_filter_.get());
621
622  // TooltipController is deleted with the Shell so removing its references.
623  RemovePreTargetHandler(tooltip_controller_.get());
624
625  // AppList needs to be released before shelf layout manager, which is
626  // destroyed with launcher container in the loop below. However, app list
627  // container is now on top of launcher container and released after it.
628  // TODO(xiyuan): Move it back when app list container is no longer needed.
629  app_list_controller_.reset();
630
631  // Destroy SystemTrayDelegate before destroying the status area(s).
632  system_tray_delegate_->Shutdown();
633  system_tray_delegate_.reset();
634
635  locale_notification_controller_.reset();
636
637  // Drag-and-drop must be canceled prior to close all windows.
638  drag_drop_controller_.reset();
639
640  // Destroy all child windows including widgets.
641  display_controller_->CloseChildWindows();
642
643  // Destroy SystemTrayNotifier after destroying SystemTray as TrayItems
644  // needs to remove observers from it.
645  system_tray_notifier_.reset();
646
647#if defined(OS_CHROMEOS)
648  // Destroy VideoActivityNotifier before destroying VideoDetector.
649  video_activity_notifier_.reset();
650#endif  // defined(OS_CHROMEOS)
651
652  // These need a valid Shell instance to clean up properly, so explicitly
653  // delete them before invalidating the instance.
654  // Alphabetical. TODO(oshima): sort.
655  magnification_controller_.reset();
656  partial_magnification_controller_.reset();
657  resize_shadow_controller_.reset();
658  shadow_controller_.reset();
659  tooltip_controller_.reset();
660  event_client_.reset();
661  window_cycle_controller_.reset();
662  nested_dispatcher_controller_.reset();
663  user_action_client_.reset();
664  visibility_controller_.reset();
665  launcher_delegate_.reset();
666  // |launcher_item_delegate_manager_| observes |launcher_model_|. It must be
667  // destroyed before |launcher_model_| is destroyed.
668  launcher_item_delegate_manager_.reset();
669  launcher_model_.reset();
670  video_detector_.reset();
671
672  power_button_controller_.reset();
673  lock_state_controller_.reset();
674  mru_window_tracker_.reset();
675
676  resolution_notification_controller_.reset();
677  desktop_background_controller_.reset();
678
679  // This also deletes all RootWindows. Note that we invoke Shutdown() on
680  // DisplayController before resetting |display_controller_|, since destruction
681  // of its owned RootWindowControllers relies on the value.
682  display_controller_->Shutdown();
683  display_controller_.reset();
684  screen_position_controller_.reset();
685
686  keyboard_controller_.reset();
687
688#if defined(OS_CHROMEOS) && defined(USE_X11)
689   if (display_change_observer_)
690    output_configurator_->RemoveObserver(display_change_observer_.get());
691  if (output_configurator_animation_)
692    output_configurator_->RemoveObserver(output_configurator_animation_.get());
693  if (display_error_observer_)
694    output_configurator_->RemoveObserver(display_error_observer_.get());
695  base::MessagePumpX11::Current()->RemoveDispatcherForRootWindow(
696      output_configurator());
697  base::MessagePumpX11::Current()->RemoveObserver(output_configurator());
698  display_change_observer_.reset();
699#endif  // defined(OS_CHROMEOS)
700
701#if defined(OS_CHROMEOS)
702  internal::PowerStatus::Shutdown();
703#endif
704
705  DCHECK(instance_ == this);
706  instance_ = NULL;
707}
708
709void Shell::Init() {
710  CommandLine* command_line = CommandLine::ForCurrentProcess();
711
712  delegate_->PreInit();
713  bool display_initialized = false;
714#if defined(OS_CHROMEOS) && defined(USE_X11)
715  output_configurator_animation_.reset(
716      new internal::OutputConfiguratorAnimation());
717  output_configurator_->AddObserver(output_configurator_animation_.get());
718  if (base::SysInfo::IsRunningOnChromeOS()) {
719    display_change_observer_.reset(new internal::DisplayChangeObserver);
720    // Register |display_change_observer_| first so that the rest of
721    // observer gets invoked after the root windows are configured.
722    output_configurator_->AddObserver(display_change_observer_.get());
723    display_error_observer_.reset(new internal::DisplayErrorObserver());
724    output_configurator_->AddObserver(display_error_observer_.get());
725    output_configurator_->set_state_controller(display_change_observer_.get());
726    if (!command_line->HasSwitch(ash::switches::kAshDisableSoftwareMirroring))
727      output_configurator_->set_mirroring_controller(display_manager_.get());
728    output_configurator_->Start(
729        delegate_->IsFirstRunAfterBoot() ? kChromeOsBootColor : 0);
730    display_initialized = true;
731  }
732#endif  // defined(OS_CHROMEOS) && defined(USE_X11)
733  if (!display_initialized)
734    display_manager_->InitFromCommandLine();
735
736  // Install the custom factory first so that views::FocusManagers for Tray,
737  // Launcher, and WallPaper could be created by the factory.
738  views::FocusManagerFactory::Install(new AshFocusManagerFactory);
739
740  // Env creates the compositor. Historically it seems to have been implicitly
741  // initialized first by the ActivationController, but now that FocusController
742  // no longer does this we need to do it explicitly.
743  aura::Env::CreateInstance();
744
745  // The WindowModalityController needs to be at the front of the input event
746  // pretarget handler list to ensure that it processes input events when modal
747  // windows are active.
748  window_modality_controller_.reset(
749      new views::corewm::WindowModalityController(this));
750
751  AddPreTargetHandler(this);
752
753  env_filter_.reset(new views::corewm::CompoundEventFilter);
754  AddPreTargetHandler(env_filter_.get());
755
756  views::corewm::FocusController* focus_controller =
757      new views::corewm::FocusController(new wm::AshFocusRules);
758  focus_client_.reset(focus_controller);
759  activation_client_ = focus_controller;
760  activation_client_->AddObserver(this);
761  focus_cycler_.reset(new internal::FocusCycler());
762
763  screen_position_controller_.reset(new internal::ScreenPositionController);
764  root_window_host_factory_.reset(delegate_->CreateRootWindowHostFactory());
765
766  display_controller_->Start();
767  display_controller_->InitPrimaryDisplay();
768  aura::RootWindow* root_window = display_controller_->GetPrimaryRootWindow();
769  target_root_window_ = root_window;
770
771  resolution_notification_controller_.reset(
772      new internal::ResolutionNotificationController);
773
774  cursor_manager_.SetDisplay(DisplayController::GetPrimaryDisplay());
775
776  nested_dispatcher_controller_.reset(new NestedDispatcherController);
777  accelerator_controller_.reset(new AcceleratorController);
778
779  // The order in which event filters are added is significant.
780  event_rewriter_filter_.reset(new internal::EventRewriterEventFilter);
781  AddPreTargetHandler(event_rewriter_filter_.get());
782
783  // UserActivityDetector passes events to observers, so let them get
784  // rewritten first.
785  user_activity_detector_.reset(new UserActivityDetector);
786  AddPreTargetHandler(user_activity_detector_.get());
787
788  overlay_filter_.reset(new internal::OverlayEventFilter);
789  AddPreTargetHandler(overlay_filter_.get());
790  AddShellObserver(overlay_filter_.get());
791
792  input_method_filter_.reset(new views::corewm::InputMethodEventFilter(
793                                 root_window->GetAcceleratedWidget()));
794  AddPreTargetHandler(input_method_filter_.get());
795
796  accelerator_filter_.reset(new internal::AcceleratorFilter);
797  AddPreTargetHandler(accelerator_filter_.get());
798
799  event_transformation_handler_.reset(new internal::EventTransformationHandler);
800  AddPreTargetHandler(event_transformation_handler_.get());
801
802  system_gesture_filter_.reset(new internal::SystemGestureEventFilter);
803  AddPreTargetHandler(system_gesture_filter_.get());
804
805  keyboard_metrics_filter_.reset(new internal::KeyboardUMAEventFilter);
806  AddPreTargetHandler(keyboard_metrics_filter_.get());
807
808  // The keyboard system must be initialized before the RootWindowController is
809  // created.
810  if (keyboard::IsKeyboardEnabled())
811    keyboard::InitializeKeyboard();
812
813  lock_state_controller_.reset(new LockStateController);
814  power_button_controller_.reset(new PowerButtonController(
815      lock_state_controller_.get()));
816  AddShellObserver(lock_state_controller_.get());
817
818  drag_drop_controller_.reset(new internal::DragDropController);
819  mouse_cursor_filter_.reset(new internal::MouseCursorEventFilter());
820  PrependPreTargetHandler(mouse_cursor_filter_.get());
821
822  // Create Controllers that may need root window.
823  // TODO(oshima): Move as many controllers before creating
824  // RootWindowController as possible.
825  visibility_controller_.reset(new AshVisibilityController);
826  user_action_client_.reset(delegate_->CreateUserActionClient());
827
828  magnification_controller_.reset(
829      MagnificationController::CreateInstance());
830  mru_window_tracker_.reset(new MruWindowTracker(activation_client_));
831
832  partial_magnification_controller_.reset(
833      new PartialMagnificationController());
834
835  autoclick_controller_.reset(AutoclickController::CreateInstance());
836
837  high_contrast_controller_.reset(new HighContrastController);
838  video_detector_.reset(new VideoDetector);
839  window_cycle_controller_.reset(new WindowCycleController());
840  window_selector_controller_.reset(new WindowSelectorController());
841
842  tooltip_controller_.reset(
843      new views::corewm::TooltipController(
844          scoped_ptr<views::corewm::Tooltip>(
845              new views::corewm::TooltipAura(gfx::SCREEN_TYPE_ALTERNATE))));
846  AddPreTargetHandler(tooltip_controller_.get());
847
848  event_client_.reset(new internal::EventClientImpl);
849
850  // This controller needs to be set before SetupManagedWindowMode.
851  desktop_background_controller_.reset(new DesktopBackgroundController());
852  user_wallpaper_delegate_.reset(delegate_->CreateUserWallpaperDelegate());
853
854  // StatusAreaWidget uses Shell's CapsLockDelegate.
855  caps_lock_delegate_.reset(delegate_->CreateCapsLockDelegate());
856
857  session_state_delegate_.reset(delegate_->CreateSessionStateDelegate());
858
859  if (!command_line->HasSwitch(views::corewm::switches::kNoDropShadows)) {
860    resize_shadow_controller_.reset(new internal::ResizeShadowController());
861    shadow_controller_.reset(
862        new views::corewm::ShadowController(activation_client_));
863  }
864
865  // Create system_tray_notifier_ before the delegate.
866  system_tray_notifier_.reset(new ash::SystemTrayNotifier());
867
868  // Initialize system_tray_delegate_ before initializing StatusAreaWidget.
869  system_tray_delegate_.reset(delegate()->CreateSystemTrayDelegate());
870  DCHECK(system_tray_delegate_.get());
871
872  internal::RootWindowController* root_window_controller =
873      new internal::RootWindowController(root_window);
874  InitRootWindowController(root_window_controller,
875                           delegate_->IsFirstRunAfterBoot());
876  InitKeyboard(root_window_controller);
877
878  locale_notification_controller_.reset(
879      new internal::LocaleNotificationController);
880
881  // Initialize system_tray_delegate_ after StatusAreaWidget is created.
882  system_tray_delegate_->Initialize();
883
884  display_controller_->InitSecondaryDisplays();
885
886  // Force Layout
887  root_window_controller->root_window_layout()->OnWindowResized();
888
889  // It needs to be created after OnWindowResized has been called, otherwise the
890  // widget will not paint when restoring after a browser crash.  Also it needs
891  // to be created after InitSecondaryDisplays() to initialize the wallpapers in
892  // the correct size.
893  user_wallpaper_delegate_->InitializeWallpaper();
894
895  if (initially_hide_cursor_)
896    cursor_manager_.HideCursor();
897  cursor_manager_.SetCursor(ui::kCursorPointer);
898
899  if (!cursor_manager_.IsCursorVisible()) {
900    // Cursor might have been hidden by something other than chrome.
901    // Let the first mouse event show the cursor.
902    env_filter_->set_cursor_hidden_by_filter(true);
903  }
904
905#if defined(OS_CHROMEOS)
906  // Set accelerator controller delegates.
907  accelerator_controller_->SetBrightnessControlDelegate(
908      scoped_ptr<ash::BrightnessControlDelegate>(
909          new ash::system::BrightnessControllerChromeos).Pass());
910
911  power_event_observer_.reset(new internal::PowerEventObserver());
912  user_activity_notifier_.reset(
913      new internal::UserActivityNotifier(user_activity_detector_.get()));
914  video_activity_notifier_.reset(
915      new internal::VideoActivityNotifier(video_detector_.get()));
916#endif
917
918  // The compositor thread and main message loop have to be running in
919  // order to create mirror window. Run it after the main message loop
920  // is started.
921  base::MessageLoopForUI::current()->PostTask(
922      FROM_HERE,
923      base::Bind(&internal::DisplayManager::CreateMirrorWindowIfAny,
924                 base::Unretained(display_manager_.get())));
925}
926
927void Shell::InitKeyboard(internal::RootWindowController* root) {
928  if (keyboard::IsKeyboardEnabled()) {
929    if (keyboard_controller_.get()) {
930      RootWindowControllerList controllers = GetAllRootWindowControllers();
931      for (RootWindowControllerList::iterator iter = controllers.begin();
932           iter != controllers.end(); ++iter) {
933        (*iter)->DeactivateKeyboard(keyboard_controller_.get());
934      }
935    }
936    keyboard::KeyboardControllerProxy* proxy =
937        delegate_->CreateKeyboardControllerProxy();
938    keyboard_controller_.reset(
939        new keyboard::KeyboardController(proxy));
940    root->ActivateKeyboard(keyboard_controller_.get());
941  }
942}
943
944void Shell::InitRootWindowController(
945    internal::RootWindowController* controller,
946    bool first_run_after_boot) {
947
948  aura::RootWindow* root_window = controller->root_window();
949  DCHECK(activation_client_);
950  DCHECK(visibility_controller_.get());
951  DCHECK(drag_drop_controller_.get());
952  DCHECK(window_cycle_controller_.get());
953
954  aura::client::SetFocusClient(root_window, focus_client_.get());
955  input_method_filter_->SetInputMethodPropertyInRootWindow(root_window);
956  aura::client::SetActivationClient(root_window, activation_client_);
957  views::corewm::FocusController* focus_controller =
958      static_cast<views::corewm::FocusController*>(activation_client_);
959  root_window->AddPreTargetHandler(focus_controller);
960  aura::client::SetVisibilityClient(root_window, visibility_controller_.get());
961  aura::client::SetDragDropClient(root_window, drag_drop_controller_.get());
962  aura::client::SetScreenPositionClient(root_window,
963                                        screen_position_controller_.get());
964  aura::client::SetCursorClient(root_window, &cursor_manager_);
965  aura::client::SetTooltipClient(root_window, tooltip_controller_.get());
966  aura::client::SetEventClient(root_window, event_client_.get());
967
968  if (nested_dispatcher_controller_) {
969    aura::client::SetDispatcherClient(root_window,
970                                      nested_dispatcher_controller_.get());
971  }
972  if (user_action_client_)
973    aura::client::SetUserActionClient(root_window, user_action_client_.get());
974
975  controller->Init(first_run_after_boot);
976}
977
978bool Shell::CanWindowReceiveEvents(aura::Window* window) {
979  RootWindowControllerList controllers = GetAllRootWindowControllers();
980  for (RootWindowControllerList::iterator iter = controllers.begin();
981       iter != controllers.end(); ++iter) {
982    internal::SystemModalContainerLayoutManager* layout_manager =
983        (*iter)->GetSystemModalLayoutManager(window);
984    if (layout_manager && layout_manager->CanWindowReceiveEvents(window))
985      return true;
986  }
987  return false;
988}
989
990////////////////////////////////////////////////////////////////////////////////
991// Shell, ui::EventTarget overrides:
992
993bool Shell::CanAcceptEvent(const ui::Event& event) {
994  return true;
995}
996
997ui::EventTarget* Shell::GetParentTarget() {
998  return NULL;
999}
1000
1001void Shell::OnEvent(ui::Event* event) {
1002}
1003
1004////////////////////////////////////////////////////////////////////////////////
1005// Shell, aura::client::ActivationChangeObserver implementation:
1006
1007void Shell::OnWindowActivated(aura::Window* gained_active,
1008                              aura::Window* lost_active) {
1009  if (gained_active)
1010    target_root_window_ = gained_active->GetRootWindow();
1011}
1012
1013}  // namespace ash
1014