display_manager.cc revision 4e180b6a0b4720a9b8e9e959a882386f690f08ff
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_manager.h"
6
7#include <cmath>
8#include <set>
9#include <string>
10#include <vector>
11
12#include "ash/ash_switches.h"
13#include "ash/display/display_layout_store.h"
14#include "ash/screen_ash.h"
15#include "ash/shell.h"
16#include "base/auto_reset.h"
17#include "base/command_line.h"
18#include "base/logging.h"
19#include "base/strings/string_number_conversions.h"
20#include "base/strings/string_split.h"
21#include "base/strings/stringprintf.h"
22#include "base/strings/utf_string_conversions.h"
23#include "grit/ash_strings.h"
24#include "ui/base/l10n/l10n_util.h"
25#include "ui/gfx/display.h"
26#include "ui/gfx/rect.h"
27#include "ui/gfx/screen.h"
28#include "ui/gfx/size_conversions.h"
29
30#if defined(USE_X11)
31#include "ui/base/x/x11_util.h"
32#endif
33
34#if defined(OS_CHROMEOS)
35#include "ash/display/output_configurator_animation.h"
36#include "base/sys_info.h"
37#include "chromeos/display/output_configurator.h"
38#endif
39
40#if defined(OS_WIN)
41#include "base/win/windows_version.h"
42#endif
43
44namespace ash {
45namespace internal {
46typedef std::vector<gfx::Display> DisplayList;
47typedef std::vector<DisplayInfo> DisplayInfoList;
48
49namespace {
50
51// The number of pixels to overlap between the primary and secondary displays,
52// in case that the offset value is too large.
53const int kMinimumOverlapForInvalidOffset = 100;
54
55// List of value UI Scale values. Scales for 2x are equivalent to 640,
56// 800, 1024, 1280, 1440, 1600 and 1920 pixel width respectively on
57// 2560 pixel width 2x density display. Please see crbug.com/233375
58// for the full list of resolutions.
59const float kUIScalesFor2x[] = {0.5f, 0.625f, 0.8f, 1.0f, 1.125f, 1.25f, 1.5f};
60const float kUIScalesFor1280[] = {0.5f, 0.625f, 0.8f, 1.0f, 1.125f };
61const float kUIScalesFor1366[] = {0.5f, 0.6f, 0.75f, 1.0f, 1.125f };
62
63struct DisplaySortFunctor {
64  bool operator()(const gfx::Display& a, const gfx::Display& b) {
65    return a.id() < b.id();
66  }
67};
68
69struct DisplayInfoSortFunctor {
70  bool operator()(const DisplayInfo& a, const DisplayInfo& b) {
71    return a.id() < b.id();
72  }
73};
74
75struct ResolutionMatcher {
76  ResolutionMatcher(const gfx::Size& size) : size(size) {}
77  bool operator()(const Resolution& resolution) {
78    return resolution.size == size;
79  }
80  gfx::Size size;
81};
82
83struct ScaleComparator {
84  ScaleComparator(float s) : scale(s) {}
85
86  bool operator()(float s) const {
87    const float kEpsilon = 0.0001f;
88    return std::abs(scale - s) < kEpsilon;
89  }
90  float scale;
91};
92
93gfx::Display& GetInvalidDisplay() {
94  static gfx::Display* invalid_display = new gfx::Display();
95  return *invalid_display;
96}
97
98void MaybeInitInternalDisplay(int64 id) {
99  CommandLine* command_line = CommandLine::ForCurrentProcess();
100  if (command_line->HasSwitch(switches::kAshUseFirstDisplayAsInternal))
101    gfx::Display::SetInternalDisplayId(id);
102}
103
104// Scoped objects used to either create or close the mirror window
105// at specific timing.
106class MirrorWindowUpdater {
107 public:
108  MirrorWindowUpdater(DisplayManager* manager,
109                      DisplayManager::Delegate* delegate)
110      : manager_(manager),
111        delegate_(delegate),
112        enabled_(manager_->software_mirroring_enabled() &&
113                 manager_->mirrored_display().is_valid()) {
114  }
115
116  ~MirrorWindowUpdater() {
117    if (!delegate_)
118      return;
119
120    if (enabled_) {
121      DisplayInfo display_info = manager_->GetDisplayInfo(
122          manager_->mirrored_display().id());
123      delegate_->CreateOrUpdateMirrorWindow(display_info);
124    } else {
125      delegate_->CloseMirrorWindow();
126    }
127  }
128
129  bool enabled() const { return enabled_; }
130
131 private:
132  DisplayManager* manager_;
133  DisplayManager::Delegate* delegate_;
134  bool enabled_;
135  DISALLOW_COPY_AND_ASSIGN(MirrorWindowUpdater);
136};
137
138}  // namespace
139
140using std::string;
141using std::vector;
142
143DisplayManager::DisplayManager()
144    : delegate_(NULL),
145      layout_store_(new DisplayLayoutStore),
146      first_display_id_(gfx::Display::kInvalidDisplayID),
147      num_connected_displays_(0),
148      force_bounds_changed_(false),
149      change_display_upon_host_resize_(false),
150      software_mirroring_enabled_(false) {
151#if defined(OS_CHROMEOS)
152  change_display_upon_host_resize_ = !base::SysInfo::IsRunningOnChromeOS();
153#endif
154}
155
156DisplayManager::~DisplayManager() {
157}
158
159// static
160std::vector<float> DisplayManager::GetScalesForDisplay(
161    const DisplayInfo& info) {
162  std::vector<float> ret;
163  if (info.device_scale_factor() == 2.0f) {
164    ret.assign(kUIScalesFor2x, kUIScalesFor2x + arraysize(kUIScalesFor2x));
165    return ret;
166  }
167  switch (info.bounds_in_native().width()) {
168    case 1280:
169      ret.assign(kUIScalesFor1280,
170                 kUIScalesFor1280 + arraysize(kUIScalesFor1280));
171      break;
172    case 1366:
173      ret.assign(kUIScalesFor1366,
174                 kUIScalesFor1366 + arraysize(kUIScalesFor1366));
175      break;
176    default:
177      ret.assign(kUIScalesFor1280,
178                 kUIScalesFor1280 + arraysize(kUIScalesFor1280));
179#if defined(OS_CHROMEOS)
180      if (base::SysInfo::IsRunningOnChromeOS())
181        NOTREACHED() << "Unknown resolution:" << info.ToString();
182#endif
183  }
184  return ret;
185}
186
187// static
188float DisplayManager::GetNextUIScale(const DisplayInfo& info, bool up) {
189  float scale = info.ui_scale();
190  std::vector<float> scales = GetScalesForDisplay(info);
191  for (size_t i = 0; i < scales.size(); ++i) {
192    if (ScaleComparator(scales[i])(scale)) {
193      if (up && i != scales.size() - 1)
194        return scales[i + 1];
195      if (!up && i != 0)
196        return scales[i - 1];
197      return scales[i];
198    }
199  }
200  // Fallback to 1.0f if the |scale| wasn't in the list.
201  return 1.0f;
202}
203
204void DisplayManager::InitFromCommandLine() {
205  DisplayInfoList info_list;
206  CommandLine* command_line = CommandLine::ForCurrentProcess();
207  const string size_str =
208      command_line->GetSwitchValueASCII(switches::kAshHostWindowBounds);
209  vector<string> parts;
210  base::SplitString(size_str, ',', &parts);
211  for (vector<string>::const_iterator iter = parts.begin();
212       iter != parts.end(); ++iter) {
213    info_list.push_back(DisplayInfo::CreateFromSpec(*iter));
214  }
215  if (info_list.size())
216    MaybeInitInternalDisplay(info_list[0].id());
217  if (info_list.size() > 1 &&
218      command_line->HasSwitch(switches::kAshEnableSoftwareMirroring)) {
219    SetSoftwareMirroring(true);
220  }
221  OnNativeDisplaysChanged(info_list);
222}
223
224// static
225void DisplayManager::UpdateDisplayBoundsForLayoutById(
226    const DisplayLayout& layout,
227    const gfx::Display& primary_display,
228    int64 secondary_display_id) {
229  DCHECK_NE(gfx::Display::kInvalidDisplayID, secondary_display_id);
230  UpdateDisplayBoundsForLayout(
231      layout, primary_display,
232      Shell::GetInstance()->display_manager()->
233      FindDisplayForId(secondary_display_id));
234}
235
236bool DisplayManager::IsActiveDisplay(const gfx::Display& display) const {
237  for (DisplayList::const_iterator iter = displays_.begin();
238       iter != displays_.end(); ++iter) {
239    if ((*iter).id() == display.id())
240      return true;
241  }
242  return false;
243}
244
245bool DisplayManager::HasInternalDisplay() const {
246  return gfx::Display::InternalDisplayId() != gfx::Display::kInvalidDisplayID;
247}
248
249bool DisplayManager::IsInternalDisplayId(int64 id) const {
250  return gfx::Display::InternalDisplayId() == id;
251}
252
253DisplayLayout DisplayManager::GetCurrentDisplayLayout() {
254  DCHECK_EQ(2U, num_connected_displays());
255  // Invert if the primary was swapped.
256  if (num_connected_displays() > 1) {
257    DisplayIdPair pair = GetCurrentDisplayIdPair();
258    return layout_store_->ComputeDisplayLayoutForDisplayIdPair(pair);
259  }
260  NOTREACHED() << "DisplayLayout is requested for single display";
261  // On release build, just fallback to default instead of blowing up.
262  DisplayLayout layout =
263      layout_store_->default_display_layout();
264  layout.primary_id = displays_[0].id();
265  return layout;
266}
267
268DisplayIdPair DisplayManager::GetCurrentDisplayIdPair() const {
269  if (IsMirrored()) {
270    DCHECK_LE(2u, num_connected_displays());
271    int64 mirrored_id = mirrored_display().id();
272    return std::make_pair(displays_[0].id(), mirrored_id);
273  } else {
274    CHECK_LE(2u, displays_.size());
275    int64 id_at_zero = displays_[0].id();
276    if (id_at_zero == gfx::Display::InternalDisplayId() ||
277        id_at_zero == first_display_id()) {
278      return std::make_pair(id_at_zero, displays_[1].id());
279    } else {
280      return std::make_pair(displays_[1].id(), id_at_zero);
281    }
282  }
283}
284
285const gfx::Display& DisplayManager::GetDisplayForId(int64 id) const {
286  gfx::Display* display =
287      const_cast<DisplayManager*>(this)->FindDisplayForId(id);
288  return display ? *display : GetInvalidDisplay();
289}
290
291const gfx::Display& DisplayManager::FindDisplayContainingPoint(
292    const gfx::Point& point_in_screen) const {
293  for (DisplayList::const_iterator iter = displays_.begin();
294       iter != displays_.end(); ++iter) {
295    const gfx::Display& display = *iter;
296    if (display.bounds().Contains(point_in_screen))
297      return display;
298  }
299  return GetInvalidDisplay();
300}
301
302bool DisplayManager::UpdateWorkAreaOfDisplay(int64 display_id,
303                                             const gfx::Insets& insets) {
304  gfx::Display* display = FindDisplayForId(display_id);
305  DCHECK(display);
306  gfx::Rect old_work_area = display->work_area();
307  display->UpdateWorkAreaFromInsets(insets);
308  return old_work_area != display->work_area();
309}
310
311void DisplayManager::SetOverscanInsets(int64 display_id,
312                                       const gfx::Insets& insets_in_dip) {
313  display_info_[display_id].SetOverscanInsets(insets_in_dip);
314  DisplayInfoList display_info_list;
315  for (DisplayList::const_iterator iter = displays_.begin();
316       iter != displays_.end(); ++iter) {
317    display_info_list.push_back(GetDisplayInfo(iter->id()));
318  }
319  AddMirrorDisplayInfoIfAny(&display_info_list);
320  UpdateDisplays(display_info_list);
321}
322
323void DisplayManager::SetDisplayRotation(int64 display_id,
324                                        gfx::Display::Rotation rotation) {
325  DisplayInfoList display_info_list;
326  for (DisplayList::const_iterator iter = displays_.begin();
327       iter != displays_.end(); ++iter) {
328    DisplayInfo info = GetDisplayInfo(iter->id());
329    if (info.id() == display_id) {
330      if (info.rotation() == rotation)
331        return;
332      info.set_rotation(rotation);
333    }
334    display_info_list.push_back(info);
335  }
336  AddMirrorDisplayInfoIfAny(&display_info_list);
337  UpdateDisplays(display_info_list);
338}
339
340void DisplayManager::SetDisplayUIScale(int64 display_id,
341                                       float ui_scale) {
342  if (!IsDisplayUIScalingEnabled() ||
343      gfx::Display::InternalDisplayId() != display_id) {
344    return;
345  }
346
347  DisplayInfoList display_info_list;
348  for (DisplayList::const_iterator iter = displays_.begin();
349       iter != displays_.end(); ++iter) {
350    DisplayInfo info = GetDisplayInfo(iter->id());
351    if (info.id() == display_id) {
352      if (info.ui_scale() == ui_scale)
353        return;
354      std::vector<float> scales = GetScalesForDisplay(info);
355      ScaleComparator comparator(ui_scale);
356      if (std::find_if(scales.begin(), scales.end(), comparator) ==
357          scales.end()) {
358        return;
359      }
360      info.set_ui_scale(ui_scale);
361    }
362    display_info_list.push_back(info);
363  }
364  AddMirrorDisplayInfoIfAny(&display_info_list);
365  UpdateDisplays(display_info_list);
366}
367
368void DisplayManager::SetDisplayResolution(int64 display_id,
369                                          const gfx::Size& resolution) {
370  DCHECK_NE(gfx::Display::InternalDisplayId(), display_id);
371  if (gfx::Display::InternalDisplayId() == display_id)
372    return;
373  const DisplayInfo& display_info = GetDisplayInfo(display_id);
374  const std::vector<Resolution>& resolutions = display_info.resolutions();
375  DCHECK_NE(0u, resolutions.size());
376  std::vector<Resolution>::const_iterator iter =
377      std::find_if(resolutions.begin(),
378                   resolutions.end(),
379                   ResolutionMatcher(resolution));
380  if (iter == resolutions.end()) {
381    LOG(WARNING) << "Unsupported resolution was requested:"
382                 << resolution.ToString();
383    return;
384  } else if (iter == resolutions.begin()) {
385    // The best resolution was set, so forget it.
386    resolutions_.erase(display_id);
387  } else {
388    resolutions_[display_id] = resolution;
389  }
390#if defined(OS_CHROMEOS) && defined(USE_X11)
391  if (base::SysInfo::IsRunningOnChromeOS())
392    Shell::GetInstance()->output_configurator()->ScheduleConfigureOutputs();
393#endif
394}
395
396void DisplayManager::RegisterDisplayProperty(
397    int64 display_id,
398    gfx::Display::Rotation rotation,
399    float ui_scale,
400    const gfx::Insets* overscan_insets,
401    const gfx::Size& resolution_in_pixels) {
402  if (display_info_.find(display_id) == display_info_.end()) {
403    display_info_[display_id] =
404        DisplayInfo(display_id, std::string(""), false);
405  }
406
407  display_info_[display_id].set_rotation(rotation);
408  // Just in case the preference file was corrupted.
409  if (0.5f <= ui_scale && ui_scale <= 2.0f)
410    display_info_[display_id].set_ui_scale(ui_scale);
411  if (overscan_insets)
412    display_info_[display_id].SetOverscanInsets(*overscan_insets);
413  if (!resolution_in_pixels.IsEmpty())
414    resolutions_[display_id] = resolution_in_pixels;
415}
416
417bool DisplayManager::GetSelectedResolutionForDisplayId(
418    int64 id,
419    gfx::Size* resolution_out) const {
420  std::map<int64, gfx::Size>::const_iterator iter =
421      resolutions_.find(id);
422  if (iter == resolutions_.end())
423    return false;
424  *resolution_out = iter->second;
425  return true;
426}
427
428bool DisplayManager::IsDisplayUIScalingEnabled() const {
429  return GetDisplayIdForUIScaling() != gfx::Display::kInvalidDisplayID;
430}
431
432gfx::Insets DisplayManager::GetOverscanInsets(int64 display_id) const {
433  std::map<int64, DisplayInfo>::const_iterator it =
434      display_info_.find(display_id);
435  return (it != display_info_.end()) ?
436      it->second.overscan_insets_in_dip() : gfx::Insets();
437}
438
439void DisplayManager::OnNativeDisplaysChanged(
440    const std::vector<DisplayInfo>& updated_displays) {
441  if (updated_displays.empty()) {
442    // If the device is booted without display, or chrome is started
443    // without --ash-host-window-bounds on linux desktop, use the
444    // default display.
445    if (displays_.empty()) {
446      std::vector<DisplayInfo> init_displays;
447      init_displays.push_back(DisplayInfo::CreateFromSpec(std::string()));
448      MaybeInitInternalDisplay(init_displays[0].id());
449      OnNativeDisplaysChanged(init_displays);
450    } else {
451      // Otherwise don't update the displays when all displays are disconnected.
452      // This happens when:
453      // - the device is idle and powerd requested to turn off all displays.
454      // - the device is suspended. (kernel turns off all displays)
455      // - the internal display's brightness is set to 0 and no external
456      //   display is connected.
457      // - the internal display's brightness is 0 and external display is
458      //   disconnected.
459      // The display will be updated when one of displays is turned on, and the
460      // display list will be updated correctly.
461    }
462    return;
463  }
464  first_display_id_ = updated_displays[0].id();
465  std::set<gfx::Point> origins;
466
467  if (updated_displays.size() == 1) {
468    VLOG(1) << "OnNativeDisplaysChanged(1):" << updated_displays[0].ToString();
469  } else {
470    VLOG(1) << "OnNativeDisplaysChanged(" << updated_displays.size()
471            << ") [0]=" << updated_displays[0].ToString()
472            << ", [1]=" << updated_displays[1].ToString();
473  }
474
475  bool internal_display_connected = false;
476  num_connected_displays_ = updated_displays.size();
477  mirrored_display_ = gfx::Display();
478  DisplayInfoList new_display_info_list;
479  for (DisplayInfoList::const_iterator iter = updated_displays.begin();
480       iter != updated_displays.end();
481       ++iter) {
482    if (!internal_display_connected)
483      internal_display_connected = IsInternalDisplayId(iter->id());
484    // Mirrored monitors have the same origins.
485    gfx::Point origin = iter->bounds_in_native().origin();
486    if (origins.find(origin) != origins.end()) {
487      InsertAndUpdateDisplayInfo(*iter);
488      mirrored_display_ = CreateDisplayFromDisplayInfoById(iter->id());
489    } else {
490      origins.insert(origin);
491      new_display_info_list.push_back(*iter);
492    }
493  }
494  if (HasInternalDisplay() &&
495      !internal_display_connected &&
496      display_info_.find(gfx::Display::InternalDisplayId()) ==
497      display_info_.end()) {
498    DisplayInfo internal_display_info(
499        gfx::Display::InternalDisplayId(),
500        l10n_util::GetStringUTF8(IDS_ASH_INTERNAL_DISPLAY_NAME),
501        false  /*Internal display must not have overscan */);
502    internal_display_info.SetBounds(gfx::Rect(0, 0, 800, 600));
503    display_info_[gfx::Display::InternalDisplayId()] = internal_display_info;
504  }
505  UpdateDisplays(new_display_info_list);
506}
507
508void DisplayManager::UpdateDisplays() {
509  DisplayInfoList display_info_list;
510  for (DisplayList::const_iterator iter = displays_.begin();
511       iter != displays_.end(); ++iter) {
512    display_info_list.push_back(GetDisplayInfo(iter->id()));
513  }
514  AddMirrorDisplayInfoIfAny(&display_info_list);
515  UpdateDisplays(display_info_list);
516}
517
518void DisplayManager::UpdateDisplays(
519    const std::vector<DisplayInfo>& updated_display_info_list) {
520#if defined(OS_WIN)
521  if (base::win::GetVersion() >= base::win::VERSION_WIN8) {
522    DCHECK_EQ(1u, updated_display_info_list.size()) <<
523        "Multiple display test does not work on Win8 bots. Please "
524        "skip (don't disable) the test using SupportsMultipleDisplays()";
525  }
526#endif
527
528  DisplayInfoList new_display_info_list = updated_display_info_list;
529  std::sort(displays_.begin(), displays_.end(), DisplaySortFunctor());
530  std::sort(new_display_info_list.begin(),
531            new_display_info_list.end(),
532            DisplayInfoSortFunctor());
533  DisplayList removed_displays;
534  std::vector<size_t> changed_display_indices;
535  std::vector<size_t> added_display_indices;
536
537  DisplayList::iterator curr_iter = displays_.begin();
538  DisplayInfoList::const_iterator new_info_iter = new_display_info_list.begin();
539
540  DisplayList new_displays;
541
542  // Use the internal display or 1st as the mirror source, then scale
543  // the root window so that it matches the external display's
544  // resolution. This is necessary in order for scaling to work while
545  // mirrored.
546  int64 mirrored_display_id = gfx::Display::kInvalidDisplayID;
547  if (software_mirroring_enabled_ && new_display_info_list.size() == 2) {
548    bool zero_is_source =
549        first_display_id_ == new_display_info_list[0].id() ||
550        gfx::Display::InternalDisplayId() == new_display_info_list[0].id();
551    mirrored_display_id = new_display_info_list[zero_is_source ? 1 : 0].id();
552  }
553
554  while (curr_iter != displays_.end() ||
555         new_info_iter != new_display_info_list.end()) {
556    if (new_info_iter != new_display_info_list.end() &&
557        mirrored_display_id == new_info_iter->id()) {
558      DisplayInfo info = *new_info_iter;
559      info.SetOverscanInsets(gfx::Insets());
560      InsertAndUpdateDisplayInfo(info);
561      mirrored_display_ = CreateDisplayFromDisplayInfoById(new_info_iter->id());
562      ++new_info_iter;
563      // Remove existing external dispaly if it is going to be mirrored.
564      if (curr_iter != displays_.end() &&
565          curr_iter->id() == mirrored_display_id) {
566        removed_displays.push_back(*curr_iter);
567        ++curr_iter;
568      }
569      continue;
570    }
571
572    if (curr_iter == displays_.end()) {
573      // more displays in new list.
574      added_display_indices.push_back(new_displays.size());
575      InsertAndUpdateDisplayInfo(*new_info_iter);
576      new_displays.push_back(
577          CreateDisplayFromDisplayInfoById(new_info_iter->id()));
578      ++new_info_iter;
579    } else if (new_info_iter == new_display_info_list.end()) {
580      // more displays in current list.
581      removed_displays.push_back(*curr_iter);
582      ++curr_iter;
583    } else if (curr_iter->id() == new_info_iter->id()) {
584      const gfx::Display& current_display = *curr_iter;
585      // Copy the info because |CreateDisplayFromInfo| updates the instance.
586      const DisplayInfo current_display_info =
587          GetDisplayInfo(current_display.id());
588      InsertAndUpdateDisplayInfo(*new_info_iter);
589      gfx::Display new_display =
590          CreateDisplayFromDisplayInfoById(new_info_iter->id());
591      const DisplayInfo& new_display_info = GetDisplayInfo(new_display.id());
592
593      bool host_window_bounds_changed =
594          current_display_info.bounds_in_native() !=
595          new_display_info.bounds_in_native();
596
597      if (force_bounds_changed_ ||
598          host_window_bounds_changed ||
599          (current_display.device_scale_factor() !=
600           new_display.device_scale_factor()) ||
601          (current_display_info.size_in_pixel() !=
602           new_display.GetSizeInPixel()) ||
603          (current_display.rotation() != new_display.rotation())) {
604
605        changed_display_indices.push_back(new_displays.size());
606      }
607
608      new_display.UpdateWorkAreaFromInsets(current_display.GetWorkAreaInsets());
609      new_displays.push_back(new_display);
610      ++curr_iter;
611      ++new_info_iter;
612    } else if (curr_iter->id() < new_info_iter->id()) {
613      // more displays in current list between ids, which means it is deleted.
614      removed_displays.push_back(*curr_iter);
615      ++curr_iter;
616    } else {
617      // more displays in new list between ids, which means it is added.
618      added_display_indices.push_back(new_displays.size());
619      InsertAndUpdateDisplayInfo(*new_info_iter);
620      new_displays.push_back(
621          CreateDisplayFromDisplayInfoById(new_info_iter->id()));
622      ++new_info_iter;
623    }
624  }
625
626  scoped_ptr<MirrorWindowUpdater> mirror_window_updater(
627      new MirrorWindowUpdater(this, delegate_));
628
629  // Do not update |displays_| if there's nothing to be updated. Without this,
630  // it will not update the display layout, which causes the bug
631  // http://crbug.com/155948.
632  if (changed_display_indices.empty() && added_display_indices.empty() &&
633      removed_displays.empty()) {
634    return;
635  }
636  if (delegate_)
637    delegate_->PreDisplayConfigurationChange(!removed_displays.empty());
638
639  size_t updated_index;
640  if (UpdateSecondaryDisplayBoundsForLayout(&new_displays, &updated_index) &&
641      std::find(added_display_indices.begin(),
642                added_display_indices.end(),
643                updated_index) == added_display_indices.end() &&
644      std::find(changed_display_indices.begin(),
645                changed_display_indices.end(),
646                updated_index) == changed_display_indices.end()) {
647    changed_display_indices.push_back(updated_index);
648  }
649
650  displays_ = new_displays;
651
652  base::AutoReset<bool> resetter(&change_display_upon_host_resize_, false);
653
654  // Temporarily add displays to be removed because display object
655  // being removed are accessed during shutting down the root.
656  displays_.insert(displays_.end(), removed_displays.begin(),
657                   removed_displays.end());
658
659  for (DisplayList::const_reverse_iterator iter = removed_displays.rbegin();
660       iter != removed_displays.rend(); ++iter) {
661    Shell::GetInstance()->screen()->NotifyDisplayRemoved(displays_.back());
662    displays_.pop_back();
663  }
664  // Close the mirror window here to avoid creating two compositor on
665  // one display.
666  if (!mirror_window_updater->enabled())
667    mirror_window_updater.reset();
668  for (std::vector<size_t>::iterator iter = added_display_indices.begin();
669       iter != added_display_indices.end(); ++iter) {
670    Shell::GetInstance()->screen()->NotifyDisplayAdded(displays_[*iter]);
671  }
672  // Create the mirror window after all displays are added so that
673  // it can mirror the display newly added. This can happen when switching
674  // from dock mode to software mirror mode.
675  mirror_window_updater.reset();
676  for (std::vector<size_t>::iterator iter = changed_display_indices.begin();
677       iter != changed_display_indices.end(); ++iter) {
678    Shell::GetInstance()->screen()->NotifyBoundsChanged(displays_[*iter]);
679  }
680  if (delegate_)
681    delegate_->PostDisplayConfigurationChange();
682
683#if defined(USE_X11) && defined(OS_CHROMEOS)
684  if (!changed_display_indices.empty() && base::SysInfo::IsRunningOnChromeOS())
685    ui::ClearX11DefaultRootWindow();
686#endif
687}
688
689const gfx::Display& DisplayManager::GetDisplayAt(size_t index) const {
690  DCHECK_LT(index, displays_.size());
691  return displays_[index];
692}
693
694const gfx::Display& DisplayManager::GetPrimaryDisplayCandidate() const {
695  if (GetNumDisplays() == 1) {
696    return displays_[0];
697  }
698  DisplayLayout layout = layout_store_->GetRegisteredDisplayLayout(
699      GetCurrentDisplayIdPair());
700  return GetDisplayForId(layout.primary_id);
701}
702
703size_t DisplayManager::GetNumDisplays() const {
704  return displays_.size();
705}
706
707bool DisplayManager::IsMirrored() const {
708  return mirrored_display_.id() != gfx::Display::kInvalidDisplayID;
709}
710
711const DisplayInfo& DisplayManager::GetDisplayInfo(int64 display_id) const {
712  std::map<int64, DisplayInfo>::const_iterator iter =
713      display_info_.find(display_id);
714  CHECK(iter != display_info_.end()) << display_id;
715  return iter->second;
716}
717
718std::string DisplayManager::GetDisplayNameForId(int64 id) {
719  if (id == gfx::Display::kInvalidDisplayID)
720    return l10n_util::GetStringUTF8(IDS_ASH_STATUS_TRAY_UNKNOWN_DISPLAY_NAME);
721
722  std::map<int64, DisplayInfo>::const_iterator iter = display_info_.find(id);
723  if (iter != display_info_.end() && !iter->second.name().empty())
724    return iter->second.name();
725
726  return base::StringPrintf("Display %d", static_cast<int>(id));
727}
728
729int64 DisplayManager::GetDisplayIdForUIScaling() const {
730  // UI Scaling is effective only on internal display.
731  int64 display_id = gfx::Display::InternalDisplayId();
732#if defined(OS_WIN)
733  display_id = first_display_id();
734#endif
735  return display_id;
736}
737
738void DisplayManager::SetMirrorMode(bool mirrored) {
739  if (num_connected_displays() <= 1)
740    return;
741
742#if defined(OS_CHROMEOS)
743  if (base::SysInfo::IsRunningOnChromeOS()) {
744    chromeos::OutputState new_state = mirrored ?
745        chromeos::STATE_DUAL_MIRROR : chromeos::STATE_DUAL_EXTENDED;
746    Shell::GetInstance()->output_configurator()->SetDisplayMode(new_state);
747    return;
748  }
749#endif
750  SetSoftwareMirroring(mirrored);
751  DisplayInfoList display_info_list;
752  int count = 0;
753  for (std::map<int64, DisplayInfo>::const_iterator iter =
754           display_info_.begin();
755       count < 2; ++iter, ++count) {
756    display_info_list.push_back(GetDisplayInfo(iter->second.id()));
757  }
758  UpdateDisplays(display_info_list);
759#if defined(OS_CHROMEOS)
760  if (Shell::GetInstance()->output_configurator_animation()) {
761    Shell::GetInstance()->output_configurator_animation()->
762        StartFadeInAnimation();
763  }
764#endif
765}
766
767void DisplayManager::AddRemoveDisplay() {
768  DCHECK(!displays_.empty());
769  std::vector<DisplayInfo> new_display_info_list;
770  const DisplayInfo& first_display = GetDisplayInfo(displays_[0].id());
771  new_display_info_list.push_back(first_display);
772  // Add if there is only one display connected.
773  if (num_connected_displays() == 1) {
774    // Layout the 2nd display below the primary as with the real device.
775    gfx::Rect host_bounds = first_display.bounds_in_native();
776    new_display_info_list.push_back(DisplayInfo::CreateFromSpec(
777        base::StringPrintf(
778            "%d+%d-500x400", host_bounds.x(), host_bounds.bottom())));
779  }
780  num_connected_displays_ = new_display_info_list.size();
781  mirrored_display_ = gfx::Display();
782  UpdateDisplays(new_display_info_list);
783}
784
785void DisplayManager::ToggleDisplayScaleFactor() {
786  DCHECK(!displays_.empty());
787  std::vector<DisplayInfo> new_display_info_list;
788  for (DisplayList::const_iterator iter = displays_.begin();
789       iter != displays_.end(); ++iter) {
790    DisplayInfo display_info = GetDisplayInfo(iter->id());
791    display_info.set_device_scale_factor(
792        display_info.device_scale_factor() == 1.0f ? 2.0f : 1.0f);
793    new_display_info_list.push_back(display_info);
794  }
795  AddMirrorDisplayInfoIfAny(&new_display_info_list);
796  UpdateDisplays(new_display_info_list);
797}
798
799void DisplayManager::SetSoftwareMirroring(bool enabled) {
800  software_mirroring_enabled_ = enabled;
801  mirrored_display_ = gfx::Display();
802}
803
804bool DisplayManager::UpdateDisplayBounds(int64 display_id,
805                                         const gfx::Rect& new_bounds) {
806  if (change_display_upon_host_resize_) {
807    display_info_[display_id].SetBounds(new_bounds);
808    // Don't notify observers if the mirrored window has changed.
809    if (software_mirroring_enabled_ && mirrored_display_.id() == display_id)
810      return false;
811    gfx::Display* display = FindDisplayForId(display_id);
812    display->SetSize(display_info_[display_id].size_in_pixel());
813    Shell::GetInstance()->screen()->NotifyBoundsChanged(*display);
814    return true;
815  }
816  return false;
817}
818
819void DisplayManager::CreateMirrorWindowIfAny() {
820  MirrorWindowUpdater updater(this, delegate_);
821}
822
823gfx::Display* DisplayManager::FindDisplayForId(int64 id) {
824  for (DisplayList::iterator iter = displays_.begin();
825       iter != displays_.end(); ++iter) {
826    if ((*iter).id() == id)
827      return &(*iter);
828  }
829  DLOG(WARNING) << "Could not find display:" << id;
830  return NULL;
831}
832
833void DisplayManager::AddMirrorDisplayInfoIfAny(
834    std::vector<DisplayInfo>* display_info_list) {
835  if (software_mirroring_enabled_ && mirrored_display_.is_valid())
836    display_info_list->push_back(GetDisplayInfo(mirrored_display_.id()));
837}
838
839void DisplayManager::InsertAndUpdateDisplayInfo(const DisplayInfo& new_info) {
840  std::map<int64, DisplayInfo>::iterator info =
841      display_info_.find(new_info.id());
842  if (info != display_info_.end())
843    info->second.Copy(new_info);
844  else {
845    display_info_[new_info.id()] = new_info;
846    display_info_[new_info.id()].set_native(false);
847  }
848  display_info_[new_info.id()].UpdateDisplaySize();
849}
850
851gfx::Display DisplayManager::CreateDisplayFromDisplayInfoById(int64 id) {
852  DCHECK(display_info_.find(id) != display_info_.end());
853  const DisplayInfo& display_info = display_info_[id];
854
855  gfx::Display new_display(display_info.id());
856  gfx::Rect bounds_in_native(display_info.size_in_pixel());
857
858  // Simply set the origin to (0,0).  The primary display's origin is
859  // always (0,0) and the secondary display's bounds will be updated
860  // in |UpdateSecondaryDisplayBoundsForLayout| called in |UpdateDisplay|.
861  new_display.SetScaleAndBounds(
862      display_info.device_scale_factor(), gfx::Rect(bounds_in_native.size()));
863  new_display.set_rotation(display_info.rotation());
864  return new_display;
865}
866
867bool DisplayManager::UpdateSecondaryDisplayBoundsForLayout(
868    DisplayList* displays,
869    size_t* updated_index) const {
870  if (displays->size() != 2U)
871    return false;
872
873  int64 id_at_zero = displays->at(0).id();
874  DisplayIdPair pair =
875      (id_at_zero == first_display_id_ ||
876       id_at_zero == gfx::Display::InternalDisplayId()) ?
877      std::make_pair(id_at_zero, displays->at(1).id()) :
878      std::make_pair(displays->at(1).id(), id_at_zero) ;
879  DisplayLayout layout =
880      layout_store_->ComputeDisplayLayoutForDisplayIdPair(pair);
881
882  // Ignore if a user has a old format (should be extremely rare)
883  // and this will be replaced with DCHECK.
884  if (layout.primary_id != gfx::Display::kInvalidDisplayID) {
885    size_t primary_index, secondary_index;
886    if (displays->at(0).id() == layout.primary_id) {
887      primary_index = 0;
888      secondary_index = 1;
889    } else {
890      primary_index = 1;
891      secondary_index = 0;
892    }
893    // This function may be called before the secondary display is
894    // registered. The bounds is empty in that case and will
895    // return true.
896    gfx::Rect bounds =
897        GetDisplayForId(displays->at(secondary_index).id()).bounds();
898    UpdateDisplayBoundsForLayout(
899        layout, displays->at(primary_index), &displays->at(secondary_index));
900    *updated_index = secondary_index;
901    return bounds != displays->at(secondary_index).bounds();
902  }
903  return false;
904}
905
906
907// static
908void DisplayManager::UpdateDisplayBoundsForLayout(
909    const DisplayLayout& layout,
910    const gfx::Display& primary_display,
911    gfx::Display* secondary_display) {
912  DCHECK_EQ("0,0", primary_display.bounds().origin().ToString());
913
914  const gfx::Rect& primary_bounds = primary_display.bounds();
915  const gfx::Rect& secondary_bounds = secondary_display->bounds();
916  gfx::Point new_secondary_origin = primary_bounds.origin();
917
918  DisplayLayout::Position position = layout.position;
919
920  // Ignore the offset in case the secondary display doesn't share edges with
921  // the primary display.
922  int offset = layout.offset;
923  if (position == DisplayLayout::TOP || position == DisplayLayout::BOTTOM) {
924    offset = std::min(
925        offset, primary_bounds.width() - kMinimumOverlapForInvalidOffset);
926    offset = std::max(
927        offset, -secondary_bounds.width() + kMinimumOverlapForInvalidOffset);
928  } else {
929    offset = std::min(
930        offset, primary_bounds.height() - kMinimumOverlapForInvalidOffset);
931    offset = std::max(
932        offset, -secondary_bounds.height() + kMinimumOverlapForInvalidOffset);
933  }
934  switch (position) {
935    case DisplayLayout::TOP:
936      new_secondary_origin.Offset(offset, -secondary_bounds.height());
937      break;
938    case DisplayLayout::RIGHT:
939      new_secondary_origin.Offset(primary_bounds.width(), offset);
940      break;
941    case DisplayLayout::BOTTOM:
942      new_secondary_origin.Offset(offset, primary_bounds.height());
943      break;
944    case DisplayLayout::LEFT:
945      new_secondary_origin.Offset(-secondary_bounds.width(), offset);
946      break;
947  }
948  gfx::Insets insets = secondary_display->GetWorkAreaInsets();
949  secondary_display->set_bounds(
950      gfx::Rect(new_secondary_origin, secondary_bounds.size()));
951  secondary_display->UpdateWorkAreaFromInsets(insets);
952}
953
954}  // namespace internal
955}  // namespace ash
956