From f76fa734d22008ec96ff64a6af1cc53e76736144 Mon Sep 17 00:00:00 2001
From: Andreas Reich <andreas@rerun.io>
Date: Thu, 19 Jan 2023 09:42:04 +0100
Subject: [PATCH] [MacOS] Fix deadlock on maximizing window from event callback

---
 CHANGELOG.md                         | 1 +
 src/platform_impl/macos/app_state.rs | 8 +++++++-
 2 files changed, 8 insertions(+), 1 deletion(-)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0c04112af7..761ca3f9e9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -166,6 +166,7 @@ And please only add new entries to the top of this list, right below the `# Unre
 - On Android, upgrade `ndk` and `ndk-glue` dependencies to the recently released `0.7.0`.
 - All platforms can now be relied on to emit a `Resumed` event. Applications are recommended to lazily initialize graphics state and windows on first resume for portability.
 - **Breaking:**: Reverse horizontal scrolling sign in `MouseScrollDelta` to match the direction of vertical scrolling. A positive X value now means moving the content to the right. The meaning of vertical scrolling stays the same: a positive Y value means moving the content down.
+- On MacOS, fix deadlock when calling `set_maximized` from event loop.
 
 # 0.26.1 (2022-01-05)
 
diff --git a/src/platform_impl/macos/app_state.rs b/src/platform_impl/macos/app_state.rs
index f9e1ea636a..834ca7596a 100644
--- a/src/platform_impl/macos/app_state.rs
+++ b/src/platform_impl/macos/app_state.rs
@@ -352,7 +352,13 @@ impl AppState {
     }
 
     pub fn handle_redraw(window_id: WindowId) {
-        HANDLER.handle_nonuser_event(EventWrapper::StaticEvent(Event::RedrawRequested(window_id)));
+        // Redraw request might come out of order from the OS.
+        // -> Don't go back into the callback when our callstack originates from there
+        if !HANDLER.in_callback.swap(true, Ordering::AcqRel) {
+            HANDLER
+                .handle_nonuser_event(EventWrapper::StaticEvent(Event::RedrawRequested(window_id)));
+            HANDLER.set_in_callback(false);
+        }
     }
 
     pub fn queue_event(wrapper: EventWrapper) {