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