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