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