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