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 "ui/gfx/screen.h"
7 #import <ApplicationServices/ApplicationServices.h>
8 #import <Cocoa/Cocoa.h>
12 #include "base/logging.h"
13 #include "base/mac/sdk_forward_declarations.h"
14 #include "base/timer/timer.h"
15 #include "ui/gfx/display.h"
16 #include "ui/gfx/display_change_notifier.h"
20 // The delay to handle the display configuration changes.
21 // See comments in ScreenMac::HandleDisplayReconfiguration.
22 const int64 kConfigureDelayMs = 500;
24 gfx::Rect ConvertCoordinateSystem(NSRect ns_rect) {
25 // Primary monitor is defined as the monitor with the menubar,
26 // which is always at index 0.
27 NSScreen* primary_screen = [[NSScreen screens] objectAtIndex:0];
28 float primary_screen_height = [primary_screen frame].size.height;
29 gfx::Rect rect(NSRectToCGRect(ns_rect));
30 rect.set_y(primary_screen_height - rect.y() - rect.height());
34 NSScreen* GetMatchingScreen(const gfx::Rect& match_rect) {
35 // Default to the monitor with the current keyboard focus, in case
36 // |match_rect| is not on any screen at all.
37 NSScreen* max_screen = [NSScreen mainScreen];
40 for (NSScreen* screen in [NSScreen screens]) {
41 gfx::Rect monitor_area = ConvertCoordinateSystem([screen frame]);
42 gfx::Rect intersection = gfx::IntersectRects(monitor_area, match_rect);
43 int area = intersection.width() * intersection.height();
44 if (area > max_area) {
53 gfx::Display GetDisplayForScreen(NSScreen* screen) {
54 NSRect frame = [screen frame];
56 CGDirectDisplayID display_id = [[[screen deviceDescription]
57 objectForKey:@"NSScreenNumber"] unsignedIntValue];
59 gfx::Display display(display_id, gfx::Rect(NSRectToCGRect(frame)));
60 NSRect visible_frame = [screen visibleFrame];
61 NSScreen* primary = [[NSScreen screens] objectAtIndex:0];
63 // Convert work area's coordinate systems.
64 if ([screen isEqual:primary]) {
65 gfx::Rect work_area = gfx::Rect(NSRectToCGRect(visible_frame));
66 work_area.set_y(frame.size.height - visible_frame.origin.y -
67 visible_frame.size.height);
68 display.set_work_area(work_area);
70 display.set_bounds(ConvertCoordinateSystem(frame));
71 display.set_work_area(ConvertCoordinateSystem(visible_frame));
74 if ([screen respondsToSelector:@selector(backingScaleFactor)])
75 scale = [screen backingScaleFactor];
77 scale = [screen userSpaceScaleFactor];
79 if (gfx::Display::HasForceDeviceScaleFactor())
80 scale = gfx::Display::GetForcedDeviceScaleFactor();
82 display.set_device_scale_factor(scale);
83 // CGDisplayRotation returns a double. Display::SetRotationAsDegree will
84 // handle the unexpected situations were the angle is not a multiple of 90.
85 display.SetRotationAsDegree(static_cast<int>(CGDisplayRotation(display_id)));
89 class ScreenMac : public gfx::Screen {
92 displays_ = BuildDisplaysFromQuartz();
94 CGDisplayRegisterReconfigurationCallback(
95 ScreenMac::DisplayReconfigurationCallBack, this);
98 ~ScreenMac() override {
99 CGDisplayRemoveReconfigurationCallback(
100 ScreenMac::DisplayReconfigurationCallBack, this);
103 gfx::Point GetCursorScreenPoint() override {
104 NSPoint mouseLocation = [NSEvent mouseLocation];
105 // Flip coordinates to gfx (0,0 in top-left corner) using primary screen.
106 NSScreen* screen = [[NSScreen screens] objectAtIndex:0];
107 mouseLocation.y = NSMaxY([screen frame]) - mouseLocation.y;
108 return gfx::Point(mouseLocation.x, mouseLocation.y);
111 gfx::NativeWindow GetWindowUnderCursor() override {
113 return gfx::NativeWindow();
116 gfx::NativeWindow GetWindowAtScreenPoint(const gfx::Point& point) override {
118 return gfx::NativeWindow();
121 int GetNumDisplays() const override { return GetAllDisplays().size(); }
123 std::vector<gfx::Display> GetAllDisplays() const override {
127 gfx::Display GetDisplayNearestWindow(gfx::NativeView view) const override {
128 NSWindow* window = nil;
129 #if !defined(USE_AURA)
131 window = [view window];
134 return GetPrimaryDisplay();
135 NSScreen* match_screen = [window screen];
137 return GetPrimaryDisplay();
138 return GetDisplayForScreen(match_screen);
141 gfx::Display GetDisplayNearestPoint(const gfx::Point& point) const override {
142 NSPoint ns_point = NSPointFromCGPoint(point.ToCGPoint());
144 NSArray* screens = [NSScreen screens];
145 NSScreen* primary = [screens objectAtIndex:0];
146 ns_point.y = NSMaxY([primary frame]) - ns_point.y;
147 for (NSScreen* screen in screens) {
148 if (NSMouseInRect(ns_point, [screen frame], NO))
149 return GetDisplayForScreen(screen);
151 return GetPrimaryDisplay();
154 // Returns the display that most closely intersects the provided bounds.
155 gfx::Display GetDisplayMatching(const gfx::Rect& match_rect) const override {
156 NSScreen* match_screen = GetMatchingScreen(match_rect);
157 return GetDisplayForScreen(match_screen);
160 // Returns the primary display.
161 gfx::Display GetPrimaryDisplay() const override {
162 // Primary display is defined as the display with the menubar,
163 // which is always at index 0.
164 NSScreen* primary = [[NSScreen screens] objectAtIndex:0];
165 gfx::Display display = GetDisplayForScreen(primary);
169 void AddObserver(gfx::DisplayObserver* observer) override {
170 change_notifier_.AddObserver(observer);
173 void RemoveObserver(gfx::DisplayObserver* observer) override {
174 change_notifier_.RemoveObserver(observer);
177 static void DisplayReconfigurationCallBack(CGDirectDisplayID display,
178 CGDisplayChangeSummaryFlags flags,
180 if (flags & kCGDisplayBeginConfigurationFlag)
183 static_cast<ScreenMac*>(userInfo)->HandleDisplayReconfiguration();
186 void HandleDisplayReconfiguration() {
187 // Given that we need to rebuild the list of displays, we want to coalesce
188 // the events. For that, we use a timer that will be reset every time we get
189 // a new event and will be fulfilled kConfigureDelayMs after the latest.
190 if (configure_timer_.get() && configure_timer_->IsRunning()) {
191 configure_timer_->Reset();
195 configure_timer_.reset(new base::OneShotTimer<ScreenMac>());
196 configure_timer_->Start(
198 base::TimeDelta::FromMilliseconds(kConfigureDelayMs),
200 &ScreenMac::ConfigureTimerFired);
204 void ConfigureTimerFired() {
205 std::vector<gfx::Display> old_displays = displays_;
206 displays_ = BuildDisplaysFromQuartz();
208 change_notifier_.NotifyDisplaysChanged(old_displays, displays_);
211 std::vector<gfx::Display> BuildDisplaysFromQuartz() const {
212 // Don't just return all online displays. This would include displays
213 // that mirror other displays, which are not desired in this list. It's
214 // tempting to use the count returned by CGGetActiveDisplayList, but active
215 // displays exclude sleeping displays, and those are desired.
217 // It would be ridiculous to have this many displays connected, but
218 // CGDirectDisplayID is just an integer, so supporting up to this many
220 CGDirectDisplayID online_displays[128];
221 CGDisplayCount online_display_count = 0;
222 if (CGGetOnlineDisplayList(arraysize(online_displays),
224 &online_display_count) != kCGErrorSuccess) {
225 return std::vector<gfx::Display>(1, GetPrimaryDisplay());
228 typedef std::map<int64, NSScreen*> ScreenIdsToScreensMap;
229 ScreenIdsToScreensMap screen_ids_to_screens;
230 for (NSScreen* screen in [NSScreen screens]) {
231 NSDictionary* screen_device_description = [screen deviceDescription];
232 int64 screen_id = [[screen_device_description
233 objectForKey:@"NSScreenNumber"] unsignedIntValue];
234 screen_ids_to_screens[screen_id] = screen;
237 std::vector<gfx::Display> displays;
238 for (CGDisplayCount online_display_index = 0;
239 online_display_index < online_display_count;
240 ++online_display_index) {
241 CGDirectDisplayID online_display = online_displays[online_display_index];
242 if (CGDisplayMirrorsDisplay(online_display) == kCGNullDirectDisplay) {
243 // If this display doesn't mirror any other, include it in the list.
244 // The primary display in a mirrored set will be counted, but those that
245 // mirror it will not be.
246 ScreenIdsToScreensMap::iterator foundScreen =
247 screen_ids_to_screens.find(online_display);
248 if (foundScreen != screen_ids_to_screens.end()) {
249 displays.push_back(GetDisplayForScreen(foundScreen->second));
254 if (!displays.size())
255 return std::vector<gfx::Display>(1, GetPrimaryDisplay());
260 // The displays currently attached to the device.
261 std::vector<gfx::Display> displays_;
263 // The timer to delay configuring outputs. See also the comments in
264 // HandleDisplayReconfiguration().
265 scoped_ptr<base::OneShotTimer<ScreenMac> > configure_timer_;
267 gfx::DisplayChangeNotifier change_notifier_;
269 DISALLOW_COPY_AND_ASSIGN(ScreenMac);
276 #if !defined(USE_AURA)
277 Screen* CreateNativeScreen() {
278 return new ScreenMac;