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