Don't preload rarely seen large images
[chromium-blink-merge.git] / ash / display / display_controller.cc
blobf2f84eaef248348f2cc531527d1fa68133ad3588
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/ime/input_method_event_handler.h"
21 #include "ash/magnifier/magnification_controller.h"
22 #include "ash/magnifier/partial_magnification_controller.h"
23 #include "ash/root_window_controller.h"
24 #include "ash/root_window_settings.h"
25 #include "ash/screen_util.h"
26 #include "ash/shell.h"
27 #include "ash/shell_delegate.h"
28 #include "ash/system/tray/system_tray.h"
29 #include "ash/wm/coordinate_conversion.h"
30 #include "ash/wm/window_util.h"
31 #include "base/command_line.h"
32 #include "base/stl_util.h"
33 #include "base/strings/stringprintf.h"
34 #include "base/strings/utf_string_conversions.h"
35 #include "ui/aura/client/capture_client.h"
36 #include "ui/aura/client/focus_client.h"
37 #include "ui/aura/client/screen_position_client.h"
38 #include "ui/aura/window.h"
39 #include "ui/aura/window_event_dispatcher.h"
40 #include "ui/aura/window_property.h"
41 #include "ui/aura/window_tracker.h"
42 #include "ui/aura/window_tree_host.h"
43 #include "ui/base/ime/input_method_factory.h"
44 #include "ui/compositor/compositor.h"
45 #include "ui/gfx/display.h"
46 #include "ui/gfx/screen.h"
47 #include "ui/wm/core/coordinate_conversion.h"
48 #include "ui/wm/public/activation_client.h"
50 #if defined(OS_CHROMEOS)
51 #include "ash/display/display_configurator_animation.h"
52 #include "base/sys_info.h"
53 #include "base/time/time.h"
54 #endif // defined(OS_CHROMEOS)
56 #if defined(USE_X11)
57 #include "ui/base/x/x11_util.h"
58 #include "ui/gfx/x/x11_types.h"
60 // Including this at the bottom to avoid other
61 // potential conflict with chrome headers.
62 #include <X11/extensions/Xrandr.h>
63 #undef RootWindow
64 #endif // defined(USE_X11)
66 #if defined(OS_CHROMEOS) && defined(USE_OZONE)
67 #include "ui/events/ozone/chromeos/cursor_controller.h"
68 #endif
70 namespace ash {
71 namespace {
73 // Primary display stored in global object as it can be
74 // accessed after Shell is deleted. A separate display instance is created
75 // during the shutdown instead of always keeping two display instances
76 // (one here and another one in display_manager) in sync, which is error prone.
77 // This is initialized in the constructor, and then in CreatePrimaryHost().
78 int64 primary_display_id = -1;
80 // Specifies how long the display change should have been disabled
81 // after each display change operations.
82 // |kCycleDisplayThrottleTimeoutMs| is set to be longer to avoid
83 // changing the settings while the system is still configurating
84 // displays. It will be overriden by |kAfterDisplayChangeThrottleTimeoutMs|
85 // when the display change happens, so the actual timeout is much shorter.
86 const int64 kAfterDisplayChangeThrottleTimeoutMs = 500;
87 const int64 kCycleDisplayThrottleTimeoutMs = 4000;
88 const int64 kSwapDisplayThrottleTimeoutMs = 500;
90 #if defined(USE_OZONE) && defined(OS_CHROMEOS)
91 // Add 20% more cursor motion on non-integrated displays.
92 const float kCursorMultiplierForExternalDisplays = 1.2f;
93 #endif
95 DisplayManager* GetDisplayManager() {
96 return Shell::GetInstance()->display_manager();
99 void SetDisplayPropertiesOnHost(AshWindowTreeHost* ash_host,
100 const gfx::Display& display) {
101 DisplayInfo info = GetDisplayManager()->GetDisplayInfo(display.id());
102 aura::WindowTreeHost* host = ash_host->AsWindowTreeHost();
103 #if defined(OS_CHROMEOS)
104 #if defined(USE_X11)
105 // Native window property (Atom in X11) that specifies the display's
106 // rotation, scale factor and if it's internal display. They are
107 // read and used by touchpad/mouse driver directly on X (contact
108 // adlr@ for more details on touchpad/mouse driver side). The value
109 // of the rotation is one of 0 (normal), 1 (90 degrees clockwise), 2
110 // (180 degree) or 3 (270 degrees clockwise). The value of the
111 // scale factor is in percent (100, 140, 200 etc).
112 const char kRotationProp[] = "_CHROME_DISPLAY_ROTATION";
113 const char kScaleFactorProp[] = "_CHROME_DISPLAY_SCALE_FACTOR";
114 const char kInternalProp[] = "_CHROME_DISPLAY_INTERNAL";
115 const char kCARDINAL[] = "CARDINAL";
116 int xrandr_rotation = RR_Rotate_0;
117 switch (info.GetActiveRotation()) {
118 case gfx::Display::ROTATE_0:
119 xrandr_rotation = RR_Rotate_0;
120 break;
121 case gfx::Display::ROTATE_90:
122 xrandr_rotation = RR_Rotate_90;
123 break;
124 case gfx::Display::ROTATE_180:
125 xrandr_rotation = RR_Rotate_180;
126 break;
127 case gfx::Display::ROTATE_270:
128 xrandr_rotation = RR_Rotate_270;
129 break;
132 int internal = display.IsInternal() ? 1 : 0;
133 gfx::AcceleratedWidget xwindow = host->GetAcceleratedWidget();
134 ui::SetIntProperty(xwindow, kInternalProp, kCARDINAL, internal);
135 ui::SetIntProperty(xwindow, kRotationProp, kCARDINAL, xrandr_rotation);
136 ui::SetIntProperty(xwindow,
137 kScaleFactorProp,
138 kCARDINAL,
139 100 * display.device_scale_factor());
140 #elif defined(USE_OZONE)
141 // Scale all motion on High-DPI displays.
142 float scale = display.device_scale_factor();
144 if (!display.IsInternal())
145 scale *= kCursorMultiplierForExternalDisplays;
147 ui::CursorController::GetInstance()->SetCursorConfigForWindow(
148 host->GetAcceleratedWidget(), info.GetActiveRotation(), scale);
149 #endif
150 #endif
151 scoped_ptr<RootWindowTransformer> transformer(
152 CreateRootWindowTransformerForDisplay(host->window(), display));
153 ash_host->SetRootWindowTransformer(transformer.Pass());
155 DisplayMode mode =
156 GetDisplayManager()->GetActiveModeForDisplayId(display.id());
157 if (mode.refresh_rate > 0.0f) {
158 host->compositor()->SetAuthoritativeVSyncInterval(
159 base::TimeDelta::FromMicroseconds(base::Time::kMicrosecondsPerSecond /
160 mode.refresh_rate));
163 // Just movnig the display requires the full redraw.
164 // chrome-os-partner:33558.
165 host->compositor()->ScheduleFullRedraw();
168 void ClearDisplayPropertiesOnHost(AshWindowTreeHost* ash_host) {
169 #if defined(OS_CHROMEOS) && defined(USE_OZONE)
170 aura::WindowTreeHost* host = ash_host->AsWindowTreeHost();
171 ui::CursorController::GetInstance()->ClearCursorConfigForWindow(
172 host->GetAcceleratedWidget());
173 #endif
176 aura::Window* GetWindow(AshWindowTreeHost* ash_host) {
177 CHECK(ash_host->AsWindowTreeHost());
178 return ash_host->AsWindowTreeHost()->window();
181 } // namespace
183 // A utility class to store/restore focused/active window
184 // when the display configuration has changed.
185 class FocusActivationStore {
186 public:
187 FocusActivationStore()
188 : activation_client_(nullptr),
189 capture_client_(nullptr),
190 focus_client_(nullptr),
191 focused_(nullptr),
192 active_(nullptr) {}
194 void Store(bool clear_focus) {
195 if (!activation_client_) {
196 aura::Window* root = Shell::GetPrimaryRootWindow();
197 activation_client_ = aura::client::GetActivationClient(root);
198 capture_client_ = aura::client::GetCaptureClient(root);
199 focus_client_ = aura::client::GetFocusClient(root);
201 focused_ = focus_client_->GetFocusedWindow();
202 if (focused_)
203 tracker_.Add(focused_);
204 active_ = activation_client_->GetActiveWindow();
205 if (active_ && focused_ != active_)
206 tracker_.Add(active_);
208 // Deactivate the window to close menu / bubble windows.
209 if (clear_focus)
210 activation_client_->DeactivateWindow(active_);
212 // Release capture if any.
213 capture_client_->SetCapture(nullptr);
214 // Clear the focused window if any. This is necessary because a
215 // window may be deleted when losing focus (fullscreen flash for
216 // example). If the focused window is still alive after move, it'll
217 // be re-focused below.
218 if (clear_focus)
219 focus_client_->FocusWindow(nullptr);
222 void Restore() {
223 // Restore focused or active window if it's still alive.
224 if (focused_ && tracker_.Contains(focused_)) {
225 focus_client_->FocusWindow(focused_);
226 } else if (active_ && tracker_.Contains(active_)) {
227 activation_client_->ActivateWindow(active_);
229 if (focused_)
230 tracker_.Remove(focused_);
231 if (active_)
232 tracker_.Remove(active_);
233 focused_ = nullptr;
234 active_ = nullptr;
237 private:
238 aura::client::ActivationClient* activation_client_;
239 aura::client::CaptureClient* capture_client_;
240 aura::client::FocusClient* focus_client_;
241 aura::WindowTracker tracker_;
242 aura::Window* focused_;
243 aura::Window* active_;
245 DISALLOW_COPY_AND_ASSIGN(FocusActivationStore);
248 ////////////////////////////////////////////////////////////////////////////////
249 // DisplayChangeLimiter
251 DisplayController::DisplayChangeLimiter::DisplayChangeLimiter()
252 : throttle_timeout_(base::Time::Now()) {
255 void DisplayController::DisplayChangeLimiter::SetThrottleTimeout(
256 int64 throttle_ms) {
257 throttle_timeout_ =
258 base::Time::Now() + base::TimeDelta::FromMilliseconds(throttle_ms);
261 bool DisplayController::DisplayChangeLimiter::IsThrottled() const {
262 return base::Time::Now() < throttle_timeout_;
265 ////////////////////////////////////////////////////////////////////////////////
266 // DisplayController
268 DisplayController::DisplayController()
269 : primary_tree_host_for_replace_(nullptr),
270 focus_activation_store_(new FocusActivationStore()),
271 cursor_window_controller_(new CursorWindowController()),
272 mirror_window_controller_(new MirrorWindowController()),
273 cursor_display_id_for_restore_(gfx::Display::kInvalidDisplayID),
274 weak_ptr_factory_(this) {
275 #if defined(OS_CHROMEOS)
276 if (base::SysInfo::IsRunningOnChromeOS())
277 limiter_.reset(new DisplayChangeLimiter);
278 #endif
279 // Reset primary display to make sure that tests don't use
280 // stale display info from previous tests.
281 primary_display_id = gfx::Display::kInvalidDisplayID;
284 DisplayController::~DisplayController() {
287 void DisplayController::Start() {
288 Shell::GetScreen()->AddObserver(this);
289 Shell::GetInstance()->display_manager()->set_delegate(this);
292 void DisplayController::Shutdown() {
293 // Unset the display manager's delegate here because
294 // DisplayManager outlives DisplayController.
295 Shell::GetInstance()->display_manager()->set_delegate(nullptr);
297 cursor_window_controller_.reset();
298 mirror_window_controller_.reset();
300 Shell::GetScreen()->RemoveObserver(this);
302 int64 primary_id = Shell::GetScreen()->GetPrimaryDisplay().id();
304 // Delete non primary root window controllers first, then
305 // delete the primary root window controller.
306 aura::Window::Windows root_windows = DisplayController::GetAllRootWindows();
307 std::vector<RootWindowController*> to_delete;
308 RootWindowController* primary_rwc = nullptr;
309 for (aura::Window::Windows::iterator iter = root_windows.begin();
310 iter != root_windows.end();
311 ++iter) {
312 RootWindowController* rwc = GetRootWindowController(*iter);
313 if (GetRootWindowSettings(*iter)->display_id == primary_id)
314 primary_rwc = rwc;
315 else
316 to_delete.push_back(rwc);
318 CHECK(primary_rwc);
320 STLDeleteElements(&to_delete);
321 delete primary_rwc;
324 void DisplayController::CreatePrimaryHost(
325 const AshWindowTreeHostInitParams& init_params) {
326 const gfx::Display& primary_candidate =
327 GetDisplayManager()->GetPrimaryDisplayCandidate();
328 primary_display_id = primary_candidate.id();
329 CHECK_NE(gfx::Display::kInvalidDisplayID, primary_display_id);
330 AddWindowTreeHostForDisplay(primary_candidate, init_params);
333 void DisplayController::InitDisplays() {
334 RootWindowController::CreateForPrimaryDisplay(
335 window_tree_hosts_[primary_display_id]);
336 DisplayManager* display_manager = GetDisplayManager();
337 for (size_t i = 0; i < display_manager->GetNumDisplays(); ++i) {
338 const gfx::Display& display = display_manager->GetDisplayAt(i);
339 if (primary_display_id != display.id()) {
340 AshWindowTreeHost* ash_host = AddWindowTreeHostForDisplay(
341 display, AshWindowTreeHostInitParams());
342 RootWindowController::CreateForSecondaryDisplay(ash_host);
346 FOR_EACH_OBSERVER(Observer, observers_, OnDisplaysInitialized());
349 void DisplayController::AddObserver(Observer* observer) {
350 observers_.AddObserver(observer);
353 void DisplayController::RemoveObserver(Observer* observer) {
354 observers_.RemoveObserver(observer);
357 // static
358 int64 DisplayController::GetPrimaryDisplayId() {
359 CHECK_NE(gfx::Display::kInvalidDisplayID, primary_display_id);
360 return primary_display_id;
363 aura::Window* DisplayController::GetPrimaryRootWindow() {
364 return GetRootWindowForDisplayId(primary_display_id);
367 aura::Window* DisplayController::GetRootWindowForDisplayId(int64 id) {
368 AshWindowTreeHost* host = GetAshWindowTreeHostForDisplayId(id);
369 CHECK(host);
370 return GetWindow(host);
373 AshWindowTreeHost* DisplayController::GetAshWindowTreeHostForDisplayId(
374 int64 display_id) {
375 CHECK_EQ(1u, window_tree_hosts_.count(display_id))
376 << "display id = " << display_id;
377 return window_tree_hosts_[display_id];
380 void DisplayController::CloseChildWindows() {
381 for (WindowTreeHostMap::const_iterator it = window_tree_hosts_.begin();
382 it != window_tree_hosts_.end();
383 ++it) {
384 aura::Window* root_window = GetWindow(it->second);
385 RootWindowController* controller = GetRootWindowController(root_window);
386 if (controller) {
387 controller->CloseChildWindows();
388 } else {
389 while (!root_window->children().empty()) {
390 aura::Window* child = root_window->children()[0];
391 delete child;
397 aura::Window::Windows DisplayController::GetAllRootWindows() {
398 aura::Window::Windows windows;
399 for (WindowTreeHostMap::const_iterator it = window_tree_hosts_.begin();
400 it != window_tree_hosts_.end();
401 ++it) {
402 DCHECK(it->second);
403 if (GetRootWindowController(GetWindow(it->second)))
404 windows.push_back(GetWindow(it->second));
406 return windows;
409 gfx::Insets DisplayController::GetOverscanInsets(int64 display_id) const {
410 return GetDisplayManager()->GetOverscanInsets(display_id);
413 void DisplayController::SetOverscanInsets(int64 display_id,
414 const gfx::Insets& insets_in_dip) {
415 GetDisplayManager()->SetOverscanInsets(display_id, insets_in_dip);
418 std::vector<RootWindowController*>
419 DisplayController::GetAllRootWindowControllers() {
420 std::vector<RootWindowController*> controllers;
421 for (WindowTreeHostMap::const_iterator it = window_tree_hosts_.begin();
422 it != window_tree_hosts_.end();
423 ++it) {
424 RootWindowController* controller =
425 GetRootWindowController(GetWindow(it->second));
426 if (controller)
427 controllers.push_back(controller);
429 return controllers;
432 void DisplayController::ToggleMirrorMode() {
433 DisplayManager* display_manager = GetDisplayManager();
434 if (display_manager->num_connected_displays() <= 1)
435 return;
437 if (limiter_) {
438 if (limiter_->IsThrottled())
439 return;
440 limiter_->SetThrottleTimeout(kCycleDisplayThrottleTimeoutMs);
442 #if defined(OS_CHROMEOS)
443 Shell* shell = Shell::GetInstance();
444 DisplayConfiguratorAnimation* animation =
445 shell->display_configurator_animation();
446 animation->StartFadeOutAnimation(base::Bind(
447 &DisplayController::SetMirrorModeAfterAnimation,
448 weak_ptr_factory_.GetWeakPtr(), !display_manager->IsInMirrorMode()));
449 #endif
452 void DisplayController::SwapPrimaryDisplay() {
453 if (limiter_) {
454 if (limiter_->IsThrottled())
455 return;
456 limiter_->SetThrottleTimeout(kSwapDisplayThrottleTimeoutMs);
459 if (Shell::GetScreen()->GetNumDisplays() > 1) {
460 #if defined(OS_CHROMEOS)
461 DisplayConfiguratorAnimation* animation =
462 Shell::GetInstance()->display_configurator_animation();
463 if (animation) {
464 animation->StartFadeOutAnimation(base::Bind(
465 &DisplayController::OnFadeOutForSwapDisplayFinished,
466 weak_ptr_factory_.GetWeakPtr()));
467 } else {
468 SetPrimaryDisplay(ScreenUtil::GetSecondaryDisplay());
470 #else
471 SetPrimaryDisplay(ScreenUtil::GetSecondaryDisplay());
472 #endif
476 void DisplayController::SetPrimaryDisplayId(int64 id) {
477 DCHECK_NE(gfx::Display::kInvalidDisplayID, id);
478 if (id == gfx::Display::kInvalidDisplayID || primary_display_id == id)
479 return;
481 const gfx::Display& display = GetDisplayManager()->GetDisplayForId(id);
482 if (display.is_valid())
483 SetPrimaryDisplay(display);
486 void DisplayController::SetPrimaryDisplay(
487 const gfx::Display& new_primary_display) {
488 DisplayManager* display_manager = GetDisplayManager();
489 DCHECK(new_primary_display.is_valid());
490 DCHECK(display_manager->GetDisplayForId(new_primary_display.id()).is_valid());
492 if (!new_primary_display.is_valid() ||
493 !display_manager->GetDisplayForId(new_primary_display.id()).is_valid()) {
494 LOG(ERROR) << "Invalid or non-existent display is requested:"
495 << new_primary_display.ToString();
496 return;
499 if (primary_display_id == new_primary_display.id() ||
500 window_tree_hosts_.size() < 2) {
501 return;
504 AshWindowTreeHost* non_primary_host =
505 window_tree_hosts_[new_primary_display.id()];
506 LOG_IF(ERROR, !non_primary_host)
507 << "Unknown display is requested in SetPrimaryDisplay: id="
508 << new_primary_display.id();
509 if (!non_primary_host)
510 return;
512 gfx::Display old_primary_display = Shell::GetScreen()->GetPrimaryDisplay();
514 // Swap root windows between current and new primary display.
515 AshWindowTreeHost* primary_host = window_tree_hosts_[primary_display_id];
516 CHECK(primary_host);
517 CHECK_NE(primary_host, non_primary_host);
519 window_tree_hosts_[new_primary_display.id()] = primary_host;
520 GetRootWindowSettings(GetWindow(primary_host))->display_id =
521 new_primary_display.id();
523 window_tree_hosts_[old_primary_display.id()] = non_primary_host;
524 GetRootWindowSettings(GetWindow(non_primary_host))->display_id =
525 old_primary_display.id();
527 primary_display_id = new_primary_display.id();
528 GetDisplayManager()->layout_store()->UpdatePrimaryDisplayId(
529 display_manager->GetCurrentDisplayIdPair(), primary_display_id);
531 UpdateWorkAreaOfDisplayNearestWindow(GetWindow(primary_host),
532 old_primary_display.GetWorkAreaInsets());
533 UpdateWorkAreaOfDisplayNearestWindow(GetWindow(non_primary_host),
534 new_primary_display.GetWorkAreaInsets());
536 // Update the dispay manager with new display info.
537 std::vector<DisplayInfo> display_info_list;
538 display_info_list.push_back(display_manager->GetDisplayInfo(
539 primary_display_id));
540 display_info_list.push_back(display_manager->GetDisplayInfo(
541 ScreenUtil::GetSecondaryDisplay().id()));
542 GetDisplayManager()->set_force_bounds_changed(true);
543 GetDisplayManager()->UpdateDisplays(display_info_list);
544 GetDisplayManager()->set_force_bounds_changed(false);
547 void DisplayController::UpdateMouseLocationAfterDisplayChange() {
548 // If the mouse is currently on a display in native location,
549 // use the same native location. Otherwise find the display closest
550 // to the current cursor location in screen coordinates.
552 gfx::Point point_in_screen = Shell::GetScreen()->GetCursorScreenPoint();
553 gfx::Point target_location_in_native;
554 int64 closest_distance_squared = -1;
555 DisplayManager* display_manager = GetDisplayManager();
557 aura::Window* dst_root_window = nullptr;
558 for (size_t i = 0; i < display_manager->GetNumDisplays(); ++i) {
559 const gfx::Display& display = display_manager->GetDisplayAt(i);
560 const DisplayInfo display_info =
561 display_manager->GetDisplayInfo(display.id());
562 aura::Window* root_window = GetRootWindowForDisplayId(display.id());
563 if (display_info.bounds_in_native().Contains(
564 cursor_location_in_native_coords_for_restore_)) {
565 dst_root_window = root_window;
566 target_location_in_native = cursor_location_in_native_coords_for_restore_;
567 break;
569 gfx::Point center = display.bounds().CenterPoint();
570 // Use the distance squared from the center of the dislay. This is not
571 // exactly "closest" display, but good enough to pick one
572 // appropriate (and there are at most two displays).
573 // We don't care about actual distance, only relative to other displays, so
574 // using the LengthSquared() is cheaper than Length().
576 int64 distance_squared = (center - point_in_screen).LengthSquared();
577 if (closest_distance_squared < 0 ||
578 closest_distance_squared > distance_squared) {
579 aura::Window* root_window = GetRootWindowForDisplayId(display.id());
580 ::wm::ConvertPointFromScreen(root_window, &center);
581 root_window->GetHost()->ConvertPointToNativeScreen(&center);
582 dst_root_window = root_window;
583 target_location_in_native = center;
584 closest_distance_squared = distance_squared;
588 gfx::Point target_location_in_root = target_location_in_native;
589 dst_root_window->GetHost()->ConvertPointFromNativeScreen(
590 &target_location_in_root);
592 #if defined(USE_OZONE)
593 gfx::Point target_location_in_screen = target_location_in_root;
594 ::wm::ConvertPointToScreen(dst_root_window, &target_location_in_screen);
595 const gfx::Display& target_display =
596 display_manager->FindDisplayContainingPoint(target_location_in_screen);
597 // If the original location isn't on any of new display, let ozone move
598 // the cursor.
599 if (!target_display.is_valid())
600 return;
601 int64 target_display_id = target_display.id();
603 // Do not move the cursor if the cursor's location did not change. This avoids
604 // moving (and showing) the cursor:
605 // - At startup.
606 // - When the device is rotated in maximized mode.
607 // |cursor_display_id_for_restore_| is checked to ensure that the cursor is
608 // moved when the cursor's native position does not change but the display
609 // that it is on has changed. This occurs when swapping the primary display.
610 if (target_location_in_native !=
611 cursor_location_in_native_coords_for_restore_ ||
612 target_display_id != cursor_display_id_for_restore_) {
613 dst_root_window->MoveCursorTo(target_location_in_root);
614 } else if (target_location_in_screen !=
615 cursor_location_in_screen_coords_for_restore_) {
616 // The cursor's native position did not change but its screen position did
617 // change. This occurs when the scale factor or the rotation of the display
618 // that the cursor is on changes.
619 Shell::GetInstance()->cursor_manager()->SetDisplay(target_display);
621 // Update the cursor's root location. This ends up dispatching a synthetic
622 // mouse move. The synthetic mouse move updates the composited cursor's
623 // location and hover effects. Synthetic mouse moves do not affect the
624 // cursor's visibility.
625 dst_root_window->GetHost()->dispatcher()->OnCursorMovedToRootLocation(
626 target_location_in_root);
628 #else
629 dst_root_window->MoveCursorTo(target_location_in_root);
630 #endif
633 bool DisplayController::UpdateWorkAreaOfDisplayNearestWindow(
634 const aura::Window* window,
635 const gfx::Insets& insets) {
636 const aura::Window* root_window = window->GetRootWindow();
637 int64 id = GetRootWindowSettings(root_window)->display_id;
638 // if id is |kInvaildDisplayID|, it's being deleted.
639 DCHECK(id != gfx::Display::kInvalidDisplayID);
640 return GetDisplayManager()->UpdateWorkAreaOfDisplay(id, insets);
643 void DisplayController::OnDisplayAdded(const gfx::Display& display) {
644 #if defined(OS_CHROMEOS)
645 // If we're switching from/to offscreen WTH, we need to
646 // create new WTH for primary display instead of reusing.
647 if (primary_tree_host_for_replace_ &&
648 (GetRootWindowSettings(GetWindow(primary_tree_host_for_replace_))
649 ->display_id == DisplayManager::kUnifiedDisplayId ||
650 display.id() == DisplayManager::kUnifiedDisplayId)) {
651 DCHECK_EQ(gfx::Display::kInvalidDisplayID, primary_display_id);
652 primary_display_id = display.id();
654 AshWindowTreeHost* ash_host =
655 AddWindowTreeHostForDisplay(display, AshWindowTreeHostInitParams());
656 RootWindowController::CreateForSecondaryDisplay(ash_host);
658 // Magnifier controllers keep pointers to the current root window.
659 // Update them here to avoid accessing them later.
660 Shell::GetInstance()->magnification_controller()->SwitchTargetRootWindow(
661 ash_host->AsWindowTreeHost()->window(), false);
662 Shell::GetInstance()
663 ->partial_magnification_controller()
664 ->SwitchTargetRootWindow(ash_host->AsWindowTreeHost()->window());
666 AshWindowTreeHost* to_delete = primary_tree_host_for_replace_;
667 primary_tree_host_for_replace_ = nullptr;
669 // Show the shelf if the original WTH had a visible system
670 // tray. It may or may not be visible depending on OOBE state.
671 ash::SystemTray* old_tray =
672 GetRootWindowController(to_delete->AsWindowTreeHost()->window())
673 ->GetSystemTray();
674 ash::SystemTray* new_tray =
675 ash::Shell::GetInstance()->GetPrimarySystemTray();
676 if (old_tray->GetWidget()->IsVisible()) {
677 new_tray->SetVisible(true);
678 new_tray->GetWidget()->Show();
681 DeleteHost(to_delete);
682 #ifndef NDEBUG
683 auto iter = std::find_if(
684 window_tree_hosts_.begin(), window_tree_hosts_.end(),
685 [to_delete](const std::pair<int64, AshWindowTreeHost*>& pair) {
686 return pair.second == to_delete;
688 DCHECK(iter == window_tree_hosts_.end());
689 #endif
690 // the host has already been removed from the window_tree_host_.
691 } else
692 #endif
693 // TODO(oshima): It should be possible to consolidate logic for
694 // unified and non unified, but I'm keeping them separated to minimize
695 // the risk in M44. I'll consolidate this in M45.
696 if (primary_tree_host_for_replace_) {
697 DCHECK(window_tree_hosts_.empty());
698 primary_display_id = display.id();
699 window_tree_hosts_[display.id()] = primary_tree_host_for_replace_;
700 GetRootWindowSettings(GetWindow(primary_tree_host_for_replace_))
701 ->display_id = display.id();
702 primary_tree_host_for_replace_ = nullptr;
703 const DisplayInfo& display_info =
704 GetDisplayManager()->GetDisplayInfo(display.id());
705 AshWindowTreeHost* ash_host = window_tree_hosts_[display.id()];
706 ash_host->AsWindowTreeHost()->SetBounds(display_info.bounds_in_native());
707 SetDisplayPropertiesOnHost(ash_host, display);
708 } else {
709 if (primary_display_id == gfx::Display::kInvalidDisplayID)
710 primary_display_id = display.id();
711 DCHECK(!window_tree_hosts_.empty());
712 AshWindowTreeHost* ash_host =
713 AddWindowTreeHostForDisplay(display, AshWindowTreeHostInitParams());
714 RootWindowController::CreateForSecondaryDisplay(ash_host);
718 void DisplayController::DeleteHost(AshWindowTreeHost* host_to_delete) {
719 ClearDisplayPropertiesOnHost(host_to_delete);
720 RootWindowController* controller =
721 GetRootWindowController(GetWindow(host_to_delete));
722 DCHECK(controller);
723 controller->MoveWindowsTo(GetPrimaryRootWindow());
724 // Delete most of root window related objects, but don't delete
725 // root window itself yet because the stack may be using it.
726 controller->Shutdown();
727 base::MessageLoop::current()->DeleteSoon(FROM_HERE, controller);
730 void DisplayController::OnDisplayRemoved(const gfx::Display& display) {
731 AshWindowTreeHost* host_to_delete = window_tree_hosts_[display.id()];
732 CHECK(host_to_delete) << display.ToString();
734 // When the primary root window's display is removed, move the primary
735 // root to the other display.
736 if (primary_display_id == display.id()) {
737 // Temporarily store the primary root window in
738 // |primary_root_window_for_replace_| when replacing the display.
739 if (window_tree_hosts_.size() == 1) {
740 primary_display_id = gfx::Display::kInvalidDisplayID;
741 primary_tree_host_for_replace_ = host_to_delete;
742 // Display for root window will be deleted when the Primary RootWindow
743 // is deleted by the Shell.
744 window_tree_hosts_.erase(display.id());
745 return;
747 for (const auto& pair : window_tree_hosts_) {
748 if (pair.first != display.id()) {
749 primary_display_id = pair.first;
750 break;
753 CHECK_NE(gfx::Display::kInvalidDisplayID, primary_display_id);
755 AshWindowTreeHost* primary_host = host_to_delete;
756 // Delete the other host instead.
757 host_to_delete = window_tree_hosts_[primary_display_id];
758 GetRootWindowSettings(GetWindow(host_to_delete))->display_id = display.id();
760 // Setup primary root.
761 window_tree_hosts_[primary_display_id] = primary_host;
762 GetRootWindowSettings(GetWindow(primary_host))->display_id =
763 primary_display_id;
765 OnDisplayMetricsChanged(
766 GetDisplayManager()->GetDisplayForId(primary_display_id),
767 DISPLAY_METRIC_BOUNDS);
770 DeleteHost(host_to_delete);
772 // The window tree host should be erased at last because some handlers can
773 // access to the host through GetRootWindowForDisplayId() during
774 // MoveWindowsTo(). See http://crbug.com/415222
775 window_tree_hosts_.erase(display.id());
778 void DisplayController::OnDisplayMetricsChanged(const gfx::Display& display,
779 uint32_t metrics) {
780 if (!(metrics & (DISPLAY_METRIC_BOUNDS | DISPLAY_METRIC_ROTATION |
781 DISPLAY_METRIC_DEVICE_SCALE_FACTOR)))
782 return;
783 const DisplayInfo& display_info =
784 GetDisplayManager()->GetDisplayInfo(display.id());
785 DCHECK(!display_info.bounds_in_native().IsEmpty());
786 AshWindowTreeHost* ash_host = window_tree_hosts_[display.id()];
787 ash_host->AsWindowTreeHost()->SetBounds(display_info.bounds_in_native());
788 SetDisplayPropertiesOnHost(ash_host, display);
791 void DisplayController::OnHostResized(const aura::WindowTreeHost* host) {
792 gfx::Display display = Shell::GetScreen()->GetDisplayNearestWindow(
793 const_cast<aura::Window*>(host->window()));
795 DisplayManager* display_manager = GetDisplayManager();
796 if (display_manager->UpdateDisplayBounds(display.id(), host->GetBounds())) {
797 mirror_window_controller_->UpdateWindow();
798 cursor_window_controller_->UpdateContainer();
802 void DisplayController::CreateOrUpdateMirroringDisplay(
803 const DisplayInfoList& info_list) {
804 if (GetDisplayManager()->IsInMirrorMode() ||
805 GetDisplayManager()->IsInUnifiedMode()) {
806 mirror_window_controller_->UpdateWindow(info_list);
807 cursor_window_controller_->UpdateContainer();
808 } else {
809 NOTREACHED();
813 void DisplayController::CloseMirroringDisplayIfNotNecessary() {
814 mirror_window_controller_->CloseIfNotNecessary();
815 // If cursor_compositing is enabled for large cursor, the cursor window is
816 // always on the desktop display (the visible cursor on the non-desktop
817 // display is drawn through compositor mirroring). Therefore, it's unnecessary
818 // to handle the cursor_window at all. See: http://crbug.com/412910
819 if (!cursor_window_controller_->is_cursor_compositing_enabled())
820 cursor_window_controller_->UpdateContainer();
823 void DisplayController::PreDisplayConfigurationChange(bool clear_focus) {
824 FOR_EACH_OBSERVER(Observer, observers_, OnDisplayConfigurationChanging());
825 focus_activation_store_->Store(clear_focus);
826 gfx::Screen* screen = Shell::GetScreen();
827 gfx::Point point_in_screen = screen->GetCursorScreenPoint();
828 cursor_location_in_screen_coords_for_restore_ = point_in_screen;
830 gfx::Display display = screen->GetDisplayNearestPoint(point_in_screen);
831 cursor_display_id_for_restore_ = display.id();
833 gfx::Point point_in_native = point_in_screen;
834 aura::Window* root_window = GetRootWindowForDisplayId(display.id());
835 ::wm::ConvertPointFromScreen(root_window, &point_in_native);
836 root_window->GetHost()->ConvertPointToNativeScreen(&point_in_native);
837 cursor_location_in_native_coords_for_restore_ = point_in_native;
840 void DisplayController::PostDisplayConfigurationChange() {
841 if (limiter_)
842 limiter_->SetThrottleTimeout(kAfterDisplayChangeThrottleTimeoutMs);
844 focus_activation_store_->Restore();
846 DisplayManager* display_manager = GetDisplayManager();
847 DisplayLayoutStore* layout_store = display_manager->layout_store();
848 if (display_manager->num_connected_displays() > 1) {
849 DisplayIdPair pair = display_manager->GetCurrentDisplayIdPair();
850 layout_store->UpdateMultiDisplayState(
851 pair, display_manager->IsInMirrorMode(),
852 display_manager->default_multi_display_mode() ==
853 DisplayManager::UNIFIED);
855 if (Shell::GetScreen()->GetNumDisplays() > 1 ) {
856 DisplayLayout layout = layout_store->GetRegisteredDisplayLayout(pair);
857 int64 primary_id = layout.primary_id;
858 SetPrimaryDisplayId(
859 primary_id == gfx::Display::kInvalidDisplayID ?
860 pair.first : primary_id);
861 // Update the primary_id in case the above call is
862 // ignored. Happens when a) default layout's primary id
863 // doesn't exist, or b) the primary_id has already been
864 // set to the same and didn't update it.
865 layout_store->UpdatePrimaryDisplayId(
866 pair, Shell::GetScreen()->GetPrimaryDisplay().id());
869 FOR_EACH_OBSERVER(Observer, observers_, OnDisplayConfigurationChanged());
870 UpdateMouseLocationAfterDisplayChange();
873 bool DisplayController::DispatchKeyEventPostIME(const ui::KeyEvent& event) {
874 // Getting the active root window to dispatch the event. This isn't
875 // significant as the event will be sent to the window resolved by
876 // aura::client::FocusClient which is FocusController in ash.
877 aura::Window* active_window = wm::GetActiveWindow();
878 aura::Window* root_window = active_window ? active_window->GetRootWindow()
879 : Shell::GetPrimaryRootWindow();
880 return root_window->GetHost()->DispatchKeyEventPostIME(event);
883 AshWindowTreeHost* DisplayController::AddWindowTreeHostForDisplay(
884 const gfx::Display& display,
885 const AshWindowTreeHostInitParams& init_params) {
886 static int host_count = 0;
887 const DisplayInfo& display_info =
888 GetDisplayManager()->GetDisplayInfo(display.id());
889 AshWindowTreeHostInitParams params_with_bounds(init_params);
890 params_with_bounds.initial_bounds = display_info.bounds_in_native();
891 params_with_bounds.offscreen =
892 display.id() == DisplayManager::kUnifiedDisplayId;
893 AshWindowTreeHost* ash_host = AshWindowTreeHost::Create(params_with_bounds);
894 aura::WindowTreeHost* host = ash_host->AsWindowTreeHost();
895 if (!input_method_) { // Singleton input method instance for Ash.
896 input_method_ = ui::CreateInputMethod(this, host->GetAcceleratedWidget());
897 input_method_->OnFocus();
898 input_method_event_handler_.reset(
899 new InputMethodEventHandler(input_method_.get()));
901 host->SetSharedInputMethod(input_method_.get());
902 ash_host->set_input_method_handler(input_method_event_handler_.get());
904 host->window()->SetName(base::StringPrintf(
905 "%sRootWindow-%d", params_with_bounds.offscreen ? "Offscreen" : "",
906 host_count++));
907 host->window()->SetTitle(base::UTF8ToUTF16(display_info.name()));
908 host->compositor()->SetBackgroundColor(SK_ColorBLACK);
909 // No need to remove our observer observer because the DisplayController
910 // outlives the host.
911 host->AddObserver(this);
912 InitRootWindowSettings(host->window())->display_id = display.id();
913 host->InitHost();
915 window_tree_hosts_[display.id()] = ash_host;
916 SetDisplayPropertiesOnHost(ash_host, display);
918 #if defined(OS_CHROMEOS)
919 if (switches::ConstrainPointerToRoot())
920 ash_host->ConfineCursorToRootWindow();
921 #endif
922 return ash_host;
925 void DisplayController::OnFadeOutForSwapDisplayFinished() {
926 #if defined(OS_CHROMEOS)
927 SetPrimaryDisplay(ScreenUtil::GetSecondaryDisplay());
928 Shell::GetInstance()->display_configurator_animation()
929 ->StartFadeInAnimation();
930 #endif
933 void DisplayController::SetMirrorModeAfterAnimation(bool mirror) {
934 GetDisplayManager()->SetMirrorMode(mirror);
937 } // namespace ash