shell.cc revision ba5b9a6411cb1792fd21f0a078d7a25cd1ceec16
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/launcher_delegate.h"
27#include "ash/launcher/launcher_model.h"
28#include "ash/magnifier/magnification_controller.h"
29#include "ash/magnifier/partial_magnification_controller.h"
30#include "ash/root_window_controller.h"
31#include "ash/screen_ash.h"
32#include "ash/session_state_delegate.h"
33#include "ash/shelf/shelf_layout_manager.h"
34#include "ash/shelf/shelf_widget.h"
35#include "ash/shell_delegate.h"
36#include "ash/shell_factory.h"
37#include "ash/shell_window_ids.h"
38#include "ash/system/locale/locale_notification_controller.h"
39#include "ash/system/status_area_widget.h"
40#include "ash/system/tray/system_tray_delegate.h"
41#include "ash/system/tray/system_tray_notifier.h"
42#include "ash/wm/activation_controller.h"
43#include "ash/wm/app_list_controller.h"
44#include "ash/wm/ash_activation_controller.h"
45#include "ash/wm/ash_focus_rules.h"
46#include "ash/wm/ash_native_cursor_manager.h"
47#include "ash/wm/base_layout_manager.h"
48#include "ash/wm/capture_controller.h"
49#include "ash/wm/coordinate_conversion.h"
50#include "ash/wm/custom_frame_view_ash.h"
51#include "ash/wm/event_client_impl.h"
52#include "ash/wm/event_rewriter_event_filter.h"
53#include "ash/wm/lock_state_controller.h"
54#include "ash/wm/lock_state_controller_impl2.h"
55#include "ash/wm/mru_window_tracker.h"
56#include "ash/wm/overlay_event_filter.h"
57#include "ash/wm/power_button_controller.h"
58#include "ash/wm/property_util.h"
59#include "ash/wm/resize_shadow_controller.h"
60#include "ash/wm/root_window_layout_manager.h"
61#include "ash/wm/screen_dimmer.h"
62#include "ash/wm/session_state_controller_impl.h"
63#include "ash/wm/system_gesture_event_filter.h"
64#include "ash/wm/system_modal_container_event_filter.h"
65#include "ash/wm/system_modal_container_layout_manager.h"
66#include "ash/wm/user_activity_detector.h"
67#include "ash/wm/video_detector.h"
68#include "ash/wm/window_animations.h"
69#include "ash/wm/window_cycle_controller.h"
70#include "ash/wm/window_properties.h"
71#include "ash/wm/window_selector_controller.h"
72#include "ash/wm/window_util.h"
73#include "ash/wm/workspace_controller.h"
74#include "base/bind.h"
75#include "base/command_line.h"
76#include "base/debug/leak_annotations.h"
77#include "ui/aura/client/aura_constants.h"
78#include "ui/aura/client/user_action_client.h"
79#include "ui/aura/env.h"
80#include "ui/aura/focus_manager.h"
81#include "ui/aura/layout_manager.h"
82#include "ui/aura/root_window.h"
83#include "ui/aura/window.h"
84#include "ui/base/ui_base_switches.h"
85#include "ui/compositor/layer.h"
86#include "ui/compositor/layer_animator.h"
87#include "ui/gfx/display.h"
88#include "ui/gfx/image/image_skia.h"
89#include "ui/gfx/screen.h"
90#include "ui/gfx/size.h"
91#include "ui/keyboard/keyboard.h"
92#include "ui/keyboard/keyboard_util.h"
93#include "ui/message_center/message_center.h"
94#include "ui/views/corewm/compound_event_filter.h"
95#include "ui/views/corewm/corewm_switches.h"
96#include "ui/views/corewm/focus_controller.h"
97#include "ui/views/corewm/input_method_event_filter.h"
98#include "ui/views/corewm/shadow_controller.h"
99#include "ui/views/corewm/tooltip_controller.h"
100#include "ui/views/corewm/visibility_controller.h"
101#include "ui/views/corewm/window_modality_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
106#if !defined(OS_MACOSX)
107#include "ash/accelerators/accelerator_controller.h"
108#include "ash/accelerators/accelerator_filter.h"
109#include "ash/accelerators/nested_dispatcher_controller.h"
110#endif
111
112#if defined(OS_CHROMEOS)
113#if defined(USE_X11)
114#include "ash/ash_constants.h"
115#include "ash/display/display_change_observer_x11.h"
116#include "ash/display/display_error_observer.h"
117#include "ash/display/output_configurator_animation.h"
118#include "base/chromeos/chromeos_version.h"
119#include "base/message_loop/message_pump_aurax11.h"
120#include "chromeos/display/output_configurator.h"
121#include "content/public/browser/gpu_data_manager.h"
122#include "content/public/common/content_switches.h"
123#include "gpu/config/gpu_feature_type.h"
124#endif  // defined(USE_X11)
125#include "ash/system/chromeos/power/power_status.h"
126#endif  // defined(OS_CHROMEOS)
127
128namespace ash {
129
130namespace {
131
132using aura::Window;
133using views::Widget;
134
135// This dummy class is used for shell unit tests. We dont have chrome delegate
136// in these tests.
137class DummyUserWallpaperDelegate : public UserWallpaperDelegate {
138 public:
139  DummyUserWallpaperDelegate() {}
140
141  virtual ~DummyUserWallpaperDelegate() {}
142
143  virtual int GetAnimationType() OVERRIDE {
144    return views::corewm::WINDOW_VISIBILITY_ANIMATION_TYPE_FADE;
145  }
146
147  virtual bool ShouldShowInitialAnimation() OVERRIDE {
148    return false;
149  }
150
151  virtual void UpdateWallpaper() OVERRIDE {
152  }
153
154  virtual void InitializeWallpaper() OVERRIDE {
155    ash::Shell::GetInstance()->desktop_background_controller()->
156        CreateEmptyWallpaper();
157  }
158
159  virtual void OpenSetWallpaperPage() OVERRIDE {
160  }
161
162  virtual bool CanOpenSetWallpaperPage() OVERRIDE {
163    return false;
164  }
165
166  virtual void OnWallpaperAnimationFinished() OVERRIDE {
167  }
168
169  virtual void OnWallpaperBootAnimationFinished() OVERRIDE {
170  }
171
172 private:
173  DISALLOW_COPY_AND_ASSIGN(DummyUserWallpaperDelegate);
174};
175
176// A Corewm VisibilityController subclass that calls the Ash animation routine
177// so we can pick up our extended animations. See ash/wm/window_animations.h.
178class AshVisibilityController : public views::corewm::VisibilityController {
179 public:
180  AshVisibilityController() {}
181  virtual ~AshVisibilityController() {}
182
183 private:
184  // Overridden from views::corewm::VisibilityController:
185  virtual bool CallAnimateOnChildWindowVisibilityChanged(
186      aura::Window* window,
187      bool visible) OVERRIDE {
188    return AnimateOnChildWindowVisibilityChanged(window, visible);
189  }
190
191  DISALLOW_COPY_AND_ASSIGN(AshVisibilityController);
192};
193
194}  // namespace
195
196// static
197Shell* Shell::instance_ = NULL;
198// static
199bool Shell::initially_hide_cursor_ = false;
200
201////////////////////////////////////////////////////////////////////////////////
202// Shell, public:
203
204Shell::Shell(ShellDelegate* delegate)
205    : screen_(new ScreenAsh),
206      target_root_window_(NULL),
207      scoped_target_root_window_(NULL),
208      delegate_(delegate),
209      activation_client_(NULL),
210#if defined(OS_CHROMEOS) && defined(USE_X11)
211      output_configurator_(new chromeos::OutputConfigurator()),
212#endif  // defined(OS_CHROMEOS)
213      native_cursor_manager_(new AshNativeCursorManager),
214      cursor_manager_(scoped_ptr<views::corewm::NativeCursorManager>(
215          native_cursor_manager_)),
216      browser_context_(NULL),
217      simulate_modal_window_open_for_testing_(false),
218      is_touch_hud_projection_enabled_(false) {
219  DCHECK(delegate_.get());
220  display_manager_.reset(new internal::DisplayManager);
221
222  ANNOTATE_LEAKING_OBJECT_PTR(screen_);  // see crbug.com/156466
223  gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_ALTERNATE, screen_);
224  if (!gfx::Screen::GetScreenByType(gfx::SCREEN_TYPE_NATIVE))
225    gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, screen_);
226  display_controller_.reset(new DisplayController);
227#if defined(OS_CHROMEOS) && defined(USE_X11)
228  bool is_panel_fitting_disabled =
229      content::GpuDataManager::GetInstance()->IsFeatureBlacklisted(
230          gpu::GPU_FEATURE_TYPE_PANEL_FITTING) ||
231      CommandLine::ForCurrentProcess()->HasSwitch(
232          ::switches::kDisablePanelFitting);
233
234  output_configurator_->Init(!is_panel_fitting_disabled);
235
236  base::MessagePumpAuraX11::Current()->AddDispatcherForRootWindow(
237      output_configurator());
238  // We can't do this with a root window listener because XI_HierarchyChanged
239  // messages don't have a target window.
240  base::MessagePumpAuraX11::Current()->AddObserver(output_configurator());
241#endif  // defined(OS_CHROMEOS)
242  AddPreTargetHandler(this);
243
244#if defined(OS_CHROMEOS)
245  internal::PowerStatus::Initialize();
246#endif
247}
248
249Shell::~Shell() {
250  views::FocusManagerFactory::Install(NULL);
251
252  // Remove the focus from any window. This will prevent overhead and side
253  // effects (e.g. crashes) from changing focus during shutdown.
254  // See bug crbug.com/134502.
255  aura::client::GetFocusClient(GetPrimaryRootWindow())->FocusWindow(NULL);
256
257  // Please keep in same order as in Init() because it's easy to miss one.
258  RemovePreTargetHandler(event_rewriter_filter_.get());
259  RemovePreTargetHandler(user_activity_detector_.get());
260  RemovePreTargetHandler(overlay_filter_.get());
261  RemovePreTargetHandler(input_method_filter_.get());
262  RemovePreTargetHandler(window_modality_controller_.get());
263  if (mouse_cursor_filter_)
264    RemovePreTargetHandler(mouse_cursor_filter_.get());
265  RemovePreTargetHandler(system_gesture_filter_.get());
266  RemovePreTargetHandler(event_transformation_handler_.get());
267#if !defined(OS_MACOSX)
268  RemovePreTargetHandler(accelerator_filter_.get());
269#endif
270
271  // TooltipController is deleted with the Shell so removing its references.
272  RemovePreTargetHandler(tooltip_controller_.get());
273
274  // AppList needs to be released before shelf layout manager, which is
275  // destroyed with launcher container in the loop below. However, app list
276  // container is now on top of launcher container and released after it.
277  // TODO(xiyuan): Move it back when app list container is no longer needed.
278  app_list_controller_.reset();
279
280  // Destroy SystemTrayDelegate before destroying the status area(s).
281  system_tray_delegate_->Shutdown();
282  system_tray_delegate_.reset();
283
284  locale_notification_controller_.reset();
285
286  // Destroy all child windows including widgets.
287  display_controller_->CloseChildWindows();
288
289  // Destroy SystemTrayNotifier after destroying SystemTray as TrayItems
290  // needs to remove observers from it.
291  system_tray_notifier_.reset();
292
293  // These need a valid Shell instance to clean up properly, so explicitly
294  // delete them before invalidating the instance.
295  // Alphabetical. TODO(oshima): sort.
296  drag_drop_controller_.reset();
297  magnification_controller_.reset();
298  partial_magnification_controller_.reset();
299  resize_shadow_controller_.reset();
300  shadow_controller_.reset();
301  tooltip_controller_.reset();
302  event_client_.reset();
303  window_cycle_controller_.reset();
304  capture_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::DisplayChangeObserverX11);
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
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  capture_controller_.reset(new internal::CaptureController);
550
551  // The keyboard system must be initialized before the RootWindowController is
552  // created.
553  if (keyboard::IsKeyboardEnabled())
554    keyboard::InitializeKeyboard();
555
556  if (command_line->HasSwitch(ash::switches::kAshDisableNewLockAnimations))
557    lock_state_controller_.reset(new SessionStateControllerImpl);
558  else
559    lock_state_controller_.reset(new LockStateControllerImpl2);
560  power_button_controller_.reset(new PowerButtonController(
561      lock_state_controller_.get()));
562  AddShellObserver(lock_state_controller_.get());
563
564  drag_drop_controller_.reset(new internal::DragDropController);
565  mouse_cursor_filter_.reset(new internal::MouseCursorEventFilter());
566  PrependPreTargetHandler(mouse_cursor_filter_.get());
567
568  // Create Controllers that may need root window.
569  // TODO(oshima): Move as many controllers before creating
570  // RootWindowController as possible.
571  visibility_controller_.reset(new AshVisibilityController);
572  user_action_client_.reset(delegate_->CreateUserActionClient());
573  window_modality_controller_.reset(
574      new views::corewm::WindowModalityController);
575  AddPreTargetHandler(window_modality_controller_.get());
576
577  magnification_controller_.reset(
578      MagnificationController::CreateInstance());
579  mru_window_tracker_.reset(new MruWindowTracker(activation_client_));
580
581  partial_magnification_controller_.reset(
582      new PartialMagnificationController());
583
584  high_contrast_controller_.reset(new HighContrastController);
585  video_detector_.reset(new VideoDetector);
586  window_cycle_controller_.reset(new WindowCycleController());
587  window_selector_controller_.reset(new WindowSelectorController());
588
589  tooltip_controller_.reset(new views::corewm::TooltipController(
590                                gfx::SCREEN_TYPE_ALTERNATE));
591  AddPreTargetHandler(tooltip_controller_.get());
592
593  event_client_.reset(new internal::EventClientImpl);
594
595  // This controller needs to be set before SetupManagedWindowMode.
596  desktop_background_controller_.reset(new DesktopBackgroundController());
597  user_wallpaper_delegate_.reset(delegate_->CreateUserWallpaperDelegate());
598  if (!user_wallpaper_delegate_)
599    user_wallpaper_delegate_.reset(new DummyUserWallpaperDelegate());
600
601  // StatusAreaWidget uses Shell's CapsLockDelegate.
602  caps_lock_delegate_.reset(delegate_->CreateCapsLockDelegate());
603
604  session_state_delegate_.reset(delegate_->CreateSessionStateDelegate());
605
606  if (!command_line->HasSwitch(views::corewm::switches::kNoDropShadows)) {
607    resize_shadow_controller_.reset(new internal::ResizeShadowController());
608    shadow_controller_.reset(
609        new views::corewm::ShadowController(activation_client_));
610  }
611
612  // Create system_tray_notifier_ before the delegate.
613  system_tray_notifier_.reset(new ash::SystemTrayNotifier());
614
615  // Initialize system_tray_delegate_ before initializing StatusAreaWidget.
616  system_tray_delegate_.reset(delegate()->CreateSystemTrayDelegate());
617  if (!system_tray_delegate_)
618    system_tray_delegate_.reset(SystemTrayDelegate::CreateDummyDelegate());
619
620  internal::RootWindowController* root_window_controller =
621      new internal::RootWindowController(root_window);
622  InitRootWindowController(root_window_controller,
623                           delegate_->IsFirstRunAfterBoot());
624
625  locale_notification_controller_.reset(
626      new internal::LocaleNotificationController);
627
628  // Initialize system_tray_delegate_ after StatusAreaWidget is created.
629  system_tray_delegate_->Initialize();
630
631  display_controller_->InitSecondaryDisplays();
632
633  // Force Layout
634  root_window_controller->root_window_layout()->OnWindowResized();
635
636  // It needs to be created after OnWindowResized has been called, otherwise the
637  // widget will not paint when restoring after a browser crash.  Also it needs
638  // to be created after InitSecondaryDisplays() to initialize the wallpapers in
639  // the correct size.
640  user_wallpaper_delegate_->InitializeWallpaper();
641
642  if (initially_hide_cursor_)
643    cursor_manager_.HideCursor();
644  cursor_manager_.SetCursor(ui::kCursorPointer);
645
646  if (!cursor_manager_.IsCursorVisible()) {
647    // Cursor might have been hidden by something other than chrome.
648    // Let the first mouse event show the cursor.
649    env_filter_->set_cursor_hidden_by_filter(true);
650  }
651}
652
653void Shell::ShowContextMenu(const gfx::Point& location_in_screen,
654                            ui::MenuSourceType source_type) {
655  // No context menus if there is no session with an active user.
656  if (!session_state_delegate_->NumberOfLoggedInUsers())
657    return;
658  // No context menus when screen is locked.
659  if (session_state_delegate_->IsScreenLocked())
660    return;
661
662  aura::RootWindow* root =
663      wm::GetRootWindowMatching(gfx::Rect(location_in_screen, gfx::Size()));
664  // TODO(oshima): The root and root window controller shouldn't be
665  // NULL even for the out-of-bounds |location_in_screen| (It should
666  // return the primary root). Investigate why/how this is
667  // happening. crbug.com/165214.
668  internal::RootWindowController* rwc = GetRootWindowController(root);
669  CHECK(rwc) << "root=" << root
670             << ", location:" << location_in_screen.ToString();
671  if (rwc)
672    rwc->ShowContextMenu(location_in_screen, source_type);
673}
674
675void Shell::ToggleAppList(aura::Window* window) {
676  // If the context window is not given, show it on the active root window.
677  if (!window)
678    window = GetActiveRootWindow();
679  if (!app_list_controller_)
680    app_list_controller_.reset(new internal::AppListController);
681  app_list_controller_->SetVisible(!app_list_controller_->IsVisible(), window);
682}
683
684bool Shell::GetAppListTargetVisibility() const {
685  return app_list_controller_.get() &&
686      app_list_controller_->GetTargetVisibility();
687}
688
689aura::Window* Shell::GetAppListWindow() {
690  return app_list_controller_.get() ? app_list_controller_->GetWindow() : NULL;
691}
692
693bool Shell::IsSystemModalWindowOpen() const {
694  if (simulate_modal_window_open_for_testing_)
695    return true;
696  const std::vector<aura::Window*> containers = GetContainersFromAllRootWindows(
697      internal::kShellWindowId_SystemModalContainer, NULL);
698  for (std::vector<aura::Window*>::const_iterator cit = containers.begin();
699       cit != containers.end(); ++cit) {
700    for (aura::Window::Windows::const_iterator wit = (*cit)->children().begin();
701         wit != (*cit)->children().end(); ++wit) {
702      if ((*wit)->GetProperty(aura::client::kModalKey) ==
703          ui::MODAL_TYPE_SYSTEM && (*wit)->TargetVisibility()) {
704        return true;
705      }
706    }
707  }
708  return false;
709}
710
711views::NonClientFrameView* Shell::CreateDefaultNonClientFrameView(
712    views::Widget* widget) {
713  // Use translucent-style window frames for dialogs.
714  CustomFrameViewAsh* frame_view = new CustomFrameViewAsh;
715  frame_view->Init(widget);
716  return frame_view;
717}
718
719void Shell::RotateFocus(Direction direction) {
720  focus_cycler_->RotateFocus(
721      direction == FORWARD ? internal::FocusCycler::FORWARD :
722                             internal::FocusCycler::BACKWARD);
723}
724
725void Shell::SetDisplayWorkAreaInsets(Window* contains,
726                                     const gfx::Insets& insets) {
727  if (!display_controller_->UpdateWorkAreaOfDisplayNearestWindow(
728          contains, insets)) {
729    return;
730  }
731  FOR_EACH_OBSERVER(ShellObserver, observers_,
732                    OnDisplayWorkAreaInsetsChanged());
733}
734
735void Shell::OnLoginStateChanged(user::LoginStatus status) {
736  FOR_EACH_OBSERVER(ShellObserver, observers_, OnLoginStateChanged(status));
737}
738
739void Shell::UpdateAfterLoginStatusChange(user::LoginStatus status) {
740  RootWindowControllerList controllers = GetAllRootWindowControllers();
741  for (RootWindowControllerList::iterator iter = controllers.begin();
742       iter != controllers.end(); ++iter)
743    (*iter)->UpdateAfterLoginStatusChange(status);
744}
745
746void Shell::OnAppTerminating() {
747  FOR_EACH_OBSERVER(ShellObserver, observers_, OnAppTerminating());
748}
749
750void Shell::OnLockStateChanged(bool locked) {
751  FOR_EACH_OBSERVER(ShellObserver, observers_, OnLockStateChanged(locked));
752#ifndef NDEBUG
753  // Make sure that there is no system modal in Lock layer when unlocked.
754  if (!locked) {
755    std::vector<aura::Window*> containers = GetContainersFromAllRootWindows(
756        internal::kShellWindowId_LockSystemModalContainer,
757        GetPrimaryRootWindow());
758    for (std::vector<aura::Window*>::const_iterator iter = containers.begin();
759         iter != containers.end(); ++iter) {
760      DCHECK_EQ(0u, (*iter)->children().size());
761    }
762  }
763#endif
764}
765
766void Shell::CreateLauncher() {
767  RootWindowControllerList controllers = GetAllRootWindowControllers();
768  for (RootWindowControllerList::iterator iter = controllers.begin();
769       iter != controllers.end(); ++iter)
770    (*iter)->shelf()->CreateLauncher();
771}
772
773void Shell::ShowLauncher() {
774  RootWindowControllerList controllers = GetAllRootWindowControllers();
775  for (RootWindowControllerList::iterator iter = controllers.begin();
776       iter != controllers.end(); ++iter)
777    (*iter)->ShowLauncher();
778}
779
780void Shell::AddShellObserver(ShellObserver* observer) {
781  observers_.AddObserver(observer);
782}
783
784void Shell::RemoveShellObserver(ShellObserver* observer) {
785  observers_.RemoveObserver(observer);
786}
787
788void Shell::UpdateShelfVisibility() {
789  RootWindowControllerList controllers = GetAllRootWindowControllers();
790  for (RootWindowControllerList::iterator iter = controllers.begin();
791       iter != controllers.end(); ++iter)
792    if ((*iter)->shelf())
793      (*iter)->UpdateShelfVisibility();
794}
795
796void Shell::SetShelfAutoHideBehavior(ShelfAutoHideBehavior behavior,
797                                     aura::RootWindow* root_window) {
798  ash::internal::ShelfLayoutManager::ForLauncher(root_window)->
799      SetAutoHideBehavior(behavior);
800}
801
802ShelfAutoHideBehavior Shell::GetShelfAutoHideBehavior(
803    aura::RootWindow* root_window) const {
804  return ash::internal::ShelfLayoutManager::ForLauncher(root_window)->
805      auto_hide_behavior();
806}
807
808void Shell::SetShelfAlignment(ShelfAlignment alignment,
809                              aura::RootWindow* root_window) {
810  if (ash::internal::ShelfLayoutManager::ForLauncher(root_window)->
811      SetAlignment(alignment)) {
812    FOR_EACH_OBSERVER(
813        ShellObserver, observers_, OnShelfAlignmentChanged(root_window));
814  }
815}
816
817ShelfAlignment Shell::GetShelfAlignment(aura::RootWindow* root_window) {
818  return GetRootWindowController(root_window)->
819      GetShelfLayoutManager()->GetAlignment();
820}
821
822void Shell::SetDimming(bool should_dim) {
823  RootWindowControllerList controllers = GetAllRootWindowControllers();
824  for (RootWindowControllerList::iterator iter = controllers.begin();
825       iter != controllers.end(); ++iter)
826    (*iter)->screen_dimmer()->SetDimming(should_dim);
827}
828
829void Shell::CreateModalBackground(aura::Window* window) {
830  if (!modality_filter_) {
831    modality_filter_.reset(new internal::SystemModalContainerEventFilter(this));
832    AddPreTargetHandler(modality_filter_.get());
833  }
834  RootWindowControllerList controllers = GetAllRootWindowControllers();
835  for (RootWindowControllerList::iterator iter = controllers.begin();
836       iter != controllers.end(); ++iter)
837    (*iter)->GetSystemModalLayoutManager(window)->CreateModalBackground();
838}
839
840void Shell::OnModalWindowRemoved(aura::Window* removed) {
841  RootWindowControllerList controllers = GetAllRootWindowControllers();
842  bool activated = false;
843  for (RootWindowControllerList::iterator iter = controllers.begin();
844       iter != controllers.end() && !activated; ++iter) {
845    activated = (*iter)->GetSystemModalLayoutManager(removed)->
846        ActivateNextModalWindow();
847  }
848  if (!activated) {
849    RemovePreTargetHandler(modality_filter_.get());
850    modality_filter_.reset();
851    for (RootWindowControllerList::iterator iter = controllers.begin();
852         iter != controllers.end(); ++iter)
853      (*iter)->GetSystemModalLayoutManager(removed)->DestroyModalBackground();
854  }
855}
856
857WebNotificationTray* Shell::GetWebNotificationTray() {
858  return GetPrimaryRootWindowController()->shelf()->
859      status_area_widget()->web_notification_tray();
860}
861
862bool Shell::HasPrimaryStatusArea() {
863  ShelfWidget* shelf = GetPrimaryRootWindowController()->shelf();
864  return shelf && shelf->status_area_widget();
865}
866
867SystemTray* Shell::GetPrimarySystemTray() {
868  return GetPrimaryRootWindowController()->GetSystemTray();
869}
870
871LauncherDelegate* Shell::GetLauncherDelegate() {
872  if (!launcher_delegate_) {
873    launcher_model_.reset(new LauncherModel);
874    launcher_delegate_.reset(
875        delegate_->CreateLauncherDelegate(launcher_model_.get()));
876  }
877  return launcher_delegate_.get();
878}
879
880void Shell::SetTouchHudProjectionEnabled(bool enabled) {
881  if (is_touch_hud_projection_enabled_ == enabled)
882    return;
883
884  is_touch_hud_projection_enabled_ = enabled;
885  FOR_EACH_OBSERVER(ShellObserver, observers_,
886                    OnTouchHudProjectionToggled(enabled));
887}
888
889void Shell::InitRootWindowForSecondaryDisplay(aura::RootWindow* root) {
890  internal::RootWindowController* controller =
891      new internal::RootWindowController(root);
892  // Pass false for the |is_first_run_after_boot| parameter so we'll show a
893  // black background on this display instead of trying to mimic the boot splash
894  // screen.
895  InitRootWindowController(controller, false);
896
897  controller->root_window_layout()->OnWindowResized();
898  desktop_background_controller_->OnRootWindowAdded(root);
899  high_contrast_controller_->OnRootWindowAdded(root);
900  root->ShowRootWindow();
901  // Activate new root for testing.
902  // TODO(oshima): remove this.
903  target_root_window_ = root;
904
905  // Create a launcher if a user is already logged.
906  if (Shell::GetInstance()->session_state_delegate()->NumberOfLoggedInUsers())
907    controller->shelf()->CreateLauncher();
908}
909
910void Shell::DoInitialWorkspaceAnimation() {
911  return GetPrimaryRootWindowController()->workspace_controller()->
912      DoInitialAnimation();
913}
914
915void Shell::InitRootWindowController(
916    internal::RootWindowController* controller,
917    bool first_run_after_boot) {
918
919  aura::RootWindow* root_window = controller->root_window();
920  DCHECK(activation_client_);
921  DCHECK(visibility_controller_.get());
922  DCHECK(drag_drop_controller_.get());
923  DCHECK(capture_controller_.get());
924  DCHECK(window_cycle_controller_.get());
925
926  aura::client::SetFocusClient(root_window, focus_client_.get());
927  input_method_filter_->SetInputMethodPropertyInRootWindow(root_window);
928  aura::client::SetActivationClient(root_window, activation_client_);
929  if (views::corewm::UseFocusController()) {
930    views::corewm::FocusController* controller =
931        static_cast<views::corewm::FocusController*>(activation_client_);
932    root_window->AddPreTargetHandler(controller);
933  }
934  aura::client::SetVisibilityClient(root_window, visibility_controller_.get());
935  aura::client::SetDragDropClient(root_window, drag_drop_controller_.get());
936  aura::client::SetCaptureClient(root_window, capture_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