winit/src/platform_impl/apple/notification_center.rs
Mads Marquart 92e9bfe0fc
Allow the user to register the application delegate on macOS and iOS (#3758)
This allows the user to override the application delegate themselves,
which opens several doors for customization that were previously closed.

To do this, we use notifications instead of top-level application delegate
methods.

One effect of not providing an application delegate on iOS is that we no
longer act as-if the application successfully open all URLs there.

This is a breaking change, although unlikely to matter in practice, since the
return value of `application:didFinishLaunchingWithOptions:` is seldom used by
the system (and is likely the preferred behaviour anyhow).
2024-08-11 23:14:18 +02:00

27 lines
886 B
Rust

use std::ptr::NonNull;
use block2::RcBlock;
use objc2::rc::Retained;
use objc2_foundation::{NSNotification, NSNotificationCenter, NSNotificationName, NSObject};
/// Observe the given notification.
///
/// This is used in Winit as an alternative to declaring an application delegate, as we want to
/// give the user full control over those.
pub fn create_observer(
center: &NSNotificationCenter,
name: &NSNotificationName,
handler: impl Fn(&NSNotification) + 'static,
) -> Retained<NSObject> {
let block = RcBlock::new(move |notification: NonNull<NSNotification>| {
handler(unsafe { notification.as_ref() });
});
unsafe {
center.addObserverForName_object_queue_usingBlock(
Some(name),
None, // No sender filter
None, // No queue, run on posting thread (i.e. main thread)
&block,
)
}
}