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