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