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 "ui/gfx/screen.h"
6
7#import <ApplicationServices/ApplicationServices.h>
8#import <Cocoa/Cocoa.h>
9
10#include <map>
11
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"
17
18namespace {
19
20// The delay to handle the display configuration changes.
21// See comments in ScreenMac::HandleDisplayReconfiguration.
22const int64 kConfigureDelayMs = 500;
23
24gfx::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());
31  return rect;
32}
33
34NSScreen* 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];
38  int max_area = 0;
39
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) {
45      max_area = area;
46      max_screen = screen;
47    }
48  }
49
50  return max_screen;
51}
52
53gfx::Display GetDisplayForScreen(NSScreen* screen) {
54  NSRect frame = [screen frame];
55
56  CGDirectDisplayID display_id = [[[screen deviceDescription]
57    objectForKey:@"NSScreenNumber"] unsignedIntValue];
58
59  gfx::Display display(display_id, gfx::Rect(NSRectToCGRect(frame)));
60  NSRect visible_frame = [screen visibleFrame];
61  NSScreen* primary = [[NSScreen screens] objectAtIndex:0];
62
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);
69  } else {
70    display.set_bounds(ConvertCoordinateSystem(frame));
71    display.set_work_area(ConvertCoordinateSystem(visible_frame));
72  }
73  CGFloat scale;
74  if ([screen respondsToSelector:@selector(backingScaleFactor)])
75    scale = [screen backingScaleFactor];
76  else
77    scale = [screen userSpaceScaleFactor];
78  display.set_device_scale_factor(scale);
79  // CGDisplayRotation returns a double. Display::SetRotationAsDegree will
80  // handle the unexpected situations were the angle is not a multiple of 90.
81  display.SetRotationAsDegree(static_cast<int>(CGDisplayRotation(display_id)));
82  return display;
83}
84
85class ScreenMac : public gfx::Screen {
86 public:
87  ScreenMac() {
88    displays_ = BuildDisplaysFromQuartz();
89
90    CGDisplayRegisterReconfigurationCallback(
91        ScreenMac::DisplayReconfigurationCallBack, this);
92  }
93
94  virtual bool IsDIPEnabled() OVERRIDE {
95    return true;
96  }
97
98  virtual gfx::Point GetCursorScreenPoint() OVERRIDE {
99    NSPoint mouseLocation  = [NSEvent mouseLocation];
100    // Flip coordinates to gfx (0,0 in top-left corner) using primary screen.
101    NSScreen* screen = [[NSScreen screens] objectAtIndex:0];
102    mouseLocation.y = NSMaxY([screen frame]) - mouseLocation.y;
103    return gfx::Point(mouseLocation.x, mouseLocation.y);
104  }
105
106  virtual gfx::NativeWindow GetWindowUnderCursor() OVERRIDE {
107    NOTIMPLEMENTED();
108    return gfx::NativeWindow();
109  }
110
111  virtual gfx::NativeWindow GetWindowAtScreenPoint(const gfx::Point& point)
112      OVERRIDE {
113    NOTIMPLEMENTED();
114    return gfx::NativeWindow();
115  }
116
117  virtual int GetNumDisplays() const OVERRIDE {
118    return GetAllDisplays().size();
119
120  }
121
122  virtual std::vector<gfx::Display> GetAllDisplays() const OVERRIDE {
123    return displays_;
124  }
125
126  virtual gfx::Display GetDisplayNearestWindow(
127      gfx::NativeView view) const OVERRIDE {
128    NSWindow* window = nil;
129#if !defined(USE_AURA)
130    window = [view window];
131#endif
132    if (!window)
133      return GetPrimaryDisplay();
134    NSScreen* match_screen = [window screen];
135    if (!match_screen)
136      return GetPrimaryDisplay();
137    return GetDisplayForScreen(match_screen);
138  }
139
140  virtual gfx::Display GetDisplayNearestPoint(
141      const gfx::Point& point) const OVERRIDE {
142    NSPoint ns_point = NSPointFromCGPoint(point.ToCGPoint());
143
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);
150    }
151    return GetPrimaryDisplay();
152  }
153
154  // Returns the display that most closely intersects the provided bounds.
155  virtual gfx::Display GetDisplayMatching(
156      const gfx::Rect& match_rect) const OVERRIDE {
157    NSScreen* match_screen = GetMatchingScreen(match_rect);
158    return GetDisplayForScreen(match_screen);
159  }
160
161  // Returns the primary display.
162  virtual gfx::Display GetPrimaryDisplay() const OVERRIDE {
163    // Primary display is defined as the display with the menubar,
164    // which is always at index 0.
165    NSScreen* primary = [[NSScreen screens] objectAtIndex:0];
166    gfx::Display display = GetDisplayForScreen(primary);
167    return display;
168  }
169
170  virtual void AddObserver(gfx::DisplayObserver* observer) OVERRIDE {
171    change_notifier_.AddObserver(observer);
172  }
173
174  virtual void RemoveObserver(gfx::DisplayObserver* observer) OVERRIDE {
175    change_notifier_.RemoveObserver(observer);
176  }
177
178  static void DisplayReconfigurationCallBack(CGDirectDisplayID display,
179                                             CGDisplayChangeSummaryFlags flags,
180                                             void* userInfo) {
181    if (flags & kCGDisplayBeginConfigurationFlag)
182      return;
183
184    static_cast<ScreenMac*>(userInfo)->HandleDisplayReconfiguration();
185  }
186
187  void HandleDisplayReconfiguration() {
188    // Given that we need to rebuild the list of displays, we want to coalesce
189    // the events. For that, we use a timer that will be reset every time we get
190    // a new event and will be fulfilled kConfigureDelayMs after the latest.
191    if (configure_timer_.get() && configure_timer_->IsRunning()) {
192      configure_timer_->Reset();
193      return;
194    }
195
196    configure_timer_.reset(new base::OneShotTimer<ScreenMac>());
197    configure_timer_->Start(
198        FROM_HERE,
199        base::TimeDelta::FromMilliseconds(kConfigureDelayMs),
200        this,
201        &ScreenMac::ConfigureTimerFired);
202  }
203
204 private:
205  void ConfigureTimerFired() {
206    std::vector<gfx::Display> old_displays = displays_;
207    displays_ = BuildDisplaysFromQuartz();
208
209    change_notifier_.NotifyDisplaysChanged(old_displays, displays_);
210  }
211
212  std::vector<gfx::Display> BuildDisplaysFromQuartz() const {
213    // Don't just return all online displays.  This would include displays
214    // that mirror other displays, which are not desired in this list.  It's
215    // tempting to use the count returned by CGGetActiveDisplayList, but active
216    // displays exclude sleeping displays, and those are desired.
217
218    // It would be ridiculous to have this many displays connected, but
219    // CGDirectDisplayID is just an integer, so supporting up to this many
220    // doesn't hurt.
221    CGDirectDisplayID online_displays[128];
222    CGDisplayCount online_display_count = 0;
223    if (CGGetOnlineDisplayList(arraysize(online_displays),
224                              online_displays,
225                              &online_display_count) != kCGErrorSuccess) {
226      return std::vector<gfx::Display>(1, GetPrimaryDisplay());
227    }
228
229    typedef std::map<int64, NSScreen*> ScreenIdsToScreensMap;
230    ScreenIdsToScreensMap screen_ids_to_screens;
231    for (NSScreen* screen in [NSScreen screens]) {
232      NSDictionary* screen_device_description = [screen deviceDescription];
233      int64 screen_id = [[screen_device_description
234        objectForKey:@"NSScreenNumber"] unsignedIntValue];
235      screen_ids_to_screens[screen_id] = screen;
236    }
237
238    std::vector<gfx::Display> displays;
239    for (CGDisplayCount online_display_index = 0;
240        online_display_index < online_display_count;
241        ++online_display_index) {
242      CGDirectDisplayID online_display = online_displays[online_display_index];
243      if (CGDisplayMirrorsDisplay(online_display) == kCGNullDirectDisplay) {
244        // If this display doesn't mirror any other, include it in the list.
245        // The primary display in a mirrored set will be counted, but those that
246        // mirror it will not be.
247        ScreenIdsToScreensMap::iterator foundScreen =
248          screen_ids_to_screens.find(online_display);
249        if (foundScreen != screen_ids_to_screens.end()) {
250            displays.push_back(GetDisplayForScreen(foundScreen->second));
251        }
252      }
253    }
254
255    if (!displays.size())
256      return std::vector<gfx::Display>(1, GetPrimaryDisplay());
257
258    return displays;
259  }
260
261  // The displays currently attached to the device.
262  std::vector<gfx::Display> displays_;
263
264  // The timer to delay configuring outputs. See also the comments in
265  // HandleDisplayReconfiguration().
266  scoped_ptr<base::OneShotTimer<ScreenMac> > configure_timer_;
267
268  gfx::DisplayChangeNotifier change_notifier_;
269
270  DISALLOW_COPY_AND_ASSIGN(ScreenMac);
271};
272
273}  // namespace
274
275namespace gfx {
276
277#if !defined(USE_AURA)
278Screen* CreateNativeScreen() {
279  return new ScreenMac;
280}
281#endif
282
283}
284