diff --git a/src/macos/view.rs b/src/macos/view.rs index abcef683..b0ba0a07 100644 --- a/src/macos/view.rs +++ b/src/macos/view.rs @@ -137,6 +137,10 @@ unsafe fn create_view_class() -> &'static Class { sel!(viewWillMoveToWindow:), view_will_move_to_window as extern "C" fn(&Object, Sel, id), ); + class.add_method( + sel!(parentWindowClosing:), + parent_window_closing as extern "C" fn(&mut Object, Sel, id), + ); class.add_method( sel!(updateTrackingAreas:), update_tracking_areas as extern "C" fn(&Object, Sel, id), @@ -217,6 +221,16 @@ extern "C" fn release(this: &mut Object, _sel: Sel) { } } +extern "C" fn parent_window_closing(this: &mut Object, _sel: Sel, _: id) { + unsafe { + let state_ptr: *mut c_void = *this.get_ivar(BASEVIEW_STATE_IVAR); + + if !state_ptr.is_null() { + WindowState::stop_and_free(this); + } + } +} + extern "C" fn dealloc(this: &mut Object, _sel: Sel) { unsafe { let class = msg_send![this, class]; diff --git a/src/macos/window.rs b/src/macos/window.rs index 08753774..a8e54b3a 100644 --- a/src/macos/window.rs +++ b/src/macos/window.rs @@ -15,7 +15,7 @@ use core_foundation::runloop::{ }; use keyboard_types::KeyboardEvent; -use objc::{msg_send, runtime::Object, sel, sel_impl}; +use objc::{class, msg_send, runtime::Object, sel, sel_impl}; use raw_window_handle::{AppKitHandle, HasRawWindowHandle, RawWindowHandle}; @@ -130,8 +130,30 @@ impl Window { panic!("Not a macOS window"); }; + let ns_window = if handle.ns_window.is_null() { + unsafe { msg_send![handle.ns_view as *mut Object, window] } + } else { + handle.ns_window + }; + let ns_view = unsafe { create_view(&options) }; + if !ns_window.is_null() { + unsafe { + let notification_center: &Object = + msg_send![class!(NSNotificationCenter), defaultCenter]; + let notification_name = + NSString::alloc(nil).init_str("NSWindowWillCloseNotification").autorelease(); + let _: () = msg_send![ + notification_center, + addObserver: ns_view + selector: sel!(parentWindowClosing:) + name: notification_name + object: ns_window + ]; + } + } + let window = Window { ns_app: None, ns_window: None,