00f6137716b4ef4f51e6609526705dd9e80387a8
[platform/framework/web/crosswalk.git] / src / ash / shell.cc
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/accelerator_controller.h"
11 #include "ash/accelerators/accelerator_filter.h"
12 #include "ash/accelerators/focus_manager_factory.h"
13 #include "ash/accelerators/nested_dispatcher_controller.h"
14 #include "ash/accelerometer/accelerometer_controller.h"
15 #include "ash/ash_switches.h"
16 #include "ash/autoclick/autoclick_controller.h"
17 #include "ash/desktop_background/desktop_background_controller.h"
18 #include "ash/desktop_background/desktop_background_view.h"
19 #include "ash/desktop_background/user_wallpaper_delegate.h"
20 #include "ash/display/cursor_window_controller.h"
21 #include "ash/display/display_controller.h"
22 #include "ash/display/display_manager.h"
23 #include "ash/display/event_transformation_handler.h"
24 #include "ash/display/mouse_cursor_event_filter.h"
25 #include "ash/display/screen_position_controller.h"
26 #include "ash/display/virtual_keyboard_window_controller.h"
27 #include "ash/drag_drop/drag_drop_controller.h"
28 #include "ash/first_run/first_run_helper_impl.h"
29 #include "ash/focus_cycler.h"
30 #include "ash/frame/custom_frame_view_ash.h"
31 #include "ash/gpu_support.h"
32 #include "ash/high_contrast/high_contrast_controller.h"
33 #include "ash/host/window_tree_host_factory.h"
34 #include "ash/keyboard_uma_event_filter.h"
35 #include "ash/magnifier/magnification_controller.h"
36 #include "ash/magnifier/partial_magnification_controller.h"
37 #include "ash/media_delegate.h"
38 #include "ash/new_window_delegate.h"
39 #include "ash/root_window_controller.h"
40 #include "ash/session_state_delegate.h"
41 #include "ash/shelf/app_list_shelf_item_delegate.h"
42 #include "ash/shelf/shelf_delegate.h"
43 #include "ash/shelf/shelf_item_delegate.h"
44 #include "ash/shelf/shelf_item_delegate_manager.h"
45 #include "ash/shelf/shelf_layout_manager.h"
46 #include "ash/shelf/shelf_model.h"
47 #include "ash/shelf/shelf_widget.h"
48 #include "ash/shelf/shelf_window_watcher.h"
49 #include "ash/shell_delegate.h"
50 #include "ash/shell_factory.h"
51 #include "ash/shell_window_ids.h"
52 #include "ash/system/locale/locale_notification_controller.h"
53 #include "ash/system/status_area_widget.h"
54 #include "ash/system/tray/system_tray_delegate.h"
55 #include "ash/system/tray/system_tray_notifier.h"
56 #include "ash/wm/app_list_controller.h"
57 #include "ash/wm/ash_focus_rules.h"
58 #include "ash/wm/ash_native_cursor_manager.h"
59 #include "ash/wm/coordinate_conversion.h"
60 #include "ash/wm/event_client_impl.h"
61 #include "ash/wm/lock_state_controller.h"
62 #include "ash/wm/maximize_mode/maximize_mode_controller.h"
63 #include "ash/wm/maximize_mode/maximize_mode_window_manager.h"
64 #include "ash/wm/mru_window_tracker.h"
65 #include "ash/wm/overlay_event_filter.h"
66 #include "ash/wm/overview/window_selector_controller.h"
67 #include "ash/wm/power_button_controller.h"
68 #include "ash/wm/resize_shadow_controller.h"
69 #include "ash/wm/root_window_layout_manager.h"
70 #include "ash/wm/screen_dimmer.h"
71 #include "ash/wm/system_gesture_event_filter.h"
72 #include "ash/wm/system_modal_container_event_filter.h"
73 #include "ash/wm/system_modal_container_layout_manager.h"
74 #include "ash/wm/toplevel_window_event_handler.h"
75 #include "ash/wm/user_activity_detector.h"
76 #include "ash/wm/video_detector.h"
77 #include "ash/wm/window_animations.h"
78 #include "ash/wm/window_positioner.h"
79 #include "ash/wm/window_properties.h"
80 #include "ash/wm/window_util.h"
81 #include "ash/wm/workspace_controller.h"
82 #include "base/bind.h"
83 #include "base/debug/trace_event.h"
84 #include "ui/aura/client/aura_constants.h"
85 #include "ui/aura/env.h"
86 #include "ui/aura/layout_manager.h"
87 #include "ui/aura/window.h"
88 #include "ui/aura/window_event_dispatcher.h"
89 #include "ui/base/ui_base_switches.h"
90 #include "ui/compositor/layer.h"
91 #include "ui/compositor/layer_animator.h"
92 #include "ui/events/event_target_iterator.h"
93 #include "ui/gfx/display.h"
94 #include "ui/gfx/image/image_skia.h"
95 #include "ui/gfx/screen.h"
96 #include "ui/gfx/size.h"
97 #include "ui/keyboard/keyboard.h"
98 #include "ui/keyboard/keyboard_controller.h"
99 #include "ui/keyboard/keyboard_switches.h"
100 #include "ui/keyboard/keyboard_util.h"
101 #include "ui/message_center/message_center.h"
102 #include "ui/views/corewm/tooltip_aura.h"
103 #include "ui/views/corewm/tooltip_controller.h"
104 #include "ui/views/focus/focus_manager_factory.h"
105 #include "ui/views/widget/native_widget_aura.h"
106 #include "ui/views/widget/widget.h"
107 #include "ui/wm/core/compound_event_filter.h"
108 #include "ui/wm/core/focus_controller.h"
109 #include "ui/wm/core/input_method_event_filter.h"
110 #include "ui/wm/core/shadow_controller.h"
111 #include "ui/wm/core/visibility_controller.h"
112 #include "ui/wm/core/window_modality_controller.h"
113
114 #if defined(OS_CHROMEOS)
115 #if defined(USE_X11)
116 #include "ash/accelerators/magnifier_key_scroller.h"
117 #include "ash/accelerators/spoken_feedback_toggler.h"
118 #include "ash/ash_constants.h"
119 #include "ash/display/display_change_observer_chromeos.h"
120 #include "ash/display/display_error_observer_chromeos.h"
121 #include "ash/display/output_configurator_animation.h"
122 #include "ash/display/projecting_observer_chromeos.h"
123 #include "ash/system/chromeos/session/last_window_closed_logout_reminder.h"
124 #include "base/message_loop/message_pump_x11.h"
125 #include "base/sys_info.h"
126 #include "ui/display/chromeos/output_configurator.h"
127 #endif  // defined(USE_X11)
128 #include "ash/display/resolution_notification_controller.h"
129 #include "ash/sticky_keys/sticky_keys_controller.h"
130 #include "ash/system/chromeos/bluetooth/bluetooth_notification_controller.h"
131 #include "ash/system/chromeos/brightness/brightness_controller_chromeos.h"
132 #include "ash/system/chromeos/power/power_event_observer.h"
133 #include "ash/system/chromeos/power/power_status.h"
134 #include "ash/system/chromeos/power/user_activity_notifier.h"
135 #include "ash/system/chromeos/power/video_activity_notifier.h"
136 #include "ash/system/chromeos/session/logout_confirmation_controller.h"
137 #include "base/bind_helpers.h"
138 #endif  // defined(OS_CHROMEOS)
139
140 namespace ash {
141
142 namespace {
143
144 using aura::Window;
145 using views::Widget;
146
147 // A Corewm VisibilityController subclass that calls the Ash animation routine
148 // so we can pick up our extended animations. See ash/wm/window_animations.h.
149 class AshVisibilityController : public ::wm::VisibilityController {
150  public:
151   AshVisibilityController() {}
152   virtual ~AshVisibilityController() {}
153
154  private:
155   // Overridden from ::wm::VisibilityController:
156   virtual bool CallAnimateOnChildWindowVisibilityChanged(
157       aura::Window* window,
158       bool visible) OVERRIDE {
159     return AnimateOnChildWindowVisibilityChanged(window, visible);
160   }
161
162   DISALLOW_COPY_AND_ASSIGN(AshVisibilityController);
163 };
164
165 }  // namespace
166
167 // static
168 Shell* Shell::instance_ = NULL;
169 // static
170 bool Shell::initially_hide_cursor_ = false;
171
172 ////////////////////////////////////////////////////////////////////////////////
173 // Shell, public:
174
175 // static
176 Shell* Shell::CreateInstance(ShellDelegate* delegate) {
177   CHECK(!instance_);
178   instance_ = new Shell(delegate);
179   instance_->Init();
180   return instance_;
181 }
182
183 // static
184 Shell* Shell::GetInstance() {
185   DCHECK(instance_);
186   return instance_;
187 }
188
189 // static
190 bool Shell::HasInstance() {
191   return !!instance_;
192 }
193
194 // static
195 void Shell::DeleteInstance() {
196   delete instance_;
197   instance_ = NULL;
198 }
199
200 // static
201 internal::RootWindowController* Shell::GetPrimaryRootWindowController() {
202   return internal::GetRootWindowController(GetPrimaryRootWindow());
203 }
204
205 // static
206 Shell::RootWindowControllerList Shell::GetAllRootWindowControllers() {
207   return Shell::GetInstance()->display_controller()->
208       GetAllRootWindowControllers();
209 }
210
211 // static
212 aura::Window* Shell::GetPrimaryRootWindow() {
213   return GetInstance()->display_controller()->GetPrimaryRootWindow();
214 }
215
216 // static
217 aura::Window* Shell::GetTargetRootWindow() {
218   Shell* shell = GetInstance();
219   if (shell->scoped_target_root_window_)
220     return shell->scoped_target_root_window_;
221   return shell->target_root_window_;
222 }
223
224 // static
225 gfx::Screen* Shell::GetScreen() {
226   return gfx::Screen::GetScreenByType(gfx::SCREEN_TYPE_ALTERNATE);
227 }
228
229 // static
230 aura::Window::Windows Shell::GetAllRootWindows() {
231   return Shell::GetInstance()->display_controller()->
232       GetAllRootWindows();
233 }
234
235 // static
236 aura::Window* Shell::GetContainer(aura::Window* root_window,
237                                   int container_id) {
238   return root_window->GetChildById(container_id);
239 }
240
241 // static
242 const aura::Window* Shell::GetContainer(const aura::Window* root_window,
243                                         int container_id) {
244   return root_window->GetChildById(container_id);
245 }
246
247 // static
248 std::vector<aura::Window*> Shell::GetContainersFromAllRootWindows(
249     int container_id,
250     aura::Window* priority_root) {
251   std::vector<aura::Window*> containers;
252   aura::Window::Windows root_windows = GetAllRootWindows();
253   for (aura::Window::Windows::const_iterator it = root_windows.begin();
254        it != root_windows.end(); ++it) {
255     aura::Window* container = (*it)->GetChildById(container_id);
256     if (container) {
257       if (priority_root && priority_root->Contains(container))
258         containers.insert(containers.begin(), container);
259       else
260         containers.push_back(container);
261     }
262   }
263   return containers;
264 }
265
266 void Shell::ShowContextMenu(const gfx::Point& location_in_screen,
267                             ui::MenuSourceType source_type) {
268   // No context menus if there is no session with an active user.
269   if (!session_state_delegate_->NumberOfLoggedInUsers())
270     return;
271   // No context menus when screen is locked.
272   if (session_state_delegate_->IsScreenLocked())
273     return;
274
275   aura::Window* root =
276       wm::GetRootWindowMatching(gfx::Rect(location_in_screen, gfx::Size()));
277   internal::GetRootWindowController(root)->
278       ShowContextMenu(location_in_screen, source_type);
279 }
280
281 void Shell::ToggleAppList(aura::Window* window) {
282   // If the context window is not given, show it on the target root window.
283   if (!window)
284     window = GetTargetRootWindow();
285   if (!app_list_controller_)
286     app_list_controller_.reset(new internal::AppListController);
287   app_list_controller_->SetVisible(!app_list_controller_->IsVisible(), window);
288 }
289
290 bool Shell::GetAppListTargetVisibility() const {
291   return app_list_controller_.get() &&
292       app_list_controller_->GetTargetVisibility();
293 }
294
295 aura::Window* Shell::GetAppListWindow() {
296   return app_list_controller_.get() ? app_list_controller_->GetWindow() : NULL;
297 }
298
299 app_list::AppListView* Shell::GetAppListView() {
300   return app_list_controller_.get() ? app_list_controller_->GetView() : NULL;
301 }
302
303 bool Shell::IsSystemModalWindowOpen() const {
304   if (simulate_modal_window_open_for_testing_)
305     return true;
306   const std::vector<aura::Window*> containers = GetContainersFromAllRootWindows(
307       internal::kShellWindowId_SystemModalContainer, NULL);
308   for (std::vector<aura::Window*>::const_iterator cit = containers.begin();
309        cit != containers.end(); ++cit) {
310     for (aura::Window::Windows::const_iterator wit = (*cit)->children().begin();
311          wit != (*cit)->children().end(); ++wit) {
312       if ((*wit)->GetProperty(aura::client::kModalKey) ==
313           ui::MODAL_TYPE_SYSTEM && (*wit)->TargetVisibility()) {
314         return true;
315       }
316     }
317   }
318   return false;
319 }
320
321 views::NonClientFrameView* Shell::CreateDefaultNonClientFrameView(
322     views::Widget* widget) {
323   // Use translucent-style window frames for dialogs.
324   return new CustomFrameViewAsh(widget);
325 }
326
327 void Shell::RotateFocus(Direction direction) {
328   focus_cycler_->RotateFocus(
329       direction == FORWARD ? internal::FocusCycler::FORWARD :
330                              internal::FocusCycler::BACKWARD);
331 }
332
333 void Shell::SetDisplayWorkAreaInsets(Window* contains,
334                                      const gfx::Insets& insets) {
335   if (!display_controller_->UpdateWorkAreaOfDisplayNearestWindow(
336           contains, insets)) {
337     return;
338   }
339   FOR_EACH_OBSERVER(ShellObserver, observers_,
340                     OnDisplayWorkAreaInsetsChanged());
341 }
342
343 void Shell::OnLoginStateChanged(user::LoginStatus status) {
344   FOR_EACH_OBSERVER(ShellObserver, observers_, OnLoginStateChanged(status));
345 }
346
347 void Shell::OnLoginUserProfilePrepared() {
348   CreateShelf();
349   CreateKeyboard();
350 }
351
352 void Shell::UpdateAfterLoginStatusChange(user::LoginStatus status) {
353   RootWindowControllerList controllers = GetAllRootWindowControllers();
354   for (RootWindowControllerList::iterator iter = controllers.begin();
355        iter != controllers.end(); ++iter)
356     (*iter)->UpdateAfterLoginStatusChange(status);
357 }
358
359 void Shell::OnAppTerminating() {
360   FOR_EACH_OBSERVER(ShellObserver, observers_, OnAppTerminating());
361 }
362
363 void Shell::OnLockStateChanged(bool locked) {
364   FOR_EACH_OBSERVER(ShellObserver, observers_, OnLockStateChanged(locked));
365 #ifndef NDEBUG
366   // Make sure that there is no system modal in Lock layer when unlocked.
367   if (!locked) {
368     std::vector<aura::Window*> containers = GetContainersFromAllRootWindows(
369         internal::kShellWindowId_LockSystemModalContainer,
370         GetPrimaryRootWindow());
371     for (std::vector<aura::Window*>::const_iterator iter = containers.begin();
372          iter != containers.end(); ++iter) {
373       DCHECK_EQ(0u, (*iter)->children().size());
374     }
375   }
376 #endif
377 }
378
379 void Shell::OnCastingSessionStartedOrStopped(bool started) {
380 #if defined(OS_CHROMEOS) && defined(USE_X11)
381   if (projecting_observer_)
382     projecting_observer_->OnCastingSessionStartedOrStopped(started);
383 #endif
384 }
385
386 void Shell::OnOverviewModeStarting() {
387   FOR_EACH_OBSERVER(ShellObserver, observers_, OnOverviewModeStarting());
388 }
389
390 void Shell::OnOverviewModeEnding() {
391   FOR_EACH_OBSERVER(ShellObserver, observers_, OnOverviewModeEnding());
392 }
393
394 void Shell::OnMaximizeModeStarted() {
395   FOR_EACH_OBSERVER(ShellObserver, observers_, OnMaximizeModeStarted());
396 }
397
398 void Shell::OnMaximizeModeEnded() {
399   FOR_EACH_OBSERVER(ShellObserver, observers_, OnMaximizeModeEnded());
400 }
401
402 void Shell::CreateShelf() {
403   RootWindowControllerList controllers = GetAllRootWindowControllers();
404   for (RootWindowControllerList::iterator iter = controllers.begin();
405        iter != controllers.end(); ++iter)
406     (*iter)->shelf()->CreateShelf();
407 }
408
409 void Shell::CreateKeyboard() {
410   // TODO(bshe): Primary root window controller may not be the controller to
411   // attach virtual keyboard. See http://crbug.com/303429
412   InitKeyboard();
413   if (keyboard::IsKeyboardUsabilityExperimentEnabled()) {
414     display_controller()->virtual_keyboard_window_controller()->
415         ActivateKeyboard(keyboard_controller_.get());
416   } else {
417     GetPrimaryRootWindowController()->
418         ActivateKeyboard(keyboard_controller_.get());
419   }
420 }
421
422 void Shell::DeactivateKeyboard() {
423   if (keyboard_controller_.get()) {
424     RootWindowControllerList controllers = GetAllRootWindowControllers();
425     for (RootWindowControllerList::iterator iter = controllers.begin();
426         iter != controllers.end(); ++iter) {
427       (*iter)->DeactivateKeyboard(keyboard_controller_.get());
428     }
429   }
430   keyboard_controller_.reset();
431 }
432
433 void Shell::ShowShelf() {
434   RootWindowControllerList controllers = GetAllRootWindowControllers();
435   for (RootWindowControllerList::iterator iter = controllers.begin();
436        iter != controllers.end(); ++iter)
437     (*iter)->ShowShelf();
438 }
439
440 void Shell::AddShellObserver(ShellObserver* observer) {
441   observers_.AddObserver(observer);
442 }
443
444 void Shell::RemoveShellObserver(ShellObserver* observer) {
445   observers_.RemoveObserver(observer);
446 }
447
448 void Shell::EnableMaximizeModeWindowManager(bool enable) {
449   if (enable && !maximize_mode_window_manager_.get()) {
450     maximize_mode_window_manager_.reset(
451         new internal::MaximizeModeWindowManager());
452   } else if (!enable && maximize_mode_window_manager_.get()) {
453     maximize_mode_window_manager_.reset();
454   }
455 }
456
457 bool Shell::IsMaximizeModeWindowManagerEnabled() {
458   return maximize_mode_window_manager_.get() != NULL;
459 }
460
461 void Shell::UpdateShelfVisibility() {
462   RootWindowControllerList controllers = GetAllRootWindowControllers();
463   for (RootWindowControllerList::iterator iter = controllers.begin();
464        iter != controllers.end(); ++iter)
465     if ((*iter)->shelf())
466       (*iter)->UpdateShelfVisibility();
467 }
468
469 void Shell::SetShelfAutoHideBehavior(ShelfAutoHideBehavior behavior,
470                                      aura::Window* root_window) {
471   ash::internal::ShelfLayoutManager::ForShelf(root_window)->
472       SetAutoHideBehavior(behavior);
473 }
474
475 ShelfAutoHideBehavior Shell::GetShelfAutoHideBehavior(
476     aura::Window* root_window) const {
477   return ash::internal::ShelfLayoutManager::ForShelf(root_window)->
478       auto_hide_behavior();
479 }
480
481 void Shell::SetShelfAlignment(ShelfAlignment alignment,
482                               aura::Window* root_window) {
483   if (ash::internal::ShelfLayoutManager::ForShelf(root_window)->
484       SetAlignment(alignment)) {
485     FOR_EACH_OBSERVER(
486         ShellObserver, observers_, OnShelfAlignmentChanged(root_window));
487   }
488 }
489
490 ShelfAlignment Shell::GetShelfAlignment(aura::Window* root_window) {
491   return internal::GetRootWindowController(root_window)->
492       GetShelfLayoutManager()->GetAlignment();
493 }
494
495 void Shell::SetDimming(bool should_dim) {
496   RootWindowControllerList controllers = GetAllRootWindowControllers();
497   for (RootWindowControllerList::iterator iter = controllers.begin();
498        iter != controllers.end(); ++iter)
499     (*iter)->screen_dimmer()->SetDimming(should_dim);
500 }
501
502 void Shell::NotifyFullscreenStateChange(bool is_fullscreen,
503                                         aura::Window* root_window) {
504   FOR_EACH_OBSERVER(ShellObserver, observers_, OnFullscreenStateChanged(
505       is_fullscreen, root_window));
506 }
507
508 void Shell::CreateModalBackground(aura::Window* window) {
509   if (!modality_filter_) {
510     modality_filter_.reset(new internal::SystemModalContainerEventFilter(this));
511     AddPreTargetHandler(modality_filter_.get());
512   }
513   RootWindowControllerList controllers = GetAllRootWindowControllers();
514   for (RootWindowControllerList::iterator iter = controllers.begin();
515        iter != controllers.end(); ++iter)
516     (*iter)->GetSystemModalLayoutManager(window)->CreateModalBackground();
517 }
518
519 void Shell::OnModalWindowRemoved(aura::Window* removed) {
520   RootWindowControllerList controllers = GetAllRootWindowControllers();
521   bool activated = false;
522   for (RootWindowControllerList::iterator iter = controllers.begin();
523        iter != controllers.end() && !activated; ++iter) {
524     activated = (*iter)->GetSystemModalLayoutManager(removed)->
525         ActivateNextModalWindow();
526   }
527   if (!activated) {
528     RemovePreTargetHandler(modality_filter_.get());
529     modality_filter_.reset();
530     for (RootWindowControllerList::iterator iter = controllers.begin();
531          iter != controllers.end(); ++iter)
532       (*iter)->GetSystemModalLayoutManager(removed)->DestroyModalBackground();
533   }
534 }
535
536 WebNotificationTray* Shell::GetWebNotificationTray() {
537   return GetPrimaryRootWindowController()->shelf()->
538       status_area_widget()->web_notification_tray();
539 }
540
541 bool Shell::HasPrimaryStatusArea() {
542   ShelfWidget* shelf = GetPrimaryRootWindowController()->shelf();
543   return shelf && shelf->status_area_widget();
544 }
545
546 SystemTray* Shell::GetPrimarySystemTray() {
547   return GetPrimaryRootWindowController()->GetSystemTray();
548 }
549
550 ShelfDelegate* Shell::GetShelfDelegate() {
551   if (!shelf_delegate_) {
552     shelf_model_.reset(new ShelfModel);
553     // Creates ShelfItemDelegateManager before ShelfDelegate.
554     shelf_item_delegate_manager_.reset(
555         new ShelfItemDelegateManager(shelf_model_.get()));
556
557     shelf_delegate_.reset(delegate_->CreateShelfDelegate(shelf_model_.get()));
558     scoped_ptr<ShelfItemDelegate> controller(
559         new internal::AppListShelfItemDelegate);
560
561     // Finding the shelf model's location of the app list and setting its
562     // ShelfItemDelegate.
563     int app_list_index = shelf_model_->GetItemIndexForType(TYPE_APP_LIST);
564     DCHECK_GE(app_list_index, 0);
565     ShelfID app_list_id = shelf_model_->items()[app_list_index].id;
566     DCHECK(app_list_id);
567     shelf_item_delegate_manager_->SetShelfItemDelegate(app_list_id,
568                                                        controller.Pass());
569     shelf_window_watcher_.reset(new internal::ShelfWindowWatcher(
570                                         shelf_model_.get(),
571                                         shelf_item_delegate_manager_.get()));
572   }
573   return shelf_delegate_.get();
574 }
575
576 void Shell::SetTouchHudProjectionEnabled(bool enabled) {
577   if (is_touch_hud_projection_enabled_ == enabled)
578     return;
579
580   is_touch_hud_projection_enabled_ = enabled;
581   FOR_EACH_OBSERVER(ShellObserver, observers_,
582                     OnTouchHudProjectionToggled(enabled));
583 }
584
585 #if defined(OS_CHROMEOS)
586 ash::FirstRunHelper* Shell::CreateFirstRunHelper() {
587   return new ash::FirstRunHelperImpl;
588 }
589
590 void Shell::SetCursorCompositingEnabled(bool enabled) {
591   display_controller_->cursor_window_controller()->SetCursorCompositingEnabled(
592       enabled);
593   native_cursor_manager_->SetNativeCursorEnabled(!enabled);
594 }
595 #endif  // defined(OS_CHROMEOS)
596
597 void Shell::DoInitialWorkspaceAnimation() {
598   return GetPrimaryRootWindowController()->workspace_controller()->
599       DoInitialAnimation();
600 }
601
602 ////////////////////////////////////////////////////////////////////////////////
603 // Shell, private:
604
605 Shell::Shell(ShellDelegate* delegate)
606     : target_root_window_(NULL),
607       scoped_target_root_window_(NULL),
608       delegate_(delegate),
609       window_positioner_(new WindowPositioner),
610       activation_client_(NULL),
611       accelerometer_controller_(new AccelerometerController()),
612 #if defined(OS_CHROMEOS) && defined(USE_X11)
613       output_configurator_(new ui::OutputConfigurator()),
614 #endif  // defined(OS_CHROMEOS) && defined(USE_X11)
615       native_cursor_manager_(new AshNativeCursorManager),
616       cursor_manager_(scoped_ptr< ::wm::NativeCursorManager>(
617           native_cursor_manager_)),
618       simulate_modal_window_open_for_testing_(false),
619       is_touch_hud_projection_enabled_(false) {
620   DCHECK(delegate_.get());
621   gpu_support_.reset(delegate_->CreateGPUSupport());
622   display_manager_.reset(new internal::DisplayManager);
623   display_controller_.reset(new DisplayController);
624 #if defined(OS_CHROMEOS) && defined(USE_X11)
625   user_metrics_recorder_.reset(new UserMetricsRecorder);
626 #endif  // defined(OS_CHROMEOS)
627
628 #if defined(OS_CHROMEOS)
629   internal::PowerStatus::Initialize();
630 #endif
631 }
632
633 Shell::~Shell() {
634   TRACE_EVENT0("shutdown", "ash::Shell::Destructor");
635
636   delegate_->PreShutdown();
637
638   views::FocusManagerFactory::Install(NULL);
639
640   // Remove the focus from any window. This will prevent overhead and side
641   // effects (e.g. crashes) from changing focus during shutdown.
642   // See bug crbug.com/134502.
643   aura::client::GetFocusClient(GetPrimaryRootWindow())->FocusWindow(NULL);
644
645   // Please keep in same order as in Init() because it's easy to miss one.
646   if (window_modality_controller_)
647     window_modality_controller_.reset();
648 #if defined(OS_CHROMEOS) && defined(USE_X11)
649   RemovePreTargetHandler(magnifier_key_scroll_handler_.get());
650   magnifier_key_scroll_handler_.reset();
651
652   RemovePreTargetHandler(speech_feedback_handler_.get());
653   speech_feedback_handler_.reset();
654 #endif
655   RemovePreTargetHandler(user_activity_detector_.get());
656   RemovePreTargetHandler(overlay_filter_.get());
657   RemovePreTargetHandler(input_method_filter_.get());
658   RemovePreTargetHandler(accelerator_filter_.get());
659   RemovePreTargetHandler(event_transformation_handler_.get());
660   RemovePreTargetHandler(toplevel_window_event_handler_.get());
661   RemovePostTargetHandler(toplevel_window_event_handler_.get());
662   RemovePreTargetHandler(system_gesture_filter_.get());
663   RemovePreTargetHandler(keyboard_metrics_filter_.get());
664   if (mouse_cursor_filter_)
665     RemovePreTargetHandler(mouse_cursor_filter_.get());
666
667   // TooltipController is deleted with the Shell so removing its references.
668   RemovePreTargetHandler(tooltip_controller_.get());
669
670   // Destroy maximize window manager early on since it has some observers which
671   // need to be removed.
672   maximize_mode_controller_.reset();
673   maximize_mode_window_manager_.reset();
674
675   // AppList needs to be released before shelf layout manager, which is
676   // destroyed with shelf container in the loop below. However, app list
677   // container is now on top of shelf container and released after it.
678   // TODO(xiyuan): Move it back when app list container is no longer needed.
679   app_list_controller_.reset();
680
681 #if defined(OS_CHROMEOS)
682   // Destroy the LastWindowClosedLogoutReminder before the
683   // LogoutConfirmationController.
684   last_window_closed_logout_reminder_.reset();
685
686   // Destroy the LogoutConfirmationController before the SystemTrayDelegate.
687   logout_confirmation_controller_.reset();
688 #endif
689
690   // Destroy SystemTrayDelegate before destroying the status area(s).
691   system_tray_delegate_->Shutdown();
692   system_tray_delegate_.reset();
693
694   locale_notification_controller_.reset();
695
696   // Drag-and-drop must be canceled prior to close all windows.
697   drag_drop_controller_.reset();
698
699   // Controllers who have WindowObserver added must be deleted
700   // before |display_controller_| is deleted.
701
702 #if defined(OS_CHROMEOS)
703   // VideoActivityNotifier must be deleted before |video_detector_| is
704   // deleted because it's observing video activity through
705   // VideoDetectorObserver interface.
706   video_activity_notifier_.reset();
707 #endif  // defined(OS_CHROMEOS)
708   video_detector_.reset();
709
710   shadow_controller_.reset();
711   resize_shadow_controller_.reset();
712
713   window_selector_controller_.reset();
714   mru_window_tracker_.reset();
715
716   // |shelf_window_watcher_| has a weak pointer to |shelf_Model_|
717   // and has window observers.
718   shelf_window_watcher_.reset();
719
720   // Destroy all child windows including widgets.
721   display_controller_->CloseChildWindows();
722   display_controller_->CloseNonDesktopDisplay();
723
724   // Chrome implementation of shelf delegate depends on FocusClient,
725   // so must be deleted before |focus_client_|.
726   shelf_delegate_.reset();
727   focus_client_.reset();
728
729   // Destroy SystemTrayNotifier after destroying SystemTray as TrayItems
730   // needs to remove observers from it.
731   system_tray_notifier_.reset();
732
733   // These need a valid Shell instance to clean up properly, so explicitly
734   // delete them before invalidating the instance.
735   // Alphabetical. TODO(oshima): sort.
736   magnification_controller_.reset();
737   partial_magnification_controller_.reset();
738   tooltip_controller_.reset();
739   event_client_.reset();
740   nested_dispatcher_controller_.reset();
741   toplevel_window_event_handler_.reset();
742   visibility_controller_.reset();
743   // |shelf_item_delegate_manager_| observes |shelf_model_|. It must be
744   // destroyed before |shelf_model_| is destroyed.
745   shelf_item_delegate_manager_.reset();
746   shelf_model_.reset();
747
748   power_button_controller_.reset();
749   lock_state_controller_.reset();
750
751 #if defined(OS_CHROMEOS)
752   resolution_notification_controller_.reset();
753 #endif
754   desktop_background_controller_.reset();
755
756   // This also deletes all RootWindows. Note that we invoke Shutdown() on
757   // DisplayController before resetting |display_controller_|, since destruction
758   // of its owned RootWindowControllers relies on the value.
759   display_manager_->CreateScreenForShutdown();
760   display_controller_->Shutdown();
761   display_controller_.reset();
762   screen_position_controller_.reset();
763
764   keyboard_controller_.reset();
765   accessibility_delegate_.reset();
766   new_window_delegate_.reset();
767   media_delegate_.reset();
768
769 #if defined(OS_CHROMEOS) && defined(USE_X11)
770   if (display_change_observer_)
771     output_configurator_->RemoveObserver(display_change_observer_.get());
772   if (output_configurator_animation_)
773     output_configurator_->RemoveObserver(output_configurator_animation_.get());
774   if (display_error_observer_)
775     output_configurator_->RemoveObserver(display_error_observer_.get());
776   if (projecting_observer_)
777     output_configurator_->RemoveObserver(projecting_observer_.get());
778   display_change_observer_.reset();
779 #endif  // defined(OS_CHROMEOS)
780
781 #if defined(OS_CHROMEOS)
782   internal::PowerStatus::Shutdown();
783 #endif
784
785   DCHECK(instance_ == this);
786   instance_ = NULL;
787 }
788
789 void Shell::Init() {
790   delegate_->PreInit();
791   if (keyboard::IsKeyboardUsabilityExperimentEnabled()) {
792     display_manager_->SetSecondDisplayMode(
793         internal::DisplayManager::VIRTUAL_KEYBOARD);
794   }
795   bool display_initialized = display_manager_->InitFromCommandLine();
796 #if defined(OS_CHROMEOS) && defined(USE_X11)
797   output_configurator_->Init(!gpu_support_->IsPanelFittingDisabled());
798   output_configurator_animation_.reset(
799       new internal::OutputConfiguratorAnimation());
800   output_configurator_->AddObserver(output_configurator_animation_.get());
801
802   projecting_observer_.reset(new internal::ProjectingObserver());
803   output_configurator_->AddObserver(projecting_observer_.get());
804
805   if (!display_initialized && base::SysInfo::IsRunningOnChromeOS()) {
806     display_change_observer_.reset(new internal::DisplayChangeObserver);
807     // Register |display_change_observer_| first so that the rest of
808     // observer gets invoked after the root windows are configured.
809     output_configurator_->AddObserver(display_change_observer_.get());
810     display_error_observer_.reset(new internal::DisplayErrorObserver());
811     output_configurator_->AddObserver(display_error_observer_.get());
812     output_configurator_->set_state_controller(display_change_observer_.get());
813     output_configurator_->set_mirroring_controller(display_manager_.get());
814     output_configurator_->ForceInitialConfigure(
815         delegate_->IsFirstRunAfterBoot() ? kChromeOsBootColor : 0);
816     display_initialized = true;
817   }
818 #endif  // defined(OS_CHROMEOS) && defined(USE_X11)
819   if (!display_initialized)
820     display_manager_->InitDefaultDisplay();
821
822   // Install the custom factory first so that views::FocusManagers for Tray,
823   // Shelf, and WallPaper could be created by the factory.
824   views::FocusManagerFactory::Install(new AshFocusManagerFactory);
825
826   // Env creates the compositor. Historically it seems to have been implicitly
827   // initialized first by the ActivationController, but now that FocusController
828   // no longer does this we need to do it explicitly.
829   aura::Env::CreateInstance();
830
831   // The WindowModalityController needs to be at the front of the input event
832   // pretarget handler list to ensure that it processes input events when modal
833   // windows are active.
834   window_modality_controller_.reset(
835       new ::wm::WindowModalityController(this));
836
837   AddPreTargetHandler(this);
838
839   env_filter_.reset(new ::wm::CompoundEventFilter);
840   AddPreTargetHandler(env_filter_.get());
841
842   ::wm::FocusController* focus_controller =
843       new ::wm::FocusController(new wm::AshFocusRules);
844   focus_client_.reset(focus_controller);
845   activation_client_ = focus_controller;
846   activation_client_->AddObserver(this);
847   focus_cycler_.reset(new internal::FocusCycler());
848
849   screen_position_controller_.reset(new internal::ScreenPositionController);
850   window_tree_host_factory_.reset(delegate_->CreateWindowTreeHostFactory());
851
852   display_controller_->Start();
853   display_controller_->InitPrimaryDisplay();
854   aura::Window* root_window = display_controller_->GetPrimaryRootWindow();
855   target_root_window_ = root_window;
856
857 #if defined(OS_CHROMEOS)
858   resolution_notification_controller_.reset(
859       new internal::ResolutionNotificationController);
860 #endif
861
862   cursor_manager_.SetDisplay(GetScreen()->GetPrimaryDisplay());
863
864   nested_dispatcher_controller_.reset(new NestedDispatcherController);
865   accelerator_controller_.reset(new AcceleratorController);
866   maximize_mode_controller_.reset(new MaximizeModeController());
867
868 #if defined(OS_CHROMEOS) && defined(USE_X11)
869   magnifier_key_scroll_handler_ = MagnifierKeyScroller::CreateHandler().Pass();
870   AddPreTargetHandler(magnifier_key_scroll_handler_.get());
871   speech_feedback_handler_ = SpokenFeedbackToggler::CreateHandler().Pass();
872   AddPreTargetHandler(speech_feedback_handler_.get());
873 #endif
874
875   // The order in which event filters are added is significant.
876
877 #if defined(OS_CHROMEOS)
878   // The StickyKeysController also rewrites events and must be added
879   // before observers, but after the EventRewriterEventFilter.
880   sticky_keys_controller_.reset(new StickyKeysController);
881   AddPreTargetHandler(sticky_keys_controller_.get());
882 #endif
883
884   // UserActivityDetector passes events to observers, so let them get
885   // rewritten first.
886   user_activity_detector_.reset(new UserActivityDetector);
887   AddPreTargetHandler(user_activity_detector_.get());
888
889   overlay_filter_.reset(new internal::OverlayEventFilter);
890   AddPreTargetHandler(overlay_filter_.get());
891   AddShellObserver(overlay_filter_.get());
892
893   input_method_filter_.reset(new ::wm::InputMethodEventFilter(
894       root_window->GetHost()->GetAcceleratedWidget()));
895   AddPreTargetHandler(input_method_filter_.get());
896
897   accelerator_filter_.reset(new internal::AcceleratorFilter);
898   AddPreTargetHandler(accelerator_filter_.get());
899
900   event_transformation_handler_.reset(new internal::EventTransformationHandler);
901   AddPreTargetHandler(event_transformation_handler_.get());
902
903   toplevel_window_event_handler_.reset(new ToplevelWindowEventHandler);
904
905   system_gesture_filter_.reset(new internal::SystemGestureEventFilter);
906   AddPreTargetHandler(system_gesture_filter_.get());
907
908   keyboard_metrics_filter_.reset(new internal::KeyboardUMAEventFilter);
909   AddPreTargetHandler(keyboard_metrics_filter_.get());
910
911   // The keyboard system must be initialized before the RootWindowController is
912   // created.
913 #if defined(OS_CHROMEOS)
914     keyboard::InitializeKeyboard();
915 #endif
916
917   lock_state_controller_.reset(new LockStateController);
918   power_button_controller_.reset(new PowerButtonController(
919       lock_state_controller_.get()));
920 #if defined(OS_CHROMEOS) && defined(USE_X11)
921   // Pass the initial display state to PowerButtonController.
922   power_button_controller_->OnDisplayModeChanged(
923       output_configurator_->cached_outputs());
924 #endif
925   AddShellObserver(lock_state_controller_.get());
926
927   drag_drop_controller_.reset(new internal::DragDropController);
928   mouse_cursor_filter_.reset(new internal::MouseCursorEventFilter());
929   PrependPreTargetHandler(mouse_cursor_filter_.get());
930
931   // Create Controllers that may need root window.
932   // TODO(oshima): Move as many controllers before creating
933   // RootWindowController as possible.
934   visibility_controller_.reset(new AshVisibilityController);
935
936   magnification_controller_.reset(
937       MagnificationController::CreateInstance());
938   mru_window_tracker_.reset(new MruWindowTracker(activation_client_));
939
940   partial_magnification_controller_.reset(
941       new PartialMagnificationController());
942
943   autoclick_controller_.reset(AutoclickController::CreateInstance());
944
945   high_contrast_controller_.reset(new HighContrastController);
946   video_detector_.reset(new VideoDetector);
947   window_selector_controller_.reset(new WindowSelectorController());
948
949   tooltip_controller_.reset(
950       new views::corewm::TooltipController(
951           scoped_ptr<views::corewm::Tooltip>(
952               new views::corewm::TooltipAura(gfx::SCREEN_TYPE_ALTERNATE))));
953   AddPreTargetHandler(tooltip_controller_.get());
954
955   event_client_.reset(new internal::EventClientImpl);
956
957   // This controller needs to be set before SetupManagedWindowMode.
958   desktop_background_controller_.reset(new DesktopBackgroundController());
959   user_wallpaper_delegate_.reset(delegate_->CreateUserWallpaperDelegate());
960
961   session_state_delegate_.reset(delegate_->CreateSessionStateDelegate());
962   accessibility_delegate_.reset(delegate_->CreateAccessibilityDelegate());
963   new_window_delegate_.reset(delegate_->CreateNewWindowDelegate());
964   media_delegate_.reset(delegate_->CreateMediaDelegate());
965
966   resize_shadow_controller_.reset(new internal::ResizeShadowController());
967   shadow_controller_.reset(
968       new ::wm::ShadowController(activation_client_));
969
970   // Create system_tray_notifier_ before the delegate.
971   system_tray_notifier_.reset(new ash::SystemTrayNotifier());
972
973   // Initialize system_tray_delegate_ before initializing StatusAreaWidget.
974   system_tray_delegate_.reset(delegate()->CreateSystemTrayDelegate());
975   DCHECK(system_tray_delegate_.get());
976
977   locale_notification_controller_.reset(
978       new internal::LocaleNotificationController);
979
980   // Initialize system_tray_delegate_ after StatusAreaWidget is created.
981   system_tray_delegate_->Initialize();
982
983 #if defined(OS_CHROMEOS)
984   // Create the LogoutConfirmationController after the SystemTrayDelegate.
985   logout_confirmation_controller_.reset(
986       new internal::LogoutConfirmationController(
987           base::Bind(&SystemTrayDelegate::SignOut,
988                      base::Unretained(system_tray_delegate_.get()))));
989 #endif
990
991   // TODO(oshima): Initialize all RootWindowControllers once, and
992   // initialize controller/delegates above when initializing the
993   // primary root window controller.
994   internal::RootWindowController::CreateForPrimaryDisplay(
995       root_window->GetHost());
996
997   display_controller_->InitSecondaryDisplays();
998
999   // It needs to be created after RootWindowController has been created
1000   // (which calls OnWindowResized has been called, otherwise the
1001   // widget will not paint when restoring after a browser crash.  Also it needs
1002   // to be created after InitSecondaryDisplays() to initialize the wallpapers in
1003   // the correct size.
1004   user_wallpaper_delegate_->InitializeWallpaper();
1005
1006   if (initially_hide_cursor_)
1007     cursor_manager_.HideCursor();
1008   cursor_manager_.SetCursor(ui::kCursorPointer);
1009
1010 #if defined(OS_CHROMEOS)
1011   // Set accelerator controller delegates.
1012   accelerator_controller_->SetBrightnessControlDelegate(
1013       scoped_ptr<ash::BrightnessControlDelegate>(
1014           new ash::system::BrightnessControllerChromeos).Pass());
1015
1016   power_event_observer_.reset(new internal::PowerEventObserver());
1017   user_activity_notifier_.reset(
1018       new internal::UserActivityNotifier(user_activity_detector_.get()));
1019   video_activity_notifier_.reset(
1020       new internal::VideoActivityNotifier(video_detector_.get()));
1021   bluetooth_notification_controller_.reset(
1022       new internal::BluetoothNotificationController);
1023   last_window_closed_logout_reminder_.reset(
1024       new internal::LastWindowClosedLogoutReminder);
1025 #endif
1026
1027   weak_display_manager_factory_.reset(
1028       new base::WeakPtrFactory<internal::DisplayManager>(
1029           display_manager_.get()));
1030   // The compositor thread and main message loop have to be running in
1031   // order to create mirror window. Run it after the main message loop
1032   // is started.
1033   base::MessageLoopForUI::current()->PostTask(
1034       FROM_HERE,
1035       base::Bind(&internal::DisplayManager::CreateMirrorWindowIfAny,
1036                  weak_display_manager_factory_->GetWeakPtr()));
1037 }
1038
1039 void Shell::InitKeyboard() {
1040   if (keyboard::IsKeyboardEnabled()) {
1041     if (keyboard_controller_.get()) {
1042       RootWindowControllerList controllers = GetAllRootWindowControllers();
1043       for (RootWindowControllerList::iterator iter = controllers.begin();
1044            iter != controllers.end(); ++iter) {
1045         (*iter)->DeactivateKeyboard(keyboard_controller_.get());
1046       }
1047     }
1048     keyboard::KeyboardControllerProxy* proxy =
1049         delegate_->CreateKeyboardControllerProxy();
1050     keyboard_controller_.reset(
1051         new keyboard::KeyboardController(proxy));
1052   }
1053 }
1054
1055 void Shell::InitRootWindow(aura::Window* root_window) {
1056   DCHECK(activation_client_);
1057   DCHECK(visibility_controller_.get());
1058   DCHECK(drag_drop_controller_.get());
1059
1060   aura::client::SetFocusClient(root_window, focus_client_.get());
1061   input_method_filter_->SetInputMethodPropertyInRootWindow(root_window);
1062   aura::client::SetActivationClient(root_window, activation_client_);
1063   ::wm::FocusController* focus_controller =
1064       static_cast< ::wm::FocusController*>(activation_client_);
1065   root_window->AddPreTargetHandler(focus_controller);
1066   aura::client::SetVisibilityClient(root_window, visibility_controller_.get());
1067   aura::client::SetDragDropClient(root_window, drag_drop_controller_.get());
1068   aura::client::SetScreenPositionClient(root_window,
1069                                         screen_position_controller_.get());
1070   aura::client::SetCursorClient(root_window, &cursor_manager_);
1071   aura::client::SetTooltipClient(root_window, tooltip_controller_.get());
1072   aura::client::SetEventClient(root_window, event_client_.get());
1073
1074   aura::client::SetWindowMoveClient(root_window,
1075       toplevel_window_event_handler_.get());
1076   root_window->AddPreTargetHandler(toplevel_window_event_handler_.get());
1077   root_window->AddPostTargetHandler(toplevel_window_event_handler_.get());
1078
1079   if (nested_dispatcher_controller_) {
1080     aura::client::SetDispatcherClient(root_window,
1081                                       nested_dispatcher_controller_.get());
1082   }
1083 }
1084
1085 bool Shell::CanWindowReceiveEvents(aura::Window* window) {
1086   RootWindowControllerList controllers = GetAllRootWindowControllers();
1087   for (RootWindowControllerList::iterator iter = controllers.begin();
1088        iter != controllers.end(); ++iter) {
1089     internal::SystemModalContainerLayoutManager* layout_manager =
1090         (*iter)->GetSystemModalLayoutManager(window);
1091     if (layout_manager && layout_manager->CanWindowReceiveEvents(window))
1092       return true;
1093     // Allow events to fall through to the virtual keyboard even if displaying
1094     // a system modal dialog.
1095     if ((*iter)->IsVirtualKeyboardWindow(window))
1096       return true;
1097   }
1098
1099   return false;
1100 }
1101
1102 ////////////////////////////////////////////////////////////////////////////////
1103 // Shell, ui::EventTarget overrides:
1104
1105 bool Shell::CanAcceptEvent(const ui::Event& event) {
1106   return true;
1107 }
1108
1109 ui::EventTarget* Shell::GetParentTarget() {
1110   return aura::Env::GetInstance();
1111 }
1112
1113 scoped_ptr<ui::EventTargetIterator> Shell::GetChildIterator() const {
1114   return scoped_ptr<ui::EventTargetIterator>();
1115 }
1116
1117 ui::EventTargeter* Shell::GetEventTargeter() {
1118   NOTREACHED();
1119   return NULL;
1120 }
1121
1122 void Shell::OnEvent(ui::Event* event) {
1123 }
1124
1125 ////////////////////////////////////////////////////////////////////////////////
1126 // Shell, aura::client::ActivationChangeObserver implementation:
1127
1128 void Shell::OnWindowActivated(aura::Window* gained_active,
1129                               aura::Window* lost_active) {
1130   if (gained_active)
1131     target_root_window_ = gained_active->GetRootWindow();
1132 }
1133
1134 }  // namespace ash