Expand description
§macOS / AppKit
Winit has the same macOS version requirements as rustc, and is tested
once in a while on as low as macOS 10.14.
§Custom NSApplicationDelegate
Winit usually handles everything related to the lifecycle events of the application. Sometimes, though, you might want to do more niche stuff, such as handle when the user re-activates the application. Such functionality is not exposed directly in Winit, since it would increase the API surface by quite a lot.
Instead, Winit guarantees that it will not register an application delegate, so the solution is
to register your own application delegate, as outlined in the following example (see
objc2-app-kit for more detailed information).
use objc2::rc::Retained;
use objc2::runtime::ProtocolObject;
use objc2::{DefinedClass, MainThreadMarker, MainThreadOnly, define_class, msg_send};
use objc2_app_kit::{NSApplication, NSApplicationDelegate};
use objc2_foundation::{NSArray, NSObject, NSObjectProtocol, NSURL};
use winit::event_loop::EventLoop;
define_class!(
#[unsafe(super(NSObject))]
#[thread_kind = MainThreadOnly]
#[name = "AppDelegate"]
struct AppDelegate;
unsafe impl NSObjectProtocol for AppDelegate {}
unsafe impl NSApplicationDelegate for AppDelegate {
#[unsafe(method(application:openURLs:))]
fn application_openURLs(&self, application: &NSApplication, urls: &NSArray<NSURL>) {
// Note: To specifically get `application:openURLs:` to work, you _might_
// have to bundle your application. This is not done in this example.
println!("open urls: {application:?}, {urls:?}");
}
}
);
impl AppDelegate {
fn new(mtm: MainThreadMarker) -> Retained<Self> {
unsafe { msg_send![super(Self::alloc(mtm).set_ivars(())), init] }
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let event_loop = EventLoop::new()?;
let mtm = MainThreadMarker::new().unwrap();
let delegate = AppDelegate::new(mtm);
// Important: Call `sharedApplication` after `EventLoop::new`,
// doing it before is not yet supported.
let app = NSApplication::sharedApplication(mtm);
app.setDelegate(Some(ProtocolObject::from_ref(&*delegate)));
// event_loop.run_app(&mut my_app);
Ok(())
}Structs§
- Event
Loop - Platform
Specific Event Loop Attributes - Window
Attributes MacOS - Window attributes that are specific to MacOS.
Enums§
- Activation
Policy - Corresponds to
NSApplicationActivationPolicy. - Option
AsAlt - Option as alt behavior.
Traits§
- Active
Event Loop ExtMacOS - Additional methods on
ActiveEventLoopthat are specific to macOS. - Application
Handler ExtMacOS - Additional events on
ApplicationHandlerthat are specific to macOS. - Event
Loop Builder ExtMacOS - Monitor
Handle ExtMacOS - Additional methods on
MonitorHandlethat are specific to MacOS. - Window
ExtMacOS - Additional methods on
Windowthat are specific to MacOS.