Remove selection expansion finch finch flag.
[chromium-blink-merge.git] / ash / display / window_tree_host_manager.cc
blobaf7d17c4b82fe83ed96b45672a5538f0b8d3301a
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/window_tree_host_manager.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, kScaleFactorProp, kCARDINAL,
137 100 * display.device_scale_factor());
138 #elif defined(USE_OZONE)
139 // Scale all motion on High-DPI displays.
140 float scale = display.device_scale_factor();
142 if (!display.IsInternal())
143 scale *= kCursorMultiplierForExternalDisplays;
145 ui::CursorController::GetInstance()->SetCursorConfigForWindow(
146 host->GetAcceleratedWidget(), info.GetActiveRotation(), scale);
147 #endif
148 #endif
149 scoped_ptr<RootWindowTransformer> transformer(
150 CreateRootWindowTransformerForDisplay(host->window(), display));
151 ash_host->SetRootWindowTransformer(transformer.Pass());
153 DisplayMode mode =
154 GetDisplayManager()->GetActiveModeForDisplayId(display.id());
155 if (mode.refresh_rate > 0.0f) {
156 host->compositor()->SetAuthoritativeVSyncInterval(
157 base::TimeDelta::FromMicroseconds(base::Time::kMicrosecondsPerSecond /
158 mode.refresh_rate));
161 // Just movnig the display requires the full redraw.
162 // chrome-os-partner:33558.
163 host->compositor()->ScheduleFullRedraw();
166 void ClearDisplayPropertiesOnHost(AshWindowTreeHost* ash_host) {
167 #if defined(OS_CHROMEOS) && defined(USE_OZONE)
168 aura::WindowTreeHost* host = ash_host->AsWindowTreeHost();
169 ui::CursorController::GetInstance()->ClearCursorConfigForWindow(
170 host->GetAcceleratedWidget());
171 #endif
174 aura::Window* GetWindow(AshWindowTreeHost* ash_host) {
175 CHECK(ash_host->AsWindowTreeHost());
176 return ash_host->AsWindowTreeHost()->window();
179 } // namespace
181 // A utility class to store/restore focused/active window
182 // when the display configuration has changed.
183 class FocusActivationStore {
184 public:
185 FocusActivationStore()
186 : activation_client_(nullptr),
187 capture_client_(nullptr),
188 focus_client_(nullptr),
189 focused_(nullptr),
190 active_(nullptr) {}
192 void Store(bool clear_focus) {
193 if (!activation_client_) {
194 aura::Window* root = Shell::GetPrimaryRootWindow();
195 activation_client_ = aura::client::GetActivationClient(root);
196 capture_client_ = aura::client::GetCaptureClient(root);
197 focus_client_ = aura::client::GetFocusClient(root);
199 focused_ = focus_client_->GetFocusedWindow();
200 if (focused_)
201 tracker_.Add(focused_);
202 active_ = activation_client_->GetActiveWindow();
203 if (active_ && focused_ != active_)
204 tracker_.Add(active_);
206 // Deactivate the window to close menu / bubble windows.
207 if (clear_focus)
208 activation_client_->DeactivateWindow(active_);
210 // Release capture if any.
211 capture_client_->SetCapture(nullptr);
212 // Clear the focused window if any. This is necessary because a
213 // window may be deleted when losing focus (fullscreen flash for
214 // example). If the focused window is still alive after move, it'll
215 // be re-focused below.
216 if (clear_focus)
217 focus_client_->FocusWindow(nullptr);
220 void Restore() {
221 // Restore focused or active window if it's still alive.
222 if (focused_ && tracker_.Contains(focused_)) {
223 focus_client_->FocusWindow(focused_);
224 } else if (active_ && tracker_.Contains(active_)) {
225 activation_client_->ActivateWindow(active_);
227 if (focused_)
228 tracker_.Remove(focused_);
229 if (active_)
230 tracker_.Remove(active_);
231 focused_ = nullptr;
232 active_ = nullptr;
235 private:
236 aura::client::ActivationClient* activation_client_;
237 aura::client::CaptureClient* capture_client_;
238 aura::client::FocusClient* focus_client_;
239 aura::WindowTracker tracker_;
240 aura::Window* focused_;
241 aura::Window* active_;
243 DISALLOW_COPY_AND_ASSIGN(FocusActivationStore);
246 ////////////////////////////////////////////////////////////////////////////////
247 // DisplayChangeLimiter
249 WindowTreeHostManager::DisplayChangeLimiter::DisplayChangeLimiter()
250 : throttle_timeout_(base::Time::Now()) {}
252 void WindowTreeHostManager::DisplayChangeLimiter::SetThrottleTimeout(
253 int64 throttle_ms) {
254 throttle_timeout_ =
255 base::Time::Now() + base::TimeDelta::FromMilliseconds(throttle_ms);
258 bool WindowTreeHostManager::DisplayChangeLimiter::IsThrottled() const {
259 return base::Time::Now() < throttle_timeout_;
262 ////////////////////////////////////////////////////////////////////////////////
263 // WindowTreeHostManager
265 WindowTreeHostManager::WindowTreeHostManager()
266 : primary_tree_host_for_replace_(nullptr),
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 WindowTreeHostManager::~WindowTreeHostManager() {}
283 void WindowTreeHostManager::Start() {
284 Shell::GetScreen()->AddObserver(this);
285 Shell::GetInstance()->display_manager()->set_delegate(this);
288 void WindowTreeHostManager::Shutdown() {
289 // Unset the display manager's delegate here because
290 // DisplayManager outlives WindowTreeHostManager.
291 Shell::GetInstance()->display_manager()->set_delegate(nullptr);
293 cursor_window_controller_.reset();
294 mirror_window_controller_.reset();
296 Shell::GetScreen()->RemoveObserver(this);
298 int64 primary_id = Shell::GetScreen()->GetPrimaryDisplay().id();
300 // Delete non primary root window controllers first, then
301 // delete the primary root window controller.
302 aura::Window::Windows root_windows =
303 WindowTreeHostManager::GetAllRootWindows();
304 std::vector<RootWindowController*> to_delete;
305 RootWindowController* primary_rwc = nullptr;
306 for (aura::Window::Windows::iterator iter = root_windows.begin();
307 iter != root_windows.end(); ++iter) {
308 RootWindowController* rwc = GetRootWindowController(*iter);
309 if (GetRootWindowSettings(*iter)->display_id == primary_id)
310 primary_rwc = rwc;
311 else
312 to_delete.push_back(rwc);
314 CHECK(primary_rwc);
316 STLDeleteElements(&to_delete);
317 delete primary_rwc;
320 void WindowTreeHostManager::CreatePrimaryHost(
321 const AshWindowTreeHostInitParams& init_params) {
322 const gfx::Display& primary_candidate =
323 GetDisplayManager()->GetPrimaryDisplayCandidate();
324 primary_display_id = primary_candidate.id();
325 CHECK_NE(gfx::Display::kInvalidDisplayID, primary_display_id);
326 AddWindowTreeHostForDisplay(primary_candidate, init_params);
329 void WindowTreeHostManager::InitHosts() {
330 RootWindowController::CreateForPrimaryDisplay(
331 window_tree_hosts_[primary_display_id]);
332 DisplayManager* display_manager = GetDisplayManager();
333 for (size_t i = 0; i < display_manager->GetNumDisplays(); ++i) {
334 const gfx::Display& display = display_manager->GetDisplayAt(i);
335 if (primary_display_id != display.id()) {
336 AshWindowTreeHost* ash_host =
337 AddWindowTreeHostForDisplay(display, AshWindowTreeHostInitParams());
338 RootWindowController::CreateForSecondaryDisplay(ash_host);
342 FOR_EACH_OBSERVER(Observer, observers_, OnDisplaysInitialized());
345 void WindowTreeHostManager::AddObserver(Observer* observer) {
346 observers_.AddObserver(observer);
349 void WindowTreeHostManager::RemoveObserver(Observer* observer) {
350 observers_.RemoveObserver(observer);
353 // static
354 int64 WindowTreeHostManager::GetPrimaryDisplayId() {
355 CHECK_NE(gfx::Display::kInvalidDisplayID, primary_display_id);
356 return primary_display_id;
359 aura::Window* WindowTreeHostManager::GetPrimaryRootWindow() {
360 return GetRootWindowForDisplayId(primary_display_id);
363 aura::Window* WindowTreeHostManager::GetRootWindowForDisplayId(int64 id) {
364 AshWindowTreeHost* host = GetAshWindowTreeHostForDisplayId(id);
365 CHECK(host);
366 return GetWindow(host);
369 AshWindowTreeHost* WindowTreeHostManager::GetAshWindowTreeHostForDisplayId(
370 int64 display_id) {
371 CHECK_EQ(1u, window_tree_hosts_.count(display_id)) << "display id = "
372 << display_id;
373 return window_tree_hosts_[display_id];
376 void WindowTreeHostManager::CloseChildWindows() {
377 for (WindowTreeHostMap::const_iterator it = window_tree_hosts_.begin();
378 it != window_tree_hosts_.end(); ++it) {
379 aura::Window* root_window = GetWindow(it->second);
380 RootWindowController* controller = GetRootWindowController(root_window);
381 if (controller) {
382 controller->CloseChildWindows();
383 } else {
384 while (!root_window->children().empty()) {
385 aura::Window* child = root_window->children()[0];
386 delete child;
392 aura::Window::Windows WindowTreeHostManager::GetAllRootWindows() {
393 aura::Window::Windows windows;
394 for (WindowTreeHostMap::const_iterator it = window_tree_hosts_.begin();
395 it != window_tree_hosts_.end(); ++it) {
396 DCHECK(it->second);
397 if (GetRootWindowController(GetWindow(it->second)))
398 windows.push_back(GetWindow(it->second));
400 return windows;
403 gfx::Insets WindowTreeHostManager::GetOverscanInsets(int64 display_id) const {
404 return GetDisplayManager()->GetOverscanInsets(display_id);
407 void WindowTreeHostManager::SetOverscanInsets(
408 int64 display_id,
409 const gfx::Insets& insets_in_dip) {
410 GetDisplayManager()->SetOverscanInsets(display_id, insets_in_dip);
413 std::vector<RootWindowController*>
414 WindowTreeHostManager::GetAllRootWindowControllers() {
415 std::vector<RootWindowController*> controllers;
416 for (WindowTreeHostMap::const_iterator it = window_tree_hosts_.begin();
417 it != window_tree_hosts_.end(); ++it) {
418 RootWindowController* controller =
419 GetRootWindowController(GetWindow(it->second));
420 if (controller)
421 controllers.push_back(controller);
423 return controllers;
426 void WindowTreeHostManager::ToggleMirrorMode() {
427 DisplayManager* display_manager = GetDisplayManager();
428 if (display_manager->num_connected_displays() <= 1)
429 return;
431 if (limiter_) {
432 if (limiter_->IsThrottled())
433 return;
434 limiter_->SetThrottleTimeout(kCycleDisplayThrottleTimeoutMs);
436 #if defined(OS_CHROMEOS)
437 Shell* shell = Shell::GetInstance();
438 DisplayConfiguratorAnimation* animation =
439 shell->display_configurator_animation();
440 animation->StartFadeOutAnimation(base::Bind(
441 &WindowTreeHostManager::SetMirrorModeAfterAnimation,
442 weak_ptr_factory_.GetWeakPtr(), !display_manager->IsInMirrorMode()));
443 #endif
446 void WindowTreeHostManager::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(
459 base::Bind(&WindowTreeHostManager::OnFadeOutForSwapDisplayFinished,
460 weak_ptr_factory_.GetWeakPtr()));
461 } else {
462 SetPrimaryDisplay(ScreenUtil::GetSecondaryDisplay());
464 #else
465 SetPrimaryDisplay(ScreenUtil::GetSecondaryDisplay());
466 #endif
470 void WindowTreeHostManager::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 WindowTreeHostManager::SetPrimaryDisplay(
481 const gfx::Display& new_primary_display) {
482 DisplayManager* display_manager = GetDisplayManager();
483 DCHECK(new_primary_display.is_valid());
484 DCHECK(display_manager->GetDisplayForId(new_primary_display.id()).is_valid());
486 if (!new_primary_display.is_valid() ||
487 !display_manager->GetDisplayForId(new_primary_display.id()).is_valid()) {
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(
533 display_manager->GetDisplayInfo(primary_display_id));
534 display_info_list.push_back(
535 display_manager->GetDisplayInfo(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 WindowTreeHostManager::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 = nullptr;
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 // If the original location isn't on any of new display, let ozone move
592 // the cursor.
593 if (!target_display.is_valid())
594 return;
595 int64 target_display_id = target_display.id();
597 // Do not move the cursor if the cursor's location did not change. This avoids
598 // moving (and showing) the cursor:
599 // - At startup.
600 // - When the device is rotated in maximized mode.
601 // |cursor_display_id_for_restore_| is checked to ensure that the cursor is
602 // moved when the cursor's native position does not change but the display
603 // that it is on has changed. This occurs when swapping the primary display.
604 if (target_location_in_native !=
605 cursor_location_in_native_coords_for_restore_ ||
606 target_display_id != cursor_display_id_for_restore_) {
607 dst_root_window->MoveCursorTo(target_location_in_root);
608 } else if (target_location_in_screen !=
609 cursor_location_in_screen_coords_for_restore_) {
610 // The cursor's native position did not change but its screen position did
611 // change. This occurs when the scale factor or the rotation of the display
612 // that the cursor is on changes.
613 Shell::GetInstance()->cursor_manager()->SetDisplay(target_display);
615 // Update the cursor's root location. This ends up dispatching a synthetic
616 // mouse move. The synthetic mouse move updates the composited cursor's
617 // location and hover effects. Synthetic mouse moves do not affect the
618 // cursor's visibility.
619 dst_root_window->GetHost()->dispatcher()->OnCursorMovedToRootLocation(
620 target_location_in_root);
622 #else
623 dst_root_window->MoveCursorTo(target_location_in_root);
624 #endif
627 bool WindowTreeHostManager::UpdateWorkAreaOfDisplayNearestWindow(
628 const aura::Window* window,
629 const gfx::Insets& insets) {
630 const aura::Window* root_window = window->GetRootWindow();
631 int64 id = GetRootWindowSettings(root_window)->display_id;
632 // if id is |kInvaildDisplayID|, it's being deleted.
633 DCHECK(id != gfx::Display::kInvalidDisplayID);
634 return GetDisplayManager()->UpdateWorkAreaOfDisplay(id, insets);
637 void WindowTreeHostManager::OnDisplayAdded(const gfx::Display& display) {
638 #if defined(OS_CHROMEOS)
639 // If we're switching from/to offscreen WTH, we need to
640 // create new WTH for primary display instead of reusing.
641 if (primary_tree_host_for_replace_ &&
642 (GetRootWindowSettings(GetWindow(primary_tree_host_for_replace_))
643 ->display_id == DisplayManager::kUnifiedDisplayId ||
644 display.id() == DisplayManager::kUnifiedDisplayId)) {
645 DCHECK_EQ(gfx::Display::kInvalidDisplayID, primary_display_id);
646 primary_display_id = display.id();
648 AshWindowTreeHost* ash_host =
649 AddWindowTreeHostForDisplay(display, AshWindowTreeHostInitParams());
650 RootWindowController::CreateForSecondaryDisplay(ash_host);
652 // Magnifier controllers keep pointers to the current root window.
653 // Update them here to avoid accessing them later.
654 Shell::GetInstance()->magnification_controller()->SwitchTargetRootWindow(
655 ash_host->AsWindowTreeHost()->window(), false);
656 Shell::GetInstance()
657 ->partial_magnification_controller()
658 ->SwitchTargetRootWindow(ash_host->AsWindowTreeHost()->window());
660 AshWindowTreeHost* to_delete = primary_tree_host_for_replace_;
661 primary_tree_host_for_replace_ = nullptr;
663 // Show the shelf if the original WTH had a visible system
664 // tray. It may or may not be visible depending on OOBE state.
665 ash::SystemTray* old_tray =
666 GetRootWindowController(to_delete->AsWindowTreeHost()->window())
667 ->GetSystemTray();
668 ash::SystemTray* new_tray =
669 ash::Shell::GetInstance()->GetPrimarySystemTray();
670 if (old_tray->GetWidget()->IsVisible()) {
671 new_tray->SetVisible(true);
672 new_tray->GetWidget()->Show();
675 DeleteHost(to_delete);
676 #ifndef NDEBUG
677 auto iter = std::find_if(
678 window_tree_hosts_.begin(), window_tree_hosts_.end(),
679 [to_delete](const std::pair<int64, AshWindowTreeHost*>& pair) {
680 return pair.second == to_delete;
682 DCHECK(iter == window_tree_hosts_.end());
683 #endif
684 // the host has already been removed from the window_tree_host_.
685 } else
686 #endif
687 // TODO(oshima): It should be possible to consolidate logic for
688 // unified and non unified, but I'm keeping them separated to minimize
689 // the risk in M44. I'll consolidate this in M45.
690 if (primary_tree_host_for_replace_) {
691 DCHECK(window_tree_hosts_.empty());
692 primary_display_id = display.id();
693 window_tree_hosts_[display.id()] = primary_tree_host_for_replace_;
694 GetRootWindowSettings(GetWindow(primary_tree_host_for_replace_))
695 ->display_id = display.id();
696 primary_tree_host_for_replace_ = nullptr;
697 const DisplayInfo& display_info =
698 GetDisplayManager()->GetDisplayInfo(display.id());
699 AshWindowTreeHost* ash_host = window_tree_hosts_[display.id()];
700 ash_host->AsWindowTreeHost()->SetBounds(display_info.bounds_in_native());
701 SetDisplayPropertiesOnHost(ash_host, display);
702 } else {
703 if (primary_display_id == gfx::Display::kInvalidDisplayID)
704 primary_display_id = display.id();
705 DCHECK(!window_tree_hosts_.empty());
706 AshWindowTreeHost* ash_host =
707 AddWindowTreeHostForDisplay(display, AshWindowTreeHostInitParams());
708 RootWindowController::CreateForSecondaryDisplay(ash_host);
712 void WindowTreeHostManager::DeleteHost(AshWindowTreeHost* host_to_delete) {
713 ClearDisplayPropertiesOnHost(host_to_delete);
714 RootWindowController* controller =
715 GetRootWindowController(GetWindow(host_to_delete));
716 DCHECK(controller);
717 controller->MoveWindowsTo(GetPrimaryRootWindow());
718 // Delete most of root window related objects, but don't delete
719 // root window itself yet because the stack may be using it.
720 controller->Shutdown();
721 base::MessageLoop::current()->DeleteSoon(FROM_HERE, controller);
724 void WindowTreeHostManager::OnDisplayRemoved(const gfx::Display& display) {
725 AshWindowTreeHost* host_to_delete = window_tree_hosts_[display.id()];
726 CHECK(host_to_delete) << display.ToString();
728 // When the primary root window's display is removed, move the primary
729 // root to the other display.
730 if (primary_display_id == display.id()) {
731 // Temporarily store the primary root window in
732 // |primary_root_window_for_replace_| when replacing the display.
733 if (window_tree_hosts_.size() == 1) {
734 primary_display_id = gfx::Display::kInvalidDisplayID;
735 primary_tree_host_for_replace_ = host_to_delete;
736 // Display for root window will be deleted when the Primary RootWindow
737 // is deleted by the Shell.
738 window_tree_hosts_.erase(display.id());
739 return;
741 for (const auto& pair : window_tree_hosts_) {
742 if (pair.first != display.id()) {
743 primary_display_id = pair.first;
744 break;
747 CHECK_NE(gfx::Display::kInvalidDisplayID, primary_display_id);
749 AshWindowTreeHost* primary_host = host_to_delete;
750 // Delete the other host instead.
751 host_to_delete = window_tree_hosts_[primary_display_id];
752 GetRootWindowSettings(GetWindow(host_to_delete))->display_id = display.id();
754 // Setup primary root.
755 window_tree_hosts_[primary_display_id] = primary_host;
756 GetRootWindowSettings(GetWindow(primary_host))->display_id =
757 primary_display_id;
759 OnDisplayMetricsChanged(
760 GetDisplayManager()->GetDisplayForId(primary_display_id),
761 DISPLAY_METRIC_BOUNDS);
764 DeleteHost(host_to_delete);
766 // The window tree host should be erased at last because some handlers can
767 // access to the host through GetRootWindowForDisplayId() during
768 // MoveWindowsTo(). See http://crbug.com/415222
769 window_tree_hosts_.erase(display.id());
772 void WindowTreeHostManager::OnDisplayMetricsChanged(const gfx::Display& display,
773 uint32_t metrics) {
774 if (!(metrics & (DISPLAY_METRIC_BOUNDS | DISPLAY_METRIC_ROTATION |
775 DISPLAY_METRIC_DEVICE_SCALE_FACTOR)))
776 return;
777 const DisplayInfo& display_info =
778 GetDisplayManager()->GetDisplayInfo(display.id());
779 DCHECK(!display_info.bounds_in_native().IsEmpty());
780 AshWindowTreeHost* ash_host = window_tree_hosts_[display.id()];
781 ash_host->AsWindowTreeHost()->SetBounds(display_info.bounds_in_native());
782 SetDisplayPropertiesOnHost(ash_host, display);
785 void WindowTreeHostManager::OnHostResized(const aura::WindowTreeHost* host) {
786 gfx::Display display = Shell::GetScreen()->GetDisplayNearestWindow(
787 const_cast<aura::Window*>(host->window()));
789 DisplayManager* display_manager = GetDisplayManager();
790 if (display_manager->UpdateDisplayBounds(display.id(), host->GetBounds())) {
791 mirror_window_controller_->UpdateWindow();
792 cursor_window_controller_->UpdateContainer();
796 void WindowTreeHostManager::CreateOrUpdateMirroringDisplay(
797 const DisplayInfoList& info_list) {
798 if (GetDisplayManager()->IsInMirrorMode() ||
799 GetDisplayManager()->IsInUnifiedMode()) {
800 mirror_window_controller_->UpdateWindow(info_list);
801 cursor_window_controller_->UpdateContainer();
802 } else {
803 NOTREACHED();
807 void WindowTreeHostManager::CloseMirroringDisplayIfNotNecessary() {
808 mirror_window_controller_->CloseIfNotNecessary();
809 // If cursor_compositing is enabled for large cursor, the cursor window is
810 // always on the desktop display (the visible cursor on the non-desktop
811 // display is drawn through compositor mirroring). Therefore, it's unnecessary
812 // to handle the cursor_window at all. See: http://crbug.com/412910
813 if (!cursor_window_controller_->is_cursor_compositing_enabled())
814 cursor_window_controller_->UpdateContainer();
817 void WindowTreeHostManager::PreDisplayConfigurationChange(bool clear_focus) {
818 FOR_EACH_OBSERVER(Observer, observers_, OnDisplayConfigurationChanging());
819 focus_activation_store_->Store(clear_focus);
820 gfx::Screen* screen = Shell::GetScreen();
821 gfx::Point point_in_screen = screen->GetCursorScreenPoint();
822 cursor_location_in_screen_coords_for_restore_ = point_in_screen;
824 gfx::Display display = screen->GetDisplayNearestPoint(point_in_screen);
825 cursor_display_id_for_restore_ = display.id();
827 gfx::Point point_in_native = point_in_screen;
828 aura::Window* root_window = GetRootWindowForDisplayId(display.id());
829 ::wm::ConvertPointFromScreen(root_window, &point_in_native);
830 root_window->GetHost()->ConvertPointToNativeScreen(&point_in_native);
831 cursor_location_in_native_coords_for_restore_ = point_in_native;
834 void WindowTreeHostManager::PostDisplayConfigurationChange() {
835 if (limiter_)
836 limiter_->SetThrottleTimeout(kAfterDisplayChangeThrottleTimeoutMs);
838 focus_activation_store_->Restore();
840 DisplayManager* display_manager = GetDisplayManager();
841 DisplayLayoutStore* layout_store = display_manager->layout_store();
842 if (display_manager->num_connected_displays() > 1) {
843 DisplayIdPair pair = display_manager->GetCurrentDisplayIdPair();
844 DisplayLayout layout = layout_store->GetRegisteredDisplayLayout(pair);
845 layout_store->UpdateMultiDisplayState(
846 pair, display_manager->IsInMirrorMode(), layout.default_unified);
848 if (Shell::GetScreen()->GetNumDisplays() > 1) {
849 int64 primary_id = layout.primary_id;
850 SetPrimaryDisplayId(primary_id == gfx::Display::kInvalidDisplayID
851 ? pair.first
852 : primary_id);
853 // Update the primary_id in case the above call is
854 // ignored. Happens when a) default layout's primary id
855 // doesn't exist, or b) the primary_id has already been
856 // set to the same and didn't update it.
857 layout_store->UpdatePrimaryDisplayId(
858 pair, Shell::GetScreen()->GetPrimaryDisplay().id());
861 FOR_EACH_OBSERVER(Observer, observers_, OnDisplayConfigurationChanged());
862 UpdateMouseLocationAfterDisplayChange();
865 ui::EventDispatchDetails WindowTreeHostManager::DispatchKeyEventPostIME(
866 ui::KeyEvent* event) {
867 // Getting the active root window to dispatch the event. This isn't
868 // significant as the event will be sent to the window resolved by
869 // aura::client::FocusClient which is FocusController in ash.
870 aura::Window* active_window = wm::GetActiveWindow();
871 aura::Window* root_window = active_window ? active_window->GetRootWindow()
872 : Shell::GetPrimaryRootWindow();
873 return root_window->GetHost()->DispatchKeyEventPostIME(event);
876 AshWindowTreeHost* WindowTreeHostManager::AddWindowTreeHostForDisplay(
877 const gfx::Display& display,
878 const AshWindowTreeHostInitParams& init_params) {
879 static int host_count = 0;
880 const DisplayInfo& display_info =
881 GetDisplayManager()->GetDisplayInfo(display.id());
882 AshWindowTreeHostInitParams params_with_bounds(init_params);
883 params_with_bounds.initial_bounds = display_info.bounds_in_native();
884 params_with_bounds.offscreen =
885 display.id() == DisplayManager::kUnifiedDisplayId;
886 AshWindowTreeHost* ash_host = AshWindowTreeHost::Create(params_with_bounds);
887 aura::WindowTreeHost* host = ash_host->AsWindowTreeHost();
888 if (!input_method_) { // Singleton input method instance for Ash.
889 input_method_ = ui::CreateInputMethod(this, host->GetAcceleratedWidget());
890 // Makes sure the input method is focused by default when created, because
891 // Ash uses singleton InputMethod and it won't call OnFocus/OnBlur when the
892 // active window changed.
893 input_method_->OnFocus();
894 input_method_event_handler_.reset(
895 new InputMethodEventHandler(input_method_.get()));
897 host->SetSharedInputMethod(input_method_.get());
898 ash_host->set_input_method_handler(input_method_event_handler_.get());
900 host->window()->SetName(base::StringPrintf(
901 "%sRootWindow-%d", params_with_bounds.offscreen ? "Offscreen" : "",
902 host_count++));
903 host->window()->SetTitle(base::UTF8ToUTF16(display_info.name()));
904 host->compositor()->SetBackgroundColor(SK_ColorBLACK);
905 // No need to remove our observer observer because the WindowTreeHostManager
906 // outlives the host.
907 host->AddObserver(this);
908 InitRootWindowSettings(host->window())->display_id = display.id();
909 host->InitHost();
911 window_tree_hosts_[display.id()] = ash_host;
912 SetDisplayPropertiesOnHost(ash_host, display);
914 #if defined(OS_CHROMEOS)
915 if (switches::ConstrainPointerToRoot())
916 ash_host->ConfineCursorToRootWindow();
917 #endif
918 return ash_host;
921 void WindowTreeHostManager::OnFadeOutForSwapDisplayFinished() {
922 #if defined(OS_CHROMEOS)
923 SetPrimaryDisplay(ScreenUtil::GetSecondaryDisplay());
924 Shell::GetInstance()
925 ->display_configurator_animation()
926 ->StartFadeInAnimation();
927 #endif
930 void WindowTreeHostManager::SetMirrorModeAfterAnimation(bool mirror) {
931 GetDisplayManager()->SetMirrorMode(mirror);
934 } // namespace ash