shell.cc revision 0529e5d033099cbfc42635f6f6183833b09dff6e
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_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_error_observer_chromeos.h"
122#include "ash/display/output_configurator_animation.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 (output_configurator_animation_)
776    display_configurator_->RemoveObserver(output_configurator_animation_.get());
777  if (display_error_observer_)
778    display_configurator_->RemoveObserver(display_error_observer_.get());
779  if (projecting_observer_)
780    display_configurator_->RemoveObserver(projecting_observer_.get());
781  display_change_observer_.reset();
782#endif  // defined(OS_CHROMEOS)
783
784#if defined(OS_CHROMEOS)
785  PowerStatus::Shutdown();
786#endif
787
788  DCHECK(instance_ == this);
789  instance_ = NULL;
790}
791
792void Shell::Init() {
793  delegate_->PreInit();
794  if (keyboard::IsKeyboardUsabilityExperimentEnabled()) {
795    display_manager_->SetSecondDisplayMode(DisplayManager::VIRTUAL_KEYBOARD);
796  }
797  bool display_initialized = display_manager_->InitFromCommandLine();
798#if defined(OS_CHROMEOS)
799  display_configurator_->Init(!gpu_support_->IsPanelFittingDisabled());
800  output_configurator_animation_.reset(new OutputConfiguratorAnimation());
801  display_configurator_->AddObserver(output_configurator_animation_.get());
802
803  projecting_observer_.reset(new ProjectingObserver());
804  display_configurator_->AddObserver(projecting_observer_.get());
805
806  if (!display_initialized && base::SysInfo::IsRunningOnChromeOS()) {
807    display_change_observer_.reset(new DisplayChangeObserver);
808    // Register |display_change_observer_| first so that the rest of
809    // observer gets invoked after the root windows are configured.
810    display_configurator_->AddObserver(display_change_observer_.get());
811    display_error_observer_.reset(new DisplayErrorObserver());
812    display_configurator_->AddObserver(display_error_observer_.get());
813    display_configurator_->set_state_controller(display_change_observer_.get());
814    display_configurator_->set_mirroring_controller(display_manager_.get());
815    display_configurator_->ForceInitialConfigure(
816        delegate_->IsFirstRunAfterBoot() ? kChromeOsBootColor : 0);
817    display_initialized = true;
818  }
819#endif  // defined(OS_CHROMEOS)
820  if (!display_initialized)
821    display_manager_->InitDefaultDisplay();
822
823  // Install the custom factory first so that views::FocusManagers for Tray,
824  // Shelf, and WallPaper could be created by the factory.
825  views::FocusManagerFactory::Install(new AshFocusManagerFactory);
826
827  // Env creates the compositor. Historically it seems to have been implicitly
828  // initialized first by the ActivationController, but now that FocusController
829  // no longer does this we need to do it explicitly.
830  aura::Env::CreateInstance();
831
832  // The WindowModalityController needs to be at the front of the input event
833  // pretarget handler list to ensure that it processes input events when modal
834  // windows are active.
835  window_modality_controller_.reset(
836      new ::wm::WindowModalityController(this));
837
838  AddPreTargetHandler(this);
839
840  env_filter_.reset(new ::wm::CompoundEventFilter);
841  AddPreTargetHandler(env_filter_.get());
842
843  ::wm::FocusController* focus_controller =
844      new ::wm::FocusController(new wm::AshFocusRules);
845  focus_client_.reset(focus_controller);
846  activation_client_ = focus_controller;
847  activation_client_->AddObserver(this);
848  focus_cycler_.reset(new FocusCycler());
849
850  screen_position_controller_.reset(new ScreenPositionController);
851
852  display_controller_->Start();
853  display_controller_->CreatePrimaryHost();
854  aura::Window* root_window = display_controller_->GetPrimaryRootWindow();
855  target_root_window_ = root_window;
856
857#if defined(OS_CHROMEOS)
858  resolution_notification_controller_.reset(
859      new ResolutionNotificationController);
860#endif
861
862  cursor_manager_.SetDisplay(GetScreen()->GetPrimaryDisplay());
863
864  nested_dispatcher_controller_.reset(new NestedDispatcherController);
865  accelerator_controller_.reset(new AcceleratorController);
866  maximize_mode_controller_.reset(new MaximizeModeController());
867
868#if defined(OS_CHROMEOS) && defined(USE_X11)
869  magnifier_key_scroll_handler_ = MagnifierKeyScroller::CreateHandler().Pass();
870  AddPreTargetHandler(magnifier_key_scroll_handler_.get());
871  speech_feedback_handler_ = SpokenFeedbackToggler::CreateHandler().Pass();
872  AddPreTargetHandler(speech_feedback_handler_.get());
873#endif
874
875  // The order in which event filters are added is significant.
876
877#if defined(OS_CHROMEOS)
878  // The StickyKeysController also rewrites events and must be added
879  // before observers, but after the EventRewriterEventFilter.
880  sticky_keys_controller_.reset(new StickyKeysController);
881  AddPreTargetHandler(sticky_keys_controller_.get());
882#endif
883
884  // wm::UserActivityDetector passes events to observers, so let them get
885  // rewritten first.
886  user_activity_detector_.reset(new ::wm::UserActivityDetector);
887  AddPreTargetHandler(user_activity_detector_.get());
888
889  overlay_filter_.reset(new OverlayEventFilter);
890  AddPreTargetHandler(overlay_filter_.get());
891  AddShellObserver(overlay_filter_.get());
892
893  input_method_filter_.reset(new ::wm::InputMethodEventFilter(
894      root_window->GetHost()->GetAcceleratedWidget()));
895  AddPreTargetHandler(input_method_filter_.get());
896
897  accelerator_filter_.reset(new AcceleratorFilter);
898  AddPreTargetHandler(accelerator_filter_.get());
899
900  event_transformation_handler_.reset(new EventTransformationHandler);
901  AddPreTargetHandler(event_transformation_handler_.get());
902
903  toplevel_window_event_handler_.reset(new ToplevelWindowEventHandler);
904
905  system_gesture_filter_.reset(new SystemGestureEventFilter);
906  AddPreTargetHandler(system_gesture_filter_.get());
907
908  keyboard_metrics_filter_.reset(new KeyboardUMAEventFilter);
909  AddPreTargetHandler(keyboard_metrics_filter_.get());
910
911  // The keyboard system must be initialized before the RootWindowController is
912  // created.
913#if defined(OS_CHROMEOS)
914    keyboard::InitializeKeyboard();
915#endif
916
917  lock_state_controller_.reset(new LockStateController);
918  power_button_controller_.reset(new PowerButtonController(
919      lock_state_controller_.get()));
920#if defined(OS_CHROMEOS)
921  // Pass the initial display state to PowerButtonController.
922  power_button_controller_->OnDisplayModeChanged(
923      display_configurator_->cached_displays());
924#endif
925  AddShellObserver(lock_state_controller_.get());
926
927  drag_drop_controller_.reset(new DragDropController);
928  mouse_cursor_filter_.reset(new MouseCursorEventFilter());
929  PrependPreTargetHandler(mouse_cursor_filter_.get());
930
931  // Create Controllers that may need root window.
932  // TODO(oshima): Move as many controllers before creating
933  // RootWindowController as possible.
934  visibility_controller_.reset(new AshVisibilityController);
935
936  magnification_controller_.reset(
937      MagnificationController::CreateInstance());
938  mru_window_tracker_.reset(new MruWindowTracker(activation_client_));
939
940  partial_magnification_controller_.reset(
941      new PartialMagnificationController());
942
943  autoclick_controller_.reset(AutoclickController::CreateInstance());
944
945  high_contrast_controller_.reset(new HighContrastController);
946  video_detector_.reset(new VideoDetector);
947  window_selector_controller_.reset(new WindowSelectorController());
948
949  tooltip_controller_.reset(
950      new views::corewm::TooltipController(
951          scoped_ptr<views::corewm::Tooltip>(
952              new views::corewm::TooltipAura(gfx::SCREEN_TYPE_ALTERNATE))));
953  AddPreTargetHandler(tooltip_controller_.get());
954
955  event_client_.reset(new EventClientImpl);
956
957  // This controller needs to be set before SetupManagedWindowMode.
958  desktop_background_controller_.reset(new DesktopBackgroundController());
959  user_wallpaper_delegate_.reset(delegate_->CreateUserWallpaperDelegate());
960
961  session_state_delegate_.reset(delegate_->CreateSessionStateDelegate());
962  accessibility_delegate_.reset(delegate_->CreateAccessibilityDelegate());
963  new_window_delegate_.reset(delegate_->CreateNewWindowDelegate());
964  media_delegate_.reset(delegate_->CreateMediaDelegate());
965
966  resize_shadow_controller_.reset(new ResizeShadowController());
967  shadow_controller_.reset(
968      new ::wm::ShadowController(activation_client_));
969
970  // Create system_tray_notifier_ before the delegate.
971  system_tray_notifier_.reset(new ash::SystemTrayNotifier());
972
973  // Initialize system_tray_delegate_ before initializing StatusAreaWidget.
974  system_tray_delegate_.reset(delegate()->CreateSystemTrayDelegate());
975  DCHECK(system_tray_delegate_.get());
976
977  locale_notification_controller_.reset(new LocaleNotificationController);
978
979  // Initialize system_tray_delegate_ after StatusAreaWidget is created.
980  system_tray_delegate_->Initialize();
981
982#if defined(OS_CHROMEOS)
983  // Create the LogoutConfirmationController after the SystemTrayDelegate.
984  logout_confirmation_controller_.reset(new LogoutConfirmationController(
985      base::Bind(&SystemTrayDelegate::SignOut,
986                 base::Unretained(system_tray_delegate_.get()))));
987#endif
988
989  display_controller_->InitDisplays();
990
991  // It needs to be created after RootWindowController has been created
992  // (which calls OnWindowResized has been called, otherwise the
993  // widget will not paint when restoring after a browser crash.  Also it needs
994  // to be created after InitSecondaryDisplays() to initialize the wallpapers in
995  // the correct size.
996  user_wallpaper_delegate_->InitializeWallpaper();
997
998  if (initially_hide_cursor_)
999    cursor_manager_.HideCursor();
1000  cursor_manager_.SetCursor(ui::kCursorPointer);
1001
1002#if defined(OS_CHROMEOS)
1003  // Set accelerator controller delegates.
1004  accelerator_controller_->SetBrightnessControlDelegate(
1005      scoped_ptr<ash::BrightnessControlDelegate>(
1006          new ash::system::BrightnessControllerChromeos).Pass());
1007
1008  power_event_observer_.reset(new PowerEventObserver());
1009  user_activity_notifier_.reset(
1010      new ui::UserActivityPowerManagerNotifier(user_activity_detector_.get()));
1011  video_activity_notifier_.reset(
1012      new VideoActivityNotifier(video_detector_.get()));
1013  bluetooth_notification_controller_.reset(new BluetoothNotificationController);
1014  last_window_closed_logout_reminder_.reset(new LastWindowClosedLogoutReminder);
1015#endif
1016
1017  weak_display_manager_factory_.reset(
1018      new base::WeakPtrFactory<DisplayManager>(display_manager_.get()));
1019  // The compositor thread and main message loop have to be running in
1020  // order to create mirror window. Run it after the main message loop
1021  // is started.
1022  base::MessageLoopForUI::current()->PostTask(
1023      FROM_HERE,
1024      base::Bind(&DisplayManager::CreateMirrorWindowIfAny,
1025                 weak_display_manager_factory_->GetWeakPtr()));
1026}
1027
1028void Shell::InitKeyboard() {
1029  if (keyboard::IsKeyboardEnabled()) {
1030    if (keyboard::KeyboardController::GetInstance()) {
1031      RootWindowControllerList controllers = GetAllRootWindowControllers();
1032      for (RootWindowControllerList::iterator iter = controllers.begin();
1033           iter != controllers.end(); ++iter) {
1034        (*iter)->DeactivateKeyboard(
1035            keyboard::KeyboardController::GetInstance());
1036      }
1037    }
1038    keyboard::KeyboardControllerProxy* proxy =
1039        delegate_->CreateKeyboardControllerProxy();
1040    keyboard::KeyboardController::ResetInstance(
1041        new keyboard::KeyboardController(proxy));
1042  }
1043}
1044
1045void Shell::InitRootWindow(aura::Window* root_window) {
1046  DCHECK(activation_client_);
1047  DCHECK(visibility_controller_.get());
1048  DCHECK(drag_drop_controller_.get());
1049
1050  aura::client::SetFocusClient(root_window, focus_client_.get());
1051  input_method_filter_->SetInputMethodPropertyInRootWindow(root_window);
1052  aura::client::SetActivationClient(root_window, activation_client_);
1053  ::wm::FocusController* focus_controller =
1054      static_cast< ::wm::FocusController*>(activation_client_);
1055  root_window->AddPreTargetHandler(focus_controller);
1056  aura::client::SetVisibilityClient(root_window, visibility_controller_.get());
1057  aura::client::SetDragDropClient(root_window, drag_drop_controller_.get());
1058  aura::client::SetScreenPositionClient(root_window,
1059                                        screen_position_controller_.get());
1060  aura::client::SetCursorClient(root_window, &cursor_manager_);
1061  aura::client::SetTooltipClient(root_window, tooltip_controller_.get());
1062  aura::client::SetEventClient(root_window, event_client_.get());
1063
1064  aura::client::SetWindowMoveClient(root_window,
1065      toplevel_window_event_handler_.get());
1066  root_window->AddPreTargetHandler(toplevel_window_event_handler_.get());
1067  root_window->AddPostTargetHandler(toplevel_window_event_handler_.get());
1068
1069  if (nested_dispatcher_controller_) {
1070    aura::client::SetDispatcherClient(root_window,
1071                                      nested_dispatcher_controller_.get());
1072  }
1073}
1074
1075bool Shell::CanWindowReceiveEvents(aura::Window* window) {
1076  RootWindowControllerList controllers = GetAllRootWindowControllers();
1077  for (RootWindowControllerList::iterator iter = controllers.begin();
1078       iter != controllers.end(); ++iter) {
1079    SystemModalContainerLayoutManager* layout_manager =
1080        (*iter)->GetSystemModalLayoutManager(window);
1081    if (layout_manager && layout_manager->CanWindowReceiveEvents(window))
1082      return true;
1083    // Allow events to fall through to the virtual keyboard even if displaying
1084    // a system modal dialog.
1085    if ((*iter)->IsVirtualKeyboardWindow(window))
1086      return true;
1087  }
1088
1089  return false;
1090}
1091
1092////////////////////////////////////////////////////////////////////////////////
1093// Shell, ui::EventTarget overrides:
1094
1095bool Shell::CanAcceptEvent(const ui::Event& event) {
1096  return true;
1097}
1098
1099ui::EventTarget* Shell::GetParentTarget() {
1100  return aura::Env::GetInstance();
1101}
1102
1103scoped_ptr<ui::EventTargetIterator> Shell::GetChildIterator() const {
1104  return scoped_ptr<ui::EventTargetIterator>();
1105}
1106
1107ui::EventTargeter* Shell::GetEventTargeter() {
1108  NOTREACHED();
1109  return NULL;
1110}
1111
1112void Shell::OnEvent(ui::Event* event) {
1113}
1114
1115////////////////////////////////////////////////////////////////////////////////
1116// Shell, aura::client::ActivationChangeObserver implementation:
1117
1118void Shell::OnWindowActivated(aura::Window* gained_active,
1119                              aura::Window* lost_active) {
1120  if (gained_active)
1121    target_root_window_ = gained_active->GetRootWindow();
1122}
1123
1124}  // namespace ash
1125