shell.cc revision 424c4d7b64af9d0d8fd9624f381f469654d5e3d2
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/focus_manager_factory.h"
11#include "ash/ash_switches.h"
12#include "ash/caps_lock_delegate.h"
13#include "ash/desktop_background/desktop_background_controller.h"
14#include "ash/desktop_background/desktop_background_view.h"
15#include "ash/desktop_background/user_wallpaper_delegate.h"
16#include "ash/display/display_controller.h"
17#include "ash/display/display_manager.h"
18#include "ash/display/event_transformation_handler.h"
19#include "ash/display/mouse_cursor_event_filter.h"
20#include "ash/display/resolution_notification_controller.h"
21#include "ash/display/screen_position_controller.h"
22#include "ash/drag_drop/drag_drop_controller.h"
23#include "ash/focus_cycler.h"
24#include "ash/high_contrast/high_contrast_controller.h"
25#include "ash/host/root_window_host_factory.h"
26#include "ash/launcher/app_list_launcher_item_delegate.h"
27#include "ash/launcher/launcher_delegate.h"
28#include "ash/launcher/launcher_item_delegate.h"
29#include "ash/launcher/launcher_item_delegate_manager.h"
30#include "ash/launcher/launcher_model.h"
31#include "ash/magnifier/magnification_controller.h"
32#include "ash/magnifier/partial_magnification_controller.h"
33#include "ash/root_window_controller.h"
34#include "ash/screen_ash.h"
35#include "ash/session_state_delegate.h"
36#include "ash/shelf/shelf_layout_manager.h"
37#include "ash/shelf/shelf_widget.h"
38#include "ash/shell_delegate.h"
39#include "ash/shell_factory.h"
40#include "ash/shell_window_ids.h"
41#include "ash/system/locale/locale_notification_controller.h"
42#include "ash/system/status_area_widget.h"
43#include "ash/system/tray/system_tray_delegate.h"
44#include "ash/system/tray/system_tray_notifier.h"
45#include "ash/wm/activation_controller.h"
46#include "ash/wm/app_list_controller.h"
47#include "ash/wm/ash_activation_controller.h"
48#include "ash/wm/ash_focus_rules.h"
49#include "ash/wm/ash_native_cursor_manager.h"
50#include "ash/wm/base_layout_manager.h"
51#include "ash/wm/coordinate_conversion.h"
52#include "ash/wm/custom_frame_view_ash.h"
53#include "ash/wm/event_client_impl.h"
54#include "ash/wm/event_rewriter_event_filter.h"
55#include "ash/wm/lock_state_controller.h"
56#include "ash/wm/lock_state_controller_impl2.h"
57#include "ash/wm/mru_window_tracker.h"
58#include "ash/wm/overlay_event_filter.h"
59#include "ash/wm/overview/window_selector_controller.h"
60#include "ash/wm/power_button_controller.h"
61#include "ash/wm/property_util.h"
62#include "ash/wm/resize_shadow_controller.h"
63#include "ash/wm/root_window_layout_manager.h"
64#include "ash/wm/screen_dimmer.h"
65#include "ash/wm/session_state_controller_impl.h"
66#include "ash/wm/system_gesture_event_filter.h"
67#include "ash/wm/system_modal_container_event_filter.h"
68#include "ash/wm/system_modal_container_layout_manager.h"
69#include "ash/wm/user_activity_detector.h"
70#include "ash/wm/video_detector.h"
71#include "ash/wm/window_animations.h"
72#include "ash/wm/window_cycle_controller.h"
73#include "ash/wm/window_properties.h"
74#include "ash/wm/window_util.h"
75#include "ash/wm/workspace_controller.h"
76#include "base/bind.h"
77#include "base/command_line.h"
78#include "base/debug/leak_annotations.h"
79#include "ui/aura/client/aura_constants.h"
80#include "ui/aura/client/user_action_client.h"
81#include "ui/aura/env.h"
82#include "ui/aura/focus_manager.h"
83#include "ui/aura/layout_manager.h"
84#include "ui/aura/root_window.h"
85#include "ui/aura/window.h"
86#include "ui/base/ui_base_switches.h"
87#include "ui/compositor/layer.h"
88#include "ui/compositor/layer_animator.h"
89#include "ui/gfx/display.h"
90#include "ui/gfx/image/image_skia.h"
91#include "ui/gfx/screen.h"
92#include "ui/gfx/size.h"
93#include "ui/keyboard/keyboard.h"
94#include "ui/keyboard/keyboard_util.h"
95#include "ui/message_center/message_center.h"
96#include "ui/views/corewm/compound_event_filter.h"
97#include "ui/views/corewm/corewm_switches.h"
98#include "ui/views/corewm/focus_controller.h"
99#include "ui/views/corewm/input_method_event_filter.h"
100#include "ui/views/corewm/shadow_controller.h"
101#include "ui/views/corewm/tooltip_controller.h"
102#include "ui/views/corewm/visibility_controller.h"
103#include "ui/views/corewm/window_modality_controller.h"
104#include "ui/views/focus/focus_manager_factory.h"
105#include "ui/views/widget/native_widget_aura.h"
106#include "ui/views/widget/widget.h"
107
108#if !defined(OS_MACOSX)
109#include "ash/accelerators/accelerator_controller.h"
110#include "ash/accelerators/accelerator_filter.h"
111#include "ash/accelerators/nested_dispatcher_controller.h"
112#endif
113
114#if defined(OS_CHROMEOS)
115#if defined(USE_X11)
116#include "ash/ash_constants.h"
117#include "ash/display/display_change_observer_chromeos.h"
118#include "ash/display/display_error_observer_chromeos.h"
119#include "ash/display/output_configurator_animation.h"
120#include "base/chromeos/chromeos_version.h"
121#include "base/message_loop/message_pump_aurax11.h"
122#include "chromeos/display/output_configurator.h"
123#include "content/public/browser/gpu_data_manager.h"
124#include "gpu/config/gpu_feature_type.h"
125#endif  // defined(USE_X11)
126#include "ash/system/chromeos/power/power_status.h"
127#endif  // defined(OS_CHROMEOS)
128
129namespace ash {
130
131namespace {
132
133using aura::Window;
134using views::Widget;
135
136// This dummy class is used for shell unit tests. We dont have chrome delegate
137// in these tests.
138class DummyUserWallpaperDelegate : public UserWallpaperDelegate {
139 public:
140  DummyUserWallpaperDelegate() {}
141
142  virtual ~DummyUserWallpaperDelegate() {}
143
144  virtual int GetAnimationType() OVERRIDE {
145    return views::corewm::WINDOW_VISIBILITY_ANIMATION_TYPE_FADE;
146  }
147
148  virtual bool ShouldShowInitialAnimation() OVERRIDE {
149    return false;
150  }
151
152  virtual void UpdateWallpaper() OVERRIDE {
153  }
154
155  virtual void InitializeWallpaper() OVERRIDE {
156    ash::Shell::GetInstance()->desktop_background_controller()->
157        CreateEmptyWallpaper();
158  }
159
160  virtual void OpenSetWallpaperPage() OVERRIDE {
161  }
162
163  virtual bool CanOpenSetWallpaperPage() OVERRIDE {
164    return false;
165  }
166
167  virtual void OnWallpaperAnimationFinished() OVERRIDE {
168  }
169
170  virtual void OnWallpaperBootAnimationFinished() OVERRIDE {
171  }
172
173 private:
174  DISALLOW_COPY_AND_ASSIGN(DummyUserWallpaperDelegate);
175};
176
177// A Corewm VisibilityController subclass that calls the Ash animation routine
178// so we can pick up our extended animations. See ash/wm/window_animations.h.
179class AshVisibilityController : public views::corewm::VisibilityController {
180 public:
181  AshVisibilityController() {}
182  virtual ~AshVisibilityController() {}
183
184 private:
185  // Overridden from views::corewm::VisibilityController:
186  virtual bool CallAnimateOnChildWindowVisibilityChanged(
187      aura::Window* window,
188      bool visible) OVERRIDE {
189    return AnimateOnChildWindowVisibilityChanged(window, visible);
190  }
191
192  DISALLOW_COPY_AND_ASSIGN(AshVisibilityController);
193};
194
195}  // namespace
196
197// static
198Shell* Shell::instance_ = NULL;
199// static
200bool Shell::initially_hide_cursor_ = false;
201
202////////////////////////////////////////////////////////////////////////////////
203// Shell, public:
204
205Shell::Shell(ShellDelegate* delegate)
206    : screen_(new ScreenAsh),
207      target_root_window_(NULL),
208      scoped_target_root_window_(NULL),
209      delegate_(delegate),
210      activation_client_(NULL),
211#if defined(OS_CHROMEOS) && defined(USE_X11)
212      output_configurator_(new chromeos::OutputConfigurator()),
213#endif  // defined(OS_CHROMEOS)
214      native_cursor_manager_(new AshNativeCursorManager),
215      cursor_manager_(scoped_ptr<views::corewm::NativeCursorManager>(
216          native_cursor_manager_)),
217      browser_context_(NULL),
218      simulate_modal_window_open_for_testing_(false),
219      is_touch_hud_projection_enabled_(false) {
220  DCHECK(delegate_.get());
221  display_manager_.reset(new internal::DisplayManager);
222
223  ANNOTATE_LEAKING_OBJECT_PTR(screen_);  // see crbug.com/156466
224  gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_ALTERNATE, screen_);
225  if (!gfx::Screen::GetScreenByType(gfx::SCREEN_TYPE_NATIVE))
226    gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, screen_);
227  display_controller_.reset(new DisplayController);
228#if defined(OS_CHROMEOS) && defined(USE_X11)
229  bool is_panel_fitting_disabled =
230      content::GpuDataManager::GetInstance()->IsFeatureBlacklisted(
231          gpu::GPU_FEATURE_TYPE_PANEL_FITTING);
232
233  output_configurator_->Init(!is_panel_fitting_disabled);
234
235  base::MessagePumpAuraX11::Current()->AddDispatcherForRootWindow(
236      output_configurator());
237  // We can't do this with a root window listener because XI_HierarchyChanged
238  // messages don't have a target window.
239  base::MessagePumpAuraX11::Current()->AddObserver(output_configurator());
240#endif  // defined(OS_CHROMEOS)
241  AddPreTargetHandler(this);
242
243#if defined(OS_CHROMEOS)
244  internal::PowerStatus::Initialize();
245#endif
246}
247
248Shell::~Shell() {
249  views::FocusManagerFactory::Install(NULL);
250
251  // Remove the focus from any window. This will prevent overhead and side
252  // effects (e.g. crashes) from changing focus during shutdown.
253  // See bug crbug.com/134502.
254  aura::client::GetFocusClient(GetPrimaryRootWindow())->FocusWindow(NULL);
255
256  // Please keep in same order as in Init() because it's easy to miss one.
257  RemovePreTargetHandler(event_rewriter_filter_.get());
258  RemovePreTargetHandler(user_activity_detector_.get());
259  RemovePreTargetHandler(overlay_filter_.get());
260  RemovePreTargetHandler(input_method_filter_.get());
261  RemovePreTargetHandler(window_modality_controller_.get());
262  if (mouse_cursor_filter_)
263    RemovePreTargetHandler(mouse_cursor_filter_.get());
264  RemovePreTargetHandler(system_gesture_filter_.get());
265  RemovePreTargetHandler(event_transformation_handler_.get());
266#if !defined(OS_MACOSX)
267  RemovePreTargetHandler(accelerator_filter_.get());
268#endif
269
270  // TooltipController is deleted with the Shell so removing its references.
271  RemovePreTargetHandler(tooltip_controller_.get());
272
273  // AppList needs to be released before shelf layout manager, which is
274  // destroyed with launcher container in the loop below. However, app list
275  // container is now on top of launcher container and released after it.
276  // TODO(xiyuan): Move it back when app list container is no longer needed.
277  app_list_controller_.reset();
278
279  // Destroy SystemTrayDelegate before destroying the status area(s).
280  system_tray_delegate_->Shutdown();
281  system_tray_delegate_.reset();
282
283  locale_notification_controller_.reset();
284
285  // Drag-and-drop must be canceled prior to close all windows.
286  drag_drop_controller_.reset();
287
288  // Destroy all child windows including widgets.
289  display_controller_->CloseChildWindows();
290
291  // Destroy SystemTrayNotifier after destroying SystemTray as TrayItems
292  // needs to remove observers from it.
293  system_tray_notifier_.reset();
294
295  // These need a valid Shell instance to clean up properly, so explicitly
296  // delete them before invalidating the instance.
297  // Alphabetical. TODO(oshima): sort.
298  magnification_controller_.reset();
299  partial_magnification_controller_.reset();
300  resize_shadow_controller_.reset();
301  shadow_controller_.reset();
302  tooltip_controller_.reset();
303  event_client_.reset();
304  window_cycle_controller_.reset();
305  nested_dispatcher_controller_.reset();
306  user_action_client_.reset();
307  visibility_controller_.reset();
308  launcher_delegate_.reset();
309  launcher_model_.reset();
310  video_detector_.reset();
311
312  power_button_controller_.reset();
313  lock_state_controller_.reset();
314  mru_window_tracker_.reset();
315
316  resolution_notification_controller_.reset();
317
318  // This also deletes all RootWindows. Note that we invoke Shutdown() on
319  // DisplayController before resetting |display_controller_|, since destruction
320  // of its owned RootWindowControllers relies on the value.
321  display_controller_->Shutdown();
322  display_controller_.reset();
323  screen_position_controller_.reset();
324
325  // Delete the activation controller after other controllers and launcher
326  // because they might have registered ActivationChangeObserver.
327  activation_controller_.reset();
328
329#if defined(OS_CHROMEOS) && defined(USE_X11)
330   if (display_change_observer_)
331    output_configurator_->RemoveObserver(display_change_observer_.get());
332  if (output_configurator_animation_)
333    output_configurator_->RemoveObserver(output_configurator_animation_.get());
334  if (display_error_observer_)
335    output_configurator_->RemoveObserver(display_error_observer_.get());
336  base::MessagePumpAuraX11::Current()->RemoveDispatcherForRootWindow(
337      output_configurator());
338  base::MessagePumpAuraX11::Current()->RemoveObserver(output_configurator());
339  display_change_observer_.reset();
340#endif  // defined(OS_CHROMEOS)
341
342#if defined(OS_CHROMEOS)
343  internal::PowerStatus::Shutdown();
344#endif
345
346  DCHECK(instance_ == this);
347  instance_ = NULL;
348}
349
350// static
351Shell* Shell::CreateInstance(ShellDelegate* delegate) {
352  CHECK(!instance_);
353  instance_ = new Shell(delegate);
354  instance_->Init();
355  return instance_;
356}
357
358// static
359Shell* Shell::GetInstance() {
360  DCHECK(instance_);
361  return instance_;
362}
363
364// static
365bool Shell::HasInstance() {
366  return !!instance_;
367}
368
369// static
370void Shell::DeleteInstance() {
371  delete instance_;
372  instance_ = NULL;
373}
374
375// static
376internal::RootWindowController* Shell::GetPrimaryRootWindowController() {
377  return GetRootWindowController(GetPrimaryRootWindow());
378}
379
380// static
381Shell::RootWindowControllerList Shell::GetAllRootWindowControllers() {
382  return Shell::GetInstance()->display_controller()->
383      GetAllRootWindowControllers();
384}
385
386// static
387aura::RootWindow* Shell::GetPrimaryRootWindow() {
388  return GetInstance()->display_controller()->GetPrimaryRootWindow();
389}
390
391// static
392aura::RootWindow* Shell::GetActiveRootWindow() {
393  Shell* shell = GetInstance();
394  if (shell->scoped_target_root_window_)
395    return shell->scoped_target_root_window_;
396  return shell->target_root_window_;
397}
398
399// static
400gfx::Screen* Shell::GetScreen() {
401  return gfx::Screen::GetScreenByType(gfx::SCREEN_TYPE_ALTERNATE);
402}
403
404// static
405Shell::RootWindowList Shell::GetAllRootWindows() {
406  return Shell::GetInstance()->display_controller()->
407      GetAllRootWindows();
408}
409
410// static
411aura::Window* Shell::GetContainer(aura::RootWindow* root_window,
412                                  int container_id) {
413  return root_window->GetChildById(container_id);
414}
415
416// static
417const aura::Window* Shell::GetContainer(const aura::RootWindow* root_window,
418                                        int container_id) {
419  return root_window->GetChildById(container_id);
420}
421
422// static
423std::vector<aura::Window*> Shell::GetContainersFromAllRootWindows(
424    int container_id,
425    aura::RootWindow* priority_root) {
426  std::vector<aura::Window*> containers;
427  RootWindowList root_windows = GetAllRootWindows();
428  for (RootWindowList::const_iterator it = root_windows.begin();
429       it != root_windows.end(); ++it) {
430    aura::Window* container = (*it)->GetChildById(container_id);
431    if (container) {
432      if (priority_root && priority_root->Contains(container))
433        containers.insert(containers.begin(), container);
434      else
435        containers.push_back(container);
436    }
437  }
438  return containers;
439}
440
441// static
442bool Shell::IsForcedMaximizeMode() {
443  CommandLine* command_line = CommandLine::ForCurrentProcess();
444  return command_line->HasSwitch(switches::kForcedMaximizeMode);
445}
446
447void Shell::Init() {
448  CommandLine* command_line = CommandLine::ForCurrentProcess();
449
450  delegate_->PreInit();
451  bool display_initialized = false;
452#if defined(OS_CHROMEOS) && defined(USE_X11)
453  output_configurator_animation_.reset(
454      new internal::OutputConfiguratorAnimation());
455  output_configurator_->AddObserver(output_configurator_animation_.get());
456  if (base::chromeos::IsRunningOnChromeOS()) {
457    display_change_observer_.reset(new internal::DisplayChangeObserver);
458    // Register |display_change_observer_| first so that the rest of
459    // observer gets invoked after the root windows are configured.
460    output_configurator_->AddObserver(display_change_observer_.get());
461    display_error_observer_.reset(new internal::DisplayErrorObserver());
462    output_configurator_->AddObserver(display_error_observer_.get());
463    output_configurator_->set_state_controller(display_change_observer_.get());
464    if (!command_line->HasSwitch(ash::switches::kAshDisableSoftwareMirroring))
465      output_configurator_->set_mirroring_controller(display_manager_.get());
466    output_configurator_->Start(
467        delegate_->IsFirstRunAfterBoot() ? kChromeOsBootColor : 0);
468    display_initialized = true;
469  }
470#endif  // defined(OS_CHROMEOS) && defined(USE_X11)
471  if (!display_initialized)
472    display_manager_->InitFromCommandLine();
473
474  // Install the custom factory first so that views::FocusManagers for Tray,
475  // Launcher, and WallPaper could be created by the factory.
476  views::FocusManagerFactory::Install(new AshFocusManagerFactory);
477
478  env_filter_.reset(new views::corewm::CompoundEventFilter);
479  AddPreTargetHandler(env_filter_.get());
480
481  // Env creates the compositor. Historically it seems to have been implicitly
482  // initialized first by the ActivationController, but now that FocusController
483  // no longer does this we need to do it explicitly.
484  aura::Env::GetInstance();
485  if (views::corewm::UseFocusController()) {
486    views::corewm::FocusController* focus_controller =
487        new views::corewm::FocusController(new wm::AshFocusRules);
488    focus_client_.reset(focus_controller);
489    activation_client_ = focus_controller;
490    activation_client_->AddObserver(this);
491  } else {
492    focus_client_.reset(new aura::FocusManager);
493    activation_controller_.reset(
494        new internal::ActivationController(
495            focus_client_.get(),
496            new internal::AshActivationController));
497    activation_client_ = activation_controller_.get();
498    AddPreTargetHandler(activation_controller_.get());
499  }
500
501  focus_cycler_.reset(new internal::FocusCycler());
502
503  screen_position_controller_.reset(new internal::ScreenPositionController);
504  root_window_host_factory_.reset(delegate_->CreateRootWindowHostFactory());
505
506  display_controller_->Start();
507  display_controller_->InitPrimaryDisplay();
508  aura::RootWindow* root_window = display_controller_->GetPrimaryRootWindow();
509  target_root_window_ = root_window;
510
511  resolution_notification_controller_.reset(
512      new internal::ResolutionNotificationController);
513
514  cursor_manager_.SetDisplay(DisplayController::GetPrimaryDisplay());
515
516#if !defined(OS_MACOSX)
517  nested_dispatcher_controller_.reset(new NestedDispatcherController);
518  accelerator_controller_.reset(new AcceleratorController);
519#endif
520
521  // The order in which event filters are added is significant.
522  event_rewriter_filter_.reset(new internal::EventRewriterEventFilter);
523  AddPreTargetHandler(event_rewriter_filter_.get());
524
525  // UserActivityDetector passes events to observers, so let them get
526  // rewritten first.
527  user_activity_detector_.reset(new UserActivityDetector);
528  AddPreTargetHandler(user_activity_detector_.get());
529
530  overlay_filter_.reset(new internal::OverlayEventFilter);
531  AddPreTargetHandler(overlay_filter_.get());
532  AddShellObserver(overlay_filter_.get());
533
534  input_method_filter_.reset(new views::corewm::InputMethodEventFilter(
535                                 root_window->GetAcceleratedWidget()));
536  AddPreTargetHandler(input_method_filter_.get());
537
538#if !defined(OS_MACOSX)
539  accelerator_filter_.reset(new internal::AcceleratorFilter);
540  AddPreTargetHandler(accelerator_filter_.get());
541#endif
542
543  event_transformation_handler_.reset(new internal::EventTransformationHandler);
544  AddPreTargetHandler(event_transformation_handler_.get());
545
546  system_gesture_filter_.reset(new internal::SystemGestureEventFilter);
547  AddPreTargetHandler(system_gesture_filter_.get());
548
549  // The keyboard system must be initialized before the RootWindowController is
550  // created.
551  if (keyboard::IsKeyboardEnabled())
552    keyboard::InitializeKeyboard();
553
554  if (command_line->HasSwitch(ash::switches::kAshDisableNewLockAnimations))
555    lock_state_controller_.reset(new SessionStateControllerImpl);
556  else
557    lock_state_controller_.reset(new LockStateControllerImpl2);
558  power_button_controller_.reset(new PowerButtonController(
559      lock_state_controller_.get()));
560  AddShellObserver(lock_state_controller_.get());
561
562  drag_drop_controller_.reset(new internal::DragDropController);
563  mouse_cursor_filter_.reset(new internal::MouseCursorEventFilter());
564  PrependPreTargetHandler(mouse_cursor_filter_.get());
565
566  // Create Controllers that may need root window.
567  // TODO(oshima): Move as many controllers before creating
568  // RootWindowController as possible.
569  visibility_controller_.reset(new AshVisibilityController);
570  user_action_client_.reset(delegate_->CreateUserActionClient());
571  window_modality_controller_.reset(
572      new views::corewm::WindowModalityController);
573  AddPreTargetHandler(window_modality_controller_.get());
574
575  magnification_controller_.reset(
576      MagnificationController::CreateInstance());
577  mru_window_tracker_.reset(new MruWindowTracker(activation_client_));
578
579  partial_magnification_controller_.reset(
580      new PartialMagnificationController());
581
582  high_contrast_controller_.reset(new HighContrastController);
583  video_detector_.reset(new VideoDetector);
584  window_cycle_controller_.reset(new WindowCycleController());
585  window_selector_controller_.reset(new WindowSelectorController());
586
587  tooltip_controller_.reset(new views::corewm::TooltipController(
588                                gfx::SCREEN_TYPE_ALTERNATE));
589  AddPreTargetHandler(tooltip_controller_.get());
590
591  event_client_.reset(new internal::EventClientImpl);
592
593  // This controller needs to be set before SetupManagedWindowMode.
594  desktop_background_controller_.reset(new DesktopBackgroundController());
595  user_wallpaper_delegate_.reset(delegate_->CreateUserWallpaperDelegate());
596  if (!user_wallpaper_delegate_)
597    user_wallpaper_delegate_.reset(new DummyUserWallpaperDelegate());
598
599  // StatusAreaWidget uses Shell's CapsLockDelegate.
600  caps_lock_delegate_.reset(delegate_->CreateCapsLockDelegate());
601
602  session_state_delegate_.reset(delegate_->CreateSessionStateDelegate());
603
604  if (!command_line->HasSwitch(views::corewm::switches::kNoDropShadows)) {
605    resize_shadow_controller_.reset(new internal::ResizeShadowController());
606    shadow_controller_.reset(
607        new views::corewm::ShadowController(activation_client_));
608  }
609
610  // Create system_tray_notifier_ before the delegate.
611  system_tray_notifier_.reset(new ash::SystemTrayNotifier());
612
613  // Initialize system_tray_delegate_ before initializing StatusAreaWidget.
614  system_tray_delegate_.reset(delegate()->CreateSystemTrayDelegate());
615  if (!system_tray_delegate_)
616    system_tray_delegate_.reset(SystemTrayDelegate::CreateDummyDelegate());
617
618  internal::RootWindowController* root_window_controller =
619      new internal::RootWindowController(root_window);
620  InitRootWindowController(root_window_controller,
621                           delegate_->IsFirstRunAfterBoot());
622
623  locale_notification_controller_.reset(
624      new internal::LocaleNotificationController);
625
626  // Initialize system_tray_delegate_ after StatusAreaWidget is created.
627  system_tray_delegate_->Initialize();
628
629  display_controller_->InitSecondaryDisplays();
630
631  // Force Layout
632  root_window_controller->root_window_layout()->OnWindowResized();
633
634  // It needs to be created after OnWindowResized has been called, otherwise the
635  // widget will not paint when restoring after a browser crash.  Also it needs
636  // to be created after InitSecondaryDisplays() to initialize the wallpapers in
637  // the correct size.
638  user_wallpaper_delegate_->InitializeWallpaper();
639
640  if (initially_hide_cursor_)
641    cursor_manager_.HideCursor();
642  cursor_manager_.SetCursor(ui::kCursorPointer);
643
644  if (!cursor_manager_.IsCursorVisible()) {
645    // Cursor might have been hidden by something other than chrome.
646    // Let the first mouse event show the cursor.
647    env_filter_->set_cursor_hidden_by_filter(true);
648  }
649}
650
651void Shell::ShowContextMenu(const gfx::Point& location_in_screen,
652                            ui::MenuSourceType source_type) {
653  // No context menus if there is no session with an active user.
654  if (!session_state_delegate_->NumberOfLoggedInUsers())
655    return;
656  // No context menus when screen is locked.
657  if (session_state_delegate_->IsScreenLocked())
658    return;
659
660  aura::RootWindow* root =
661      wm::GetRootWindowMatching(gfx::Rect(location_in_screen, gfx::Size()));
662  // TODO(oshima): The root and root window controller shouldn't be
663  // NULL even for the out-of-bounds |location_in_screen| (It should
664  // return the primary root). Investigate why/how this is
665  // happening. crbug.com/165214.
666  internal::RootWindowController* rwc = GetRootWindowController(root);
667  CHECK(rwc) << "root=" << root
668             << ", location:" << location_in_screen.ToString();
669  if (rwc)
670    rwc->ShowContextMenu(location_in_screen, source_type);
671}
672
673void Shell::ToggleAppList(aura::Window* window) {
674  // If the context window is not given, show it on the active root window.
675  if (!window)
676    window = GetActiveRootWindow();
677  if (!app_list_controller_)
678    app_list_controller_.reset(new internal::AppListController);
679  app_list_controller_->SetVisible(!app_list_controller_->IsVisible(), window);
680}
681
682bool Shell::GetAppListTargetVisibility() const {
683  return app_list_controller_.get() &&
684      app_list_controller_->GetTargetVisibility();
685}
686
687aura::Window* Shell::GetAppListWindow() {
688  return app_list_controller_.get() ? app_list_controller_->GetWindow() : NULL;
689}
690
691bool Shell::IsSystemModalWindowOpen() const {
692  if (simulate_modal_window_open_for_testing_)
693    return true;
694  const std::vector<aura::Window*> containers = GetContainersFromAllRootWindows(
695      internal::kShellWindowId_SystemModalContainer, NULL);
696  for (std::vector<aura::Window*>::const_iterator cit = containers.begin();
697       cit != containers.end(); ++cit) {
698    for (aura::Window::Windows::const_iterator wit = (*cit)->children().begin();
699         wit != (*cit)->children().end(); ++wit) {
700      if ((*wit)->GetProperty(aura::client::kModalKey) ==
701          ui::MODAL_TYPE_SYSTEM && (*wit)->TargetVisibility()) {
702        return true;
703      }
704    }
705  }
706  return false;
707}
708
709views::NonClientFrameView* Shell::CreateDefaultNonClientFrameView(
710    views::Widget* widget) {
711  // Use translucent-style window frames for dialogs.
712  CustomFrameViewAsh* frame_view = new CustomFrameViewAsh;
713  frame_view->Init(widget);
714  return frame_view;
715}
716
717void Shell::RotateFocus(Direction direction) {
718  focus_cycler_->RotateFocus(
719      direction == FORWARD ? internal::FocusCycler::FORWARD :
720                             internal::FocusCycler::BACKWARD);
721}
722
723void Shell::SetDisplayWorkAreaInsets(Window* contains,
724                                     const gfx::Insets& insets) {
725  if (!display_controller_->UpdateWorkAreaOfDisplayNearestWindow(
726          contains, insets)) {
727    return;
728  }
729  FOR_EACH_OBSERVER(ShellObserver, observers_,
730                    OnDisplayWorkAreaInsetsChanged());
731}
732
733void Shell::OnLoginStateChanged(user::LoginStatus status) {
734  FOR_EACH_OBSERVER(ShellObserver, observers_, OnLoginStateChanged(status));
735}
736
737void Shell::UpdateAfterLoginStatusChange(user::LoginStatus status) {
738  RootWindowControllerList controllers = GetAllRootWindowControllers();
739  for (RootWindowControllerList::iterator iter = controllers.begin();
740       iter != controllers.end(); ++iter)
741    (*iter)->UpdateAfterLoginStatusChange(status);
742}
743
744void Shell::OnAppTerminating() {
745  FOR_EACH_OBSERVER(ShellObserver, observers_, OnAppTerminating());
746}
747
748void Shell::OnLockStateChanged(bool locked) {
749  FOR_EACH_OBSERVER(ShellObserver, observers_, OnLockStateChanged(locked));
750#ifndef NDEBUG
751  // Make sure that there is no system modal in Lock layer when unlocked.
752  if (!locked) {
753    std::vector<aura::Window*> containers = GetContainersFromAllRootWindows(
754        internal::kShellWindowId_LockSystemModalContainer,
755        GetPrimaryRootWindow());
756    for (std::vector<aura::Window*>::const_iterator iter = containers.begin();
757         iter != containers.end(); ++iter) {
758      DCHECK_EQ(0u, (*iter)->children().size());
759    }
760  }
761#endif
762}
763
764void Shell::CreateLauncher() {
765  RootWindowControllerList controllers = GetAllRootWindowControllers();
766  for (RootWindowControllerList::iterator iter = controllers.begin();
767       iter != controllers.end(); ++iter)
768    (*iter)->shelf()->CreateLauncher();
769}
770
771void Shell::ShowLauncher() {
772  RootWindowControllerList controllers = GetAllRootWindowControllers();
773  for (RootWindowControllerList::iterator iter = controllers.begin();
774       iter != controllers.end(); ++iter)
775    (*iter)->ShowLauncher();
776}
777
778void Shell::AddShellObserver(ShellObserver* observer) {
779  observers_.AddObserver(observer);
780}
781
782void Shell::RemoveShellObserver(ShellObserver* observer) {
783  observers_.RemoveObserver(observer);
784}
785
786void Shell::UpdateShelfVisibility() {
787  RootWindowControllerList controllers = GetAllRootWindowControllers();
788  for (RootWindowControllerList::iterator iter = controllers.begin();
789       iter != controllers.end(); ++iter)
790    if ((*iter)->shelf())
791      (*iter)->UpdateShelfVisibility();
792}
793
794void Shell::SetShelfAutoHideBehavior(ShelfAutoHideBehavior behavior,
795                                     aura::RootWindow* root_window) {
796  ash::internal::ShelfLayoutManager::ForLauncher(root_window)->
797      SetAutoHideBehavior(behavior);
798}
799
800ShelfAutoHideBehavior Shell::GetShelfAutoHideBehavior(
801    aura::RootWindow* root_window) const {
802  return ash::internal::ShelfLayoutManager::ForLauncher(root_window)->
803      auto_hide_behavior();
804}
805
806void Shell::SetShelfAlignment(ShelfAlignment alignment,
807                              aura::RootWindow* root_window) {
808  if (ash::internal::ShelfLayoutManager::ForLauncher(root_window)->
809      SetAlignment(alignment)) {
810    FOR_EACH_OBSERVER(
811        ShellObserver, observers_, OnShelfAlignmentChanged(root_window));
812  }
813}
814
815ShelfAlignment Shell::GetShelfAlignment(aura::RootWindow* root_window) {
816  return GetRootWindowController(root_window)->
817      GetShelfLayoutManager()->GetAlignment();
818}
819
820void Shell::SetDimming(bool should_dim) {
821  RootWindowControllerList controllers = GetAllRootWindowControllers();
822  for (RootWindowControllerList::iterator iter = controllers.begin();
823       iter != controllers.end(); ++iter)
824    (*iter)->screen_dimmer()->SetDimming(should_dim);
825}
826
827void Shell::CreateModalBackground(aura::Window* window) {
828  if (!modality_filter_) {
829    modality_filter_.reset(new internal::SystemModalContainerEventFilter(this));
830    AddPreTargetHandler(modality_filter_.get());
831  }
832  RootWindowControllerList controllers = GetAllRootWindowControllers();
833  for (RootWindowControllerList::iterator iter = controllers.begin();
834       iter != controllers.end(); ++iter)
835    (*iter)->GetSystemModalLayoutManager(window)->CreateModalBackground();
836}
837
838void Shell::OnModalWindowRemoved(aura::Window* removed) {
839  RootWindowControllerList controllers = GetAllRootWindowControllers();
840  bool activated = false;
841  for (RootWindowControllerList::iterator iter = controllers.begin();
842       iter != controllers.end() && !activated; ++iter) {
843    activated = (*iter)->GetSystemModalLayoutManager(removed)->
844        ActivateNextModalWindow();
845  }
846  if (!activated) {
847    RemovePreTargetHandler(modality_filter_.get());
848    modality_filter_.reset();
849    for (RootWindowControllerList::iterator iter = controllers.begin();
850         iter != controllers.end(); ++iter)
851      (*iter)->GetSystemModalLayoutManager(removed)->DestroyModalBackground();
852  }
853}
854
855WebNotificationTray* Shell::GetWebNotificationTray() {
856  return GetPrimaryRootWindowController()->shelf()->
857      status_area_widget()->web_notification_tray();
858}
859
860bool Shell::HasPrimaryStatusArea() {
861  ShelfWidget* shelf = GetPrimaryRootWindowController()->shelf();
862  return shelf && shelf->status_area_widget();
863}
864
865SystemTray* Shell::GetPrimarySystemTray() {
866  return GetPrimaryRootWindowController()->GetSystemTray();
867}
868
869LauncherDelegate* Shell::GetLauncherDelegate() {
870  if (!launcher_delegate_) {
871    // Creates LauncherItemDelegateManager before LauncherDelegate.
872    launcher_item_delegate_manager_.reset(new LauncherItemDelegateManager);
873    launcher_model_.reset(new LauncherModel);
874    launcher_delegate_.reset(
875        delegate_->CreateLauncherDelegate(launcher_model_.get()));
876    app_list_launcher_item_delegate_.reset(
877        new internal::AppListLauncherItemDelegate);
878  }
879  return launcher_delegate_.get();
880}
881
882void Shell::SetTouchHudProjectionEnabled(bool enabled) {
883  if (is_touch_hud_projection_enabled_ == enabled)
884    return;
885
886  is_touch_hud_projection_enabled_ = enabled;
887  FOR_EACH_OBSERVER(ShellObserver, observers_,
888                    OnTouchHudProjectionToggled(enabled));
889}
890
891void Shell::InitRootWindowForSecondaryDisplay(aura::RootWindow* root) {
892  internal::RootWindowController* controller =
893      new internal::RootWindowController(root);
894  // Pass false for the |is_first_run_after_boot| parameter so we'll show a
895  // black background on this display instead of trying to mimic the boot splash
896  // screen.
897  InitRootWindowController(controller, false);
898
899  controller->root_window_layout()->OnWindowResized();
900  desktop_background_controller_->OnRootWindowAdded(root);
901  high_contrast_controller_->OnRootWindowAdded(root);
902  root->ShowRootWindow();
903  // Activate new root for testing.
904  // TODO(oshima): remove this.
905  target_root_window_ = root;
906
907  // Create a launcher if a user is already logged.
908  if (Shell::GetInstance()->session_state_delegate()->NumberOfLoggedInUsers())
909    controller->shelf()->CreateLauncher();
910}
911
912void Shell::DoInitialWorkspaceAnimation() {
913  return GetPrimaryRootWindowController()->workspace_controller()->
914      DoInitialAnimation();
915}
916
917void Shell::InitRootWindowController(
918    internal::RootWindowController* controller,
919    bool first_run_after_boot) {
920
921  aura::RootWindow* root_window = controller->root_window();
922  DCHECK(activation_client_);
923  DCHECK(visibility_controller_.get());
924  DCHECK(drag_drop_controller_.get());
925  DCHECK(window_cycle_controller_.get());
926
927  aura::client::SetFocusClient(root_window, focus_client_.get());
928  input_method_filter_->SetInputMethodPropertyInRootWindow(root_window);
929  aura::client::SetActivationClient(root_window, activation_client_);
930  if (views::corewm::UseFocusController()) {
931    views::corewm::FocusController* controller =
932        static_cast<views::corewm::FocusController*>(activation_client_);
933    root_window->AddPreTargetHandler(controller);
934  }
935  aura::client::SetVisibilityClient(root_window, visibility_controller_.get());
936  aura::client::SetDragDropClient(root_window, drag_drop_controller_.get());
937  aura::client::SetScreenPositionClient(root_window,
938                                        screen_position_controller_.get());
939  aura::client::SetCursorClient(root_window, &cursor_manager_);
940  aura::client::SetTooltipClient(root_window, tooltip_controller_.get());
941  aura::client::SetEventClient(root_window, event_client_.get());
942
943  if (nested_dispatcher_controller_) {
944    aura::client::SetDispatcherClient(root_window,
945                                      nested_dispatcher_controller_.get());
946  }
947  if (user_action_client_)
948    aura::client::SetUserActionClient(root_window, user_action_client_.get());
949
950  controller->Init(first_run_after_boot);
951
952  mru_window_tracker_->OnRootWindowAdded(root_window);
953}
954
955////////////////////////////////////////////////////////////////////////////////
956// Shell, private:
957
958bool Shell::CanWindowReceiveEvents(aura::Window* window) {
959  RootWindowControllerList controllers = GetAllRootWindowControllers();
960  for (RootWindowControllerList::iterator iter = controllers.begin();
961       iter != controllers.end(); ++iter) {
962    internal::SystemModalContainerLayoutManager* layout_manager =
963        (*iter)->GetSystemModalLayoutManager(window);
964    if (layout_manager && layout_manager->CanWindowReceiveEvents(window))
965      return true;
966  }
967  return false;
968}
969
970////////////////////////////////////////////////////////////////////////////////
971// Shell, ui::EventTarget overrides:
972
973bool Shell::CanAcceptEvent(const ui::Event& event) {
974  return true;
975}
976
977ui::EventTarget* Shell::GetParentTarget() {
978  return NULL;
979}
980
981void Shell::OnEvent(ui::Event* event) {
982}
983
984////////////////////////////////////////////////////////////////////////////////
985// Shell, aura::client::ActivationChangeObserver implementation:
986
987void Shell::OnWindowActivated(aura::Window* gained_active,
988                              aura::Window* lost_active) {
989  if (gained_active)
990    target_root_window_ = gained_active->GetRootWindow();
991}
992
993}  // namespace ash
994