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