display_manager.cc revision 68043e1e95eeb07d5cae7aca370b26518b0867d6
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/chromeos/chromeos_version.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::chromeos::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::chromeos::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    int64 mirrored_id = mirrored_display().id();
271    return displays_[0].id() == mirrored_id ?
272        std::make_pair(displays_[1].id(), mirrored_id) :
273        std::make_pair(displays_[0].id(), mirrored_id);
274  } else {
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::chromeos::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    mirrored_display_id = new_display_info_list[1].id();
549
550  while (curr_iter != displays_.end() ||
551         new_info_iter != new_display_info_list.end()) {
552    if (new_info_iter != new_display_info_list.end() &&
553        mirrored_display_id == new_info_iter->id()) {
554      DisplayInfo info = *new_info_iter;
555      info.SetOverscanInsets(gfx::Insets());
556      InsertAndUpdateDisplayInfo(info);
557      mirrored_display_ = CreateDisplayFromDisplayInfoById(new_info_iter->id());
558      ++new_info_iter;
559      // Remove existing external dispaly if it is going to be mirrored.
560      if (curr_iter != displays_.end() &&
561          curr_iter->id() == mirrored_display_id) {
562        removed_displays.push_back(*curr_iter);
563        ++curr_iter;
564      }
565      continue;
566    }
567
568    if (curr_iter == displays_.end()) {
569      // more displays in new list.
570      added_display_indices.push_back(new_displays.size());
571      InsertAndUpdateDisplayInfo(*new_info_iter);
572      new_displays.push_back(
573          CreateDisplayFromDisplayInfoById(new_info_iter->id()));
574      ++new_info_iter;
575    } else if (new_info_iter == new_display_info_list.end()) {
576      // more displays in current list.
577      removed_displays.push_back(*curr_iter);
578      ++curr_iter;
579    } else if (curr_iter->id() == new_info_iter->id()) {
580      const gfx::Display& current_display = *curr_iter;
581      // Copy the info because |CreateDisplayFromInfo| updates the instance.
582      const DisplayInfo current_display_info =
583          GetDisplayInfo(current_display.id());
584      InsertAndUpdateDisplayInfo(*new_info_iter);
585      gfx::Display new_display =
586          CreateDisplayFromDisplayInfoById(new_info_iter->id());
587      const DisplayInfo& new_display_info = GetDisplayInfo(new_display.id());
588
589      bool host_window_bounds_changed =
590          current_display_info.bounds_in_native() !=
591          new_display_info.bounds_in_native();
592
593      if (force_bounds_changed_ ||
594          host_window_bounds_changed ||
595          (current_display.device_scale_factor() !=
596           new_display.device_scale_factor()) ||
597          (current_display_info.size_in_pixel() !=
598           new_display.GetSizeInPixel()) ||
599          (current_display.rotation() != new_display.rotation())) {
600
601        changed_display_indices.push_back(new_displays.size());
602      }
603
604      new_display.UpdateWorkAreaFromInsets(current_display.GetWorkAreaInsets());
605      new_displays.push_back(new_display);
606      ++curr_iter;
607      ++new_info_iter;
608    } else if (curr_iter->id() < new_info_iter->id()) {
609      // more displays in current list between ids, which means it is deleted.
610      removed_displays.push_back(*curr_iter);
611      ++curr_iter;
612    } else {
613      // more displays in new list between ids, which means it is added.
614      added_display_indices.push_back(new_displays.size());
615      InsertAndUpdateDisplayInfo(*new_info_iter);
616      new_displays.push_back(
617          CreateDisplayFromDisplayInfoById(new_info_iter->id()));
618      ++new_info_iter;
619    }
620  }
621
622  scoped_ptr<MirrorWindowUpdater> mirror_window_updater(
623      new MirrorWindowUpdater(this, delegate_));
624
625  // Do not update |displays_| if there's nothing to be updated. Without this,
626  // it will not update the display layout, which causes the bug
627  // http://crbug.com/155948.
628  if (changed_display_indices.empty() && added_display_indices.empty() &&
629      removed_displays.empty()) {
630    return;
631  }
632  if (delegate_)
633    delegate_->PreDisplayConfigurationChange(!removed_displays.empty());
634
635  size_t updated_index;
636  if (UpdateSecondaryDisplayBoundsForLayout(&new_displays, &updated_index) &&
637      std::find(added_display_indices.begin(),
638                added_display_indices.end(),
639                updated_index) == added_display_indices.end() &&
640      std::find(changed_display_indices.begin(),
641                changed_display_indices.end(),
642                updated_index) == changed_display_indices.end()) {
643    changed_display_indices.push_back(updated_index);
644  }
645
646  displays_ = new_displays;
647
648  base::AutoReset<bool> resetter(&change_display_upon_host_resize_, false);
649
650  // Temporarily add displays to be removed because display object
651  // being removed are accessed during shutting down the root.
652  displays_.insert(displays_.end(), removed_displays.begin(),
653                   removed_displays.end());
654
655  for (DisplayList::const_reverse_iterator iter = removed_displays.rbegin();
656       iter != removed_displays.rend(); ++iter) {
657    Shell::GetInstance()->screen()->NotifyDisplayRemoved(displays_.back());
658    displays_.pop_back();
659  }
660  // Close the mirror window here to avoid creating two compositor on
661  // one display.
662  if (!mirror_window_updater->enabled())
663    mirror_window_updater.reset();
664  for (std::vector<size_t>::iterator iter = added_display_indices.begin();
665       iter != added_display_indices.end(); ++iter) {
666    Shell::GetInstance()->screen()->NotifyDisplayAdded(displays_[*iter]);
667  }
668  // Create the mirror window after all displays are added so that
669  // it can mirror the display newly added. This can happen when switching
670  // from dock mode to software mirror mode.
671  mirror_window_updater.reset();
672  for (std::vector<size_t>::iterator iter = changed_display_indices.begin();
673       iter != changed_display_indices.end(); ++iter) {
674    Shell::GetInstance()->screen()->NotifyBoundsChanged(displays_[*iter]);
675  }
676  if (delegate_)
677    delegate_->PostDisplayConfigurationChange();
678
679#if defined(USE_X11) && defined(OS_CHROMEOS)
680  if (!changed_display_indices.empty() && base::chromeos::IsRunningOnChromeOS())
681    ui::ClearX11DefaultRootWindow();
682#endif
683}
684
685const gfx::Display& DisplayManager::GetDisplayAt(size_t index) const {
686  DCHECK_LT(index, displays_.size());
687  return displays_[index];
688}
689
690const gfx::Display& DisplayManager::GetPrimaryDisplayCandidate() const {
691  if (GetNumDisplays() == 1) {
692    return displays_[0];
693  }
694  DisplayLayout layout = layout_store_->GetRegisteredDisplayLayout(
695      GetCurrentDisplayIdPair());
696  return GetDisplayForId(layout.primary_id);
697}
698
699size_t DisplayManager::GetNumDisplays() const {
700  return displays_.size();
701}
702
703bool DisplayManager::IsMirrored() const {
704  return mirrored_display_.id() != gfx::Display::kInvalidDisplayID;
705}
706
707const DisplayInfo& DisplayManager::GetDisplayInfo(int64 display_id) const {
708  std::map<int64, DisplayInfo>::const_iterator iter =
709      display_info_.find(display_id);
710  CHECK(iter != display_info_.end()) << display_id;
711  return iter->second;
712}
713
714std::string DisplayManager::GetDisplayNameForId(int64 id) {
715  if (id == gfx::Display::kInvalidDisplayID)
716    return l10n_util::GetStringUTF8(IDS_ASH_STATUS_TRAY_UNKNOWN_DISPLAY_NAME);
717
718  std::map<int64, DisplayInfo>::const_iterator iter = display_info_.find(id);
719  if (iter != display_info_.end() && !iter->second.name().empty())
720    return iter->second.name();
721
722  return base::StringPrintf("Display %d", static_cast<int>(id));
723}
724
725int64 DisplayManager::GetDisplayIdForUIScaling() const {
726  // UI Scaling is effective only on internal display.
727  int64 display_id = gfx::Display::InternalDisplayId();
728#if defined(OS_WIN)
729  display_id = first_display_id();
730#endif
731  return display_id;
732}
733
734void DisplayManager::SetMirrorMode(bool mirrored) {
735  if (num_connected_displays() <= 1)
736    return;
737
738#if defined(OS_CHROMEOS)
739  if (base::chromeos::IsRunningOnChromeOS()) {
740    chromeos::OutputState new_state = mirrored ?
741        chromeos::STATE_DUAL_MIRROR : chromeos::STATE_DUAL_EXTENDED;
742    Shell::GetInstance()->output_configurator()->SetDisplayMode(new_state);
743    return;
744  }
745#endif
746  SetSoftwareMirroring(mirrored);
747  DisplayInfoList display_info_list;
748  int count = 0;
749  for (std::map<int64, DisplayInfo>::const_iterator iter =
750           display_info_.begin();
751       count < 2; ++iter, ++count) {
752    display_info_list.push_back(GetDisplayInfo(iter->second.id()));
753  }
754  UpdateDisplays(display_info_list);
755#if defined(OS_CHROMEOS)
756  if (Shell::GetInstance()->output_configurator_animation()) {
757    Shell::GetInstance()->output_configurator_animation()->
758        StartFadeInAnimation();
759  }
760#endif
761}
762
763void DisplayManager::AddRemoveDisplay() {
764  DCHECK(!displays_.empty());
765  std::vector<DisplayInfo> new_display_info_list;
766  const DisplayInfo& first_display = GetDisplayInfo(displays_[0].id());
767  new_display_info_list.push_back(first_display);
768  // Add if there is only one display connected.
769  if (num_connected_displays() == 1) {
770    // Layout the 2nd display below the primary as with the real device.
771    gfx::Rect host_bounds = first_display.bounds_in_native();
772    new_display_info_list.push_back(DisplayInfo::CreateFromSpec(
773        base::StringPrintf(
774            "%d+%d-500x400", host_bounds.x(), host_bounds.bottom())));
775  }
776  num_connected_displays_ = new_display_info_list.size();
777  mirrored_display_ = gfx::Display();
778  UpdateDisplays(new_display_info_list);
779}
780
781void DisplayManager::ToggleDisplayScaleFactor() {
782  DCHECK(!displays_.empty());
783  std::vector<DisplayInfo> new_display_info_list;
784  for (DisplayList::const_iterator iter = displays_.begin();
785       iter != displays_.end(); ++iter) {
786    DisplayInfo display_info = GetDisplayInfo(iter->id());
787    display_info.set_device_scale_factor(
788        display_info.device_scale_factor() == 1.0f ? 2.0f : 1.0f);
789    new_display_info_list.push_back(display_info);
790  }
791  AddMirrorDisplayInfoIfAny(&new_display_info_list);
792  UpdateDisplays(new_display_info_list);
793}
794
795void DisplayManager::SetSoftwareMirroring(bool enabled) {
796  software_mirroring_enabled_ = enabled;
797  mirrored_display_ = gfx::Display();
798}
799
800bool DisplayManager::UpdateDisplayBounds(int64 display_id,
801                                         const gfx::Rect& new_bounds) {
802  if (change_display_upon_host_resize_) {
803    display_info_[display_id].SetBounds(new_bounds);
804    // Don't notify observers if the mirrored window has changed.
805    if (software_mirroring_enabled_ && mirrored_display_.id() == display_id)
806      return false;
807    gfx::Display* display = FindDisplayForId(display_id);
808    display->SetSize(display_info_[display_id].size_in_pixel());
809    Shell::GetInstance()->screen()->NotifyBoundsChanged(*display);
810    return true;
811  }
812  return false;
813}
814
815void DisplayManager::CreateMirrorWindowIfAny() {
816  MirrorWindowUpdater updater(this, delegate_);
817}
818
819gfx::Display* DisplayManager::FindDisplayForId(int64 id) {
820  for (DisplayList::iterator iter = displays_.begin();
821       iter != displays_.end(); ++iter) {
822    if ((*iter).id() == id)
823      return &(*iter);
824  }
825  DLOG(WARNING) << "Could not find display:" << id;
826  return NULL;
827}
828
829void DisplayManager::AddMirrorDisplayInfoIfAny(
830    std::vector<DisplayInfo>* display_info_list) {
831  if (software_mirroring_enabled_ && mirrored_display_.is_valid())
832    display_info_list->push_back(GetDisplayInfo(mirrored_display_.id()));
833}
834
835void DisplayManager::InsertAndUpdateDisplayInfo(const DisplayInfo& new_info) {
836  std::map<int64, DisplayInfo>::iterator info =
837      display_info_.find(new_info.id());
838  if (info != display_info_.end())
839    info->second.Copy(new_info);
840  else {
841    display_info_[new_info.id()] = new_info;
842    display_info_[new_info.id()].set_native(false);
843  }
844  display_info_[new_info.id()].UpdateDisplaySize();
845}
846
847gfx::Display DisplayManager::CreateDisplayFromDisplayInfoById(int64 id) {
848  DCHECK(display_info_.find(id) != display_info_.end());
849  const DisplayInfo& display_info = display_info_[id];
850
851  gfx::Display new_display(display_info.id());
852  gfx::Rect bounds_in_native(display_info.size_in_pixel());
853
854  // Simply set the origin to (0,0).  The primary display's origin is
855  // always (0,0) and the secondary display's bounds will be updated
856  // in |UpdateSecondaryDisplayBoundsForLayout| called in |UpdateDisplay|.
857  new_display.SetScaleAndBounds(
858      display_info.device_scale_factor(), gfx::Rect(bounds_in_native.size()));
859  new_display.set_rotation(display_info.rotation());
860  return new_display;
861}
862
863bool DisplayManager::UpdateSecondaryDisplayBoundsForLayout(
864    DisplayList* displays,
865    size_t* updated_index) const {
866  if (displays->size() != 2U)
867    return false;
868
869  int64 id_at_zero = displays->at(0).id();
870  DisplayIdPair pair =
871      (id_at_zero == first_display_id_ ||
872       id_at_zero == gfx::Display::InternalDisplayId()) ?
873      std::make_pair(id_at_zero, displays->at(1).id()) :
874      std::make_pair(displays->at(1).id(), id_at_zero) ;
875  DisplayLayout layout =
876      layout_store_->ComputeDisplayLayoutForDisplayIdPair(pair);
877
878  // Ignore if a user has a old format (should be extremely rare)
879  // and this will be replaced with DCHECK.
880  if (layout.primary_id != gfx::Display::kInvalidDisplayID) {
881    size_t primary_index, secondary_index;
882    if (displays->at(0).id() == layout.primary_id) {
883      primary_index = 0;
884      secondary_index = 1;
885    } else {
886      primary_index = 1;
887      secondary_index = 0;
888    }
889    // This function may be called before the secondary display is
890    // registered. The bounds is empty in that case and will
891    // return true.
892    gfx::Rect bounds =
893        GetDisplayForId(displays->at(secondary_index).id()).bounds();
894    UpdateDisplayBoundsForLayout(
895        layout, displays->at(primary_index), &displays->at(secondary_index));
896    *updated_index = secondary_index;
897    return bounds != displays->at(secondary_index).bounds();
898  }
899  return false;
900}
901
902
903// static
904void DisplayManager::UpdateDisplayBoundsForLayout(
905    const DisplayLayout& layout,
906    const gfx::Display& primary_display,
907    gfx::Display* secondary_display) {
908  DCHECK_EQ("0,0", primary_display.bounds().origin().ToString());
909
910  const gfx::Rect& primary_bounds = primary_display.bounds();
911  const gfx::Rect& secondary_bounds = secondary_display->bounds();
912  gfx::Point new_secondary_origin = primary_bounds.origin();
913
914  DisplayLayout::Position position = layout.position;
915
916  // Ignore the offset in case the secondary display doesn't share edges with
917  // the primary display.
918  int offset = layout.offset;
919  if (position == DisplayLayout::TOP || position == DisplayLayout::BOTTOM) {
920    offset = std::min(
921        offset, primary_bounds.width() - kMinimumOverlapForInvalidOffset);
922    offset = std::max(
923        offset, -secondary_bounds.width() + kMinimumOverlapForInvalidOffset);
924  } else {
925    offset = std::min(
926        offset, primary_bounds.height() - kMinimumOverlapForInvalidOffset);
927    offset = std::max(
928        offset, -secondary_bounds.height() + kMinimumOverlapForInvalidOffset);
929  }
930  switch (position) {
931    case DisplayLayout::TOP:
932      new_secondary_origin.Offset(offset, -secondary_bounds.height());
933      break;
934    case DisplayLayout::RIGHT:
935      new_secondary_origin.Offset(primary_bounds.width(), offset);
936      break;
937    case DisplayLayout::BOTTOM:
938      new_secondary_origin.Offset(offset, primary_bounds.height());
939      break;
940    case DisplayLayout::LEFT:
941      new_secondary_origin.Offset(-secondary_bounds.width(), offset);
942      break;
943  }
944  gfx::Insets insets = secondary_display->GetWorkAreaInsets();
945  secondary_display->set_bounds(
946      gfx::Rect(new_secondary_origin, secondary_bounds.size()));
947  secondary_display->UpdateWorkAreaFromInsets(insets);
948}
949
950}  // namespace internal
951}  // namespace ash
952