SDL: macOS: always use Objective-C ARC (automatic ref counting).

From ec8fa57750423978086cd7a96bd92e7e3ff46cc9 Mon Sep 17 00:00:00 2001
From: Alex Szpakowski <[EMAIL REDACTED]>
Date: Sat, 7 May 2022 21:57:23 -0300
Subject: [PATCH] macOS: always use Objective-C ARC (automatic ref counting).

Change Cocoa SDL_VideoData and SDL_WindowData implementations from C structs to Objective-C objects, since bridging between C and ObjC is easier that way.
---
 CMakeLists.txt                                |   2 +-
 Xcode/SDL/SDL.xcodeproj/project.pbxproj       |   8 +-
 .../SDLTest/SDLTest.xcodeproj/project.pbxproj |   2 +
 src/render/metal/SDL_render_metal.m           |  90 +----
 src/video/cocoa/SDL_cocoaclipboard.h          |   4 +-
 src/video/cocoa/SDL_cocoaclipboard.m          |  12 +-
 src/video/cocoa/SDL_cocoaevents.m             |  33 +-
 src/video/cocoa/SDL_cocoakeyboard.m           |  55 ++-
 src/video/cocoa/SDL_cocoamessagebox.m         |  12 +-
 src/video/cocoa/SDL_cocoametalview.m          |  10 +-
 src/video/cocoa/SDL_cocoamodes.m              |   2 +-
 src/video/cocoa/SDL_cocoamouse.m              |  42 +-
 src/video/cocoa/SDL_cocoaopengl.m             |  56 +--
 src/video/cocoa/SDL_cocoaopengles.m           |  37 +-
 src/video/cocoa/SDL_cocoashape.m              |  17 +-
 src/video/cocoa/SDL_cocoavideo.h              |  23 +-
 src/video/cocoa/SDL_cocoavideo.m              |  50 ++-
 src/video/cocoa/SDL_cocoawindow.h             |  30 +-
 src/video/cocoa/SDL_cocoawindow.m             | 380 +++++++++---------
 19 files changed, 396 insertions(+), 469 deletions(-)

diff --git a/CMakeLists.txt b/CMakeLists.txt
index 99a5385980b..22e23a33ca6 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -2902,7 +2902,7 @@ if(ANDROID)
   target_include_directories(sdl-build-options INTERFACE "${ANDROID_NDK}/sources/android/cpufeatures")
 endif()
 
-if(IOS OR TVOS)
+if(APPLE)
   target_compile_options(sdl-build-options INTERFACE "-fobjc-arc")
 endif()
 
diff --git a/Xcode/SDL/SDL.xcodeproj/project.pbxproj b/Xcode/SDL/SDL.xcodeproj/project.pbxproj
index 9f39ca64849..c6001f1ef74 100644
--- a/Xcode/SDL/SDL.xcodeproj/project.pbxproj
+++ b/Xcode/SDL/SDL.xcodeproj/project.pbxproj
@@ -3469,13 +3469,13 @@
 		F395C1A22569C68F00942BFF /* SDL_iokitjoystick.c in Sources */ = {isa = PBXBuildFile; fileRef = F395C1922569C68E00942BFF /* SDL_iokitjoystick.c */; };
 		F395C1A32569C68F00942BFF /* SDL_iokitjoystick.c in Sources */ = {isa = PBXBuildFile; fileRef = F395C1922569C68E00942BFF /* SDL_iokitjoystick.c */; };
 		F395C1A42569C68F00942BFF /* SDL_iokitjoystick.c in Sources */ = {isa = PBXBuildFile; fileRef = F395C1922569C68E00942BFF /* SDL_iokitjoystick.c */; };
-		F395C1B12569C6A000942BFF /* SDL_mfijoystick.m in Sources */ = {isa = PBXBuildFile; fileRef = F395C1AF2569C6A000942BFF /* SDL_mfijoystick.m */; settings = {COMPILER_FLAGS = "-fobjc-arc"; }; };
+		F395C1B12569C6A000942BFF /* SDL_mfijoystick.m in Sources */ = {isa = PBXBuildFile; fileRef = F395C1AF2569C6A000942BFF /* SDL_mfijoystick.m */; };
 		F395C1B22569C6A000942BFF /* SDL_mfijoystick.m in Sources */ = {isa = PBXBuildFile; fileRef = F395C1AF2569C6A000942BFF /* SDL_mfijoystick.m */; };
 		F395C1B32569C6A000942BFF /* SDL_mfijoystick.m in Sources */ = {isa = PBXBuildFile; fileRef = F395C1AF2569C6A000942BFF /* SDL_mfijoystick.m */; };
-		F395C1B42569C6A000942BFF /* SDL_mfijoystick.m in Sources */ = {isa = PBXBuildFile; fileRef = F395C1AF2569C6A000942BFF /* SDL_mfijoystick.m */; settings = {COMPILER_FLAGS = "-fobjc-arc"; }; };
+		F395C1B42569C6A000942BFF /* SDL_mfijoystick.m in Sources */ = {isa = PBXBuildFile; fileRef = F395C1AF2569C6A000942BFF /* SDL_mfijoystick.m */; };
 		F395C1B52569C6A000942BFF /* SDL_mfijoystick.m in Sources */ = {isa = PBXBuildFile; fileRef = F395C1AF2569C6A000942BFF /* SDL_mfijoystick.m */; };
 		F395C1B62569C6A000942BFF /* SDL_mfijoystick.m in Sources */ = {isa = PBXBuildFile; fileRef = F395C1AF2569C6A000942BFF /* SDL_mfijoystick.m */; };
-		F395C1B72569C6A000942BFF /* SDL_mfijoystick.m in Sources */ = {isa = PBXBuildFile; fileRef = F395C1AF2569C6A000942BFF /* SDL_mfijoystick.m */; settings = {COMPILER_FLAGS = "-fobjc-arc"; }; };
+		F395C1B72569C6A000942BFF /* SDL_mfijoystick.m in Sources */ = {isa = PBXBuildFile; fileRef = F395C1AF2569C6A000942BFF /* SDL_mfijoystick.m */; };
 		F395C1B82569C6A000942BFF /* SDL_mfijoystick.m in Sources */ = {isa = PBXBuildFile; fileRef = F395C1AF2569C6A000942BFF /* SDL_mfijoystick.m */; };
 		F395C1B92569C6A000942BFF /* SDL_mfijoystick.m in Sources */ = {isa = PBXBuildFile; fileRef = F395C1AF2569C6A000942BFF /* SDL_mfijoystick.m */; };
 		F395C1BA2569C6A000942BFF /* SDL_mfijoystick_c.h in Headers */ = {isa = PBXBuildFile; fileRef = F395C1B02569C6A000942BFF /* SDL_mfijoystick_c.h */; };
@@ -9188,6 +9188,7 @@
 			buildSettings = {
 				ALWAYS_SEARCH_USER_PATHS = NO;
 				CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
+				CLANG_ENABLE_OBJC_ARC = YES;
 				CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
 				CLANG_WARN_BOOL_CONVERSION = YES;
 				CLANG_WARN_COMMA = YES;
@@ -9273,6 +9274,7 @@
 			buildSettings = {
 				ALWAYS_SEARCH_USER_PATHS = NO;
 				CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
+				CLANG_ENABLE_OBJC_ARC = YES;
 				CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
 				CLANG_WARN_BOOL_CONVERSION = YES;
 				CLANG_WARN_COMMA = YES;
diff --git a/Xcode/SDLTest/SDLTest.xcodeproj/project.pbxproj b/Xcode/SDLTest/SDLTest.xcodeproj/project.pbxproj
index 72e2c53080a..e7e1d23bc11 100644
--- a/Xcode/SDLTest/SDLTest.xcodeproj/project.pbxproj
+++ b/Xcode/SDLTest/SDLTest.xcodeproj/project.pbxproj
@@ -4041,6 +4041,7 @@
 			isa = XCBuildConfiguration;
 			buildSettings = {
 				ALWAYS_SEARCH_USER_PATHS = NO;
+				CLANG_ENABLE_OBJC_ARC = YES;
 				FRAMEWORK_SEARCH_PATHS = (
 					"$(SRCROOT)/../SDL/build/$(CONFIGURATION)",
 					"$(HOME)/Library/Frameworks",
@@ -4168,6 +4169,7 @@
 			isa = XCBuildConfiguration;
 			buildSettings = {
 				ALWAYS_SEARCH_USER_PATHS = NO;
+				CLANG_ENABLE_OBJC_ARC = YES;
 				FRAMEWORK_SEARCH_PATHS = (
 					"$(SRCROOT)/../SDL/build/$(CONFIGURATION)",
 					"$(HOME)/Library/Frameworks",
diff --git a/src/render/metal/SDL_render_metal.m b/src/render/metal/SDL_render_metal.m
index 329e5b3a01f..6ade20c12cc 100644
--- a/src/render/metal/SDL_render_metal.m
+++ b/src/render/metal/SDL_render_metal.m
@@ -142,24 +142,6 @@ @interface METAL_RenderData : NSObject
 @end
 
 @implementation METAL_RenderData
-#if !__has_feature(objc_arc)
-- (void)dealloc
-{
-    [_mtldevice release];
-    [_mtlcmdqueue release];
-    [_mtlcmdbuffer release];
-    [_mtlcmdencoder release];
-    [_mtllibrary release];
-    [_mtlbackbuffer release];
-    [_mtlsamplernearest release];
-    [_mtlsamplerlinear release];
-    [_mtlbufconstants release];
-    [_mtlbufquadindices release];
-    [_mtllayer release];
-    [_mtlpassdesc release];
-    [super dealloc];
-}
-#endif
 @end
 
 @interface METAL_TextureData : NSObject
@@ -178,16 +160,6 @@ @interface METAL_TextureData : NSObject
 @end
 
 @implementation METAL_TextureData
-#if !__has_feature(objc_arc)
-- (void)dealloc
-{
-    [_mtltexture release];
-    [_mtltexture_uv release];
-    [_mtlsampler release];
-    [_lockedbuffer release];
-    [super dealloc];
-}
-#endif
 @end
 
 static int
@@ -342,13 +314,6 @@ - (void)dealloc
 
     METAL_PipelineState *states = SDL_realloc(cache->states, (cache->count + 1) * sizeof(pipeline));
 
-#if !__has_feature(objc_arc)
-    [mtlpipedesc release];  // !!! FIXME: can these be reused for each creation, or does the pipeline obtain it?
-    [mtlvertfn release];
-    [mtlfragfn release];
-    [state release];
-#endif
-
     if (states) {
         states[cache->count++] = pipeline;
         cache->states = states;
@@ -632,9 +597,6 @@ - (void)dealloc
     if (yuv || nv12) {
         mtltexture_uv = [data.mtldevice newTextureWithDescriptor:mtltexdesc];
         if (mtltexture_uv == nil) {
-#if !__has_feature(objc_arc)
-            [mtltexture release];
-#endif
             return SDL_SetError("Texture allocation failed");
         }
     }
@@ -677,12 +639,6 @@ - (void)dealloc
 #endif
     texture->driverdata = (void*)CFBridgingRetain(texturedata);
 
-#if !__has_feature(objc_arc)
-    [texturedata release];
-    [mtltexture release];
-    [mtltexture_uv release];
-#endif
-
     return 0;
 }}
 
@@ -742,10 +698,6 @@ - (void)dealloc
         return SDL_OutOfMemory();
     }
 
-#if !__has_feature(objc_arc)
-    [stagingtex autorelease];
-#endif
-
     METAL_UploadTextureData(stagingtex, stagingrect, 0, pixels, pitch);
 
     if (data.mtlcmdencoder != nil) {
@@ -917,11 +869,6 @@ - (void)dealloc
     texturedata.lockedbuffer = lockedbuffer;
     *pixels = [lockedbuffer contents];
 
-    /* METAL_TextureData.lockedbuffer retains. */
-#if !__has_feature(objc_arc)
-    [lockedbuffer release];
-#endif
-
     return 0;
 }}
 
@@ -1209,13 +1156,8 @@ - (void)dealloc
 
 typedef struct
 {
-    #if __has_feature(objc_arc)
     __unsafe_unretained id<MTLRenderPipelineState> pipeline;
     __unsafe_unretained id<MTLBuffer> vertex_buffer;
-    #else
-    id<MTLRenderPipelineState> pipeline;
-    id<MTLBuffer> vertex_buffer;
-    #endif
     size_t constants_offset;
     SDL_Texture *texture;
     SDL_bool cliprect_dirty;
@@ -1365,9 +1307,6 @@ - (void)dealloc
          * TODO: this buffer is also used for constants. Is performance still
          * good for those, or should we have a managed buffer for them? */
         mtlbufvertex = [data.mtldevice newBufferWithLength:vertsize options:MTLResourceStorageModeShared];
-        #if !__has_feature(objc_arc)
-        [mtlbufvertex autorelease];
-        #endif
         mtlbufvertex.label = @"SDL vertex data";
         SDL_memcpy([mtlbufvertex contents], vertices, vertsize);
 
@@ -1711,9 +1650,6 @@ static SDL_MetalView GetWindowView(SDL_Window *window)
     }
 
     if (view == NULL) {
-#if !__has_feature(objc_arc)
-        [mtldevice release];
-#endif
         SDL_free(renderer);
         if (changed_window) {
             SDL_RecreateWindow(window, window_flags);
@@ -1725,9 +1661,6 @@ static SDL_MetalView GetWindowView(SDL_Window *window)
     data = [[METAL_RenderData alloc] init];
 
     if (data == nil) {
-#if !__has_feature(objc_arc)
-        [mtldevice release];
-#endif
         /* Release the metal view instead of destroying it,
            in case we want to use it later (recreating the renderer)
          */
@@ -1746,7 +1679,7 @@ in case we want to use it later (recreating the renderer)
     data.mtlview = view;
 
 #ifdef __MACOSX__
-    layer = (CAMetalLayer *)[(NSView *)view layer];
+    layer = (CAMetalLayer *)[(__bridge NSView *)view layer];
 #else
     layer = (CAMetalLayer *)[(__bridge UIView *)view layer];
 #endif
@@ -1771,9 +1704,6 @@ in case we want to use it later (recreating the renderer)
     id<MTLLibrary> mtllibrary = [data.mtldevice newLibraryWithData:mtllibdata error:&err];
     data.mtllibrary = mtllibrary;
     SDL_assert(err == nil);
-#if !__has_feature(objc_arc)
-    dispatch_release(mtllibdata);
-#endif
     data.mtllibrary.label = @"SDL Metal renderer shader library";
 
     /* Do some shader pipeline state loading up-front rather than on demand. */
@@ -1831,9 +1761,6 @@ in case we want to use it later (recreating the renderer)
     };
 
     id<MTLBuffer> mtlbufconstantstaging = [data.mtldevice newBufferWithLength:CONSTANTS_LENGTH options:MTLResourceStorageModeShared];
-    #if !__has_feature(objc_arc)
-    [mtlbufconstantstaging autorelease];
-    #endif
 
     char *constantdata = [mtlbufconstantstaging contents];
     SDL_memcpy(constantdata + CONSTANTS_OFFSET_IDENTITY, identitytransform, sizeof(identitytransform));
@@ -1845,9 +1772,6 @@ in case we want to use it later (recreating the renderer)
     int quadcount = UINT16_MAX / 4;
     size_t indicessize = sizeof(UInt16) * quadcount * 6;
     id<MTLBuffer> mtlbufquadindicesstaging = [data.mtldevice newBufferWithLength:indicessize options:MTLResourceStorageModeShared];
-#if !__has_feature(objc_arc)
-    [mtlbufquadindicesstaging autorelease];
-#endif
 
     /* Quads in the following vertex order (matches the FillRects vertices):
      * 1---3
@@ -1965,18 +1889,6 @@ in case we want to use it later (recreating the renderer)
     renderer->info.max_texture_width = maxtexsize;
     renderer->info.max_texture_height = maxtexsize;
 
-#if !__has_feature(objc_arc)
-    [mtlcmdqueue release];
-    [mtllibrary release];
-    [samplerdesc release];
-    [mtlsamplernearest release];
-    [mtlsamplerlinear release];
-    [mtlbufconstants release];
-    [mtlbufquadindices release];
-    [data release];
-    [mtldevice release];
-#endif
-
     return renderer;
 }}
 
diff --git a/src/video/cocoa/SDL_cocoaclipboard.h b/src/video/cocoa/SDL_cocoaclipboard.h
index dd5e25224ae..c8c4d68080a 100644
--- a/src/video/cocoa/SDL_cocoaclipboard.h
+++ b/src/video/cocoa/SDL_cocoaclipboard.h
@@ -24,12 +24,12 @@
 #define SDL_cocoaclipboard_h_
 
 /* Forward declaration */
-struct SDL_VideoData;
+@class SDL_VideoData;
 
 extern int Cocoa_SetClipboardText(_THIS, const char *text);
 extern char *Cocoa_GetClipboardText(_THIS);
 extern SDL_bool Cocoa_HasClipboardText(_THIS);
-extern void Cocoa_CheckClipboardUpdate(struct SDL_VideoData * data);
+extern void Cocoa_CheckClipboardUpdate(SDL_VideoData * data);
 
 #endif /* SDL_cocoaclipboard_h_ */
 
diff --git a/src/video/cocoa/SDL_cocoaclipboard.m b/src/video/cocoa/SDL_cocoaclipboard.m
index 1995c7289a3..e3878ce8f4c 100644
--- a/src/video/cocoa/SDL_cocoaclipboard.m
+++ b/src/video/cocoa/SDL_cocoaclipboard.m
@@ -29,7 +29,7 @@
 Cocoa_SetClipboardText(_THIS, const char *text)
 { @autoreleasepool
 {
-    SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
+    SDL_VideoData *data = (__bridge SDL_VideoData *) _this->driverdata;
     NSPasteboard *pasteboard;
     NSString *format = NSPasteboardTypeString;
     NSString *nsstr = [NSString stringWithUTF8String:text];
@@ -38,7 +38,7 @@
     }
 
     pasteboard = [NSPasteboard generalPasteboard];
-    data->clipboard_count = [pasteboard declareTypes:[NSArray arrayWithObject:format] owner:nil];
+    data.clipboard_count = [pasteboard declareTypes:[NSArray arrayWithObject:format] owner:nil];
     [pasteboard setString:nsstr forType:format];
 
     return 0;
@@ -86,7 +86,7 @@
 }
 
 void
-Cocoa_CheckClipboardUpdate(struct SDL_VideoData * data)
+Cocoa_CheckClipboardUpdate(SDL_VideoData * data)
 { @autoreleasepool
 {
     NSPasteboard *pasteboard;
@@ -94,11 +94,11 @@
 
     pasteboard = [NSPasteboard generalPasteboard];
     count = [pasteboard changeCount];
-    if (count != data->clipboard_count) {
-        if (data->clipboard_count) {
+    if (count != data.clipboard_count) {
+        if (data.clipboard_count) {
             SDL_SendClipboardUpdate();
         }
-        data->clipboard_count = count;
+        data.clipboard_count = count;
     }
 }}
 
diff --git a/src/video/cocoa/SDL_cocoaevents.m b/src/video/cocoa/SDL_cocoaevents.m
index d077bad6ed6..774a93b6391 100644
--- a/src/video/cocoa/SDL_cocoaevents.m
+++ b/src/video/cocoa/SDL_cocoaevents.m
@@ -45,7 +45,7 @@
     SDL_VideoDevice *device = SDL_GetVideoDevice();
     if (device && device->windows) {
         for (sdlwindow = device->windows; sdlwindow; sdlwindow = sdlwindow->next) {
-            NSWindow *nswindow = ((SDL_WindowData *) sdlwindow->driverdata)->nswindow;
+            NSWindow *nswindow = ((__bridge SDL_WindowData *) sdlwindow->driverdata).nswindow;
             if (win == nswindow)
                 return sdlwindow;
         }
@@ -121,7 +121,6 @@ + (void)registerUserDefaults
                                  [NSNumber numberWithBool:YES], @"ApplePersistenceIgnoreState",
                                  nil];
     [[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults];
-    [appDefaults release];
 }
 
 @end // SDLApplication
@@ -182,8 +181,6 @@ - (void)dealloc
             removeEventHandlerForEventClass:kInternetEventClass
                                  andEventID:kAEGetURL];
     }
-
-    [super dealloc];
 }
 
 - (void)windowWillClose:(NSNotification *)notification;
@@ -374,9 +371,6 @@ - (void)handleURLEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEv
     /* Create the main menu bar */
     [NSApp setMainMenu:mainMenu];
 
-    [mainMenu release];  /* we're done with it, let NSApp own it. */
-    mainMenu = nil;
-
     /* Create the application menu */
     appName = GetApplicationName();
     appleMenu = [[NSMenu alloc] initWithTitle:@""];
@@ -396,7 +390,6 @@ - (void)handleURLEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEv
     [menuItem setSubmenu:serviceMenu];
 
     [NSApp setServicesMenu:serviceMenu];
-    [serviceMenu release];
 
     [appleMenu addItem:[NSMenuItem separatorItem]];
 
@@ -417,12 +410,9 @@ - (void)handleURLEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEv
     menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
     [menuItem setSubmenu:appleMenu];
     [[NSApp mainMenu] addItem:menuItem];
-    [menuItem release];
 
     /* Tell the application object that this is now the application menu */
     [NSApp setAppleMenu:appleMenu];
-    [appleMenu release];
-
 
     /* Create the window menu */
     windowMenu = [[NSMenu alloc] initWithTitle:@"Window"];
@@ -442,18 +432,15 @@ - (void)handleURLEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEv
         menuItem = [[NSMenuItem alloc] initWithTitle:@"Toggle Full Screen" action:@selector(toggleFullScreen:) keyEquivalent:@"f"];
         [menuItem setKeyEquivalentModifierMask:NSEventModifierFlagControl | NSEventModifierFlagCommand];
         [windowMenu addItem:menuItem];
-        [menuItem release];
     }
 
     /* Put menu into the menubar */
     menuItem = [[NSMenuItem alloc] initWithTitle:@"Window" action:nil keyEquivalent:@""];
     [menuItem setSubmenu:windowMenu];
     [[NSApp mainMenu] addItem:menuItem];
-    [menuItem release];
 
     /* Tell the application object that this is now the window menu */
     [NSApp setWindowsMenu:windowMenu];
-    [windowMenu release];
 }
 
 void
@@ -576,7 +563,7 @@ - (void)handleURLEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEv
 void Cocoa_SendWakeupEvent(_THIS, SDL_Window *window)
 { @autoreleasepool
 {
-    NSWindow *nswindow = ((SDL_WindowData *) window->driverdata)->nswindow;
+    NSWindow *nswindow = ((__bridge SDL_WindowData *) window->driverdata).nswindow;
 
     NSEvent* event = [NSEvent otherEventWithType: NSEventTypeApplicationDefined
                                     location: NSMakePoint(0,0)
@@ -595,15 +582,15 @@ void Cocoa_SendWakeupEvent(_THIS, SDL_Window *window)
 Cocoa_SuspendScreenSaver(_THIS)
 { @autoreleasepool
 {
-    SDL_VideoData *data = (SDL_VideoData *)_this->driverdata;
+    SDL_VideoData *data = (__bridge SDL_VideoData *)_this->driverdata;
 
-    if (!data->screensaver_use_iopm) {
+    if (!data.screensaver_use_iopm) {
         return;
     }
 
-    if (data->screensaver_assertion) {
-        IOPMAssertionRelease(data->screensaver_assertion);
-        data->screensaver_assertion = 0;
+    if (data.screensaver_assertion) {
+        IOPMAssertionRelease(data.screensaver_assertion);
+        data.screensaver_assertion = kIOPMNullAssertionID;
     }
 
     if (_this->suspend_screensaver) {
@@ -612,11 +599,13 @@ void Cocoa_SendWakeupEvent(_THIS, SDL_Window *window)
          * seen by OS X power users. there's an additional optional human-readable
          * (localized) reason parameter which we don't set.
          */
+        IOPMAssertionID assertion = kIOPMNullAssertionID;
         NSString *name = [GetApplicationName() stringByAppendingString:@" using SDL_DisableScreenSaver"];
         IOPMAssertionCreateWithDescription(kIOPMAssertPreventUserIdleDisplaySleep,
-                                           (CFStringRef) name,
+                                           (__bridge CFStringRef) name,
                                            NULL, NULL, NULL, 0, NULL,
-                                           &data->screensaver_assertion);
+                                           &assertion);
+        data.screensaver_assertion = assertion;
     }
 }}
 
diff --git a/src/video/cocoa/SDL_cocoakeyboard.m b/src/video/cocoa/SDL_cocoakeyboard.m
index b229ac3f662..2c9606b0f01 100644
--- a/src/video/cocoa/SDL_cocoakeyboard.m
+++ b/src/video/cocoa/SDL_cocoakeyboard.m
@@ -104,8 +104,7 @@ - (void)setMarkedText:(id)aString selectedRange:(NSRange)selectedRange replaceme
     }
 
     if (_markedText != aString) {
-        [_markedText release];
-        _markedText = [aString retain];
+        _markedText = aString;
     }
 
     _selectedRange = selectedRange;
@@ -120,7 +119,6 @@ - (void)setMarkedText:(id)aString selectedRange:(NSRange)selectedRange replaceme
 
 - (void)unmarkText
 {
-    [_markedText release];
     _markedText = nil;
 
     SDL_SendEditingText("", 0, 0);
@@ -381,14 +379,14 @@ - (NSArray *)validAttributesForMarkedText
 static void
 HandleModifiers(_THIS, unsigned short scancode, unsigned int modifierFlags)
 {
-    SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
+    SDL_VideoData *data = (__bridge SDL_VideoData *) _this->driverdata;
 
-    if (modifierFlags == data->modifierFlags) {
+    if (modifierFlags == data.modifierFlags) {
         return;
     }
 
-    DoSidedModifiers(scancode, data->modifierFlags, modifierFlags);
-    data->modifierFlags = modifierFlags;
+    DoSidedModifiers(scancode, data.modifierFlags, modifierFlags);
+    data.modifierFlags = modifierFlags;
 }
 
 static void
@@ -402,10 +400,10 @@ - (NSArray *)validAttributesForMarkedText
 
     /* See if the keymap needs to be updated */
     key_layout = TISCopyCurrentKeyboardLayoutInputSource();
-    if (key_layout == data->key_layout) {
+    if (key_layout == data.key_layout) {
         return;
     }
-    data->key_layout = key_layout;
+    data.key_layout = key_layout;
 
     SDL_GetDefaultKeymap(keymap);
 
@@ -461,7 +459,7 @@ - (NSArray *)validAttributesForMarkedText
 void
 Cocoa_InitKeyboard(_THIS)
 {
-    SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
+    SDL_VideoData *data = (__bridge SDL_VideoData *) _this->driverdata;
 
     UpdateKeymap(data, SDL_FALSE);
 
@@ -473,19 +471,19 @@ - (NSArray *)validAttributesForMarkedText
     SDL_SetScancodeName(SDL_SCANCODE_RALT, "Right Option");
     SDL_SetScancodeName(SDL_SCANCODE_RGUI, "Right Command");
 
-    data->modifierFlags = (unsigned int)[NSEvent modifierFlags];
-    SDL_ToggleModState(KMOD_CAPS, (data->modifierFlags & NSEventModifierFlagCapsLock) != 0);
+    data.modifierFlags = (unsigned int)[NSEvent modifierFlags];
+    SDL_ToggleModState(KMOD_CAPS, (data.modifierFlags & NSEventModifierFlagCapsLock) != 0);
 }
 
 void
 Cocoa_StartTextInput(_THIS)
 { @autoreleasepool
 {
-    SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
+    SDL_VideoData *data = (__bridge SDL_VideoData *) _this->driverdata;
     SDL_Window *window = SDL_GetKeyboardFocus();
     NSWindow *nswindow = nil;
     if (window) {
-        nswindow = ((SDL_WindowData*)window->driverdata)->nswindow;
+        nswindow = ((__bridge SDL_WindowData*)window->driverdata).nswindow;
     }
 
     NSView *parentView = [nswindow contentView];
@@ -495,16 +493,16 @@ - (NSArray *)validAttributesForMarkedText
      * than one copy. When we switched to another window and requesting for
      * text input, simply remove the field editor from its superview then add
      * it to the front most window's content view */
-    if (!data->fieldEdit) {
-        data->fieldEdit =
+    if (!data.fieldEdit) {
+        data.fieldEdit =
             [[SDLTranslatorResponder alloc] initWithFrame: NSMakeRect(0.0, 0.0, 0.0, 0.0)];
     }
 
-    if (![[data->fieldEdit superview] isEqual:parentView]) {
+    if (![[data.fieldEdit superview] isEqual:parentView]) {
         /* DEBUG_IME(@"add fieldEdit to window contentView"); */
-        [data->fieldEdit removeFromSuperview];
-        [parentView addSubview: data->fieldEdit];
-        [nswindow makeFirstResponder: data->fieldEdit];
+        [data.fieldEdit removeFromSuperview];
+        [parentView addSubview: data.fieldEdit];
+        [nswindow makeFirstResponder: data.fieldEdit];
     }
 }}
 
@@ -512,32 +510,31 @@ - (NSArray *)validAttributesForMarkedText
 Cocoa_StopTextInput(_THIS)
 { @autoreleasepool
 {
-    SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
+    SDL_VideoData *data = (__bridge SDL_VideoData *) _this->driverdata;
 
-    if (data && data->fieldEdit) {
-        [data->fieldEdit removeFromSuperview];
-        [data->fieldEdit release];
-        data->fieldEdit = nil;
+    if (data && data.fieldEdit) {
+        [data.fieldEdit removeFromSuperview];
+        data.fieldEdit = nil;
     }
 }}
 
 void
 Cocoa_SetTextInputRect(_THIS, SDL_Rect *rect)
 {
-    SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
+    SDL_VideoData *data = (__bridge SDL_VideoData *) _this->driverdata;
 
     if (!rect) {
         SDL_InvalidParamError("rect");
         return;
     }
 
-    [data->fieldEdit setInputRect:rect];
+    [data.fieldEdit setInputRect:rect];
 }
 
 void
 Cocoa_HandleKeyEvent(_THIS, NSEvent *event)
 {
-    SDL_VideoData *data = _this ? ((SDL_VideoData *) _this->driverdata) : NULL;
+    SDL_VideoData *data = _this ? ((__bridge SDL_VideoData *) _this->driverdata) : nil;
     if (!data) {
         return;  /* can happen when returning from fullscreen Space on shutdown */
     }
@@ -575,7 +572,7 @@ - (NSArray *)validAttributesForMarkedText
 #endif
         if (SDL_EventState(SDL_TEXTINPUT, SDL_QUERY)) {
             /* FIXME CW 2007-08-16: only send those events to the field editor for which we actually want text events, not e.g. esc or function keys. Arrow keys in particular seem to produce crashes sometimes. */
-            [data->fieldEdit interpretKeyEvents:[NSArray arrayWithObject:event]];
+            [data.fieldEdit interpretKeyEvents:[NSArray arrayWithObject:event]];
 #if 0
             text = [[event characters] UTF8String];
             if(text && *text) {
diff --git a/src/video/cocoa/SDL_cocoamessagebox.m b/src/video/cocoa/SDL_cocoamessagebox.m
index e3fc20b7e9f..494f88d7154 100644
--- a/src/video/cocoa/SDL_cocoamessagebox.m
+++ b/src/video/cocoa/SDL_cocoamessagebox.m
@@ -45,9 +45,9 @@ - (id) initWithParentWindow:(SDL_Window *)window
 
         /* Retain the NSWindow because we'll show the alert later on the main thread */
         if (window) {
-            nswindow = [((SDL_WindowData *) window->driverdata)->nswindow retain];
+            nswindow = ((__bridge SDL_WindowData *) window->driverdata).nswindow;
         } else {
-            nswindow = NULL;
+            nswindow = nil;
         }
     }
 
@@ -60,7 +60,7 @@ - (void)showAlert:(NSAlert*)alert
 #ifdef MAC_OS_X_VERSION_10_9
         if ([alert respondsToSelector:@selector(beginSheetModalForWindow:completionHandler:)]) {
             [alert beginSheetModalForWindow:nswindow completionHandler:^(NSModalResponse returnCode) {
-                clicked = returnCode;
+                self->clicked = returnCode;
             }];
         } else
 #endif
@@ -75,7 +75,7 @@ - (void)showAlert:(NSAlert*)alert
             SDL_Delay(100);
         }
 
-        [nswindow release];
+        nswindow = nil;
     } else {
         clicked = [alert runModal];
     }
@@ -94,7 +94,7 @@ - (void) alertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextIn
 {
     Cocoa_RegisterApp();
 
-    NSAlert* alert = [[[NSAlert alloc] init] autorelease];
+    NSAlert* alert = [[NSAlert alloc] init];
 
     if (messageboxdata->flags & SDL_MESSAGEBOX_ERROR) {
         [alert setAlertStyle:NSAlertStyleCritical];
@@ -129,7 +129,7 @@ - (void) alertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextIn
         }
     }
 
-    SDLMessageBoxPresenter* presenter = [[[SDLMessageBoxPresenter alloc] initWithParentWindow:messageboxdata->window] autorelease];
+    SDLMessageBoxPresenter* presenter = [[SDLMessageBoxPresenter alloc] initWithParentWindow:messageboxdata->window];
 
     [presenter showAlert:alert];
 
diff --git a/src/video/cocoa/SDL_cocoametalview.m b/src/video/cocoa/SDL_cocoametalview.m
index 6e33c4899ae..3732ebb9ea8 100644
--- a/src/video/cocoa/SDL_cocoametalview.m
+++ b/src/video/cocoa/SDL_cocoametalview.m
@@ -89,7 +89,7 @@ - (instancetype)initWithFrame:(NSRect)frame
         /* Allow resize. */
         self.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
 
-        SDL_AddEventWatch(SDL_MetalViewEventWatch, self);
+        SDL_AddEventWatch(SDL_MetalViewEventWatch, (__bridge void *)(self));
 
         [self updateDrawableSize];
     }
@@ -99,8 +99,7 @@ - (instancetype)initWithFrame:(NSRect)frame
 
 - (void)dealloc
 {
-    SDL_DelEventWatch(SDL_MetalViewEventWatch, self);
-    [super dealloc];
+    SDL_DelEventWatch(SDL_MetalViewEventWatch, (__bridge void *)(self));
 }
 
 - (NSInteger)tag
@@ -135,7 +134,7 @@ - (NSView *)hitTest:(NSPoint)point {
 Cocoa_Metal_CreateView(_THIS, SDL_Window * window)
 { @autoreleasepool {
     SDL_WindowData* data = (__bridge SDL_WindowData *)window->driverdata;
-    NSView *view = data->nswindow.contentView;
+    NSView *view = data.nswindow.contentView;
     BOOL highDPI = (window->flags & SDL_WINDOW_ALLOW_HIGHDPI) != 0;
     Uint32 windowID = SDL_GetWindowID(window);
     SDL_cocoametalview *newview;
@@ -151,7 +150,6 @@ - (NSView *)hitTest:(NSPoint)point {
     [view addSubview:newview];
 
     metalview = (SDL_MetalView)CFBridgingRetain(newview);
-    [newview release];
 
     return metalview;
 }}
@@ -174,7 +172,7 @@ - (NSView *)hitTest:(NSPoint)point {
 Cocoa_Metal_GetDrawableSize(_THIS, SDL_Window * window, int * w, int * h)
 { @autoreleasepool {
     SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata;
-    NSView *contentView = data->sdlContentView;
+    NSView *contentView = data.sdlContentView;
     SDL_cocoametalview* metalview = [contentView viewWithTag:SDL_METALVIEW_TAG];
     if (metalview) {
         CAMetalLayer *layer = (CAMetalLayer*)metalview.layer;
diff --git a/src/video/cocoa/SDL_cocoamodes.m b/src/video/cocoa/SDL_cocoamodes.m
index 7d19030b219..140425856d4 100644
--- a/src/video/cocoa/SDL_cocoamodes.m
+++ b/src/video/cocoa/SDL_cocoamodes.m
@@ -306,7 +306,7 @@
     /* This API is deprecated in 10.9 with no good replacement (as of 10.15). */
     io_service_t servicePort = CGDisplayIOServicePort(displayID);
     CFDictionaryRef deviceInfo = IODisplayCreateInfoDictionary(servicePort, kIODisplayOnlyPreferredName);
-    NSDictionary *localizedNames = [(NSDictionary *)deviceInfo objectForKey:[NSString stringWithUTF8String:kDisplayProductName]];
+    NSDictionary *localizedNames = [(__bridge NSDictionary *)deviceInfo objectForKey:[NSString stringWithUTF8String:kDisplayProductName]];
     const char* displayName = NULL;
 
     if ([localizedNames count] > 0) {
diff --git a/src/video/cocoa/SDL_cocoamouse.m b/src/video/cocoa/SDL_cocoamouse.m
index 8b5a1848397..70d2db37896 100644
--- a/src/video/cocoa/SDL_cocoamouse.m
+++ b/src/video/cocoa/SDL_cocoamouse.m
@@ -53,7 +53,7 @@ + (NSCursor *)invisibleCursor
         NSData *cursorData = [NSData dataWithBytesNoCopy:&cursorBytes[0]
                                                   length:sizeof(cursorBytes)
                                             freeWhenDone:NO];
-        NSImage *cursorImage = [[[NSImage alloc] initWithData:cursorData] autorelease];
+        NSImage *cursorImage = [[NSImage alloc] initWithData:cursorData];
         invisibleCursor = [[NSCursor alloc] initWithImage:cursorImage
                                                   hotSpot:NSZeroPoint];
     }
@@ -75,8 +75,7 @@ + (NSCursor *)invisibleCursor
     if (nscursor) {
         cursor = SDL_calloc(1, sizeof(*cursor));
         if

(Patch may be truncated, please check the link at the top of this post.)