SDL_cocoamodes.m 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2025 Sam Lantinga <[email protected]>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "SDL_internal.h"
  19. #ifdef SDL_VIDEO_DRIVER_COCOA
  20. #include "SDL_cocoavideo.h"
  21. #include "../../events/SDL_events_c.h"
  22. // We need this for IODisplayCreateInfoDictionary and kIODisplayOnlyPreferredName
  23. #include <IOKit/graphics/IOGraphicsLib.h>
  24. // We need this for CVDisplayLinkGetNominalOutputVideoRefreshPeriod
  25. #include <CoreVideo/CVBase.h>
  26. #include <CoreVideo/CVDisplayLink.h>
  27. #if (IOGRAPHICSTYPES_REV < 40)
  28. #define kDisplayModeNativeFlag 0x02000000
  29. #endif
  30. static bool CG_SetError(const char *prefix, CGDisplayErr result)
  31. {
  32. const char *error;
  33. switch (result) {
  34. case kCGErrorFailure:
  35. error = "kCGErrorFailure";
  36. break;
  37. case kCGErrorIllegalArgument:
  38. error = "kCGErrorIllegalArgument";
  39. break;
  40. case kCGErrorInvalidConnection:
  41. error = "kCGErrorInvalidConnection";
  42. break;
  43. case kCGErrorInvalidContext:
  44. error = "kCGErrorInvalidContext";
  45. break;
  46. case kCGErrorCannotComplete:
  47. error = "kCGErrorCannotComplete";
  48. break;
  49. case kCGErrorNotImplemented:
  50. error = "kCGErrorNotImplemented";
  51. break;
  52. case kCGErrorRangeCheck:
  53. error = "kCGErrorRangeCheck";
  54. break;
  55. case kCGErrorTypeCheck:
  56. error = "kCGErrorTypeCheck";
  57. break;
  58. case kCGErrorInvalidOperation:
  59. error = "kCGErrorInvalidOperation";
  60. break;
  61. case kCGErrorNoneAvailable:
  62. error = "kCGErrorNoneAvailable";
  63. break;
  64. default:
  65. error = "Unknown Error";
  66. break;
  67. }
  68. return SDL_SetError("%s: %s", prefix, error);
  69. }
  70. static NSScreen *GetNSScreenForDisplayID(CGDirectDisplayID displayID)
  71. {
  72. NSArray *screens = [NSScreen screens];
  73. // !!! FIXME: maybe track the NSScreen in SDL_DisplayData?
  74. for (NSScreen *screen in screens) {
  75. const CGDirectDisplayID thisDisplay = (CGDirectDisplayID)[[[screen deviceDescription] objectForKey:@"NSScreenNumber"] unsignedIntValue];
  76. if (thisDisplay == displayID) {
  77. return screen;
  78. }
  79. }
  80. return nil;
  81. }
  82. SDL_VideoDisplay *Cocoa_FindSDLDisplayByCGDirectDisplayID(SDL_VideoDevice *_this, CGDirectDisplayID displayid)
  83. {
  84. for (int i = 0; i < _this->num_displays; i++) {
  85. const SDL_DisplayData *displaydata = _this->displays[i]->internal;
  86. if (displaydata && (displaydata->display == displayid)) {
  87. return _this->displays[i];
  88. }
  89. }
  90. return NULL;
  91. }
  92. static float GetDisplayModeRefreshRate(CGDisplayModeRef vidmode, CVDisplayLinkRef link)
  93. {
  94. float refreshRate = (float)CGDisplayModeGetRefreshRate(vidmode);
  95. // CGDisplayModeGetRefreshRate can return 0 (eg for built-in displays).
  96. if (refreshRate == 0 && link != NULL) {
  97. CVTime time = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(link);
  98. if ((time.flags & kCVTimeIsIndefinite) == 0 && time.timeValue != 0) {
  99. refreshRate = (float)time.timeScale / time.timeValue;
  100. }
  101. }
  102. return refreshRate;
  103. }
  104. static bool HasValidDisplayModeFlags(CGDisplayModeRef vidmode)
  105. {
  106. uint32_t ioflags = CGDisplayModeGetIOFlags(vidmode);
  107. // Filter out modes which have flags that we don't want.
  108. if (ioflags & (kDisplayModeNeverShowFlag | kDisplayModeNotGraphicsQualityFlag)) {
  109. return false;
  110. }
  111. // Filter out modes which don't have flags that we want.
  112. if (!(ioflags & kDisplayModeValidFlag) || !(ioflags & kDisplayModeSafeFlag)) {
  113. return false;
  114. }
  115. return true;
  116. }
  117. static Uint32 GetDisplayModePixelFormat(CGDisplayModeRef vidmode)
  118. {
  119. // This API is deprecated in 10.11 with no good replacement (as of 10.15).
  120. CFStringRef fmt = CGDisplayModeCopyPixelEncoding(vidmode);
  121. Uint32 pixelformat = SDL_PIXELFORMAT_UNKNOWN;
  122. if (CFStringCompare(fmt, CFSTR(IO32BitDirectPixels),
  123. kCFCompareCaseInsensitive) == kCFCompareEqualTo) {
  124. pixelformat = SDL_PIXELFORMAT_ARGB8888;
  125. } else if (CFStringCompare(fmt, CFSTR(IO16BitDirectPixels),
  126. kCFCompareCaseInsensitive) == kCFCompareEqualTo) {
  127. pixelformat = SDL_PIXELFORMAT_ARGB1555;
  128. } else if (CFStringCompare(fmt, CFSTR(kIO30BitDirectPixels),
  129. kCFCompareCaseInsensitive) == kCFCompareEqualTo) {
  130. pixelformat = SDL_PIXELFORMAT_ARGB2101010;
  131. } else {
  132. // ignore 8-bit and such for now.
  133. }
  134. CFRelease(fmt);
  135. return pixelformat;
  136. }
  137. static bool GetDisplayMode(CGDisplayModeRef vidmode, bool vidmodeCurrent, CFArrayRef modelist, CVDisplayLinkRef link, SDL_DisplayMode *mode)
  138. {
  139. SDL_DisplayModeData *data;
  140. bool usableForGUI = CGDisplayModeIsUsableForDesktopGUI(vidmode);
  141. size_t width = CGDisplayModeGetWidth(vidmode);
  142. size_t height = CGDisplayModeGetHeight(vidmode);
  143. size_t pixelW = width;
  144. size_t pixelH = height;
  145. uint32_t ioflags = CGDisplayModeGetIOFlags(vidmode);
  146. float refreshrate = GetDisplayModeRefreshRate(vidmode, link);
  147. Uint32 format = GetDisplayModePixelFormat(vidmode);
  148. bool interlaced = (ioflags & kDisplayModeInterlacedFlag) != 0;
  149. CFMutableArrayRef modes;
  150. if (format == SDL_PIXELFORMAT_UNKNOWN) {
  151. return false;
  152. }
  153. /* Don't fail the current mode based on flags because this could prevent Cocoa_InitModes from
  154. * succeeding if the current mode lacks certain flags (esp kDisplayModeSafeFlag). */
  155. if (!vidmodeCurrent && !HasValidDisplayModeFlags(vidmode)) {
  156. return false;
  157. }
  158. modes = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
  159. CFArrayAppendValue(modes, vidmode);
  160. /* If a list of possible display modes is passed in, use it to filter out
  161. * modes that have duplicate sizes. We don't just rely on SDL's higher level
  162. * duplicate filtering because this code can choose what properties are
  163. * preferred, and it can add CGDisplayModes to the DisplayModeData's list of
  164. * modes to try (see comment below for why that's necessary). */
  165. pixelW = CGDisplayModeGetPixelWidth(vidmode);
  166. pixelH = CGDisplayModeGetPixelHeight(vidmode);
  167. if (modelist != NULL) {
  168. CFIndex modescount = CFArrayGetCount(modelist);
  169. int i;
  170. for (i = 0; i < modescount; i++) {
  171. size_t otherW, otherH, otherpixelW, otherpixelH;
  172. float otherrefresh;
  173. Uint32 otherformat;
  174. bool otherGUI;
  175. CGDisplayModeRef othermode = (CGDisplayModeRef)CFArrayGetValueAtIndex(modelist, i);
  176. uint32_t otherioflags = CGDisplayModeGetIOFlags(othermode);
  177. if (CFEqual(vidmode, othermode)) {
  178. continue;
  179. }
  180. if (!HasValidDisplayModeFlags(othermode)) {
  181. continue;
  182. }
  183. otherW = CGDisplayModeGetWidth(othermode);
  184. otherH = CGDisplayModeGetHeight(othermode);
  185. otherpixelW = CGDisplayModeGetPixelWidth(othermode);
  186. otherpixelH = CGDisplayModeGetPixelHeight(othermode);
  187. otherrefresh = GetDisplayModeRefreshRate(othermode, link);
  188. otherformat = GetDisplayModePixelFormat(othermode);
  189. otherGUI = CGDisplayModeIsUsableForDesktopGUI(othermode);
  190. /* Ignore this mode if it's interlaced and there's a non-interlaced
  191. * mode in the list with the same properties.
  192. */
  193. if (interlaced && ((otherioflags & kDisplayModeInterlacedFlag) == 0) && width == otherW && height == otherH && pixelW == otherpixelW && pixelH == otherpixelH && refreshrate == otherrefresh && format == otherformat && usableForGUI == otherGUI) {
  194. CFRelease(modes);
  195. return false;
  196. }
  197. /* Ignore this mode if it's not usable for desktop UI and its
  198. * properties are equal to another GUI-capable mode in the list.
  199. */
  200. if (width == otherW && height == otherH && pixelW == otherpixelW && pixelH == otherpixelH && !usableForGUI && otherGUI && refreshrate == otherrefresh && format == otherformat) {
  201. CFRelease(modes);
  202. return false;
  203. }
  204. /* If multiple modes have the exact same properties, they'll all
  205. * go in the list of modes to try when SetDisplayMode is called.
  206. * This is needed because kCGDisplayShowDuplicateLowResolutionModes
  207. * (which is used to expose highdpi display modes) can make the
  208. * list of modes contain duplicates (according to their properties
  209. * obtained via public APIs) which don't work with SetDisplayMode.
  210. * Those duplicate non-functional modes *do* have different pixel
  211. * formats according to their internal data structure viewed with
  212. * NSLog, but currently no public API can detect that.
  213. * https://bugzilla.libsdl.org/show_bug.cgi?id=4822
  214. *
  215. * As of macOS 10.15.0, those duplicates have the exact same
  216. * properties via public APIs in every way (even their IO flags and
  217. * CGDisplayModeGetIODisplayModeID is the same), so we could test
  218. * those for equality here too, but I'm intentionally not doing that
  219. * in case there are duplicate modes with different IO flags or IO
  220. * display mode IDs in the future. In that case I think it's better
  221. * to try them all in SetDisplayMode than to risk one of them being
  222. * correct but it being filtered out by SDL_AddFullscreenDisplayMode
  223. * as being a duplicate.
  224. */
  225. if (width == otherW && height == otherH && pixelW == otherpixelW && pixelH == otherpixelH && usableForGUI == otherGUI && refreshrate == otherrefresh && format == otherformat) {
  226. CFArrayAppendValue(modes, othermode);
  227. }
  228. }
  229. }
  230. SDL_zerop(mode);
  231. data = (SDL_DisplayModeData *)SDL_malloc(sizeof(*data));
  232. if (!data) {
  233. CFRelease(modes);
  234. return false;
  235. }
  236. data->modes = modes;
  237. mode->format = format;
  238. mode->w = (int)width;
  239. mode->h = (int)height;
  240. mode->pixel_density = (float)pixelW / width;
  241. mode->refresh_rate = refreshrate;
  242. mode->internal = data;
  243. return true;
  244. }
  245. static char *Cocoa_GetDisplayName(CGDirectDisplayID displayID)
  246. {
  247. // This API is deprecated in 10.9 with no good replacement (as of 10.15).
  248. io_service_t servicePort = CGDisplayIOServicePort(displayID);
  249. CFDictionaryRef deviceInfo = IODisplayCreateInfoDictionary(servicePort, kIODisplayOnlyPreferredName);
  250. NSDictionary *localizedNames = [(__bridge NSDictionary *)deviceInfo objectForKey:[NSString stringWithUTF8String:kDisplayProductName]];
  251. char *displayName = NULL;
  252. if ([localizedNames count] > 0) {
  253. displayName = SDL_strdup([[localizedNames objectForKey:[[localizedNames allKeys] objectAtIndex:0]] UTF8String]);
  254. }
  255. CFRelease(deviceInfo);
  256. return displayName;
  257. }
  258. static void Cocoa_GetHDRProperties(CGDirectDisplayID displayID, SDL_HDROutputProperties *HDR)
  259. {
  260. HDR->SDR_white_level = 1.0f;
  261. HDR->HDR_headroom = 1.0f;
  262. if (@available(macOS 10.15, *)) {
  263. NSScreen *screen = GetNSScreenForDisplayID(displayID);
  264. if (screen) {
  265. if (screen.maximumExtendedDynamicRangeColorComponentValue > 1.0f) {
  266. HDR->HDR_headroom = screen.maximumExtendedDynamicRangeColorComponentValue;
  267. } else {
  268. HDR->HDR_headroom = screen.maximumPotentialExtendedDynamicRangeColorComponentValue;
  269. }
  270. }
  271. }
  272. }
  273. bool Cocoa_AddDisplay(CGDirectDisplayID display, bool send_event)
  274. {
  275. CGDisplayModeRef moderef = CGDisplayCopyDisplayMode(display);
  276. if (!moderef) {
  277. return false;
  278. }
  279. SDL_DisplayData *displaydata = (SDL_DisplayData *)SDL_malloc(sizeof(*displaydata));
  280. if (!displaydata) {
  281. CGDisplayModeRelease(moderef);
  282. return false;
  283. }
  284. displaydata->display = display;
  285. CVDisplayLinkRef link = NULL;
  286. CVDisplayLinkCreateWithCGDisplay(display, &link);
  287. SDL_VideoDisplay viddisplay;
  288. SDL_zero(viddisplay);
  289. viddisplay.name = Cocoa_GetDisplayName(display); // this returns a strdup'ed string
  290. SDL_DisplayMode mode;
  291. if (!GetDisplayMode(moderef, true, NULL, link, &mode)) {
  292. CVDisplayLinkRelease(link);
  293. CGDisplayModeRelease(moderef);
  294. SDL_free(viddisplay.name);
  295. SDL_free(displaydata);
  296. return false;
  297. }
  298. CVDisplayLinkRelease(link);
  299. CGDisplayModeRelease(moderef);
  300. Cocoa_GetHDRProperties(displaydata->display, &viddisplay.HDR);
  301. viddisplay.desktop_mode = mode;
  302. viddisplay.internal = displaydata;
  303. const bool retval = SDL_AddVideoDisplay(&viddisplay, send_event);
  304. SDL_free(viddisplay.name);
  305. return retval;
  306. }
  307. static void Cocoa_DisplayReconfigurationCallback(CGDirectDisplayID displayid, CGDisplayChangeSummaryFlags flags, void *userInfo)
  308. {
  309. #if 0
  310. SDL_Log("COCOA DISPLAY RECONFIG CALLBACK! display=%u", (unsigned int) displayid);
  311. #define CHECK_DISPLAY_RECONFIG_FLAG(x) if (flags & x) { SDL_Log(" - " #x); }
  312. CHECK_DISPLAY_RECONFIG_FLAG(kCGDisplayBeginConfigurationFlag);
  313. CHECK_DISPLAY_RECONFIG_FLAG(kCGDisplayMovedFlag);
  314. CHECK_DISPLAY_RECONFIG_FLAG(kCGDisplaySetMainFlag);
  315. CHECK_DISPLAY_RECONFIG_FLAG(kCGDisplaySetModeFlag);
  316. CHECK_DISPLAY_RECONFIG_FLAG(kCGDisplayAddFlag);
  317. CHECK_DISPLAY_RECONFIG_FLAG(kCGDisplayRemoveFlag);
  318. CHECK_DISPLAY_RECONFIG_FLAG(kCGDisplayEnabledFlag);
  319. CHECK_DISPLAY_RECONFIG_FLAG(kCGDisplayDisabledFlag);
  320. CHECK_DISPLAY_RECONFIG_FLAG(kCGDisplayMirrorFlag);
  321. CHECK_DISPLAY_RECONFIG_FLAG(kCGDisplayUnMirrorFlag);
  322. CHECK_DISPLAY_RECONFIG_FLAG(kCGDisplayDesktopShapeChangedFlag);
  323. #undef CHECK_DISPLAY_RECONFIG_FLAG
  324. #endif
  325. SDL_VideoDevice *_this = (SDL_VideoDevice *) userInfo;
  326. SDL_VideoDisplay *display = Cocoa_FindSDLDisplayByCGDirectDisplayID(_this, displayid); // will be NULL for newly-added (or newly-unmirrored) displays!
  327. if (flags & kCGDisplayDisabledFlag) {
  328. flags |= kCGDisplayRemoveFlag; // treat this like a display leaving, even though it's still plugged in.
  329. }
  330. if (flags & kCGDisplayEnabledFlag) {
  331. flags |= kCGDisplayAddFlag; // treat this like a display leaving, even though it's still plugged in.
  332. }
  333. if (flags & kCGDisplayMirrorFlag) {
  334. flags |= kCGDisplayRemoveFlag; // treat this like a display leaving, even though it's still actually here.
  335. }
  336. if (flags & kCGDisplayUnMirrorFlag) {
  337. flags |= kCGDisplayAddFlag; // treat this like a new display arriving, even though it was here all along.
  338. }
  339. if ((flags & kCGDisplayAddFlag) && (flags & kCGDisplayRemoveFlag)) {
  340. // both adding _and_ removing? Treat it as a remove exclusively. This can happen if a display is unmirroring because it's being disabled, etc.
  341. flags &= ~kCGDisplayAddFlag;
  342. }
  343. if (flags & kCGDisplayAddFlag) {
  344. if (!display) {
  345. if (!Cocoa_AddDisplay(displayid, true)) {
  346. return; // oh well.
  347. }
  348. display = Cocoa_FindSDLDisplayByCGDirectDisplayID(_this, displayid);
  349. SDL_assert(display != NULL);
  350. }
  351. }
  352. if (flags & kCGDisplayRemoveFlag) {
  353. if (display) {
  354. SDL_DelVideoDisplay(display->id, true);
  355. display = NULL;
  356. }
  357. }
  358. if (flags & kCGDisplaySetModeFlag) {
  359. if (display) {
  360. CGDisplayModeRef moderef = CGDisplayCopyDisplayMode(displayid);
  361. if (moderef) {
  362. CVDisplayLinkRef link = NULL;
  363. CVDisplayLinkCreateWithCGDisplay(displayid, &link);
  364. if (link) {
  365. SDL_DisplayMode mode;
  366. if (GetDisplayMode(moderef, true, NULL, link, &mode)) {
  367. SDL_SetDesktopDisplayMode(display, &mode);
  368. }
  369. CVDisplayLinkRelease(link);
  370. }
  371. CGDisplayModeRelease(moderef);
  372. }
  373. }
  374. }
  375. if (flags & kCGDisplaySetMainFlag) {
  376. if (display) {
  377. for (int i = 0; i < _this->num_displays; i++) {
  378. if (_this->displays[i] == display) {
  379. if (i > 0) {
  380. // move this display to the front of _this->displays so it's treated as primary.
  381. SDL_memmove(&_this->displays[1], &_this->displays[0], sizeof (*_this->displays) * i);
  382. _this->displays[0] = display;
  383. }
  384. flags |= kCGDisplayMovedFlag; // we don't have an SDL event atm for "this display became primary," so at least let everyone know it "moved".
  385. break;
  386. }
  387. }
  388. }
  389. }
  390. if (flags & kCGDisplayMovedFlag) {
  391. if (display) {
  392. SDL_SendDisplayEvent(display, SDL_EVENT_DISPLAY_MOVED, 0, 0);
  393. }
  394. }
  395. if (flags & kCGDisplayDesktopShapeChangedFlag) {
  396. SDL_UpdateDesktopBounds();
  397. }
  398. }
  399. void Cocoa_InitModes(SDL_VideoDevice *_this)
  400. {
  401. @autoreleasepool {
  402. CGDisplayErr result;
  403. CGDisplayCount numDisplays = 0;
  404. result = CGGetOnlineDisplayList(0, NULL, &numDisplays);
  405. if (result != kCGErrorSuccess) {
  406. CG_SetError("CGGetOnlineDisplayList()", result);
  407. return;
  408. }
  409. bool isstack;
  410. CGDirectDisplayID *displays = SDL_small_alloc(CGDirectDisplayID, numDisplays, &isstack);
  411. result = CGGetOnlineDisplayList(numDisplays, displays, &numDisplays);
  412. if (result != kCGErrorSuccess) {
  413. CG_SetError("CGGetOnlineDisplayList()", result);
  414. SDL_small_free(displays, isstack);
  415. return;
  416. }
  417. // future updates to the display graph will come through this callback.
  418. CGDisplayRegisterReconfigurationCallback(Cocoa_DisplayReconfigurationCallback, _this);
  419. // Pick up the primary display in the first pass, then get the rest
  420. for (int pass = 0; pass < 2; ++pass) {
  421. for (int i = 0; i < numDisplays; ++i) {
  422. if (pass == 0) {
  423. if (!CGDisplayIsMain(displays[i])) {
  424. continue;
  425. }
  426. } else {
  427. if (CGDisplayIsMain(displays[i])) {
  428. continue;
  429. }
  430. }
  431. if (CGDisplayMirrorsDisplay(displays[i]) != kCGNullDirectDisplay) {
  432. continue;
  433. }
  434. Cocoa_AddDisplay(displays[i], false);
  435. }
  436. }
  437. SDL_small_free(displays, isstack);
  438. }
  439. }
  440. void Cocoa_UpdateDisplays(SDL_VideoDevice *_this)
  441. {
  442. SDL_HDROutputProperties HDR;
  443. int i;
  444. for (i = 0; i < _this->num_displays; ++i) {
  445. SDL_VideoDisplay *display = _this->displays[i];
  446. SDL_DisplayData *displaydata = (SDL_DisplayData *)display->internal;
  447. Cocoa_GetHDRProperties(displaydata->display, &HDR);
  448. SDL_SetDisplayHDRProperties(display, &HDR);
  449. }
  450. }
  451. bool Cocoa_GetDisplayBounds(SDL_VideoDevice *_this, SDL_VideoDisplay *display, SDL_Rect *rect)
  452. {
  453. SDL_DisplayData *displaydata = (SDL_DisplayData *)display->internal;
  454. CGRect cgrect;
  455. cgrect = CGDisplayBounds(displaydata->display);
  456. rect->x = (int)cgrect.origin.x;
  457. rect->y = (int)cgrect.origin.y;
  458. rect->w = (int)cgrect.size.width;
  459. rect->h = (int)cgrect.size.height;
  460. return true;
  461. }
  462. bool Cocoa_GetDisplayUsableBounds(SDL_VideoDevice *_this, SDL_VideoDisplay *display, SDL_Rect *rect)
  463. {
  464. SDL_DisplayData *displaydata = (SDL_DisplayData *)display->internal;
  465. NSScreen *screen = GetNSScreenForDisplayID(displaydata->display);
  466. if (screen == nil) {
  467. return SDL_SetError("Couldn't get NSScreen for display");
  468. }
  469. {
  470. const NSRect frame = [screen visibleFrame];
  471. rect->x = (int)frame.origin.x;
  472. rect->y = (int)(CGDisplayPixelsHigh(kCGDirectMainDisplay) - frame.origin.y - frame.size.height);
  473. rect->w = (int)frame.size.width;
  474. rect->h = (int)frame.size.height;
  475. }
  476. return true;
  477. }
  478. bool Cocoa_GetDisplayModes(SDL_VideoDevice *_this, SDL_VideoDisplay *display)
  479. {
  480. SDL_DisplayData *data = (SDL_DisplayData *)display->internal;
  481. CVDisplayLinkRef link = NULL;
  482. CFArrayRef modes;
  483. CFDictionaryRef dict = NULL;
  484. const CFStringRef dictkeys[] = { kCGDisplayShowDuplicateLowResolutionModes };
  485. const CFBooleanRef dictvalues[] = { kCFBooleanTrue };
  486. CVDisplayLinkCreateWithCGDisplay(data->display, &link);
  487. /* By default, CGDisplayCopyAllDisplayModes will only get a subset of the
  488. * system's available modes. For example on a 15" 2016 MBP, users can
  489. * choose 1920x1080@2x in System Preferences but it won't show up here,
  490. * unless we specify the option below.
  491. * The display modes returned by CGDisplayCopyAllDisplayModes are also not
  492. * high dpi-capable unless this option is set.
  493. * macOS 10.15 also seems to have a bug where entering, exiting, and
  494. * re-entering exclusive fullscreen with a low dpi display mode can cause
  495. * the content of the screen to move up, which this setting avoids:
  496. * https://bugzilla.libsdl.org/show_bug.cgi?id=4822
  497. */
  498. dict = CFDictionaryCreate(NULL,
  499. (const void **)dictkeys,
  500. (const void **)dictvalues,
  501. 1,
  502. &kCFCopyStringDictionaryKeyCallBacks,
  503. &kCFTypeDictionaryValueCallBacks);
  504. modes = CGDisplayCopyAllDisplayModes(data->display, dict);
  505. if (dict) {
  506. CFRelease(dict);
  507. }
  508. if (modes) {
  509. CFIndex i;
  510. const CFIndex count = CFArrayGetCount(modes);
  511. for (i = 0; i < count; i++) {
  512. CGDisplayModeRef moderef = (CGDisplayModeRef)CFArrayGetValueAtIndex(modes, i);
  513. SDL_DisplayMode mode;
  514. if (GetDisplayMode(moderef, false, modes, link, &mode)) {
  515. if (!SDL_AddFullscreenDisplayMode(display, &mode)) {
  516. CFRelease(mode.internal->modes);
  517. SDL_free(mode.internal);
  518. }
  519. }
  520. }
  521. CFRelease(modes);
  522. }
  523. CVDisplayLinkRelease(link);
  524. return true;
  525. }
  526. static CGError SetDisplayModeForDisplay(CGDirectDisplayID display, SDL_DisplayModeData *data)
  527. {
  528. /* SDL_DisplayModeData can contain multiple CGDisplayModes to try (with
  529. * identical properties), some of which might not work. See GetDisplayMode.
  530. */
  531. CGError result = kCGErrorFailure;
  532. for (CFIndex i = 0; i < CFArrayGetCount(data->modes); i++) {
  533. CGDisplayModeRef moderef = (CGDisplayModeRef)CFArrayGetValueAtIndex(data->modes, i);
  534. result = CGDisplaySetDisplayMode(display, moderef, NULL);
  535. if (result == kCGErrorSuccess) {
  536. // If this mode works, try it first next time.
  537. CFArrayExchangeValuesAtIndices(data->modes, i, 0);
  538. break;
  539. }
  540. }
  541. return result;
  542. }
  543. bool Cocoa_SetDisplayMode(SDL_VideoDevice *_this, SDL_VideoDisplay *display, SDL_DisplayMode *mode)
  544. {
  545. SDL_DisplayData *displaydata = (SDL_DisplayData *)display->internal;
  546. SDL_DisplayModeData *data = mode->internal;
  547. CGDisplayFadeReservationToken fade_token = kCGDisplayFadeReservationInvalidToken;
  548. CGError result = kCGErrorSuccess;
  549. b_inModeTransition = true;
  550. // Fade to black to hide resolution-switching flicker
  551. if (CGAcquireDisplayFadeReservation(5, &fade_token) == kCGErrorSuccess) {
  552. CGDisplayFade(fade_token, 0.3, kCGDisplayBlendNormal, kCGDisplayBlendSolidColor, 0.0, 0.0, 0.0, TRUE);
  553. }
  554. if (data == display->desktop_mode.internal) {
  555. // Restoring desktop mode
  556. SetDisplayModeForDisplay(displaydata->display, data);
  557. } else {
  558. // Do the physical switch
  559. result = SetDisplayModeForDisplay(displaydata->display, data);
  560. }
  561. // Fade in again (asynchronously)
  562. if (fade_token != kCGDisplayFadeReservationInvalidToken) {
  563. CGDisplayFade(fade_token, 0.5, kCGDisplayBlendSolidColor, kCGDisplayBlendNormal, 0.0, 0.0, 0.0, FALSE);
  564. CGReleaseDisplayFadeReservation(fade_token);
  565. }
  566. b_inModeTransition = false;
  567. if (result != kCGErrorSuccess) {
  568. return CG_SetError("CGDisplaySwitchToMode()", result);
  569. }
  570. return true;
  571. }
  572. void Cocoa_QuitModes(SDL_VideoDevice *_this)
  573. {
  574. int i, j;
  575. CGDisplayRemoveReconfigurationCallback(Cocoa_DisplayReconfigurationCallback, _this);
  576. for (i = 0; i < _this->num_displays; ++i) {
  577. SDL_VideoDisplay *display = _this->displays[i];
  578. SDL_DisplayModeData *mode;
  579. if (display->current_mode->internal != display->desktop_mode.internal) {
  580. Cocoa_SetDisplayMode(_this, display, &display->desktop_mode);
  581. }
  582. mode = display->desktop_mode.internal;
  583. CFRelease(mode->modes);
  584. for (j = 0; j < display->num_fullscreen_modes; j++) {
  585. mode = display->fullscreen_modes[j].internal;
  586. CFRelease(mode->modes);
  587. }
  588. }
  589. }
  590. #endif // SDL_VIDEO_DRIVER_COCOA