SDL: Disassociate the SDLOpenGLContext from the view before deleting it (61309)

From 61309b4382b17187d4f6098e853d3a78aeb2c736 Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Wed, 8 Mar 2023 01:35:21 -0800
Subject: [PATCH] Disassociate the SDLOpenGLContext from the view before
 deleting it

If we don't do this, the view will be blanked even if another context is current and rendering from that context won't be visible.

Fixes https://github.com/libsdl-org/SDL/issues/4986
---
 src/video/cocoa/SDL_cocoaopengl.h |  2 +-
 src/video/cocoa/SDL_cocoaopengl.m | 19 ++++++++++++-------
 2 files changed, 13 insertions(+), 8 deletions(-)

diff --git a/src/video/cocoa/SDL_cocoaopengl.h b/src/video/cocoa/SDL_cocoaopengl.h
index 43fdf8f13176..20c5eadd5867 100644
--- a/src/video/cocoa/SDL_cocoaopengl.h
+++ b/src/video/cocoa/SDL_cocoaopengl.h
@@ -62,7 +62,7 @@ struct SDL_GLDriverData
 - (void)setWindow:(SDL_Window *)window;
 - (SDL_Window *)window;
 - (void)explicitUpdate;
-- (void)dealloc;
+- (void)cleanup;
 
 @property(retain, nonatomic) NSOpenGLPixelFormat *openglPixelFormat; // macOS 10.10 has -[NSOpenGLContext pixelFormat] but this handles older OS releases.
 
diff --git a/src/video/cocoa/SDL_cocoaopengl.m b/src/video/cocoa/SDL_cocoaopengl.m
index 9ce6e50d9c32..553cfaf62344 100644
--- a/src/video/cocoa/SDL_cocoaopengl.m
+++ b/src/video/cocoa/SDL_cocoaopengl.m
@@ -174,11 +174,10 @@ - (void)setWindow:(SDL_Window *)newWindow
             }
         }
     } else {
-        [self clearDrawable];
-        if (self == [NSOpenGLContext currentContext]) {
-            [self explicitUpdate];
+        if ([NSThread isMainThread]) {
+            [self setView:nil];
         } else {
-            [self scheduleUpdate];
+            dispatch_sync(dispatch_get_main_queue(), ^{ [self setView:nil]; });
         }
     }
 }
@@ -205,17 +204,22 @@ - (void)explicitUpdate
     }
 }
 
-- (void)dealloc
+- (void)cleanup
 {
+    [self setWindow:NULL];
+
     SDL_DelHintCallback(SDL_HINT_MAC_OPENGL_ASYNC_DISPATCH, SDL_OpenGLAsyncDispatchChanged, NULL);
     if (self->displayLink) {
         CVDisplayLinkRelease(self->displayLink);
+        self->displayLink = nil;
     }
     if (self->swapIntervalCond) {
         SDL_DestroyCond(self->swapIntervalCond);
+        self->swapIntervalCond = NULL;
     }
     if (self->swapIntervalMutex) {
         SDL_DestroyMutex(self->swapIntervalMutex);
+        self->swapIntervalMutex = NULL;
     }
 }
 
@@ -518,8 +522,9 @@ int Cocoa_GL_SwapWindow(_THIS, SDL_Window *window)
 int Cocoa_GL_DeleteContext(_THIS, SDL_GLContext context)
 {
     @autoreleasepool {
-        SDLOpenGLContext *nscontext = (SDLOpenGLContext *)CFBridgingRelease(context);
-        [nscontext setWindow:NULL];
+        SDLOpenGLContext *nscontext = (__bridge SDLOpenGLContext *)context;
+        [nscontext cleanup];
+        CFRelease(context);
     }
     return 0;
 }