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