SDL: macOS: Fix reference counts of internal window data.

From e9c7b5191c3ed783489d66ba825f2101810a9b58 Mon Sep 17 00:00:00 2001
From: Alex Szpakowski <[EMAIL REDACTED]>
Date: Mon, 16 May 2022 21:03:41 -0300
Subject: [PATCH] macOS: Fix reference counts of internal window data.

Fixes crashes when destroying or recreating a window (#5664).
---
 src/video/cocoa/SDL_cocoawindow.h | 5 ++++-
 src/video/cocoa/SDL_cocoawindow.m | 6 ++++++
 2 files changed, 10 insertions(+), 1 deletion(-)

diff --git a/src/video/cocoa/SDL_cocoawindow.h b/src/video/cocoa/SDL_cocoawindow.h
index 0fd29ce0f18..61324550a04 100644
--- a/src/video/cocoa/SDL_cocoawindow.h
+++ b/src/video/cocoa/SDL_cocoawindow.h
@@ -40,7 +40,10 @@ typedef enum
 } PendingWindowOperation;
 
 @interface Cocoa_WindowListener : NSResponder <NSWindowDelegate> {
-    SDL_WindowData *_data;
+    /* SDL_WindowData owns this Listener and has a strong reference to it.
+     * To avoid reference cycles, we could have either a weak or an
+     * unretained ref to the WindowData. */
+    __weak SDL_WindowData *_data;
     BOOL observingVisible;
     BOOL wasCtrlLeft;
     BOOL wasVisible;
diff --git a/src/video/cocoa/SDL_cocoawindow.m b/src/video/cocoa/SDL_cocoawindow.m
index 79430251b9c..44e91440c64 100644
--- a/src/video/cocoa/SDL_cocoawindow.m
+++ b/src/video/cocoa/SDL_cocoawindow.m
@@ -1653,6 +1653,12 @@ - (BOOL)acceptsFirstMouse:(NSEvent *)theEvent
         SDL_SetKeyboardFocus(data.window);
     }
 
+    /* SDL_WindowData will be holding a strong reference to the NSWindow, and
+     * it will also call [NSWindow close] in DestroyWindow before releasing the
+     * NSWindow, so the extra release provided by releasedWhenClosed isn't
+     * necessary. */
+    nswindow.releasedWhenClosed = NO;
+
     /* Prevents the window's "window device" from being destroyed when it is
      * hidden. See http://www.mikeash.com/pyblog/nsopenglcontext-and-one-shot.html
      */