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