1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "ash/display/window_tree_host_manager.h"
6 
7 #include <algorithm>
8 #include <cmath>
9 #include <map>
10 #include <memory>
11 #include <utility>
12 
13 #include "ash/display/cursor_window_controller.h"
14 #include "ash/display/mirror_window_controller.h"
15 #include "ash/display/root_window_transformers.h"
16 #include "ash/host/ash_window_tree_host.h"
17 #include "ash/host/ash_window_tree_host_init_params.h"
18 #include "ash/host/root_window_transformer.h"
19 #include "ash/magnifier/magnification_controller.h"
20 #include "ash/magnifier/partial_magnification_controller.h"
21 #include "ash/public/cpp/ash_features.h"
22 #include "ash/root_window_controller.h"
23 #include "ash/root_window_settings.h"
24 #include "ash/session/session_controller_impl.h"
25 #include "ash/shell.h"
26 #include "ash/system/status_area_widget.h"
27 #include "ash/system/unified/unified_system_tray.h"
28 #include "ash/wm/window_util.h"
29 #include "base/command_line.h"
30 #include "base/metrics/histogram.h"
31 #include "base/metrics/histogram_functions.h"
32 #include "base/strings/stringprintf.h"
33 #include "base/strings/utf_string_conversions.h"
34 #include "base/threading/thread_task_runner_handle.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_tracker.h"
41 #include "ui/aura/window_tree_host.h"
42 #include "ui/base/class_property.h"
43 #include "ui/base/ime/init/input_method_factory.h"
44 #include "ui/base/l10n/l10n_util.h"
45 #include "ui/base/ui_base_features.h"
46 #include "ui/compositor/compositor.h"
47 #include "ui/compositor/compositor_switches.h"
48 #include "ui/display/display.h"
49 #include "ui/display/display_layout.h"
50 #include "ui/display/display_transform.h"
51 #include "ui/display/manager/display_configurator.h"
52 #include "ui/display/manager/display_layout_store.h"
53 #include "ui/display/manager/display_manager.h"
54 #include "ui/display/screen.h"
55 #include "ui/display/types/display_constants.h"
56 #include "ui/wm/core/coordinate_conversion.h"
57 #include "ui/wm/public/activation_client.h"
58 
59 namespace ash {
60 namespace {
61 
62 // Primary display stored in global object as it can be
63 // accessed after Shell is deleted. A separate display instance is created
64 // during the shutdown instead of always keeping two display instances
65 // (one here and another one in display_manager) in sync, which is error prone.
66 // This is initialized in the constructor, and then in CreatePrimaryHost().
67 int64_t primary_display_id = -1;
68 
69 // The default memory limit: 512mb.
70 const char kUICompositorDefaultMemoryLimitMB[] = "512";
71 
72 // An UMA signal for the current effective resolution is sent at this rate. This
73 // keeps track of the effective resolution most used on internal display by the
74 // user.
75 constexpr base::TimeDelta kEffectiveResolutionRepeatingDelay =
76     base::TimeDelta::FromMinutes(30);
77 
GetDisplayManager()78 display::DisplayManager* GetDisplayManager() {
79   return Shell::Get()->display_manager();
80 }
81 
SetDisplayPropertiesOnHost(AshWindowTreeHost * ash_host,const display::Display & display)82 void SetDisplayPropertiesOnHost(AshWindowTreeHost* ash_host,
83                                 const display::Display& display) {
84   const display::Display::Rotation effective_rotation =
85       display.panel_rotation();
86   aura::WindowTreeHost* host = ash_host->AsWindowTreeHost();
87   ash_host->SetCursorConfig(display, effective_rotation);
88   std::unique_ptr<RootWindowTransformer> transformer(
89       CreateRootWindowTransformerForDisplay(display));
90   ash_host->SetRootWindowTransformer(std::move(transformer));
91 
92   host->SetDisplayTransformHint(
93       display::DisplayRotationToOverlayTransform(effective_rotation));
94 
95   // Just moving the display requires the full redraw.
96   // chrome-os-partner:33558.
97   host->compositor()->ScheduleFullRedraw();
98 }
99 
ClearDisplayPropertiesOnHost(AshWindowTreeHost * ash_host)100 void ClearDisplayPropertiesOnHost(AshWindowTreeHost* ash_host) {
101   ash_host->ClearCursorConfig();
102 }
103 
GetWindow(AshWindowTreeHost * ash_host)104 aura::Window* GetWindow(AshWindowTreeHost* ash_host) {
105   CHECK(ash_host->AsWindowTreeHost());
106   return ash_host->AsWindowTreeHost()->window();
107 }
108 
109 // Returns the index to the enum - |EffectiveResolution|. The enum value
110 // represents the resolution that exactly matches the primary display's
111 // effective resolution.
GetEffectiveResolutionUMAIndex(const display::Display & display)112 int GetEffectiveResolutionUMAIndex(const display::Display& display) {
113   const gfx::Size effective_size = display.size();
114 
115   // The UMA enum index for portrait mode has 1 subtracted from itself. This
116   // differentiates it from the landscape mode.
117   return effective_size.width() > effective_size.height()
118              ? effective_size.width() * effective_size.height()
119              : effective_size.width() * effective_size.height() - 1;
120 }
121 
RepeatingEffectiveResolutionUMA(base::RepeatingTimer * timer,bool is_first_run)122 void RepeatingEffectiveResolutionUMA(base::RepeatingTimer* timer,
123                                      bool is_first_run) {
124   display::Display internal_display;
125   const auto* session_controller = Shell::Get()->session_controller();
126 
127   // Record the UMA only when this is an active user session and the
128   // internal display is present.
129   if (display::Display::HasInternalDisplay() &&
130       display::Screen::GetScreen()->GetDisplayWithDisplayId(
131           display::Display::InternalDisplayId(), &internal_display) &&
132       session_controller->IsActiveUserSessionStarted() &&
133       session_controller->GetSessionState() ==
134           session_manager::SessionState::ACTIVE) {
135     base::UmaHistogramSparse(
136         "Ash.Display.InternalDisplay.ActiveEffectiveResolution",
137         GetEffectiveResolutionUMAIndex(internal_display));
138   }
139 
140   // The first run of the repeating timer is half the actual delay. Reset the
141   // timer after the first run with the correct delay.
142   if (is_first_run && timer) {
143     timer->Start(
144         FROM_HERE, kEffectiveResolutionRepeatingDelay,
145         base::BindRepeating(&RepeatingEffectiveResolutionUMA,
146                             nullptr /*timer=*/, false /*is_first_run=*/));
147   }
148 }
149 
150 }  // namespace
151 
152 // A utility class to store/restore focused/active window
153 // when the display configuration has changed.
154 class FocusActivationStore {
155  public:
FocusActivationStore()156   FocusActivationStore()
157       : activation_client_(nullptr),
158         capture_client_(nullptr),
159         focus_client_(nullptr),
160         focused_(nullptr),
161         active_(nullptr) {}
162 
Store(bool clear_focus)163   void Store(bool clear_focus) {
164     if (!activation_client_) {
165       aura::Window* root = Shell::GetPrimaryRootWindow();
166       activation_client_ = ::wm::GetActivationClient(root);
167       capture_client_ = aura::client::GetCaptureClient(root);
168       focus_client_ = aura::client::GetFocusClient(root);
169     }
170     focused_ = focus_client_->GetFocusedWindow();
171     if (focused_)
172       tracker_.Add(focused_);
173     active_ = activation_client_->GetActiveWindow();
174     if (active_ && focused_ != active_)
175       tracker_.Add(active_);
176 
177     // Deactivate the window to close menu / bubble windows. Deactivating by
178     // setting active window to nullptr to avoid side effects of activating an
179     // arbitrary window, such as covering |active_| before Restore().
180     if (clear_focus && active_)
181       activation_client_->ActivateWindow(nullptr);
182 
183     // Release capture if any.
184     capture_client_->SetCapture(nullptr);
185 
186     // Clear the focused window if any. This is necessary because a
187     // window may be deleted when losing focus (fullscreen flash for
188     // example).  If the focused window is still alive after move, it'll
189     // be re-focused below.
190     if (clear_focus)
191       focus_client_->FocusWindow(nullptr);
192   }
193 
Restore()194   void Restore() {
195     // Restore focused or active window if it's still alive.
196     if (focused_ && tracker_.Contains(focused_)) {
197       focus_client_->FocusWindow(focused_);
198     } else if (active_ && tracker_.Contains(active_)) {
199       activation_client_->ActivateWindow(active_);
200     }
201     if (focused_)
202       tracker_.Remove(focused_);
203     if (active_)
204       tracker_.Remove(active_);
205     focused_ = nullptr;
206     active_ = nullptr;
207   }
208 
209  private:
210   ::wm::ActivationClient* activation_client_;
211   aura::client::CaptureClient* capture_client_;
212   aura::client::FocusClient* focus_client_;
213   aura::WindowTracker tracker_;
214   aura::Window* focused_;
215   aura::Window* active_;
216 
217   DISALLOW_COPY_AND_ASSIGN(FocusActivationStore);
218 };
219 
220 ////////////////////////////////////////////////////////////////////////////////
221 // WindowTreeHostManager
222 
WindowTreeHostManager()223 WindowTreeHostManager::WindowTreeHostManager()
224     : primary_tree_host_for_replace_(nullptr),
225       focus_activation_store_(new FocusActivationStore()),
226       cursor_window_controller_(new CursorWindowController()),
227       mirror_window_controller_(new MirrorWindowController()),
228       cursor_display_id_for_restore_(display::kInvalidDisplayId) {
229   // Reset primary display to make sure that tests don't use
230   // stale display info from previous tests.
231   primary_display_id = display::kInvalidDisplayId;
232 }
233 
234 WindowTreeHostManager::~WindowTreeHostManager() = default;
235 
Start()236 void WindowTreeHostManager::Start() {
237   display::Screen::GetScreen()->AddObserver(this);
238   Shell::Get()
239       ->display_configurator()
240       ->content_protection_manager()
241       ->AddObserver(this);
242   Shell::Get()->display_manager()->set_delegate(this);
243 
244   // Start a repeating timer to send UMA at fixed intervals. The first run is at
245   // half the delay time.
246   effective_resolution_UMA_timer_ = std::make_unique<base::RepeatingTimer>();
247   effective_resolution_UMA_timer_->Start(
248       FROM_HERE, kEffectiveResolutionRepeatingDelay / 2,
249       base::BindRepeating(&RepeatingEffectiveResolutionUMA,
250                           effective_resolution_UMA_timer_.get(),
251                           true /*is_first_run=*/));
252 }
253 
Shutdown()254 void WindowTreeHostManager::Shutdown() {
255   for (auto& observer : observers_)
256     observer.OnWindowTreeHostManagerShutdown();
257 
258   effective_resolution_UMA_timer_->Reset();
259 
260   // Unset the display manager's delegate here because
261   // DisplayManager outlives WindowTreeHostManager.
262   Shell::Get()->display_manager()->set_delegate(nullptr);
263 
264   cursor_window_controller_.reset();
265   mirror_window_controller_.reset();
266 
267   Shell::Get()
268       ->display_configurator()
269       ->content_protection_manager()
270       ->RemoveObserver(this);
271   display::Screen::GetScreen()->RemoveObserver(this);
272 
273   int64_t primary_id = display::Screen::GetScreen()->GetPrimaryDisplay().id();
274 
275   // Delete non primary root window controllers first, then
276   // delete the primary root window controller.
277   aura::Window::Windows root_windows =
278       WindowTreeHostManager::GetAllRootWindows();
279   std::vector<RootWindowController*> to_delete;
280   RootWindowController* primary_rwc = nullptr;
281   for (aura::Window::Windows::iterator iter = root_windows.begin();
282        iter != root_windows.end(); ++iter) {
283     RootWindowController* rwc = RootWindowController::ForWindow(*iter);
284     if (GetRootWindowSettings(*iter)->display_id == primary_id)
285       primary_rwc = rwc;
286     else
287       to_delete.push_back(rwc);
288   }
289   CHECK(primary_rwc);
290 
291   Shell::SetRootWindowForNewWindows(nullptr);
292   for (auto* rwc : to_delete)
293     delete rwc;
294   delete primary_rwc;
295 }
296 
CreatePrimaryHost(const AshWindowTreeHostInitParams & init_params)297 void WindowTreeHostManager::CreatePrimaryHost(
298     const AshWindowTreeHostInitParams& init_params) {
299   auto* command_line = base::CommandLine::ForCurrentProcess();
300   if (!command_line->HasSwitch(
301           switches::kUiCompositorMemoryLimitWhenVisibleMB)) {
302     command_line->AppendSwitchASCII(
303         switches::kUiCompositorMemoryLimitWhenVisibleMB,
304         kUICompositorDefaultMemoryLimitMB);
305   }
306 
307   const display::Display& primary_candidate =
308       GetDisplayManager()->GetPrimaryDisplayCandidate();
309   primary_display_id = primary_candidate.id();
310   CHECK_NE(display::kInvalidDisplayId, primary_display_id);
311   AddWindowTreeHostForDisplay(primary_candidate, init_params);
312 }
313 
InitHosts()314 void WindowTreeHostManager::InitHosts() {
315   RootWindowController::CreateForPrimaryDisplay(
316       window_tree_hosts_[primary_display_id]);
317   display::DisplayManager* display_manager = GetDisplayManager();
318   for (size_t i = 0; i < display_manager->GetNumDisplays(); ++i) {
319     const display::Display& display = display_manager->GetDisplayAt(i);
320     if (primary_display_id != display.id()) {
321       AshWindowTreeHost* ash_host =
322           AddWindowTreeHostForDisplay(display, AshWindowTreeHostInitParams());
323       RootWindowController::CreateForSecondaryDisplay(ash_host);
324     }
325   }
326 
327   // Record display zoom for the primary display for https://crbug.com/955071.
328   // This can be removed after M79.
329   const display::ManagedDisplayInfo& display_info =
330       display_manager->GetDisplayInfo(primary_display_id);
331   int zoom_percent = std::round(display_info.zoom_factor() * 100);
332   constexpr int kMaxValue = 300;
333   constexpr int kBucketSize = 5;
334   constexpr int kBucketCount = kMaxValue / kBucketSize + 1;
335   base::LinearHistogram::FactoryGet(
336       "Ash.Display.PrimaryDisplayZoomAtStartup", kBucketSize, kMaxValue,
337       kBucketCount, base::HistogramBase::kUmaTargetedHistogramFlag)
338       ->Add(zoom_percent);
339 
340   for (auto& observer : observers_)
341     observer.OnDisplaysInitialized();
342 }
343 
AddObserver(Observer * observer)344 void WindowTreeHostManager::AddObserver(Observer* observer) {
345   observers_.AddObserver(observer);
346 }
347 
RemoveObserver(Observer * observer)348 void WindowTreeHostManager::RemoveObserver(Observer* observer) {
349   observers_.RemoveObserver(observer);
350 }
351 
352 // static
GetPrimaryDisplayId()353 int64_t WindowTreeHostManager::GetPrimaryDisplayId() {
354   CHECK_NE(display::kInvalidDisplayId, primary_display_id);
355   return primary_display_id;
356 }
357 
358 // static
HasValidPrimaryDisplayId()359 bool WindowTreeHostManager::HasValidPrimaryDisplayId() {
360   return primary_display_id != display::kInvalidDisplayId;
361 }
362 
GetPrimaryRootWindow()363 aura::Window* WindowTreeHostManager::GetPrimaryRootWindow() {
364   // If |primary_tree_host_for_replace_| is set, it means |primary_display_id|
365   // is kInvalidDisplayId.
366   if (primary_tree_host_for_replace_)
367     return GetWindow(primary_tree_host_for_replace_);
368   return GetRootWindowForDisplayId(primary_display_id);
369 }
370 
GetRootWindowForDisplayId(int64_t id)371 aura::Window* WindowTreeHostManager::GetRootWindowForDisplayId(int64_t id) {
372   AshWindowTreeHost* host = GetAshWindowTreeHostForDisplayId(id);
373   return host ? GetWindow(host) : nullptr;
374 }
375 
GetAshWindowTreeHostForDisplayId(int64_t display_id)376 AshWindowTreeHost* WindowTreeHostManager::GetAshWindowTreeHostForDisplayId(
377     int64_t display_id) {
378   const auto host = window_tree_hosts_.find(display_id);
379   if (host != window_tree_hosts_.end())
380     return host->second;
381   return mirror_window_controller_->GetAshWindowTreeHostForDisplayId(
382       display_id);
383 }
384 
GetAllRootWindows()385 aura::Window::Windows WindowTreeHostManager::GetAllRootWindows() {
386   aura::Window::Windows windows;
387   for (WindowTreeHostMap::const_iterator it = window_tree_hosts_.begin();
388        it != window_tree_hosts_.end(); ++it) {
389     DCHECK(it->second);
390     if (RootWindowController::ForWindow(GetWindow(it->second)))
391       windows.push_back(GetWindow(it->second));
392   }
393   return windows;
394 }
395 
GetOverscanInsets(int64_t display_id) const396 gfx::Insets WindowTreeHostManager::GetOverscanInsets(int64_t display_id) const {
397   return GetDisplayManager()->GetOverscanInsets(display_id);
398 }
399 
SetOverscanInsets(int64_t display_id,const gfx::Insets & insets_in_dip)400 void WindowTreeHostManager::SetOverscanInsets(
401     int64_t display_id,
402     const gfx::Insets& insets_in_dip) {
403   GetDisplayManager()->SetOverscanInsets(display_id, insets_in_dip);
404 }
405 
406 std::vector<RootWindowController*>
GetAllRootWindowControllers()407 WindowTreeHostManager::GetAllRootWindowControllers() {
408   std::vector<RootWindowController*> controllers;
409   for (WindowTreeHostMap::const_iterator it = window_tree_hosts_.begin();
410        it != window_tree_hosts_.end(); ++it) {
411     RootWindowController* controller =
412         RootWindowController::ForWindow(GetWindow(it->second));
413     if (controller)
414       controllers.push_back(controller);
415   }
416   return controllers;
417 }
418 
UpdateMouseLocationAfterDisplayChange()419 void WindowTreeHostManager::UpdateMouseLocationAfterDisplayChange() {
420   // If the mouse is currently on a display in native location,
421   // use the same native location. Otherwise find the display closest
422   // to the current cursor location in screen coordinates.
423 
424   gfx::Point point_in_screen =
425       display::Screen::GetScreen()->GetCursorScreenPoint();
426   gfx::Point target_location_in_native;
427   int64_t closest_distance_squared = -1;
428   display::DisplayManager* display_manager = GetDisplayManager();
429 
430   aura::Window* dst_root_window = nullptr;
431   for (size_t i = 0; i < display_manager->GetNumDisplays(); ++i) {
432     const display::Display& display = display_manager->GetDisplayAt(i);
433     const display::ManagedDisplayInfo display_info =
434         display_manager->GetDisplayInfo(display.id());
435     aura::Window* root_window = GetRootWindowForDisplayId(display.id());
436     if (display_info.bounds_in_native().Contains(
437             cursor_location_in_native_coords_for_restore_)) {
438       dst_root_window = root_window;
439       target_location_in_native = cursor_location_in_native_coords_for_restore_;
440       break;
441     }
442     gfx::Point center = display.bounds().CenterPoint();
443     // Use the distance squared from the center of the dislay. This is not
444     // exactly "closest" display, but good enough to pick one
445     // appropriate (and there are at most two displays).
446     // We don't care about actual distance, only relative to other displays, so
447     // using the LengthSquared() is cheaper than Length().
448 
449     int64_t distance_squared = (center - point_in_screen).LengthSquared();
450     if (closest_distance_squared < 0 ||
451         closest_distance_squared > distance_squared) {
452       aura::Window* root_window = GetRootWindowForDisplayId(display.id());
453       ::wm::ConvertPointFromScreen(root_window, &center);
454       root_window->GetHost()->ConvertDIPToScreenInPixels(&center);
455       dst_root_window = root_window;
456       target_location_in_native = center;
457       closest_distance_squared = distance_squared;
458     }
459   }
460 
461   gfx::Point target_location_in_root = target_location_in_native;
462   dst_root_window->GetHost()->ConvertScreenInPixelsToDIP(
463       &target_location_in_root);
464 
465   gfx::Point target_location_in_screen = target_location_in_root;
466   ::wm::ConvertPointToScreen(dst_root_window, &target_location_in_screen);
467   const display::Display& target_display =
468       display_manager->FindDisplayContainingPoint(target_location_in_screen);
469   // If the original location isn't on any of new display, let ozone move
470   // the cursor.
471   if (!target_display.is_valid())
472     return;
473   int64_t target_display_id = target_display.id();
474 
475   // Do not move the cursor if the cursor's location did not change. This avoids
476   // moving (and showing) the cursor:
477   // - At startup.
478   // - When the device is rotated in tablet mode.
479   // |cursor_display_id_for_restore_| is checked to ensure that the cursor is
480   // moved when the cursor's native position does not change but the display
481   // that it is on has changed. This occurs when swapping the primary display.
482   if (target_location_in_native !=
483           cursor_location_in_native_coords_for_restore_ ||
484       target_display_id != cursor_display_id_for_restore_) {
485     if (Shell::Get()->cursor_manager()) {
486       if (Shell::Get()->cursor_manager()->IsCursorVisible()) {
487         dst_root_window->MoveCursorTo(target_location_in_root);
488       } else if (target_display_id != cursor_display_id_for_restore_) {
489         Shell::Get()->cursor_manager()->SetDisplay(target_display);
490       }
491     }
492 
493   } else if (target_location_in_screen !=
494              cursor_location_in_screen_coords_for_restore_) {
495     // The cursor's native position did not change but its screen position did
496     // change. This occurs when the scale factor or the rotation of the display
497     // that the cursor is on changes.
498     // TODO: conditional should not be necessary. http://crbug.com/631103.
499     if (Shell::Get()->cursor_manager())
500       Shell::Get()->cursor_manager()->SetDisplay(target_display);
501 
502     // Update the cursor's root location. This ends up dispatching a synthetic
503     // mouse move. The synthetic mouse move updates the composited cursor's
504     // location and hover effects. Synthetic mouse moves do not affect the
505     // cursor's visibility.
506     dst_root_window->GetHost()->dispatcher()->OnCursorMovedToRootLocation(
507         target_location_in_root);
508   }
509 }
510 
UpdateWorkAreaOfDisplayNearestWindow(const aura::Window * window,const gfx::Insets & insets)511 bool WindowTreeHostManager::UpdateWorkAreaOfDisplayNearestWindow(
512     const aura::Window* window,
513     const gfx::Insets& insets) {
514   const aura::Window* root_window = window->GetRootWindow();
515   int64_t id = GetRootWindowSettings(root_window)->display_id;
516   // if id is |kInvaildDisplayID|, it's being deleted.
517   DCHECK(id != display::kInvalidDisplayId);
518   return GetDisplayManager()->UpdateWorkAreaOfDisplay(id, insets);
519 }
520 
OnDisplayAdded(const display::Display & display)521 void WindowTreeHostManager::OnDisplayAdded(const display::Display& display) {
522   // If we're switching from/to offscreen WTH, we need to
523   // create new WTH for primary display instead of reusing.
524   if (primary_tree_host_for_replace_ &&
525       (GetRootWindowSettings(GetWindow(primary_tree_host_for_replace_))
526                ->display_id == display::kUnifiedDisplayId ||
527        display.id() == display::kUnifiedDisplayId)) {
528     DCHECK_EQ(display::kInvalidDisplayId, primary_display_id);
529     primary_display_id = display.id();
530 
531     AshWindowTreeHost* ash_host =
532         AddWindowTreeHostForDisplay(display, AshWindowTreeHostInitParams());
533     RootWindowController* new_root_window_controller =
534         RootWindowController::CreateForSecondaryDisplay(ash_host);
535 
536     // Magnifier controllers keep pointers to the current root window.
537     // Update them here to avoid accessing them later.
538     Shell::Get()->magnification_controller()->SwitchTargetRootWindow(
539         ash_host->AsWindowTreeHost()->window(), false);
540     Shell::Get()
541         ->partial_magnification_controller()
542         ->SwitchTargetRootWindowIfNeeded(
543             ash_host->AsWindowTreeHost()->window());
544 
545     AshWindowTreeHost* to_delete = primary_tree_host_for_replace_;
546 
547     // Show the shelf if the original WTH had a visible system
548     // tray. It may or may not be visible depending on OOBE state.
549     RootWindowController* old_root_window_controller =
550         RootWindowController::ForWindow(
551             to_delete->AsWindowTreeHost()->window());
552     TrayBackgroundView* old_tray =
553         old_root_window_controller->GetStatusAreaWidget()
554             ->unified_system_tray();
555     TrayBackgroundView* new_tray =
556         new_root_window_controller->GetStatusAreaWidget()
557             ->unified_system_tray();
558     if (old_tray->GetWidget()->IsVisible()) {
559       new_tray->SetVisiblePreferred(true);
560       new_tray->GetWidget()->Show();
561     }
562 
563     // |to_delete| has already been removed from |window_tree_hosts_|.
564     DCHECK(std::none_of(
565         window_tree_hosts_.cbegin(), window_tree_hosts_.cend(),
566         [to_delete](const std::pair<int64_t, AshWindowTreeHost*>& pair) {
567           return pair.second == to_delete;
568         }));
569 
570     DeleteHost(to_delete);
571     DCHECK(!primary_tree_host_for_replace_);
572   } else if (primary_tree_host_for_replace_) {
573     // TODO(oshima): It should be possible to consolidate logic for
574     // unified and non unified, but I'm keeping them separated to minimize
575     // the risk in M44. I'll consolidate this in M45.
576     DCHECK(window_tree_hosts_.empty());
577     AshWindowTreeHost* ash_host = primary_tree_host_for_replace_;
578     primary_tree_host_for_replace_ = nullptr;
579     primary_display_id = display.id();
580     window_tree_hosts_[display.id()] = ash_host;
581     GetRootWindowSettings(GetWindow(ash_host))->display_id = display.id();
582     const display::ManagedDisplayInfo& display_info =
583         GetDisplayManager()->GetDisplayInfo(display.id());
584     ash_host->AsWindowTreeHost()->SetBoundsInPixels(
585         display_info.bounds_in_native());
586     SetDisplayPropertiesOnHost(ash_host, display);
587   } else {
588     if (primary_display_id == display::kInvalidDisplayId)
589       primary_display_id = display.id();
590     DCHECK(!window_tree_hosts_.empty());
591     AshWindowTreeHost* ash_host =
592         AddWindowTreeHostForDisplay(display, AshWindowTreeHostInitParams());
593     RootWindowController::CreateForSecondaryDisplay(ash_host);
594   }
595 }
596 
DeleteHost(AshWindowTreeHost * host_to_delete)597 void WindowTreeHostManager::DeleteHost(AshWindowTreeHost* host_to_delete) {
598   ClearDisplayPropertiesOnHost(host_to_delete);
599   aura::Window* root_being_deleted = GetWindow(host_to_delete);
600   RootWindowController* controller =
601       RootWindowController::ForWindow(root_being_deleted);
602   DCHECK(controller);
603   aura::Window* primary_root_after_host_deletion =
604       GetRootWindowForDisplayId(GetPrimaryDisplayId());
605   controller->MoveWindowsTo(primary_root_after_host_deletion);
606   // Delete most of root window related objects, but don't delete
607   // root window itself yet because the stack may be using it.
608   controller->Shutdown();
609   if (primary_tree_host_for_replace_ == host_to_delete)
610     primary_tree_host_for_replace_ = nullptr;
611   DCHECK_EQ(primary_root_after_host_deletion, Shell::GetPrimaryRootWindow());
612   if (Shell::GetRootWindowForNewWindows() == root_being_deleted) {
613     Shell::SetRootWindowForNewWindows(primary_root_after_host_deletion);
614   }
615   // NOTE: ShelfWidget is gone, but Shelf still exists until this task runs.
616   base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, controller);
617 }
618 
OnDisplayRemoved(const display::Display & display)619 void WindowTreeHostManager::OnDisplayRemoved(const display::Display& display) {
620   AshWindowTreeHost* host_to_delete = window_tree_hosts_[display.id()];
621   CHECK(host_to_delete) << display.ToString();
622 
623   // When the primary root window's display is removed, move the primary
624   // root to the other display.
625   if (primary_display_id == display.id()) {
626     // Temporarily store the primary root window in
627     // |primary_root_window_for_replace_| when replacing the display.
628     if (window_tree_hosts_.size() == 1) {
629       primary_display_id = display::kInvalidDisplayId;
630       primary_tree_host_for_replace_ = host_to_delete;
631       // Display for root window will be deleted when the Primary RootWindow
632       // is deleted by the Shell.
633       window_tree_hosts_.erase(display.id());
634       return;
635     }
636     for (const auto& pair : window_tree_hosts_) {
637       if (pair.first != display.id()) {
638         primary_display_id = pair.first;
639         break;
640       }
641     }
642     CHECK_NE(display::kInvalidDisplayId, primary_display_id);
643 
644     AshWindowTreeHost* primary_host = host_to_delete;
645     // Delete the other host instead.
646     host_to_delete = window_tree_hosts_[primary_display_id];
647     GetRootWindowSettings(GetWindow(host_to_delete))->display_id = display.id();
648 
649     // Setup primary root.
650     window_tree_hosts_[primary_display_id] = primary_host;
651     GetRootWindowSettings(GetWindow(primary_host))->display_id =
652         primary_display_id;
653 
654     OnDisplayMetricsChanged(
655         GetDisplayManager()->GetDisplayForId(primary_display_id),
656         DISPLAY_METRIC_BOUNDS);
657   }
658 
659   DeleteHost(host_to_delete);
660 
661   // The window tree host should be erased at last because some handlers can
662   // access to the host through GetRootWindowForDisplayId() during
663   // MoveWindowsTo(). See http://crbug.com/415222
664   window_tree_hosts_.erase(display.id());
665 }
666 
OnDisplayMetricsChanged(const display::Display & display,uint32_t metrics)667 void WindowTreeHostManager::OnDisplayMetricsChanged(
668     const display::Display& display,
669     uint32_t metrics) {
670   if (!(metrics & (DISPLAY_METRIC_BOUNDS | DISPLAY_METRIC_ROTATION |
671                    DISPLAY_METRIC_DEVICE_SCALE_FACTOR))) {
672     return;
673   }
674 
675   const display::ManagedDisplayInfo& display_info =
676       GetDisplayManager()->GetDisplayInfo(display.id());
677   DCHECK(!display_info.bounds_in_native().IsEmpty());
678   AshWindowTreeHost* ash_host = window_tree_hosts_[display.id()];
679   ash_host->AsWindowTreeHost()->SetBoundsInPixels(
680       display_info.bounds_in_native());
681   SetDisplayPropertiesOnHost(ash_host, display);
682 }
683 
OnHostResized(aura::WindowTreeHost * host)684 void WindowTreeHostManager::OnHostResized(aura::WindowTreeHost* host) {
685   display::Display display =
686       display::Screen::GetScreen()->GetDisplayNearestWindow(host->window());
687 
688   display::DisplayManager* display_manager = GetDisplayManager();
689   if (display_manager->UpdateDisplayBounds(display.id(),
690                                            host->GetBoundsInPixels())) {
691     mirror_window_controller_->UpdateWindow();
692     cursor_window_controller_->UpdateContainer();
693   }
694 }
695 
OnDisplaySecurityChanged(int64_t display_id,bool secure)696 void WindowTreeHostManager::OnDisplaySecurityChanged(int64_t display_id,
697                                                      bool secure) {
698   AshWindowTreeHost* host = GetAshWindowTreeHostForDisplayId(display_id);
699   // No host for internal display in docked mode.
700   if (!host)
701     return;
702 
703   ui::Compositor* compositor = host->AsWindowTreeHost()->compositor();
704   compositor->SetOutputIsSecure(secure);
705   compositor->ScheduleFullRedraw();
706 }
707 
CreateOrUpdateMirroringDisplay(const display::DisplayInfoList & info_list)708 void WindowTreeHostManager::CreateOrUpdateMirroringDisplay(
709     const display::DisplayInfoList& info_list) {
710   if (GetDisplayManager()->IsInMirrorMode() ||
711       GetDisplayManager()->IsInUnifiedMode()) {
712     mirror_window_controller_->UpdateWindow(info_list);
713     cursor_window_controller_->UpdateContainer();
714   } else {
715     NOTREACHED();
716   }
717 }
718 
CloseMirroringDisplayIfNotNecessary()719 void WindowTreeHostManager::CloseMirroringDisplayIfNotNecessary() {
720   mirror_window_controller_->CloseIfNotNecessary();
721   // If cursor_compositing is enabled for large cursor, the cursor window is
722   // always on the desktop display (the visible cursor on the non-desktop
723   // display is drawn through compositor mirroring). Therefore, it's unnecessary
724   // to handle the cursor_window at all. See: http://crbug.com/412910
725   if (!cursor_window_controller_->is_cursor_compositing_enabled())
726     cursor_window_controller_->UpdateContainer();
727 }
728 
PreDisplayConfigurationChange(bool clear_focus)729 void WindowTreeHostManager::PreDisplayConfigurationChange(bool clear_focus) {
730   for (auto& observer : observers_)
731     observer.OnDisplayConfigurationChanging();
732   focus_activation_store_->Store(clear_focus);
733   display::Screen* screen = display::Screen::GetScreen();
734   gfx::Point point_in_screen = screen->GetCursorScreenPoint();
735   cursor_location_in_screen_coords_for_restore_ = point_in_screen;
736 
737   display::Display display = screen->GetDisplayNearestPoint(point_in_screen);
738   cursor_display_id_for_restore_ = display.id();
739 
740   gfx::Point point_in_native = point_in_screen;
741   aura::Window* root_window = GetRootWindowForDisplayId(display.id());
742   ::wm::ConvertPointFromScreen(root_window, &point_in_native);
743   root_window->GetHost()->ConvertDIPToScreenInPixels(&point_in_native);
744   cursor_location_in_native_coords_for_restore_ = point_in_native;
745 }
746 
SetPrimaryDisplayId(int64_t id)747 void WindowTreeHostManager::SetPrimaryDisplayId(int64_t id) {
748   // TODO(oshima): Move primary display management to DisplayManager.
749   DCHECK_NE(display::kInvalidDisplayId, id);
750   if (id == display::kInvalidDisplayId || primary_display_id == id ||
751       window_tree_hosts_.size() < 2) {
752     return;
753   }
754 
755   const display::Display& new_primary_display =
756       GetDisplayManager()->GetDisplayForId(id);
757   if (!new_primary_display.is_valid()) {
758     LOG(ERROR) << "Invalid or non-existent display is requested:"
759                << new_primary_display.ToString();
760     return;
761   }
762 
763   display::DisplayManager* display_manager = GetDisplayManager();
764   DCHECK(new_primary_display.is_valid());
765   DCHECK(display_manager->GetDisplayForId(new_primary_display.id()).is_valid());
766 
767   AshWindowTreeHost* non_primary_host =
768       window_tree_hosts_[new_primary_display.id()];
769   LOG_IF(ERROR, !non_primary_host)
770       << "Unknown display is requested in SetPrimaryDisplay: id="
771       << new_primary_display.id();
772   if (!non_primary_host)
773     return;
774 
775   display::Display old_primary_display =
776       display::Screen::GetScreen()->GetPrimaryDisplay();
777   DCHECK_EQ(old_primary_display.id(), primary_display_id);
778 
779   // Swap root windows between current and new primary display.
780   AshWindowTreeHost* primary_host = window_tree_hosts_[primary_display_id];
781   CHECK(primary_host);
782   CHECK_NE(primary_host, non_primary_host);
783 
784   aura::Window* primary_window = GetWindow(primary_host);
785   aura::Window* non_primary_window = GetWindow(non_primary_host);
786   window_tree_hosts_[new_primary_display.id()] = primary_host;
787   GetRootWindowSettings(primary_window)->display_id = new_primary_display.id();
788 
789   window_tree_hosts_[old_primary_display.id()] = non_primary_host;
790   GetRootWindowSettings(non_primary_window)->display_id =
791       old_primary_display.id();
792 
793   base::string16 old_primary_title = primary_window->GetTitle();
794   primary_window->SetTitle(non_primary_window->GetTitle());
795   non_primary_window->SetTitle(old_primary_title);
796 
797   const display::DisplayLayout& layout =
798       GetDisplayManager()->GetCurrentDisplayLayout();
799   // The requested primary id can be same as one in the stored layout
800   // when the primary id is set after new displays are connected.
801   // Only update the layout if it is requested to swap primary display.
802   if (layout.primary_id != new_primary_display.id()) {
803     std::unique_ptr<display::DisplayLayout> swapped_layout = layout.Copy();
804     swapped_layout->SwapPrimaryDisplay(new_primary_display.id());
805     display::DisplayIdList list = display_manager->GetCurrentDisplayIdList();
806     GetDisplayManager()->layout_store()->RegisterLayoutForDisplayIdList(
807         list, std::move(swapped_layout));
808   }
809 
810   primary_display_id = new_primary_display.id();
811 
812   UpdateWorkAreaOfDisplayNearestWindow(GetWindow(primary_host),
813                                        old_primary_display.GetWorkAreaInsets());
814   UpdateWorkAreaOfDisplayNearestWindow(GetWindow(non_primary_host),
815                                        new_primary_display.GetWorkAreaInsets());
816 
817   // Update the dispay manager with new display info.
818   GetDisplayManager()->set_force_bounds_changed(true);
819   GetDisplayManager()->UpdateDisplays();
820   GetDisplayManager()->set_force_bounds_changed(false);
821 }
822 
PostDisplayConfigurationChange()823 void WindowTreeHostManager::PostDisplayConfigurationChange() {
824   focus_activation_store_->Restore();
825 
826   for (auto& observer : observers_)
827     observer.OnDisplayConfigurationChanged();
828   UpdateMouseLocationAfterDisplayChange();
829 
830   // Enable cursor compositing, so that cursor could be mirrored to destination
831   // displays along with other display content.
832   Shell::Get()->UpdateCursorCompositingEnabled();
833 }
834 
DispatchKeyEventPostIME(ui::KeyEvent * event)835 ui::EventDispatchDetails WindowTreeHostManager::DispatchKeyEventPostIME(
836     ui::KeyEvent* event) {
837   aura::Window* root_window = nullptr;
838   if (event->target()) {
839     root_window = static_cast<aura::Window*>(event->target())->GetRootWindow();
840     DCHECK(root_window);
841   } else {
842     // Getting the active root window to dispatch the event. This isn't
843     // significant as the event will be sent to the window resolved by
844     // aura::client::FocusClient which is FocusController in ash.
845     aura::Window* active_window = window_util::GetActiveWindow();
846     root_window = active_window ? active_window->GetRootWindow()
847                                 : Shell::GetPrimaryRootWindow();
848   }
849   return root_window->GetHost()->DispatchKeyEventPostIME(event);
850 }
851 
AddWindowTreeHostForDisplay(const display::Display & display,const AshWindowTreeHostInitParams & init_params)852 AshWindowTreeHost* WindowTreeHostManager::AddWindowTreeHostForDisplay(
853     const display::Display& display,
854     const AshWindowTreeHostInitParams& init_params) {
855   static int host_count = 0;
856   const display::ManagedDisplayInfo& display_info =
857       GetDisplayManager()->GetDisplayInfo(display.id());
858   AshWindowTreeHostInitParams params_with_bounds(init_params);
859   params_with_bounds.initial_bounds = display_info.bounds_in_native();
860   if (display.id() == display::kUnifiedDisplayId) {
861     params_with_bounds.offscreen = true;
862     params_with_bounds.mirroring_delegate = mirror_window_controller();
863   }
864   params_with_bounds.display_id = display.id();
865   params_with_bounds.device_scale_factor = display.device_scale_factor();
866   // The AshWindowTreeHost ends up owned by the RootWindowControllers created
867   // by this class.
868   AshWindowTreeHost* ash_host =
869       AshWindowTreeHost::Create(params_with_bounds).release();
870   aura::WindowTreeHost* host = ash_host->AsWindowTreeHost();
871   DCHECK(!host->has_input_method());
872   if (!input_method_) {  // Singleton input method instance for Ash.
873     input_method_ = ui::CreateInputMethod(this, host->GetAcceleratedWidget());
874     // Makes sure the input method is focused by default when created, because
875     // Ash uses singleton InputMethod and it won't call OnFocus/OnBlur when
876     // the active window changed.
877     input_method_->OnFocus();
878   }
879   host->SetSharedInputMethod(input_method_.get());
880 
881   host->window()->SetName(base::StringPrintf(
882       "%sRootWindow-%d", params_with_bounds.offscreen ? "Offscreen" : "",
883       host_count++));
884   host->window()->SetTitle(base::UTF8ToUTF16(display_info.name()));
885   host->compositor()->SetBackgroundColor(SK_ColorBLACK);
886   // No need to remove our observer observer because the WindowTreeHostManager
887   // outlives the host.
888   host->AddObserver(this);
889   InitRootWindowSettings(host->window())->display_id = display.id();
890   host->InitHost();
891   host->window()->Show();
892 
893   window_tree_hosts_[display.id()] = ash_host;
894   SetDisplayPropertiesOnHost(ash_host, display);
895 
896   ash_host->ConfineCursorToRootWindow();
897 
898   return ash_host;
899 }
900 
901 }  // namespace ash
902