Port Android relocation packer to chromium build
[chromium-blink-merge.git] / ash / display / display_controller.cc
blob166a76f0cdc26dce639190d0720e37504d73ce59
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.
5 #include "ash/display/display_controller.h"
7 #include <algorithm>
8 #include <cmath>
9 #include <map>
11 #include "ash/ash_switches.h"
12 #include "ash/display/cursor_window_controller.h"
13 #include "ash/display/display_layout_store.h"
14 #include "ash/display/display_manager.h"
15 #include "ash/display/mirror_window_controller.h"
16 #include "ash/display/root_window_transformers.h"
17 #include "ash/host/ash_window_tree_host.h"
18 #include "ash/host/ash_window_tree_host_init_params.h"
19 #include "ash/host/root_window_transformer.h"
20 #include "ash/root_window_controller.h"
21 #include "ash/root_window_settings.h"
22 #include "ash/screen_util.h"
23 #include "ash/shell.h"
24 #include "ash/shell_delegate.h"
25 #include "ash/wm/coordinate_conversion.h"
26 #include "base/command_line.h"
27 #include "base/stl_util.h"
28 #include "base/strings/stringprintf.h"
29 #include "base/strings/utf_string_conversions.h"
30 #include "ui/aura/client/capture_client.h"
31 #include "ui/aura/client/focus_client.h"
32 #include "ui/aura/client/screen_position_client.h"
33 #include "ui/aura/window.h"
34 #include "ui/aura/window_event_dispatcher.h"
35 #include "ui/aura/window_property.h"
36 #include "ui/aura/window_tracker.h"
37 #include "ui/aura/window_tree_host.h"
38 #include "ui/compositor/compositor.h"
39 #include "ui/compositor/compositor_vsync_manager.h"
40 #include "ui/gfx/display.h"
41 #include "ui/gfx/screen.h"
42 #include "ui/wm/core/coordinate_conversion.h"
43 #include "ui/wm/public/activation_client.h"
45 #if defined(OS_CHROMEOS)
46 #include "ash/display/display_configurator_animation.h"
47 #include "base/sys_info.h"
48 #include "base/time/time.h"
49 #endif // defined(OS_CHROMEOS)
51 #if defined(USE_X11)
52 #include "ui/base/x/x11_util.h"
53 #include "ui/gfx/x/x11_types.h"
55 // Including this at the bottom to avoid other
56 // potential conflict with chrome headers.
57 #include <X11/extensions/Xrandr.h>
58 #undef RootWindow
59 #endif // defined(USE_X11)
61 #if defined(OS_CHROMEOS) && defined(USE_OZONE)
62 #include "ui/events/ozone/chromeos/cursor_controller.h"
63 #endif
65 namespace ash {
66 namespace {
68 // Primary display stored in global object as it can be
69 // accessed after Shell is deleted. A separate display instance is created
70 // during the shutdown instead of always keeping two display instances
71 // (one here and another one in display_manager) in sync, which is error prone.
72 // This is initialized in the constructor, and then in CreatePrimaryHost().
73 int64 primary_display_id = -1;
75 // Specifies how long the display change should have been disabled
76 // after each display change operations.
77 // |kCycleDisplayThrottleTimeoutMs| is set to be longer to avoid
78 // changing the settings while the system is still configurating
79 // displays. It will be overriden by |kAfterDisplayChangeThrottleTimeoutMs|
80 // when the display change happens, so the actual timeout is much shorter.
81 const int64 kAfterDisplayChangeThrottleTimeoutMs = 500;
82 const int64 kCycleDisplayThrottleTimeoutMs = 4000;
83 const int64 kSwapDisplayThrottleTimeoutMs = 500;
85 #if defined(USE_OZONE) && defined(OS_CHROMEOS)
86 // Add 20% more cursor motion on non-integrated displays.
87 const float kCursorMultiplierForExternalDisplays = 1.2f;
88 #endif
90 DisplayManager* GetDisplayManager() {
91 return Shell::GetInstance()->display_manager();
94 void SetDisplayPropertiesOnHost(AshWindowTreeHost* ash_host,
95 const gfx::Display& display) {
96 DisplayInfo info = GetDisplayManager()->GetDisplayInfo(display.id());
97 aura::WindowTreeHost* host = ash_host->AsWindowTreeHost();
98 #if defined(OS_CHROMEOS)
99 #if defined(USE_X11)
100 // Native window property (Atom in X11) that specifies the display's
101 // rotation, scale factor and if it's internal display. They are
102 // read and used by touchpad/mouse driver directly on X (contact
103 // adlr@ for more details on touchpad/mouse driver side). The value
104 // of the rotation is one of 0 (normal), 1 (90 degrees clockwise), 2
105 // (180 degree) or 3 (270 degrees clockwise). The value of the
106 // scale factor is in percent (100, 140, 200 etc).
107 const char kRotationProp[] = "_CHROME_DISPLAY_ROTATION";
108 const char kScaleFactorProp[] = "_CHROME_DISPLAY_SCALE_FACTOR";
109 const char kInternalProp[] = "_CHROME_DISPLAY_INTERNAL";
110 const char kCARDINAL[] = "CARDINAL";
111 int xrandr_rotation = RR_Rotate_0;
112 switch (info.rotation()) {
113 case gfx::Display::ROTATE_0:
114 xrandr_rotation = RR_Rotate_0;
115 break;
116 case gfx::Display::ROTATE_90:
117 xrandr_rotation = RR_Rotate_90;
118 break;
119 case gfx::Display::ROTATE_180:
120 xrandr_rotation = RR_Rotate_180;
121 break;
122 case gfx::Display::ROTATE_270:
123 xrandr_rotation = RR_Rotate_270;
124 break;
127 int internal = display.IsInternal() ? 1 : 0;
128 gfx::AcceleratedWidget xwindow = host->GetAcceleratedWidget();
129 ui::SetIntProperty(xwindow, kInternalProp, kCARDINAL, internal);
130 ui::SetIntProperty(xwindow, kRotationProp, kCARDINAL, xrandr_rotation);
131 ui::SetIntProperty(xwindow,
132 kScaleFactorProp,
133 kCARDINAL,
134 100 * display.device_scale_factor());
135 #elif defined(USE_OZONE)
136 // Scale all motion on High-DPI displays.
137 float scale = display.device_scale_factor();
139 if (!display.IsInternal())
140 scale *= kCursorMultiplierForExternalDisplays;
142 ui::CursorController::GetInstance()->SetCursorConfigForWindow(
143 host->GetAcceleratedWidget(), info.rotation(), scale);
144 #endif
145 #endif
146 scoped_ptr<RootWindowTransformer> transformer(
147 CreateRootWindowTransformerForDisplay(host->window(), display));
148 ash_host->SetRootWindowTransformer(transformer.Pass());
150 DisplayMode mode =
151 GetDisplayManager()->GetActiveModeForDisplayId(display.id());
152 if (mode.refresh_rate > 0.0f) {
153 host->compositor()->vsync_manager()->SetAuthoritativeVSyncInterval(
154 base::TimeDelta::FromMicroseconds(
155 base::Time::kMicrosecondsPerSecond / mode.refresh_rate));
158 // Just movnig the display requires the full redraw.
159 // chrome-os-partner:33558.
160 host->compositor()->ScheduleFullRedraw();
163 void ClearDisplayPropertiesOnHost(AshWindowTreeHost* ash_host,
164 const gfx::Display& display) {
165 #if defined(OS_CHROMEOS) && defined(USE_OZONE)
166 aura::WindowTreeHost* host = ash_host->AsWindowTreeHost();
167 ui::CursorController::GetInstance()->ClearCursorConfigForWindow(
168 host->GetAcceleratedWidget());
169 #endif
172 aura::Window* GetWindow(AshWindowTreeHost* ash_host) {
173 CHECK(ash_host->AsWindowTreeHost());
174 return ash_host->AsWindowTreeHost()->window();
177 } // namespace
179 // A utility class to store/restore focused/active window
180 // when the display configuration has changed.
181 class FocusActivationStore {
182 public:
183 FocusActivationStore()
184 : activation_client_(NULL),
185 capture_client_(NULL),
186 focus_client_(NULL),
187 focused_(NULL),
188 active_(NULL) {
191 void Store(bool clear_focus) {
192 if (!activation_client_) {
193 aura::Window* root = Shell::GetPrimaryRootWindow();
194 activation_client_ = aura::client::GetActivationClient(root);
195 capture_client_ = aura::client::GetCaptureClient(root);
196 focus_client_ = aura::client::GetFocusClient(root);
198 focused_ = focus_client_->GetFocusedWindow();
199 if (focused_)
200 tracker_.Add(focused_);
201 active_ = activation_client_->GetActiveWindow();
202 if (active_ && focused_ != active_)
203 tracker_.Add(active_);
205 // Deactivate the window to close menu / bubble windows.
206 if (clear_focus)
207 activation_client_->DeactivateWindow(active_);
209 // Release capture if any.
210 capture_client_->SetCapture(NULL);
211 // Clear the focused window if any. This is necessary because a
212 // window may be deleted when losing focus (fullscreen flash for
213 // example). If the focused window is still alive after move, it'll
214 // be re-focused below.
215 if (clear_focus)
216 focus_client_->FocusWindow(NULL);
219 void Restore() {
220 // Restore focused or active window if it's still alive.
221 if (focused_ && tracker_.Contains(focused_)) {
222 focus_client_->FocusWindow(focused_);
223 } else if (active_ && tracker_.Contains(active_)) {
224 activation_client_->ActivateWindow(active_);
226 if (focused_)
227 tracker_.Remove(focused_);
228 if (active_)
229 tracker_.Remove(active_);
230 focused_ = NULL;
231 active_ = NULL;
234 private:
235 aura::client::ActivationClient* activation_client_;
236 aura::client::CaptureClient* capture_client_;
237 aura::client::FocusClient* focus_client_;
238 aura::WindowTracker tracker_;
239 aura::Window* focused_;
240 aura::Window* active_;
242 DISALLOW_COPY_AND_ASSIGN(FocusActivationStore);
245 ////////////////////////////////////////////////////////////////////////////////
246 // DisplayChangeLimiter
248 DisplayController::DisplayChangeLimiter::DisplayChangeLimiter()
249 : throttle_timeout_(base::Time::Now()) {
252 void DisplayController::DisplayChangeLimiter::SetThrottleTimeout(
253 int64 throttle_ms) {
254 throttle_timeout_ =
255 base::Time::Now() + base::TimeDelta::FromMilliseconds(throttle_ms);
258 bool DisplayController::DisplayChangeLimiter::IsThrottled() const {
259 return base::Time::Now() < throttle_timeout_;
262 ////////////////////////////////////////////////////////////////////////////////
263 // DisplayController
265 DisplayController::DisplayController()
266 : primary_tree_host_for_replace_(NULL),
267 focus_activation_store_(new FocusActivationStore()),
268 cursor_window_controller_(new CursorWindowController()),
269 mirror_window_controller_(new MirrorWindowController()),
270 cursor_display_id_for_restore_(gfx::Display::kInvalidDisplayID),
271 weak_ptr_factory_(this) {
272 #if defined(OS_CHROMEOS)
273 if (base::SysInfo::IsRunningOnChromeOS())
274 limiter_.reset(new DisplayChangeLimiter);
275 #endif
276 // Reset primary display to make sure that tests don't use
277 // stale display info from previous tests.
278 primary_display_id = gfx::Display::kInvalidDisplayID;
281 DisplayController::~DisplayController() {
284 void DisplayController::Start() {
285 Shell::GetScreen()->AddObserver(this);
286 Shell::GetInstance()->display_manager()->set_delegate(this);
289 void DisplayController::Shutdown() {
290 // Unset the display manager's delegate here because
291 // DisplayManager outlives DisplayController.
292 Shell::GetInstance()->display_manager()->set_delegate(NULL);
294 cursor_window_controller_.reset();
295 mirror_window_controller_.reset();
297 Shell::GetScreen()->RemoveObserver(this);
299 int64 primary_id = Shell::GetScreen()->GetPrimaryDisplay().id();
301 // Delete non primary root window controllers first, then
302 // delete the primary root window controller.
303 aura::Window::Windows root_windows = DisplayController::GetAllRootWindows();
304 std::vector<RootWindowController*> to_delete;
305 RootWindowController* primary_rwc = NULL;
306 for (aura::Window::Windows::iterator iter = root_windows.begin();
307 iter != root_windows.end();
308 ++iter) {
309 RootWindowController* rwc = GetRootWindowController(*iter);
310 if (GetRootWindowSettings(*iter)->display_id == primary_id)
311 primary_rwc = rwc;
312 else
313 to_delete.push_back(rwc);
315 CHECK(primary_rwc);
317 STLDeleteElements(&to_delete);
318 delete primary_rwc;
321 void DisplayController::CreatePrimaryHost(
322 const AshWindowTreeHostInitParams& init_params) {
323 const gfx::Display& primary_candidate =
324 GetDisplayManager()->GetPrimaryDisplayCandidate();
325 primary_display_id = primary_candidate.id();
326 CHECK_NE(gfx::Display::kInvalidDisplayID, primary_display_id);
327 AddWindowTreeHostForDisplay(primary_candidate, init_params);
330 void DisplayController::InitDisplays() {
331 RootWindowController::CreateForPrimaryDisplay(
332 window_tree_hosts_[primary_display_id]);
334 DisplayManager* display_manager = GetDisplayManager();
335 for (size_t i = 0; i < display_manager->GetNumDisplays(); ++i) {
336 const gfx::Display& display = display_manager->GetDisplayAt(i);
337 if (primary_display_id != display.id()) {
338 AshWindowTreeHost* ash_host = AddWindowTreeHostForDisplay(
339 display, AshWindowTreeHostInitParams());
340 RootWindowController::CreateForSecondaryDisplay(ash_host);
343 UpdateHostWindowNames();
345 FOR_EACH_OBSERVER(Observer, observers_, OnDisplaysInitialized());
348 void DisplayController::AddObserver(Observer* observer) {
349 observers_.AddObserver(observer);
352 void DisplayController::RemoveObserver(Observer* observer) {
353 observers_.RemoveObserver(observer);
356 // static
357 int64 DisplayController::GetPrimaryDisplayId() {
358 CHECK_NE(gfx::Display::kInvalidDisplayID, primary_display_id);
359 return primary_display_id;
362 aura::Window* DisplayController::GetPrimaryRootWindow() {
363 return GetRootWindowForDisplayId(primary_display_id);
366 aura::Window* DisplayController::GetRootWindowForDisplayId(int64 id) {
367 CHECK_EQ(1u, window_tree_hosts_.count(id));
368 AshWindowTreeHost* host = window_tree_hosts_[id];
369 CHECK(host);
370 return GetWindow(host);
373 void DisplayController::CloseChildWindows() {
374 for (WindowTreeHostMap::const_iterator it = window_tree_hosts_.begin();
375 it != window_tree_hosts_.end();
376 ++it) {
377 aura::Window* root_window = GetWindow(it->second);
378 RootWindowController* controller = GetRootWindowController(root_window);
379 if (controller) {
380 controller->CloseChildWindows();
381 } else {
382 while (!root_window->children().empty()) {
383 aura::Window* child = root_window->children()[0];
384 delete child;
390 aura::Window::Windows DisplayController::GetAllRootWindows() {
391 aura::Window::Windows windows;
392 for (WindowTreeHostMap::const_iterator it = window_tree_hosts_.begin();
393 it != window_tree_hosts_.end();
394 ++it) {
395 DCHECK(it->second);
396 if (GetRootWindowController(GetWindow(it->second)))
397 windows.push_back(GetWindow(it->second));
399 return windows;
402 gfx::Insets DisplayController::GetOverscanInsets(int64 display_id) const {
403 return GetDisplayManager()->GetOverscanInsets(display_id);
406 void DisplayController::SetOverscanInsets(int64 display_id,
407 const gfx::Insets& insets_in_dip) {
408 GetDisplayManager()->SetOverscanInsets(display_id, insets_in_dip);
411 std::vector<RootWindowController*>
412 DisplayController::GetAllRootWindowControllers() {
413 std::vector<RootWindowController*> controllers;
414 for (WindowTreeHostMap::const_iterator it = window_tree_hosts_.begin();
415 it != window_tree_hosts_.end();
416 ++it) {
417 RootWindowController* controller =
418 GetRootWindowController(GetWindow(it->second));
419 if (controller)
420 controllers.push_back(controller);
422 return controllers;
425 void DisplayController::ToggleMirrorMode() {
426 DisplayManager* display_manager = GetDisplayManager();
427 if (display_manager->num_connected_displays() <= 1)
428 return;
430 if (limiter_) {
431 if (limiter_->IsThrottled())
432 return;
433 limiter_->SetThrottleTimeout(kCycleDisplayThrottleTimeoutMs);
435 #if defined(OS_CHROMEOS)
436 Shell* shell = Shell::GetInstance();
437 DisplayConfiguratorAnimation* animation =
438 shell->display_configurator_animation();
439 animation->StartFadeOutAnimation(
440 base::Bind(&DisplayController::SetMirrorModeAfterAnimation,
441 weak_ptr_factory_.GetWeakPtr(),
442 !display_manager->IsMirrored()));
443 #endif
446 void DisplayController::SwapPrimaryDisplay() {
447 if (limiter_) {
448 if (limiter_->IsThrottled())
449 return;
450 limiter_->SetThrottleTimeout(kSwapDisplayThrottleTimeoutMs);
453 if (Shell::GetScreen()->GetNumDisplays() > 1) {
454 #if defined(OS_CHROMEOS)
455 DisplayConfiguratorAnimation* animation =
456 Shell::GetInstance()->display_configurator_animation();
457 if (animation) {
458 animation->StartFadeOutAnimation(base::Bind(
459 &DisplayController::OnFadeOutForSwapDisplayFinished,
460 weak_ptr_factory_.GetWeakPtr()));
461 } else {
462 SetPrimaryDisplay(ScreenUtil::GetSecondaryDisplay());
464 #else
465 SetPrimaryDisplay(ScreenUtil::GetSecondaryDisplay());
466 #endif
470 void DisplayController::SetPrimaryDisplayId(int64 id) {
471 DCHECK_NE(gfx::Display::kInvalidDisplayID, id);
472 if (id == gfx::Display::kInvalidDisplayID || primary_display_id == id)
473 return;
475 const gfx::Display& display = GetDisplayManager()->GetDisplayForId(id);
476 if (display.is_valid())
477 SetPrimaryDisplay(display);
480 void DisplayController::SetPrimaryDisplay(
481 const gfx::Display& new_primary_display) {
482 DisplayManager* display_manager = GetDisplayManager();
483 DCHECK(new_primary_display.is_valid());
484 DCHECK(display_manager->IsActiveDisplay(new_primary_display));
486 if (!new_primary_display.is_valid() ||
487 !display_manager->IsActiveDisplay(new_primary_display)) {
488 LOG(ERROR) << "Invalid or non-existent display is requested:"
489 << new_primary_display.ToString();
490 return;
493 if (primary_display_id == new_primary_display.id() ||
494 window_tree_hosts_.size() < 2) {
495 return;
498 AshWindowTreeHost* non_primary_host =
499 window_tree_hosts_[new_primary_display.id()];
500 LOG_IF(ERROR, !non_primary_host)
501 << "Unknown display is requested in SetPrimaryDisplay: id="
502 << new_primary_display.id();
503 if (!non_primary_host)
504 return;
506 gfx::Display old_primary_display = Shell::GetScreen()->GetPrimaryDisplay();
508 // Swap root windows between current and new primary display.
509 AshWindowTreeHost* primary_host = window_tree_hosts_[primary_display_id];
510 CHECK(primary_host);
511 CHECK_NE(primary_host, non_primary_host);
513 window_tree_hosts_[new_primary_display.id()] = primary_host;
514 GetRootWindowSettings(GetWindow(primary_host))->display_id =
515 new_primary_display.id();
517 window_tree_hosts_[old_primary_display.id()] = non_primary_host;
518 GetRootWindowSettings(GetWindow(non_primary_host))->display_id =
519 old_primary_display.id();
521 primary_display_id = new_primary_display.id();
522 GetDisplayManager()->layout_store()->UpdatePrimaryDisplayId(
523 display_manager->GetCurrentDisplayIdPair(), primary_display_id);
525 UpdateWorkAreaOfDisplayNearestWindow(GetWindow(primary_host),
526 old_primary_display.GetWorkAreaInsets());
527 UpdateWorkAreaOfDisplayNearestWindow(GetWindow(non_primary_host),
528 new_primary_display.GetWorkAreaInsets());
530 // Update the dispay manager with new display info.
531 std::vector<DisplayInfo> display_info_list;
532 display_info_list.push_back(display_manager->GetDisplayInfo(
533 primary_display_id));
534 display_info_list.push_back(display_manager->GetDisplayInfo(
535 ScreenUtil::GetSecondaryDisplay().id()));
536 GetDisplayManager()->set_force_bounds_changed(true);
537 GetDisplayManager()->UpdateDisplays(display_info_list);
538 GetDisplayManager()->set_force_bounds_changed(false);
541 void DisplayController::UpdateMouseLocationAfterDisplayChange() {
542 // If the mouse is currently on a display in native location,
543 // use the same native location. Otherwise find the display closest
544 // to the current cursor location in screen coordinates.
546 gfx::Point point_in_screen = Shell::GetScreen()->GetCursorScreenPoint();
547 gfx::Point target_location_in_native;
548 int64 closest_distance_squared = -1;
549 DisplayManager* display_manager = GetDisplayManager();
551 aura::Window* dst_root_window = NULL;
552 for (size_t i = 0; i < display_manager->GetNumDisplays(); ++i) {
553 const gfx::Display& display = display_manager->GetDisplayAt(i);
554 const DisplayInfo display_info =
555 display_manager->GetDisplayInfo(display.id());
556 aura::Window* root_window = GetRootWindowForDisplayId(display.id());
557 if (display_info.bounds_in_native().Contains(
558 cursor_location_in_native_coords_for_restore_)) {
559 dst_root_window = root_window;
560 target_location_in_native = cursor_location_in_native_coords_for_restore_;
561 break;
563 gfx::Point center = display.bounds().CenterPoint();
564 // Use the distance squared from the center of the dislay. This is not
565 // exactly "closest" display, but good enough to pick one
566 // appropriate (and there are at most two displays).
567 // We don't care about actual distance, only relative to other displays, so
568 // using the LengthSquared() is cheaper than Length().
570 int64 distance_squared = (center - point_in_screen).LengthSquared();
571 if (closest_distance_squared < 0 ||
572 closest_distance_squared > distance_squared) {
573 aura::Window* root_window = GetRootWindowForDisplayId(display.id());
574 ::wm::ConvertPointFromScreen(root_window, &center);
575 root_window->GetHost()->ConvertPointToNativeScreen(&center);
576 dst_root_window = root_window;
577 target_location_in_native = center;
578 closest_distance_squared = distance_squared;
582 gfx::Point target_location_in_root = target_location_in_native;
583 dst_root_window->GetHost()->ConvertPointFromNativeScreen(
584 &target_location_in_root);
586 #if defined(USE_OZONE)
587 gfx::Point target_location_in_screen = target_location_in_root;
588 ::wm::ConvertPointToScreen(dst_root_window, &target_location_in_screen);
589 const gfx::Display& target_display =
590 display_manager->FindDisplayContainingPoint(target_location_in_screen);
591 int64 target_display_id = target_display.id();
593 // Do not move the cursor if the cursor's location did not change. This avoids
594 // moving (and showing) the cursor:
595 // - At startup.
596 // - When the device is rotated in maximized mode.
597 // |cursor_display_id_for_restore_| is checked to ensure that the cursor is
598 // moved when the cursor's native position does not change but the display
599 // that it is on has changed. This occurs when swapping the primary display.
600 if (target_location_in_native !=
601 cursor_location_in_native_coords_for_restore_ ||
602 target_display_id != cursor_display_id_for_restore_) {
603 dst_root_window->MoveCursorTo(target_location_in_root);
604 } else if (target_location_in_screen !=
605 cursor_location_in_screen_coords_for_restore_) {
606 // The cursor's native position did not change but its screen position did
607 // change. This occurs when the scale factor or the rotation of the display
608 // that the cursor is on changes.
609 Shell::GetInstance()->cursor_manager()->SetDisplay(target_display);
611 // Update the cursor's root location. This ends up dispatching a synthetic
612 // mouse move. The synthetic mouse move updates the composited cursor's
613 // location and hover effects. Synthetic mouse moves do not affect the
614 // cursor's visibility.
615 dst_root_window->GetHost()->dispatcher()->OnCursorMovedToRootLocation(
616 target_location_in_root);
618 #else
619 dst_root_window->MoveCursorTo(target_location_in_root);
620 #endif
623 bool DisplayController::UpdateWorkAreaOfDisplayNearestWindow(
624 const aura::Window* window,
625 const gfx::Insets& insets) {
626 const aura::Window* root_window = window->GetRootWindow();
627 int64 id = GetRootWindowSettings(root_window)->display_id;
628 // if id is |kInvaildDisplayID|, it's being deleted.
629 DCHECK(id != gfx::Display::kInvalidDisplayID);
630 return GetDisplayManager()->UpdateWorkAreaOfDisplay(id, insets);
633 void DisplayController::OnDisplayAdded(const gfx::Display& display) {
634 if (primary_tree_host_for_replace_) {
635 DCHECK(window_tree_hosts_.empty());
636 primary_display_id = display.id();
637 window_tree_hosts_[display.id()] = primary_tree_host_for_replace_;
638 GetRootWindowSettings(GetWindow(primary_tree_host_for_replace_))
639 ->display_id = display.id();
640 primary_tree_host_for_replace_ = NULL;
641 const DisplayInfo& display_info =
642 GetDisplayManager()->GetDisplayInfo(display.id());
643 AshWindowTreeHost* ash_host = window_tree_hosts_[display.id()];
644 ash_host->AsWindowTreeHost()->SetBounds(display_info.bounds_in_native());
645 SetDisplayPropertiesOnHost(ash_host, display);
646 } else {
647 if (primary_display_id == gfx::Display::kInvalidDisplayID)
648 primary_display_id = display.id();
649 DCHECK(!window_tree_hosts_.empty());
650 AshWindowTreeHost* ash_host = AddWindowTreeHostForDisplay(
651 display, AshWindowTreeHostInitParams());
652 RootWindowController::CreateForSecondaryDisplay(ash_host);
656 void DisplayController::OnDisplayRemoved(const gfx::Display& display) {
657 AshWindowTreeHost* host_to_delete = window_tree_hosts_[display.id()];
658 CHECK(host_to_delete) << display.ToString();
660 // When the primary root window's display is removed, move the primary
661 // root to the other display.
662 if (primary_display_id == display.id()) {
663 // Temporarily store the primary root window in
664 // |primary_root_window_for_replace_| when replacing the display.
665 if (window_tree_hosts_.size() == 1) {
666 primary_display_id = gfx::Display::kInvalidDisplayID;
667 primary_tree_host_for_replace_ = host_to_delete;
668 // Display for root window will be deleted when the Primary RootWindow
669 // is deleted by the Shell.
670 window_tree_hosts_.erase(display.id());
671 return;
673 for (const auto& pair : window_tree_hosts_) {
674 if (pair.first != display.id()) {
675 primary_display_id = pair.first;
676 break;
679 CHECK_NE(gfx::Display::kInvalidDisplayID, primary_display_id);
681 AshWindowTreeHost* primary_host = host_to_delete;
682 // Delete the other host instead.
683 host_to_delete = window_tree_hosts_[primary_display_id];
684 GetRootWindowSettings(GetWindow(host_to_delete))->display_id = display.id();
686 // Setup primary root.
687 window_tree_hosts_[primary_display_id] = primary_host;
688 GetRootWindowSettings(GetWindow(primary_host))->display_id =
689 primary_display_id;
691 OnDisplayMetricsChanged(
692 GetDisplayManager()->GetDisplayForId(primary_display_id),
693 DISPLAY_METRIC_BOUNDS);
695 ClearDisplayPropertiesOnHost(host_to_delete, display);
696 RootWindowController* controller =
697 GetRootWindowController(GetWindow(host_to_delete));
698 DCHECK(controller);
699 controller->MoveWindowsTo(GetPrimaryRootWindow());
700 // Delete most of root window related objects, but don't delete
701 // root window itself yet because the stack may be using it.
702 controller->Shutdown();
703 base::MessageLoop::current()->DeleteSoon(FROM_HERE, controller);
705 // The window tree host should be erased at last because some handlers can
706 // access to the host through GetRootWindowForDisplayId() during
707 // MoveWindowsTo(). See http://crbug.com/415222
708 window_tree_hosts_.erase(display.id());
711 void DisplayController::OnDisplayMetricsChanged(const gfx::Display& display,
712 uint32_t metrics) {
713 if (!(metrics & (DISPLAY_METRIC_BOUNDS | DISPLAY_METRIC_ROTATION |
714 DISPLAY_METRIC_DEVICE_SCALE_FACTOR)))
715 return;
716 const DisplayInfo& display_info =
717 GetDisplayManager()->GetDisplayInfo(display.id());
718 DCHECK(!display_info.bounds_in_native().IsEmpty());
719 AshWindowTreeHost* ash_host = window_tree_hosts_[display.id()];
720 ash_host->AsWindowTreeHost()->SetBounds(display_info.bounds_in_native());
721 SetDisplayPropertiesOnHost(ash_host, display);
724 void DisplayController::OnHostResized(const aura::WindowTreeHost* host) {
725 gfx::Display display = Shell::GetScreen()->GetDisplayNearestWindow(
726 const_cast<aura::Window*>(host->window()));
728 DisplayManager* display_manager = GetDisplayManager();
729 if (display_manager->UpdateDisplayBounds(display.id(), host->GetBounds())) {
730 mirror_window_controller_->UpdateWindow();
731 cursor_window_controller_->UpdateContainer();
735 void DisplayController::CreateOrUpdateMirroringDisplay(
736 const DisplayInfo& info) {
737 switch (GetDisplayManager()->second_display_mode()) {
738 case DisplayManager::MIRRORING:
739 mirror_window_controller_->UpdateWindow(info);
740 cursor_window_controller_->UpdateContainer();
741 break;
742 case DisplayManager::EXTENDED:
743 NOTREACHED();
747 void DisplayController::CloseMirroringDisplay() {
748 mirror_window_controller_->Close();
749 // If cursor_compositing is enabled for large cursor, the cursor window is
750 // always on the desktop display (the visible cursor on the non-desktop
751 // display is drawn through compositor mirroring). Therefore, it's unnecessary
752 // to handle the cursor_window at all. See: http://crbug.com/412910
753 if (!cursor_window_controller_->is_cursor_compositing_enabled())
754 cursor_window_controller_->UpdateContainer();
757 void DisplayController::PreDisplayConfigurationChange(bool clear_focus) {
758 FOR_EACH_OBSERVER(Observer, observers_, OnDisplayConfigurationChanging());
759 focus_activation_store_->Store(clear_focus);
760 gfx::Screen* screen = Shell::GetScreen();
761 gfx::Point point_in_screen = screen->GetCursorScreenPoint();
762 cursor_location_in_screen_coords_for_restore_ = point_in_screen;
764 gfx::Display display = screen->GetDisplayNearestPoint(point_in_screen);
765 cursor_display_id_for_restore_ = display.id();
767 gfx::Point point_in_native = point_in_screen;
768 aura::Window* root_window = GetRootWindowForDisplayId(display.id());
769 ::wm::ConvertPointFromScreen(root_window, &point_in_native);
770 root_window->GetHost()->ConvertPointToNativeScreen(&point_in_native);
771 cursor_location_in_native_coords_for_restore_ = point_in_native;
774 void DisplayController::PostDisplayConfigurationChange() {
775 if (limiter_)
776 limiter_->SetThrottleTimeout(kAfterDisplayChangeThrottleTimeoutMs);
778 focus_activation_store_->Restore();
780 DisplayManager* display_manager = GetDisplayManager();
781 DisplayLayoutStore* layout_store = display_manager->layout_store();
782 if (display_manager->num_connected_displays() > 1) {
783 DisplayIdPair pair = display_manager->GetCurrentDisplayIdPair();
784 layout_store->UpdateMirrorStatus(pair, display_manager->IsMirrored());
785 DisplayLayout layout = layout_store->GetRegisteredDisplayLayout(pair);
787 if (Shell::GetScreen()->GetNumDisplays() > 1 ) {
788 int64 primary_id = layout.primary_id;
789 SetPrimaryDisplayId(
790 primary_id == gfx::Display::kInvalidDisplayID ?
791 pair.first : primary_id);
792 // Update the primary_id in case the above call is
793 // ignored. Happens when a) default layout's primary id
794 // doesn't exist, or b) the primary_id has already been
795 // set to the same and didn't update it.
796 layout_store->UpdatePrimaryDisplayId(
797 pair, Shell::GetScreen()->GetPrimaryDisplay().id());
800 FOR_EACH_OBSERVER(Observer, observers_, OnDisplayConfigurationChanged());
801 UpdateHostWindowNames();
802 UpdateMouseLocationAfterDisplayChange();
805 AshWindowTreeHost* DisplayController::AddWindowTreeHostForDisplay(
806 const gfx::Display& display,
807 const AshWindowTreeHostInitParams& init_params) {
808 static int host_count = 0;
809 const DisplayInfo& display_info =
810 GetDisplayManager()->GetDisplayInfo(display.id());
811 AshWindowTreeHostInitParams params_with_bounds(init_params);
812 params_with_bounds.initial_bounds = display_info.bounds_in_native();
813 AshWindowTreeHost* ash_host = AshWindowTreeHost::Create(params_with_bounds);
814 aura::WindowTreeHost* host = ash_host->AsWindowTreeHost();
816 host->window()->SetName(base::StringPrintf("RootWindow-%d", host_count++));
817 host->window()->SetTitle(base::UTF8ToUTF16(display_info.name()));
818 host->compositor()->SetBackgroundColor(SK_ColorBLACK);
819 // No need to remove our observer observer because the DisplayController
820 // outlives the host.
821 host->AddObserver(this);
822 InitRootWindowSettings(host->window())->display_id = display.id();
823 host->InitHost();
825 window_tree_hosts_[display.id()] = ash_host;
826 SetDisplayPropertiesOnHost(ash_host, display);
828 #if defined(OS_CHROMEOS)
829 static bool force_constrain_pointer_to_root =
830 base::CommandLine::ForCurrentProcess()->HasSwitch(
831 switches::kAshConstrainPointerToRoot);
832 if (base::SysInfo::IsRunningOnChromeOS() || force_constrain_pointer_to_root)
833 ash_host->ConfineCursorToRootWindow();
834 #endif
835 return ash_host;
838 void DisplayController::OnFadeOutForSwapDisplayFinished() {
839 #if defined(OS_CHROMEOS)
840 SetPrimaryDisplay(ScreenUtil::GetSecondaryDisplay());
841 Shell::GetInstance()->display_configurator_animation()
842 ->StartFadeInAnimation();
843 #endif
846 void DisplayController::SetMirrorModeAfterAnimation(bool mirror) {
847 GetDisplayManager()->SetMirrorMode(mirror);
850 void DisplayController::UpdateHostWindowNames() {
851 #if defined(USE_X11)
852 // crbug.com/120229 - set the window title for the primary dislpay
853 // to "aura_root_0" so gtalk can find the primary root window to broadcast.
854 // TODO(jhorwich) Remove this once Chrome supports window-based broadcasting.
855 aura::Window* primary = Shell::GetPrimaryRootWindow();
856 aura::Window::Windows root_windows = Shell::GetAllRootWindows();
857 for (size_t i = 0; i < root_windows.size(); ++i) {
858 std::string name =
859 root_windows[i] == primary ? "aura_root_0" : "aura_root_x";
860 gfx::AcceleratedWidget xwindow =
861 root_windows[i]->GetHost()->GetAcceleratedWidget();
862 XStoreName(gfx::GetXDisplay(), xwindow, name.c_str());
864 #endif
867 } // namespace ash