SDL: cocoa: Make sure GL context destruction happens on the main thread. (5cb87)

From 5cb87ff99f01d930f618dabda75c39c1bc57e537 Mon Sep 17 00:00:00 2001
From: "Ryan C. Gordon" <[EMAIL REDACTED]>
Date: Thu, 24 Oct 2024 14:53:16 -0400
Subject: [PATCH] cocoa: Make sure GL context destruction happens on the main
 thread.

Fixes #10900.

(cherry picked from commit 344546b4ea79a070e8b6bcccab542551ab5bdf55)
---
 src/video/cocoa/SDL_cocoaopengl.m | 30 +++++++++++++++++++++++++-----
 1 file changed, 25 insertions(+), 5 deletions(-)

diff --git a/src/video/cocoa/SDL_cocoaopengl.m b/src/video/cocoa/SDL_cocoaopengl.m
index bda93159da66b..d56de5fff6364 100644
--- a/src/video/cocoa/SDL_cocoaopengl.m
+++ b/src/video/cocoa/SDL_cocoaopengl.m
@@ -507,13 +507,33 @@ int Cocoa_GL_SwapWindow(_THIS, SDL_Window * window)
     return 0;
 }}
 
+static void DispatchedDeleteContext(SDL_GLContext context)
+{
+    @autoreleasepool {
+        SDLOpenGLContext *nscontext = (__bridge SDLOpenGLContext *)context;
+        [nscontext cleanup];
+        CFRelease(context);
+    }
+}
+
 void Cocoa_GL_DeleteContext(_THIS, SDL_GLContext context)
-{ @autoreleasepool
 {
-    SDLOpenGLContext *nscontext = (__bridge SDLOpenGLContext *)context;
-    [nscontext cleanup];
-    CFRelease(context);
-}}
+    if ([NSThread isMainThread]) {
+        DispatchedDeleteContext(context);
+    } else {
+        if (SDL_opengl_async_dispatch) {
+            dispatch_async(dispatch_get_main_queue(), ^{
+              DispatchedDeleteContext(context);
+            });
+        } else {
+            dispatch_sync(dispatch_get_main_queue(), ^{
+              DispatchedDeleteContext(context);
+            });
+        }
+    }
+
+    return true;
+}
 
 /* We still support OpenGL as long as Apple offers it, deprecated or not, so disable deprecation warnings about it. */
 #ifdef __clang__