Upstream version 5.34.104.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/strings/string_number_conversions.h"
21 #include "base/strings/string_split.h"
22 #include "base/strings/stringprintf.h"
23 #include "base/strings/utf_string_conversions.h"
24 #include "grit/ash_strings.h"
25 #include "ui/base/l10n/l10n_util.h"
26 #include "ui/gfx/display.h"
27 #include "ui/gfx/rect.h"
28 #include "ui/gfx/screen.h"
29 #include "ui/gfx/size_conversions.h"
30
31 #if defined(USE_X11)
32 #include "ui/base/x/x11_util.h"
33 #endif
34
35 #if defined(OS_CHROMEOS)
36 #include "ash/display/output_configurator_animation.h"
37 #include "base/sys_info.h"
38 #include "chromeos/display/output_configurator.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()->ScheduleConfigureOutputs();
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   if (display_info_.find(display_id) == display_info_.end())
470     display_info_[display_id] = DisplayInfo(display_id, std::string(), false);
471
472   display_info_[display_id].set_rotation(rotation);
473   // Just in case the preference file was corrupted.
474   if (0.5f <= ui_scale && ui_scale <= 2.0f)
475     display_info_[display_id].set_configured_ui_scale(ui_scale);
476   if (overscan_insets)
477     display_info_[display_id].SetOverscanInsets(*overscan_insets);
478   if (!resolution_in_pixels.IsEmpty()) {
479     // Default refresh rate, until OnNativeDisplaysChanged() updates us with the
480     // actual display info, is 60 Hz.
481     display_modes_[display_id] =
482         DisplayMode(resolution_in_pixels, 60.0f, false, false);
483   }
484 }
485
486 bool DisplayManager::GetSelectedModeForDisplayId(int64 id,
487                                                  DisplayMode* mode_out) const {
488   std::map<int64, DisplayMode>::const_iterator iter = display_modes_.find(id);
489   if (iter == display_modes_.end())
490     return false;
491   *mode_out = iter->second;
492   return true;
493 }
494
495 bool DisplayManager::IsDisplayUIScalingEnabled() const {
496   return GetDisplayIdForUIScaling() != gfx::Display::kInvalidDisplayID;
497 }
498
499 gfx::Insets DisplayManager::GetOverscanInsets(int64 display_id) const {
500   std::map<int64, DisplayInfo>::const_iterator it =
501       display_info_.find(display_id);
502   return (it != display_info_.end()) ?
503       it->second.overscan_insets_in_dip() : gfx::Insets();
504 }
505
506 void DisplayManager::OnNativeDisplaysChanged(
507     const std::vector<DisplayInfo>& updated_displays) {
508   if (updated_displays.empty()) {
509     VLOG(1) << "OnNativeDisplayChanged(0): # of current displays="
510             << displays_.size();
511     // If the device is booted without display, or chrome is started
512     // without --ash-host-window-bounds on linux desktop, use the
513     // default display.
514     if (displays_.empty()) {
515       std::vector<DisplayInfo> init_displays;
516       init_displays.push_back(DisplayInfo::CreateFromSpec(std::string()));
517       MaybeInitInternalDisplay(init_displays[0].id());
518       OnNativeDisplaysChanged(init_displays);
519     } else {
520       // Otherwise don't update the displays when all displays are disconnected.
521       // This happens when:
522       // - the device is idle and powerd requested to turn off all displays.
523       // - the device is suspended. (kernel turns off all displays)
524       // - the internal display's brightness is set to 0 and no external
525       //   display is connected.
526       // - the internal display's brightness is 0 and external display is
527       //   disconnected.
528       // The display will be updated when one of displays is turned on, and the
529       // display list will be updated correctly.
530     }
531     return;
532   }
533   first_display_id_ = updated_displays[0].id();
534   std::set<gfx::Point> origins;
535
536   if (updated_displays.size() == 1) {
537     VLOG(1) << "OnNativeDisplaysChanged(1):" << updated_displays[0].ToString();
538   } else {
539     VLOG(1) << "OnNativeDisplaysChanged(" << updated_displays.size()
540             << ") [0]=" << updated_displays[0].ToString()
541             << ", [1]=" << updated_displays[1].ToString();
542   }
543
544   bool internal_display_connected = false;
545   num_connected_displays_ = updated_displays.size();
546   mirrored_display_id_ = gfx::Display::kInvalidDisplayID;
547   non_desktop_display_ = gfx::Display();
548   DisplayInfoList new_display_info_list;
549   for (DisplayInfoList::const_iterator iter = updated_displays.begin();
550        iter != updated_displays.end();
551        ++iter) {
552     if (!internal_display_connected)
553       internal_display_connected = IsInternalDisplayId(iter->id());
554     // Mirrored monitors have the same origins.
555     gfx::Point origin = iter->bounds_in_native().origin();
556     if (origins.find(origin) != origins.end()) {
557       InsertAndUpdateDisplayInfo(*iter);
558       mirrored_display_id_ = iter->id();
559     } else {
560       origins.insert(origin);
561       new_display_info_list.push_back(*iter);
562     }
563
564     const gfx::Size& resolution = iter->bounds_in_native().size();
565     const std::vector<DisplayMode>& display_modes = iter->display_modes();
566     // This is empty the displays are initialized from InitFromCommandLine.
567     if (!display_modes.size())
568       continue;
569     std::vector<DisplayMode>::const_iterator display_modes_iter =
570         std::find_if(display_modes.begin(),
571                      display_modes.end(),
572                      DisplayModeMatcher(resolution));
573     // Update the actual resolution selected as the resolution request may fail.
574     if (display_modes_iter == display_modes.end())
575       display_modes_.erase(iter->id());
576     else if (display_modes_.find(iter->id()) != display_modes_.end())
577       display_modes_[iter->id()] = *display_modes_iter;
578   }
579   if (HasInternalDisplay() &&
580       !internal_display_connected &&
581       display_info_.find(gfx::Display::InternalDisplayId()) ==
582       display_info_.end()) {
583     DisplayInfo internal_display_info(
584         gfx::Display::InternalDisplayId(),
585         l10n_util::GetStringUTF8(IDS_ASH_INTERNAL_DISPLAY_NAME),
586         false  /*Internal display must not have overscan */);
587     internal_display_info.SetBounds(gfx::Rect(0, 0, 800, 600));
588     display_info_[gfx::Display::InternalDisplayId()] = internal_display_info;
589   }
590   UpdateDisplays(new_display_info_list);
591 }
592
593 void DisplayManager::UpdateDisplays() {
594   DisplayInfoList display_info_list;
595   for (DisplayList::const_iterator iter = displays_.begin();
596        iter != displays_.end(); ++iter) {
597     display_info_list.push_back(GetDisplayInfo(iter->id()));
598   }
599   AddMirrorDisplayInfoIfAny(&display_info_list);
600   UpdateDisplays(display_info_list);
601 }
602
603 void DisplayManager::UpdateDisplays(
604     const std::vector<DisplayInfo>& updated_display_info_list) {
605 #if defined(OS_WIN)
606   if (base::win::GetVersion() >= base::win::VERSION_WIN8) {
607     DCHECK_EQ(1u, updated_display_info_list.size()) <<
608         "Multiple display test does not work on Win8 bots. Please "
609         "skip (don't disable) the test using SupportsMultipleDisplays()";
610   }
611 #endif
612
613   DisplayInfoList new_display_info_list = updated_display_info_list;
614   std::sort(displays_.begin(), displays_.end(), DisplaySortFunctor());
615   std::sort(new_display_info_list.begin(),
616             new_display_info_list.end(),
617             DisplayInfoSortFunctor());
618   DisplayList removed_displays;
619   std::vector<size_t> changed_display_indices;
620   std::vector<size_t> added_display_indices;
621
622   DisplayList::iterator curr_iter = displays_.begin();
623   DisplayInfoList::const_iterator new_info_iter = new_display_info_list.begin();
624
625   DisplayList new_displays;
626
627   // Use the internal display or 1st as the mirror source, then scale
628   // the root window so that it matches the external display's
629   // resolution. This is necessary in order for scaling to work while
630   // mirrored.
631   int64 non_desktop_display_id = gfx::Display::kInvalidDisplayID;
632
633   if (second_display_mode_ != EXTENDED && new_display_info_list.size() == 2) {
634     bool zero_is_source =
635         first_display_id_ == new_display_info_list[0].id() ||
636         gfx::Display::InternalDisplayId() == new_display_info_list[0].id();
637     if (second_display_mode_ == MIRRORING) {
638       mirrored_display_id_ = new_display_info_list[zero_is_source ? 1 : 0].id();
639       non_desktop_display_id = mirrored_display_id_;
640     } else {
641       // TODO(oshima|bshe): The virtual keyboard is currently assigned to
642       // the 1st display.
643       non_desktop_display_id =
644           new_display_info_list[zero_is_source ? 0 : 1].id();
645     }
646   }
647
648   while (curr_iter != displays_.end() ||
649          new_info_iter != new_display_info_list.end()) {
650     if (new_info_iter != new_display_info_list.end() &&
651         non_desktop_display_id == new_info_iter->id()) {
652       DisplayInfo info = *new_info_iter;
653       info.SetOverscanInsets(gfx::Insets());
654       InsertAndUpdateDisplayInfo(info);
655       non_desktop_display_ =
656           CreateDisplayFromDisplayInfoById(non_desktop_display_id);
657       ++new_info_iter;
658       // Remove existing external display if it is going to be used as
659       // non desktop.
660       if (curr_iter != displays_.end() &&
661           curr_iter->id() == non_desktop_display_id) {
662         removed_displays.push_back(*curr_iter);
663         ++curr_iter;
664       }
665       continue;
666     }
667
668     if (curr_iter == displays_.end()) {
669       // more displays in new list.
670       added_display_indices.push_back(new_displays.size());
671       InsertAndUpdateDisplayInfo(*new_info_iter);
672       new_displays.push_back(
673           CreateDisplayFromDisplayInfoById(new_info_iter->id()));
674       ++new_info_iter;
675     } else if (new_info_iter == new_display_info_list.end()) {
676       // more displays in current list.
677       removed_displays.push_back(*curr_iter);
678       ++curr_iter;
679     } else if (curr_iter->id() == new_info_iter->id()) {
680       const gfx::Display& current_display = *curr_iter;
681       // Copy the info because |CreateDisplayFromInfo| updates the instance.
682       const DisplayInfo current_display_info =
683           GetDisplayInfo(current_display.id());
684       InsertAndUpdateDisplayInfo(*new_info_iter);
685       gfx::Display new_display =
686           CreateDisplayFromDisplayInfoById(new_info_iter->id());
687       const DisplayInfo& new_display_info = GetDisplayInfo(new_display.id());
688
689       bool host_window_bounds_changed =
690           current_display_info.bounds_in_native() !=
691           new_display_info.bounds_in_native();
692
693       if (force_bounds_changed_ ||
694           host_window_bounds_changed ||
695           (current_display.device_scale_factor() !=
696            new_display.device_scale_factor()) ||
697           (current_display_info.size_in_pixel() !=
698            new_display.GetSizeInPixel()) ||
699           (current_display.rotation() != new_display.rotation())) {
700         changed_display_indices.push_back(new_displays.size());
701       }
702
703       new_display.UpdateWorkAreaFromInsets(current_display.GetWorkAreaInsets());
704       new_displays.push_back(new_display);
705       ++curr_iter;
706       ++new_info_iter;
707     } else if (curr_iter->id() < new_info_iter->id()) {
708       // more displays in current list between ids, which means it is deleted.
709       removed_displays.push_back(*curr_iter);
710       ++curr_iter;
711     } else {
712       // more displays in new list between ids, which means it is added.
713       added_display_indices.push_back(new_displays.size());
714       InsertAndUpdateDisplayInfo(*new_info_iter);
715       new_displays.push_back(
716           CreateDisplayFromDisplayInfoById(new_info_iter->id()));
717       ++new_info_iter;
718     }
719   }
720
721   scoped_ptr<NonDesktopDisplayUpdater> non_desktop_display_updater(
722       new NonDesktopDisplayUpdater(this, delegate_));
723
724   // Do not update |displays_| if there's nothing to be updated. Without this,
725   // it will not update the display layout, which causes the bug
726   // http://crbug.com/155948.
727   if (changed_display_indices.empty() && added_display_indices.empty() &&
728       removed_displays.empty()) {
729     return;
730   }
731   // Clear focus if the display has been removed, but don't clear focus if
732   // the destkop has been moved from one display to another
733   // (mirror -> docked, docked -> single internal).
734   bool clear_focus =
735       !removed_displays.empty() &&
736       !(removed_displays.size() == 1 && added_display_indices.size() == 1);
737   if (delegate_)
738     delegate_->PreDisplayConfigurationChange(clear_focus);
739
740   size_t updated_index;
741   if (UpdateSecondaryDisplayBoundsForLayout(&new_displays, &updated_index) &&
742       std::find(added_display_indices.begin(),
743                 added_display_indices.end(),
744                 updated_index) == added_display_indices.end() &&
745       std::find(changed_display_indices.begin(),
746                 changed_display_indices.end(),
747                 updated_index) == changed_display_indices.end()) {
748     changed_display_indices.push_back(updated_index);
749   }
750
751   displays_ = new_displays;
752
753   base::AutoReset<bool> resetter(&change_display_upon_host_resize_, false);
754
755   // Temporarily add displays to be removed because display object
756   // being removed are accessed during shutting down the root.
757   displays_.insert(displays_.end(), removed_displays.begin(),
758                    removed_displays.end());
759
760   for (DisplayList::const_reverse_iterator iter = removed_displays.rbegin();
761        iter != removed_displays.rend(); ++iter) {
762     screen_ash_->NotifyDisplayRemoved(displays_.back());
763     displays_.pop_back();
764   }
765   // Close the non desktop window here to avoid creating two compositor on
766   // one display.
767   if (!non_desktop_display_updater->enabled())
768     non_desktop_display_updater.reset();
769   for (std::vector<size_t>::iterator iter = added_display_indices.begin();
770        iter != added_display_indices.end(); ++iter) {
771     screen_ash_->NotifyDisplayAdded(displays_[*iter]);
772   }
773   // Create the non destkop window after all displays are added so that
774   // it can mirror the display newly added. This can happen when switching
775   // from dock mode to software mirror mode.
776   non_desktop_display_updater.reset();
777   for (std::vector<size_t>::iterator iter = changed_display_indices.begin();
778        iter != changed_display_indices.end(); ++iter) {
779     screen_ash_->NotifyBoundsChanged(displays_[*iter]);
780   }
781   if (delegate_)
782     delegate_->PostDisplayConfigurationChange();
783
784 #if defined(USE_X11) && defined(OS_CHROMEOS)
785   if (!changed_display_indices.empty() && base::SysInfo::IsRunningOnChromeOS())
786     ui::ClearX11DefaultRootWindow();
787 #endif
788 }
789
790 const gfx::Display& DisplayManager::GetDisplayAt(size_t index) const {
791   DCHECK_LT(index, displays_.size());
792   return displays_[index];
793 }
794
795 const gfx::Display& DisplayManager::GetPrimaryDisplayCandidate() const {
796   if (GetNumDisplays() == 1)
797     return displays_[0];
798   DisplayLayout layout = layout_store_->GetRegisteredDisplayLayout(
799       GetCurrentDisplayIdPair());
800   return GetDisplayForId(layout.primary_id);
801 }
802
803 size_t DisplayManager::GetNumDisplays() const {
804   return displays_.size();
805 }
806
807 bool DisplayManager::IsMirrored() const {
808   return mirrored_display_id_ != gfx::Display::kInvalidDisplayID;
809 }
810
811 const DisplayInfo& DisplayManager::GetDisplayInfo(int64 display_id) const {
812   std::map<int64, DisplayInfo>::const_iterator iter =
813       display_info_.find(display_id);
814   CHECK(iter != display_info_.end()) << display_id;
815   return iter->second;
816 }
817
818 std::string DisplayManager::GetDisplayNameForId(int64 id) {
819   if (id == gfx::Display::kInvalidDisplayID)
820     return l10n_util::GetStringUTF8(IDS_ASH_STATUS_TRAY_UNKNOWN_DISPLAY_NAME);
821
822   std::map<int64, DisplayInfo>::const_iterator iter = display_info_.find(id);
823   if (iter != display_info_.end() && !iter->second.name().empty())
824     return iter->second.name();
825
826   return base::StringPrintf("Display %d", static_cast<int>(id));
827 }
828
829 int64 DisplayManager::GetDisplayIdForUIScaling() const {
830   // UI Scaling is effective only on internal display.
831   int64 display_id = gfx::Display::InternalDisplayId();
832 #if defined(OS_WIN)
833   display_id = first_display_id();
834 #endif
835   return display_id;
836 }
837
838 void DisplayManager::SetMirrorMode(bool mirrored) {
839   if (num_connected_displays() <= 1)
840     return;
841
842 #if defined(OS_CHROMEOS)
843   if (base::SysInfo::IsRunningOnChromeOS()) {
844     ui::OutputState new_state = mirrored ? ui::OUTPUT_STATE_DUAL_MIRROR :
845                                            ui::OUTPUT_STATE_DUAL_EXTENDED;
846     Shell::GetInstance()->output_configurator()->SetDisplayMode(new_state);
847     return;
848   }
849 #endif
850   // This is fallback path to emulate mirroroing on desktop.
851   SetSecondDisplayMode(mirrored ? MIRRORING : EXTENDED);
852   DisplayInfoList display_info_list;
853   int count = 0;
854   for (std::map<int64, DisplayInfo>::const_iterator iter =
855            display_info_.begin();
856        count < 2; ++iter, ++count) {
857     display_info_list.push_back(GetDisplayInfo(iter->second.id()));
858   }
859   UpdateDisplays(display_info_list);
860 #if defined(OS_CHROMEOS)
861   if (Shell::GetInstance()->output_configurator_animation()) {
862     Shell::GetInstance()->output_configurator_animation()->
863         StartFadeInAnimation();
864   }
865 #endif
866 }
867
868 void DisplayManager::AddRemoveDisplay() {
869   DCHECK(!displays_.empty());
870   std::vector<DisplayInfo> new_display_info_list;
871   const DisplayInfo& first_display = GetDisplayInfo(displays_[0].id());
872   new_display_info_list.push_back(first_display);
873   // Add if there is only one display connected.
874   if (num_connected_displays() == 1) {
875     // Layout the 2nd display below the primary as with the real device.
876     gfx::Rect host_bounds = first_display.bounds_in_native();
877     new_display_info_list.push_back(DisplayInfo::CreateFromSpec(
878         base::StringPrintf(
879             "%d+%d-500x400", host_bounds.x(), host_bounds.bottom())));
880   }
881   num_connected_displays_ = new_display_info_list.size();
882   mirrored_display_id_ = gfx::Display::kInvalidDisplayID;
883   non_desktop_display_ = gfx::Display();
884   UpdateDisplays(new_display_info_list);
885 }
886
887 void DisplayManager::ToggleDisplayScaleFactor() {
888   DCHECK(!displays_.empty());
889   std::vector<DisplayInfo> new_display_info_list;
890   for (DisplayList::const_iterator iter = displays_.begin();
891        iter != displays_.end(); ++iter) {
892     DisplayInfo display_info = GetDisplayInfo(iter->id());
893     display_info.set_device_scale_factor(
894         display_info.device_scale_factor() == 1.0f ? 2.0f : 1.0f);
895     new_display_info_list.push_back(display_info);
896   }
897   AddMirrorDisplayInfoIfAny(&new_display_info_list);
898   UpdateDisplays(new_display_info_list);
899 }
900
901 #if defined(OS_CHROMEOS)
902 void DisplayManager::SetSoftwareMirroring(bool enabled) {
903   // TODO(oshima|bshe): Support external display on the system
904   // that has virtual keyboard display.
905   if (second_display_mode_ == VIRTUAL_KEYBOARD)
906     return;
907   SetSecondDisplayMode(enabled ? MIRRORING : EXTENDED);
908 }
909 #endif
910
911 void DisplayManager::SetSecondDisplayMode(SecondDisplayMode mode) {
912   second_display_mode_ = mode;
913   mirrored_display_id_ = gfx::Display::kInvalidDisplayID;
914   non_desktop_display_ = gfx::Display();
915 }
916
917 bool DisplayManager::UpdateDisplayBounds(int64 display_id,
918                                          const gfx::Rect& new_bounds) {
919   if (change_display_upon_host_resize_) {
920     display_info_[display_id].SetBounds(new_bounds);
921     // Don't notify observers if the mirrored window has changed.
922     if (software_mirroring_enabled() && mirrored_display_id_ == display_id)
923       return false;
924     gfx::Display* display = FindDisplayForId(display_id);
925     display->SetSize(display_info_[display_id].size_in_pixel());
926     screen_ash_->NotifyBoundsChanged(*display);
927     return true;
928   }
929   return false;
930 }
931
932 void DisplayManager::CreateMirrorWindowIfAny() {
933   NonDesktopDisplayUpdater updater(this, delegate_);
934 }
935
936 void DisplayManager::CreateScreenForShutdown() const {
937   bool native_is_ash =
938       gfx::Screen::GetScreenByType(gfx::SCREEN_TYPE_NATIVE) ==
939       screen_ash_.get();
940   delete screen_for_shutdown;
941   screen_for_shutdown = screen_ash_->CloneForShutdown();
942   gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_ALTERNATE,
943                                  screen_for_shutdown);
944   if (native_is_ash) {
945     gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE,
946                                    screen_for_shutdown);
947   }
948 }
949
950 gfx::Display* DisplayManager::FindDisplayForId(int64 id) {
951   for (DisplayList::iterator iter = displays_.begin();
952        iter != displays_.end(); ++iter) {
953     if ((*iter).id() == id)
954       return &(*iter);
955   }
956   DLOG(WARNING) << "Could not find display:" << id;
957   return NULL;
958 }
959
960 void DisplayManager::AddMirrorDisplayInfoIfAny(
961     std::vector<DisplayInfo>* display_info_list) {
962   if (software_mirroring_enabled() && IsMirrored())
963     display_info_list->push_back(GetDisplayInfo(mirrored_display_id_));
964 }
965
966 void DisplayManager::InsertAndUpdateDisplayInfo(const DisplayInfo& new_info) {
967   std::map<int64, DisplayInfo>::iterator info =
968       display_info_.find(new_info.id());
969   if (info != display_info_.end()) {
970     info->second.Copy(new_info);
971   } else {
972     display_info_[new_info.id()] = new_info;
973     display_info_[new_info.id()].set_native(false);
974   }
975   display_info_[new_info.id()].UpdateDisplaySize();
976 }
977
978 gfx::Display DisplayManager::CreateDisplayFromDisplayInfoById(int64 id) {
979   DCHECK(display_info_.find(id) != display_info_.end());
980   const DisplayInfo& display_info = display_info_[id];
981
982   gfx::Display new_display(display_info.id());
983   gfx::Rect bounds_in_native(display_info.size_in_pixel());
984   float device_scale_factor = display_info.device_scale_factor();
985   if (device_scale_factor == 2.0f && display_info.configured_ui_scale() == 2.0f)
986     device_scale_factor = 1.0f;
987
988   // Simply set the origin to (0,0).  The primary display's origin is
989   // always (0,0) and the secondary display's bounds will be updated
990   // in |UpdateSecondaryDisplayBoundsForLayout| called in |UpdateDisplay|.
991   new_display.SetScaleAndBounds(
992       device_scale_factor, gfx::Rect(bounds_in_native.size()));
993   new_display.set_rotation(display_info.rotation());
994   new_display.set_touch_support(display_info.touch_support());
995   return new_display;
996 }
997
998 bool DisplayManager::UpdateSecondaryDisplayBoundsForLayout(
999     DisplayList* displays,
1000     size_t* updated_index) const {
1001   if (displays->size() != 2U)
1002     return false;
1003
1004   int64 id_at_zero = displays->at(0).id();
1005   DisplayIdPair pair =
1006       (id_at_zero == first_display_id_ ||
1007        id_at_zero == gfx::Display::InternalDisplayId()) ?
1008       std::make_pair(id_at_zero, displays->at(1).id()) :
1009       std::make_pair(displays->at(1).id(), id_at_zero);
1010   DisplayLayout layout =
1011       layout_store_->ComputeDisplayLayoutForDisplayIdPair(pair);
1012
1013   // Ignore if a user has a old format (should be extremely rare)
1014   // and this will be replaced with DCHECK.
1015   if (layout.primary_id != gfx::Display::kInvalidDisplayID) {
1016     size_t primary_index, secondary_index;
1017     if (displays->at(0).id() == layout.primary_id) {
1018       primary_index = 0;
1019       secondary_index = 1;
1020     } else {
1021       primary_index = 1;
1022       secondary_index = 0;
1023     }
1024     // This function may be called before the secondary display is
1025     // registered. The bounds is empty in that case and will
1026     // return true.
1027     gfx::Rect bounds =
1028         GetDisplayForId(displays->at(secondary_index).id()).bounds();
1029     UpdateDisplayBoundsForLayout(
1030         layout, displays->at(primary_index), &displays->at(secondary_index));
1031     *updated_index = secondary_index;
1032     return bounds != displays->at(secondary_index).bounds();
1033   }
1034   return false;
1035 }
1036
1037 // static
1038 void DisplayManager::UpdateDisplayBoundsForLayout(
1039     const DisplayLayout& layout,
1040     const gfx::Display& primary_display,
1041     gfx::Display* secondary_display) {
1042   DCHECK_EQ("0,0", primary_display.bounds().origin().ToString());
1043
1044   const gfx::Rect& primary_bounds = primary_display.bounds();
1045   const gfx::Rect& secondary_bounds = secondary_display->bounds();
1046   gfx::Point new_secondary_origin = primary_bounds.origin();
1047
1048   DisplayLayout::Position position = layout.position;
1049
1050   // Ignore the offset in case the secondary display doesn't share edges with
1051   // the primary display.
1052   int offset = layout.offset;
1053   if (position == DisplayLayout::TOP || position == DisplayLayout::BOTTOM) {
1054     offset = std::min(
1055         offset, primary_bounds.width() - kMinimumOverlapForInvalidOffset);
1056     offset = std::max(
1057         offset, -secondary_bounds.width() + kMinimumOverlapForInvalidOffset);
1058   } else {
1059     offset = std::min(
1060         offset, primary_bounds.height() - kMinimumOverlapForInvalidOffset);
1061     offset = std::max(
1062         offset, -secondary_bounds.height() + kMinimumOverlapForInvalidOffset);
1063   }
1064   switch (position) {
1065     case DisplayLayout::TOP:
1066       new_secondary_origin.Offset(offset, -secondary_bounds.height());
1067       break;
1068     case DisplayLayout::RIGHT:
1069       new_secondary_origin.Offset(primary_bounds.width(), offset);
1070       break;
1071     case DisplayLayout::BOTTOM:
1072       new_secondary_origin.Offset(offset, primary_bounds.height());
1073       break;
1074     case DisplayLayout::LEFT:
1075       new_secondary_origin.Offset(-secondary_bounds.width(), offset);
1076       break;
1077   }
1078   gfx::Insets insets = secondary_display->GetWorkAreaInsets();
1079   secondary_display->set_bounds(
1080       gfx::Rect(new_secondary_origin, secondary_bounds.size()));
1081   secondary_display->UpdateWorkAreaFromInsets(insets);
1082 }
1083
1084 }  // namespace internal
1085 }  // namespace ash