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