From 477619c0a7aa0d6178fbe2edbe1b8716edf07cd8 Mon Sep 17 00:00:00 2001 From: Mads Marquart Date: Wed, 30 Aug 2023 15:19:30 +0200 Subject: [PATCH] Ensure that winit initializes NSApplication (#3069) --- src/platform_impl/macos/event_loop.rs | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/platform_impl/macos/event_loop.rs b/src/platform_impl/macos/event_loop.rs index 5a25789d..bd1ea070 100644 --- a/src/platform_impl/macos/event_loop.rs +++ b/src/platform_impl/macos/event_loop.rs @@ -19,6 +19,7 @@ use core_foundation::runloop::{ }; use icrate::Foundation::MainThreadMarker; use objc2::rc::{autoreleasepool, Id}; +use objc2::runtime::NSObjectProtocol; use objc2::{msg_send_id, ClassType}; use raw_window_handle::{AppKitDisplayHandle, RawDisplayHandle}; @@ -109,7 +110,10 @@ impl EventLoopWindowTarget { pub struct EventLoop { /// Store a reference to the application for convenience. - app: Id, + /// + /// We intentially don't store `WinitApplication` since we want to have + /// the possiblity of swapping that out at some point. + app: Id, /// The delegate is only weakly referenced by NSApplication, so we keep /// it around here as well. _delegate: Id, @@ -152,15 +156,15 @@ impl EventLoop { attributes: &PlatformSpecificEventLoopAttributes, ) -> Result { let mtm = MainThreadMarker::new() - .expect("On macOS, `EventLoop` must be created on the main thread!"); + .expect("on macOS, `EventLoop` must be created on the main thread!"); - // This must be done before `NSApp()` (equivalent to sending - // `sharedApplication`) is called anywhere else, or we'll end up - // with the wrong `NSApplication` class and the wrong thread could - // be marked as main. - let app: Id = + let app: Id = unsafe { msg_send_id![WinitApplication::class(), sharedApplication] }; + if !app.is_kind_of::() { + panic!("`winit` requires control over the principal class. You must create the event loop before other parts of your application initialize NSApplication"); + } + use NSApplicationActivationPolicy::*; let activation_policy = match attributes.activation_policy { ActivationPolicy::Regular => NSApplicationActivationPolicyRegular,