display_controller.cc revision d0247b1b59f9c528cb6df88b4f2b9afaf80d181e
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/display_controller.h"
6
7#include <algorithm>
8#include <cmath>
9#include <map>
10
11#include "ash/ash_switches.h"
12#include "ash/display/display_layout_store.h"
13#include "ash/display/display_manager.h"
14#include "ash/display/mirror_window_controller.h"
15#include "ash/display/root_window_transformers.h"
16#include "ash/host/root_window_host_factory.h"
17#include "ash/root_window_controller.h"
18#include "ash/root_window_settings.h"
19#include "ash/screen_ash.h"
20#include "ash/shell.h"
21#include "ash/wm/coordinate_conversion.h"
22#include "base/command_line.h"
23#include "base/strings/stringprintf.h"
24#include "third_party/skia/include/utils/SkMatrix44.h"
25#include "ui/aura/client/activation_client.h"
26#include "ui/aura/client/capture_client.h"
27#include "ui/aura/client/cursor_client.h"
28#include "ui/aura/client/focus_client.h"
29#include "ui/aura/client/screen_position_client.h"
30#include "ui/aura/root_window.h"
31#include "ui/aura/root_window_transformer.h"
32#include "ui/aura/window.h"
33#include "ui/aura/window_property.h"
34#include "ui/aura/window_tracker.h"
35#include "ui/compositor/compositor.h"
36#include "ui/compositor/dip_util.h"
37#include "ui/gfx/display.h"
38#include "ui/gfx/screen.h"
39
40#if defined(OS_CHROMEOS)
41#include "base/chromeos/chromeos_version.h"
42#include "base/time/time.h"
43#if defined(USE_X11)
44#include "ash/display/output_configurator_animation.h"
45#include "chromeos/display/output_configurator.h"
46#include "ui/base/x/x11_util.h"
47
48// Including this at the bottom to avoid other
49// potential conflict with chrome headers.
50#include <X11/extensions/Xrandr.h>
51#undef RootWindow
52#endif  // defined(USE_X11)
53#endif  // defined(OS_CHROMEOS)
54
55namespace ash {
56namespace {
57
58// Primary display stored in global object as it can be
59// accessed after Shell is deleted. A separate display instance is created
60// during the shutdown instead of always keeping two display instances
61// (one here and another one in display_manager) in sync, which is error prone.
62int64 primary_display_id = gfx::Display::kInvalidDisplayID;
63gfx::Display* primary_display_for_shutdown = NULL;
64// Keeps the number of displays during the shutdown after
65// ash::Shell:: is deleted.
66int num_displays_for_shutdown = -1;
67
68// Specifies how long the display change should have been disabled
69// after each display change operations.
70// |kCycleDisplayThrottleTimeoutMs| is set to be longer to avoid
71// changing the settings while the system is still configurating
72// displays. It will be overriden by |kAfterDisplayChangeThrottleTimeoutMs|
73// when the display change happens, so the actual timeout is much shorter.
74const int64 kAfterDisplayChangeThrottleTimeoutMs = 500;
75const int64 kCycleDisplayThrottleTimeoutMs = 4000;
76const int64 kSwapDisplayThrottleTimeoutMs = 500;
77
78internal::DisplayManager* GetDisplayManager() {
79  return Shell::GetInstance()->display_manager();
80}
81
82void SetDisplayPropertiesOnHostWindow(aura::RootWindow* root,
83                                      const gfx::Display& display) {
84  internal::DisplayInfo info =
85      GetDisplayManager()->GetDisplayInfo(display.id());
86#if defined(OS_CHROMEOS) && defined(USE_X11)
87  // Native window property (Atom in X11) that specifies the display's
88  // rotation, scale factor and if it's internal display.  They are
89  // read and used by touchpad/mouse driver directly on X (contact
90  // adlr@ for more details on touchpad/mouse driver side). The value
91  // of the rotation is one of 0 (normal), 1 (90 degrees clockwise), 2
92  // (180 degree) or 3 (270 degrees clockwise).  The value of the
93  // scale factor is in percent (100, 140, 200 etc).
94  const char kRotationProp[] = "_CHROME_DISPLAY_ROTATION";
95  const char kScaleFactorProp[] = "_CHROME_DISPLAY_SCALE_FACTOR";
96  const char kInternalProp[] = "_CHROME_DISPLAY_INTERNAL";
97  const char kCARDINAL[] = "CARDINAL";
98  int xrandr_rotation = RR_Rotate_0;
99  switch (info.rotation()) {
100    case gfx::Display::ROTATE_0:
101      xrandr_rotation = RR_Rotate_0;
102      break;
103    case gfx::Display::ROTATE_90:
104      xrandr_rotation = RR_Rotate_90;
105      break;
106    case gfx::Display::ROTATE_180:
107      xrandr_rotation = RR_Rotate_180;
108      break;
109    case gfx::Display::ROTATE_270:
110      xrandr_rotation = RR_Rotate_270;
111      break;
112  }
113
114  int internal = display.IsInternal() ? 1 : 0;
115  gfx::AcceleratedWidget xwindow = root->GetAcceleratedWidget();
116  ui::SetIntProperty(xwindow, kInternalProp, kCARDINAL, internal);
117  ui::SetIntProperty(xwindow, kRotationProp, kCARDINAL, xrandr_rotation);
118  ui::SetIntProperty(xwindow,
119                     kScaleFactorProp,
120                     kCARDINAL,
121                     100 * display.device_scale_factor());
122#endif
123  scoped_ptr<aura::RootWindowTransformer> transformer(
124      internal::CreateRootWindowTransformerForDisplay(root, display));
125  root->SetRootWindowTransformer(transformer.Pass());
126}
127
128}  // namespace
129
130namespace internal {
131
132// A utility class to store/restore focused/active window
133// when the display configuration has changed.
134class FocusActivationStore {
135 public:
136  FocusActivationStore()
137      : activation_client_(NULL),
138        capture_client_(NULL),
139        focus_client_(NULL),
140        focused_(NULL),
141        active_(NULL) {
142  }
143
144  void Store(bool display_removed) {
145    if (!activation_client_) {
146      aura::RootWindow* root = Shell::GetPrimaryRootWindow();
147      activation_client_ = aura::client::GetActivationClient(root);
148      capture_client_ = aura::client::GetCaptureClient(root);
149      focus_client_ = aura::client::GetFocusClient(root);
150    }
151    focused_ = focus_client_->GetFocusedWindow();
152    if (focused_)
153      tracker_.Add(focused_);
154    active_ = activation_client_->GetActiveWindow();
155    if (active_ && focused_ != active_)
156      tracker_.Add(active_);
157
158    // Deactivate the window to close menu / bubble windows.
159    if (display_removed)
160      activation_client_->DeactivateWindow(active_);
161
162    // Release capture if any.
163    capture_client_->SetCapture(NULL);
164    // Clear the focused window if any. This is necessary because a
165    // window may be deleted when losing focus (fullscreen flash for
166    // example).  If the focused window is still alive after move, it'll
167    // be re-focused below.
168    if (display_removed)
169      focus_client_->FocusWindow(NULL);
170  }
171
172  void Restore() {
173    // Restore focused or active window if it's still alive.
174    if (focused_ && tracker_.Contains(focused_)) {
175      focus_client_->FocusWindow(focused_);
176    } else if (active_ && tracker_.Contains(active_)) {
177      activation_client_->ActivateWindow(active_);
178    }
179    if (focused_)
180      tracker_.Remove(focused_);
181    if (active_)
182      tracker_.Remove(active_);
183    focused_ = NULL;
184    active_ = NULL;
185  }
186
187 private:
188  aura::client::ActivationClient* activation_client_;
189  aura::client::CaptureClient* capture_client_;
190  aura::client::FocusClient* focus_client_;
191  aura::WindowTracker tracker_;
192  aura::Window* focused_;
193  aura::Window* active_;
194
195  DISALLOW_COPY_AND_ASSIGN(FocusActivationStore);
196};
197
198}  // namespace internal
199
200////////////////////////////////////////////////////////////////////////////////
201// DisplayChangeLimiter
202
203DisplayController::DisplayChangeLimiter::DisplayChangeLimiter()
204    : throttle_timeout_(base::Time::Now()) {
205}
206
207void DisplayController::DisplayChangeLimiter::SetThrottleTimeout(
208    int64 throttle_ms) {
209  throttle_timeout_ =
210      base::Time::Now() + base::TimeDelta::FromMilliseconds(throttle_ms);
211}
212
213bool DisplayController::DisplayChangeLimiter::IsThrottled() const {
214  return base::Time::Now() < throttle_timeout_;
215}
216
217////////////////////////////////////////////////////////////////////////////////
218// DisplayController
219
220DisplayController::DisplayController()
221    : primary_root_window_for_replace_(NULL),
222      focus_activation_store_(new internal::FocusActivationStore()),
223      mirror_window_controller_(new internal::MirrorWindowController) {
224  CommandLine* command_line = CommandLine::ForCurrentProcess();
225#if defined(OS_CHROMEOS)
226  if (!command_line->HasSwitch(switches::kAshDisableDisplayChangeLimiter) &&
227      base::chromeos::IsRunningOnChromeOS())
228    limiter_.reset(new DisplayChangeLimiter);
229#endif
230  // Reset primary display to make sure that tests don't use
231  // stale display info from previous tests.
232  primary_display_id = gfx::Display::kInvalidDisplayID;
233  delete primary_display_for_shutdown;
234  primary_display_for_shutdown = NULL;
235  num_displays_for_shutdown = -1;
236}
237
238DisplayController::~DisplayController() {
239  DCHECK(primary_display_for_shutdown);
240}
241
242void DisplayController::Start() {
243  Shell::GetScreen()->AddObserver(this);
244  Shell::GetInstance()->display_manager()->set_delegate(this);
245}
246
247void DisplayController::Shutdown() {
248  // Unset the display manager's delegate here because
249  // DisplayManager outlives DisplayController.
250  Shell::GetInstance()->display_manager()->set_delegate(NULL);
251
252  mirror_window_controller_.reset();
253
254  DCHECK(!primary_display_for_shutdown);
255  primary_display_for_shutdown = new gfx::Display(
256      GetDisplayManager()->GetDisplayForId(primary_display_id));
257  num_displays_for_shutdown = GetDisplayManager()->GetNumDisplays();
258
259  Shell::GetScreen()->RemoveObserver(this);
260  // Delete all root window controllers, which deletes root window
261  // from the last so that the primary root window gets deleted last.
262  for (std::map<int64, aura::RootWindow*>::const_reverse_iterator it =
263           root_windows_.rbegin(); it != root_windows_.rend(); ++it) {
264    internal::RootWindowController* controller =
265        internal::GetRootWindowController(it->second);
266    DCHECK(controller);
267    delete controller;
268  }
269}
270
271// static
272const gfx::Display& DisplayController::GetPrimaryDisplay() {
273  DCHECK_NE(primary_display_id, gfx::Display::kInvalidDisplayID);
274  if (primary_display_for_shutdown)
275    return *primary_display_for_shutdown;
276  return GetDisplayManager()->GetDisplayForId(primary_display_id);
277}
278
279// static
280int DisplayController::GetNumDisplays() {
281  if (num_displays_for_shutdown >= 0)
282    return num_displays_for_shutdown;
283  return GetDisplayManager()->GetNumDisplays();
284}
285
286void DisplayController::InitPrimaryDisplay() {
287  const gfx::Display& primary_candidate =
288      GetDisplayManager()->GetPrimaryDisplayCandidate();
289  primary_display_id = primary_candidate.id();
290  AddRootWindowForDisplay(primary_candidate);
291}
292
293void DisplayController::InitSecondaryDisplays() {
294  internal::DisplayManager* display_manager = GetDisplayManager();
295  for (size_t i = 0; i < display_manager->GetNumDisplays(); ++i) {
296    const gfx::Display& display = display_manager->GetDisplayAt(i);
297    if (primary_display_id != display.id()) {
298      aura::RootWindow* root = AddRootWindowForDisplay(display);
299      Shell::GetInstance()->InitRootWindowForSecondaryDisplay(root);
300    }
301  }
302  UpdateHostWindowNames();
303}
304
305void DisplayController::AddObserver(Observer* observer) {
306  observers_.AddObserver(observer);
307}
308
309void DisplayController::RemoveObserver(Observer* observer) {
310  observers_.RemoveObserver(observer);
311}
312
313aura::RootWindow* DisplayController::GetPrimaryRootWindow() {
314  DCHECK(!root_windows_.empty());
315  return root_windows_[primary_display_id];
316}
317
318aura::RootWindow* DisplayController::GetRootWindowForDisplayId(int64 id) {
319  return root_windows_[id];
320}
321
322void DisplayController::CloseChildWindows() {
323  for (std::map<int64, aura::RootWindow*>::const_iterator it =
324           root_windows_.begin(); it != root_windows_.end(); ++it) {
325    aura::RootWindow* root_window = it->second;
326    internal::RootWindowController* controller =
327        internal::GetRootWindowController(root_window);
328    if (controller) {
329      controller->CloseChildWindows();
330    } else {
331      while (!root_window->children().empty()) {
332        aura::Window* child = root_window->children()[0];
333        delete child;
334      }
335    }
336  }
337}
338
339std::vector<aura::RootWindow*> DisplayController::GetAllRootWindows() {
340  std::vector<aura::RootWindow*> windows;
341  for (std::map<int64, aura::RootWindow*>::const_iterator it =
342           root_windows_.begin(); it != root_windows_.end(); ++it) {
343    DCHECK(it->second);
344    if (internal::GetRootWindowController(it->second))
345      windows.push_back(it->second);
346  }
347  return windows;
348}
349
350gfx::Insets DisplayController::GetOverscanInsets(int64 display_id) const {
351  return GetDisplayManager()->GetOverscanInsets(display_id);
352}
353
354void DisplayController::SetOverscanInsets(int64 display_id,
355                                          const gfx::Insets& insets_in_dip) {
356  GetDisplayManager()->SetOverscanInsets(display_id, insets_in_dip);
357}
358
359std::vector<internal::RootWindowController*>
360DisplayController::GetAllRootWindowControllers() {
361  std::vector<internal::RootWindowController*> controllers;
362  for (std::map<int64, aura::RootWindow*>::const_iterator it =
363           root_windows_.begin(); it != root_windows_.end(); ++it) {
364    internal::RootWindowController* controller =
365        internal::GetRootWindowController(it->second);
366    if (controller)
367      controllers.push_back(controller);
368  }
369  return controllers;
370}
371
372void DisplayController::SetLayoutForCurrentDisplays(
373    const DisplayLayout& layout_relative_to_primary) {
374  DCHECK_EQ(2U, GetDisplayManager()->GetNumDisplays());
375  if (GetDisplayManager()->GetNumDisplays() < 2)
376    return;
377  const gfx::Display& primary = GetPrimaryDisplay();
378  const DisplayIdPair pair = GetDisplayManager()->GetCurrentDisplayIdPair();
379  // Invert if the primary was swapped.
380  DisplayLayout to_set = pair.first == primary.id() ?
381      layout_relative_to_primary : layout_relative_to_primary.Invert();
382
383  internal::DisplayLayoutStore* layout_store =
384      GetDisplayManager()->layout_store();
385  DisplayLayout current_layout =
386      layout_store->GetRegisteredDisplayLayout(pair);
387  if (to_set.position != current_layout.position ||
388      to_set.offset != current_layout.offset) {
389    to_set.primary_id = primary.id();
390    layout_store->RegisterLayoutForDisplayIdPair(
391        pair.first, pair.second, to_set);
392    PreDisplayConfigurationChange(false);
393    // TODO(oshima): Call UpdateDisplays instead.
394    UpdateDisplayBoundsForLayout();
395    // Primary's bounds stay the same. Just notify bounds change
396    // on the secondary.
397    Shell::GetInstance()->screen()->NotifyBoundsChanged(
398        ScreenAsh::GetSecondaryDisplay());
399    PostDisplayConfigurationChange();
400  }
401}
402
403void DisplayController::ToggleMirrorMode() {
404  internal::DisplayManager* display_manager = GetDisplayManager();
405  if (display_manager->num_connected_displays() <= 1)
406    return;
407
408  if (limiter_) {
409    if  (limiter_->IsThrottled())
410      return;
411    limiter_->SetThrottleTimeout(kCycleDisplayThrottleTimeoutMs);
412  }
413#if defined(OS_CHROMEOS) && defined(USE_X11)
414  Shell* shell = Shell::GetInstance();
415  internal::OutputConfiguratorAnimation* animation =
416      shell->output_configurator_animation();
417  animation->StartFadeOutAnimation(base::Bind(
418      base::IgnoreResult(&internal::DisplayManager::SetMirrorMode),
419      base::Unretained(display_manager),
420      !display_manager->IsMirrored()));
421#endif
422}
423
424void DisplayController::SwapPrimaryDisplay() {
425  if (limiter_) {
426    if  (limiter_->IsThrottled())
427      return;
428    limiter_->SetThrottleTimeout(kSwapDisplayThrottleTimeoutMs);
429  }
430
431  if (Shell::GetScreen()->GetNumDisplays() > 1) {
432#if defined(OS_CHROMEOS) && defined(USE_X11)
433    internal::OutputConfiguratorAnimation* animation =
434        Shell::GetInstance()->output_configurator_animation();
435    if (animation) {
436      animation->StartFadeOutAnimation(base::Bind(
437          &DisplayController::OnFadeOutForSwapDisplayFinished,
438          base::Unretained(this)));
439    } else {
440      SetPrimaryDisplay(ScreenAsh::GetSecondaryDisplay());
441    }
442#else
443    SetPrimaryDisplay(ScreenAsh::GetSecondaryDisplay());
444#endif
445  }
446}
447
448void DisplayController::SetPrimaryDisplayId(int64 id) {
449  DCHECK_NE(gfx::Display::kInvalidDisplayID, id);
450  if (id == gfx::Display::kInvalidDisplayID || primary_display_id == id)
451    return;
452
453  const gfx::Display& display = GetDisplayManager()->GetDisplayForId(id);
454  if (display.is_valid())
455    SetPrimaryDisplay(display);
456}
457
458void DisplayController::SetPrimaryDisplay(
459    const gfx::Display& new_primary_display) {
460  internal::DisplayManager* display_manager = GetDisplayManager();
461  DCHECK(new_primary_display.is_valid());
462  DCHECK(display_manager->IsActiveDisplay(new_primary_display));
463
464  if (!new_primary_display.is_valid() ||
465      !display_manager->IsActiveDisplay(new_primary_display)) {
466    LOG(ERROR) << "Invalid or non-existent display is requested:"
467               << new_primary_display.ToString();
468    return;
469  }
470
471  if (primary_display_id == new_primary_display.id() ||
472      root_windows_.size() < 2) {
473    return;
474  }
475
476  aura::RootWindow* non_primary_root = root_windows_[new_primary_display.id()];
477  LOG_IF(ERROR, !non_primary_root)
478      << "Unknown display is requested in SetPrimaryDisplay: id="
479      << new_primary_display.id();
480  if (!non_primary_root)
481    return;
482
483  gfx::Display old_primary_display = GetPrimaryDisplay();
484
485  // Swap root windows between current and new primary display.
486  aura::RootWindow* primary_root = root_windows_[primary_display_id];
487  DCHECK(primary_root);
488  DCHECK_NE(primary_root, non_primary_root);
489
490  root_windows_[new_primary_display.id()] = primary_root;
491  internal::GetRootWindowSettings(primary_root)->display_id =
492      new_primary_display.id();
493
494  root_windows_[old_primary_display.id()] = non_primary_root;
495  internal::GetRootWindowSettings(non_primary_root)->display_id =
496      old_primary_display.id();
497
498  primary_display_id = new_primary_display.id();
499  GetDisplayManager()->layout_store()->UpdatePrimaryDisplayId(
500      display_manager->GetCurrentDisplayIdPair(), primary_display_id);
501
502  UpdateWorkAreaOfDisplayNearestWindow(
503      primary_root, old_primary_display.GetWorkAreaInsets());
504  UpdateWorkAreaOfDisplayNearestWindow(
505      non_primary_root, new_primary_display.GetWorkAreaInsets());
506
507  // Update the dispay manager with new display info.
508  std::vector<internal::DisplayInfo> display_info_list;
509  display_info_list.push_back(display_manager->GetDisplayInfo(
510      primary_display_id));
511  display_info_list.push_back(display_manager->GetDisplayInfo(
512      ScreenAsh::GetSecondaryDisplay().id()));
513  GetDisplayManager()->set_force_bounds_changed(true);
514  GetDisplayManager()->UpdateDisplays(display_info_list);
515  GetDisplayManager()->set_force_bounds_changed(false);
516}
517
518void DisplayController::EnsurePointerInDisplays() {
519  // If the mouse is currently on a display in native location,
520  // use the same native location. Otherwise find the display closest
521  // to the current cursor location in screen coordinates.
522
523  gfx::Point point_in_screen = Shell::GetScreen()->GetCursorScreenPoint();
524  gfx::Point target_location_in_native;
525  int64 closest_distance_squared = -1;
526  internal::DisplayManager* display_manager = GetDisplayManager();
527
528  aura::RootWindow* dst_root_window = NULL;
529  for (size_t i = 0; i < display_manager->GetNumDisplays(); ++i) {
530    const gfx::Display& display = display_manager->GetDisplayAt(i);
531    const internal::DisplayInfo display_info =
532        display_manager->GetDisplayInfo(display.id());
533    aura::RootWindow* root_window = GetRootWindowForDisplayId(display.id());
534    if (display_info.bounds_in_pixel().Contains(
535            cursor_location_in_native_coords_for_restore_)) {
536      dst_root_window = root_window;
537      target_location_in_native = cursor_location_in_native_coords_for_restore_;
538      break;
539    }
540    gfx::Point center = display.bounds().CenterPoint();
541    // Use the distance squared from the center of the dislay. This is not
542    // exactly "closest" display, but good enough to pick one
543    // appropriate (and there are at most two displays).
544    // We don't care about actual distance, only relative to other displays, so
545    // using the LengthSquared() is cheaper than Length().
546
547    int64 distance_squared = (center - point_in_screen).LengthSquared();
548    if (closest_distance_squared < 0 ||
549        closest_distance_squared > distance_squared) {
550      aura::RootWindow* root_window = GetRootWindowForDisplayId(display.id());
551      aura::client::ScreenPositionClient* client =
552          aura::client::GetScreenPositionClient(root_window);
553      client->ConvertPointFromScreen(root_window, &center);
554      root_window->ConvertPointToNativeScreen(&center);
555      dst_root_window = root_window;
556      target_location_in_native = center;
557      closest_distance_squared = distance_squared;
558    }
559  }
560  dst_root_window->ConvertPointFromNativeScreen(&target_location_in_native);
561  dst_root_window->MoveCursorTo(target_location_in_native);
562}
563
564bool DisplayController::UpdateWorkAreaOfDisplayNearestWindow(
565    const aura::Window* window,
566    const gfx::Insets& insets) {
567  const aura::RootWindow* root_window = window->GetRootWindow();
568  int64 id = internal::GetRootWindowSettings(root_window)->display_id;
569  // if id is |kInvaildDisplayID|, it's being deleted.
570  DCHECK(id != gfx::Display::kInvalidDisplayID);
571  return GetDisplayManager()->UpdateWorkAreaOfDisplay(id, insets);
572}
573
574const gfx::Display& DisplayController::GetDisplayNearestWindow(
575    const aura::Window* window) const {
576  if (!window)
577    return GetPrimaryDisplay();
578  const aura::RootWindow* root_window = window->GetRootWindow();
579  if (!root_window)
580    return GetPrimaryDisplay();
581  int64 id = internal::GetRootWindowSettings(root_window)->display_id;
582  // if id is |kInvaildDisplayID|, it's being deleted.
583  DCHECK(id != gfx::Display::kInvalidDisplayID);
584
585  internal::DisplayManager* display_manager = GetDisplayManager();
586  // RootWindow needs Display to determine its device scale factor.
587  // TODO(oshima): We don't need full display info for mirror
588  // window. Refactor so that RootWindow doesn't use it.
589  if (display_manager->mirrored_display().id() == id)
590    return display_manager->mirrored_display();
591
592  return display_manager->GetDisplayForId(id);
593}
594
595const gfx::Display& DisplayController::GetDisplayNearestPoint(
596    const gfx::Point& point) const {
597  // Fallback to the primary display if there is no root display containing
598  // the |point|.
599  const gfx::Display& display =
600      GetDisplayManager()->FindDisplayContainingPoint(point);
601  return display.is_valid() ? display : GetPrimaryDisplay();
602}
603
604const gfx::Display& DisplayController::GetDisplayMatching(
605    const gfx::Rect& rect) const {
606  if (rect.IsEmpty())
607    return GetDisplayNearestPoint(rect.origin());
608
609  int max_area = 0;
610  const gfx::Display* matching = NULL;
611  for (size_t i = 0; i < GetDisplayManager()->GetNumDisplays(); ++i) {
612    const gfx::Display& display = GetDisplayManager()->GetDisplayAt(i);
613    gfx::Rect intersect = gfx::IntersectRects(display.bounds(), rect);
614    int area = intersect.width() * intersect.height();
615    if (area > max_area) {
616      max_area = area;
617      matching = &display;
618    }
619  }
620  // Fallback to the primary display if there is no matching display.
621  return matching ? *matching : GetPrimaryDisplay();
622}
623
624void DisplayController::OnDisplayBoundsChanged(const gfx::Display& display) {
625  const internal::DisplayInfo& display_info =
626      GetDisplayManager()->GetDisplayInfo(display.id());
627  DCHECK(!display_info.bounds_in_pixel().IsEmpty());
628  aura::RootWindow* root = root_windows_[display.id()];
629  root->SetHostBounds(display_info.bounds_in_pixel());
630  SetDisplayPropertiesOnHostWindow(root, display);
631}
632
633void DisplayController::OnDisplayAdded(const gfx::Display& display) {
634  if (primary_root_window_for_replace_) {
635    DCHECK(root_windows_.empty());
636    primary_display_id = display.id();
637    root_windows_[display.id()] = primary_root_window_for_replace_;
638    internal::GetRootWindowSettings(primary_root_window_for_replace_)->
639        display_id = display.id();
640    primary_root_window_for_replace_ = NULL;
641    const internal::DisplayInfo& display_info =
642        GetDisplayManager()->GetDisplayInfo(display.id());
643    root_windows_[display.id()]->SetHostBounds(
644        display_info.bounds_in_pixel());
645  } else {
646    if (primary_display_id == gfx::Display::kInvalidDisplayID)
647      primary_display_id = display.id();
648    DCHECK(!root_windows_.empty());
649    aura::RootWindow* root = AddRootWindowForDisplay(display);
650    Shell::GetInstance()->InitRootWindowForSecondaryDisplay(root);
651  }
652}
653
654void DisplayController::OnDisplayRemoved(const gfx::Display& display) {
655  aura::RootWindow* root_to_delete = root_windows_[display.id()];
656  DCHECK(root_to_delete) << display.ToString();
657
658  // Display for root window will be deleted when the Primary RootWindow
659  // is deleted by the Shell.
660  root_windows_.erase(display.id());
661
662  // When the primary root window's display is removed, move the primary
663  // root to the other display.
664  if (primary_display_id == display.id()) {
665    // Temporarily store the primary root window in
666    // |primary_root_window_for_replace_| when replacing the display.
667    if (root_windows_.size() == 0) {
668      primary_display_id = gfx::Display::kInvalidDisplayID;
669      primary_root_window_for_replace_ = root_to_delete;
670      return;
671    }
672    DCHECK_EQ(1U, root_windows_.size());
673    primary_display_id = ScreenAsh::GetSecondaryDisplay().id();
674    aura::RootWindow* primary_root = root_to_delete;
675
676    // Delete the other root instead.
677    root_to_delete = root_windows_[primary_display_id];
678    internal::GetRootWindowSettings(root_to_delete)->display_id = display.id();
679
680    // Setup primary root.
681    root_windows_[primary_display_id] = primary_root;
682    internal::GetRootWindowSettings(primary_root)->display_id =
683        primary_display_id;
684
685    OnDisplayBoundsChanged(
686        GetDisplayManager()->GetDisplayForId(primary_display_id));
687  }
688  internal::RootWindowController* controller =
689      internal::GetRootWindowController(root_to_delete);
690  DCHECK(controller);
691  controller->MoveWindowsTo(GetPrimaryRootWindow());
692  // Delete most of root window related objects, but don't delete
693  // root window itself yet because the stack may be using it.
694  controller->Shutdown();
695  base::MessageLoop::current()->DeleteSoon(FROM_HERE, controller);
696}
697
698void DisplayController::OnRootWindowHostResized(const aura::RootWindow* root) {
699  internal::DisplayManager* display_manager = GetDisplayManager();
700  gfx::Display display = GetDisplayNearestWindow(root);
701  if (display_manager->UpdateDisplayBounds(
702          display.id(),
703          gfx::Rect(root->GetHostOrigin(), root->GetHostSize()))) {
704    mirror_window_controller_->UpdateWindow();
705  }
706}
707
708void DisplayController::CreateOrUpdateMirrorWindow(
709    const internal::DisplayInfo& info) {
710  mirror_window_controller_->UpdateWindow(info);
711}
712
713void DisplayController::CloseMirrorWindow() {
714  mirror_window_controller_->Close();
715}
716
717void DisplayController::PreDisplayConfigurationChange(bool display_removed) {
718  FOR_EACH_OBSERVER(Observer, observers_, OnDisplayConfigurationChanging());
719  focus_activation_store_->Store(display_removed);
720
721  gfx::Point point_in_screen = Shell::GetScreen()->GetCursorScreenPoint();
722  gfx::Display display =
723      Shell::GetScreen()->GetDisplayNearestPoint(point_in_screen);
724  aura::RootWindow* root_window = GetRootWindowForDisplayId(display.id());
725
726  aura::client::ScreenPositionClient* client =
727      aura::client::GetScreenPositionClient(root_window);
728  client->ConvertPointFromScreen(root_window, &point_in_screen);
729  root_window->ConvertPointToNativeScreen(&point_in_screen);
730  cursor_location_in_native_coords_for_restore_ = point_in_screen;
731}
732
733void DisplayController::PostDisplayConfigurationChange() {
734  if (limiter_)
735    limiter_->SetThrottleTimeout(kAfterDisplayChangeThrottleTimeoutMs);
736
737  focus_activation_store_->Restore();
738
739  internal::DisplayManager* display_manager = GetDisplayManager();
740  internal::DisplayLayoutStore* layout_store = display_manager->layout_store();
741  if (display_manager->num_connected_displays() > 1) {
742    DisplayIdPair pair = display_manager->GetCurrentDisplayIdPair();
743    layout_store->UpdateMirrorStatus(pair, display_manager->IsMirrored());
744    DisplayLayout layout = layout_store->GetRegisteredDisplayLayout(pair);
745
746    if (Shell::GetScreen()->GetNumDisplays() > 1 ) {
747      int64 primary_id = layout.primary_id;
748      SetPrimaryDisplayId(
749          primary_id == gfx::Display::kInvalidDisplayID ?
750          pair.first : primary_id);
751      // Update the primary_id in case the above call is
752      // ignored. Happens when a) default layout's primary id
753      // doesn't exist, or b) the primary_id has already been
754      // set to the same and didn't update it.
755      layout_store->UpdatePrimaryDisplayId(pair, GetPrimaryDisplay().id());
756    }
757  }
758  FOR_EACH_OBSERVER(Observer, observers_, OnDisplayConfigurationChanged());
759  UpdateHostWindowNames();
760  EnsurePointerInDisplays();
761}
762
763aura::RootWindow* DisplayController::AddRootWindowForDisplay(
764    const gfx::Display& display) {
765  static int root_window_count = 0;
766  const internal::DisplayInfo& display_info =
767      GetDisplayManager()->GetDisplayInfo(display.id());
768  const gfx::Rect& bounds_in_pixel = display_info.bounds_in_pixel();
769  aura::RootWindow::CreateParams params(bounds_in_pixel);
770  params.host = Shell::GetInstance()->root_window_host_factory()->
771      CreateRootWindowHost(bounds_in_pixel);
772  aura::RootWindow* root_window = new aura::RootWindow(params);
773  root_window->SetName(
774      base::StringPrintf("RootWindow-%d", root_window_count++));
775  root_window->compositor()->SetBackgroundColor(SK_ColorBLACK);
776  // No need to remove RootWindowObserver because
777  // the DisplayController object outlives RootWindow objects.
778  root_window->AddRootWindowObserver(this);
779  internal::InitRootWindowSettings(root_window)->display_id = display.id();
780  root_window->Init();
781
782  root_windows_[display.id()] = root_window;
783  SetDisplayPropertiesOnHostWindow(root_window, display);
784
785#if defined(OS_CHROMEOS)
786  static bool force_constrain_pointer_to_root =
787      CommandLine::ForCurrentProcess()->HasSwitch(
788          switches::kAshConstrainPointerToRoot);
789  if (base::chromeos::IsRunningOnChromeOS() || force_constrain_pointer_to_root)
790    root_window->ConfineCursorToWindow();
791#endif
792  return root_window;
793}
794
795void DisplayController::UpdateDisplayBoundsForLayout() {
796  internal::DisplayManager* display_manager = GetDisplayManager();
797  if (Shell::GetScreen()->GetNumDisplays() < 2 ||
798      display_manager->num_connected_displays() < 2) {
799    return;
800  }
801  DCHECK_EQ(2, Shell::GetScreen()->GetNumDisplays());
802
803  const DisplayLayout layout = display_manager->GetCurrentDisplayLayout();
804  display_manager->UpdateDisplayBoundsForLayoutById(
805      layout, GetPrimaryDisplay(),
806      ScreenAsh::GetSecondaryDisplay().id());
807}
808
809void DisplayController::OnFadeOutForSwapDisplayFinished() {
810#if defined(OS_CHROMEOS) && defined(USE_X11)
811  SetPrimaryDisplay(ScreenAsh::GetSecondaryDisplay());
812  Shell::GetInstance()->output_configurator_animation()->StartFadeInAnimation();
813#endif
814}
815
816void DisplayController::UpdateHostWindowNames() {
817#if defined(USE_X11)
818  // crbug.com/120229 - set the window title for the primary dislpay
819  // to "aura_root_0" so gtalk can find the primary root window to broadcast.
820  // TODO(jhorwich) Remove this once Chrome supports window-based broadcasting.
821  aura::RootWindow* primary = Shell::GetPrimaryRootWindow();
822  Shell::RootWindowList root_windows = Shell::GetAllRootWindows();
823  for (size_t i = 0; i < root_windows.size(); ++i) {
824    std::string name =
825        root_windows[i] == primary ? "aura_root_0" : "aura_root_x";
826    gfx::AcceleratedWidget xwindow = root_windows[i]->GetAcceleratedWidget();
827    XStoreName(ui::GetXDisplay(), xwindow, name.c_str());
828  }
829#endif
830}
831
832}  // namespace ash
833