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