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