From 51c61d7cdf5171aa9f79e7408f91ecf6984f4585 Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Tue, 27 Jul 2021 14:57:18 -0700
Subject: [PATCH] Run the entire Cocoa messagebox function on the main thread.
This fixes bug https://github.com/libsdl-org/SDL/issues/4420
---
src/video/cocoa/SDL_cocoamessagebox.m | 27 ++++++++++++++++++---------
test/testmessage.c | 2 +-
2 files changed, 19 insertions(+), 10 deletions(-)
diff --git a/src/video/cocoa/SDL_cocoamessagebox.m b/src/video/cocoa/SDL_cocoamessagebox.m
index f1345e54b6..a1f5e40c4d 100644
--- a/src/video/cocoa/SDL_cocoamessagebox.m
+++ b/src/video/cocoa/SDL_cocoamessagebox.m
@@ -89,10 +89,8 @@ - (void) alertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextIn
@end
-/* Display a Cocoa message box */
-int
-Cocoa_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid)
-{ @autoreleasepool
+static void
+Cocoa_ShowMessageBoxImpl(const SDL_MessageBoxData *messageboxdata, int *buttonid, int *returnValue)
{
Cocoa_RegisterApp();
@@ -133,11 +131,8 @@ - (void) alertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextIn
SDLMessageBoxPresenter* presenter = [[[SDLMessageBoxPresenter alloc] initWithParentWindow:messageboxdata->window] autorelease];
- [presenter performSelectorOnMainThread:@selector(showAlert:)
- withObject:alert
- waitUntilDone:YES];
+ [presenter showAlert:alert];
- int returnValue = 0;
NSInteger clicked = presenter->clicked;
if (clicked >= NSAlertFirstButtonReturn) {
clicked -= NSAlertFirstButtonReturn;
@@ -145,10 +140,24 @@ - (void) alertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextIn
clicked = messageboxdata->numbuttons - 1 - clicked;
}
*buttonid = buttons[clicked].buttonid;
+ *returnValue = 0;
} else {
- returnValue = SDL_SetError("Did not get a valid `clicked button' id: %ld", (long)clicked);
+ *returnValue = SDL_SetError("Did not get a valid `clicked button' id: %ld", (long)clicked);
}
+}
+/* Display a Cocoa message box */
+int
+Cocoa_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid)
+{ @autoreleasepool
+{
+ __block int returnValue = 0;
+
+ if ([NSThread isMainThread]) {
+ Cocoa_ShowMessageBoxImpl(messageboxdata, buttonid, &returnValue);
+ } else {
+ dispatch_sync(dispatch_get_main_queue(), ^{ Cocoa_ShowMessageBoxImpl(messageboxdata, buttonid, &returnValue); });
+ }
return returnValue;
}}
diff --git a/test/testmessage.c b/test/testmessage.c
index a93ad70279..b10ab703b6 100644
--- a/test/testmessage.c
+++ b/test/testmessage.c
@@ -197,7 +197,7 @@ main(int argc, char *argv[])
success = SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR,
"Simple MessageBox",
- "This is a simple error MessageBox with a parent window",
+ "This is a simple error MessageBox with a parent window. Press a key or close the window after dismissing this messagebox.",
window);
if (success == -1) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error Presenting MessageBox: %s\n", SDL_GetError());