Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow freeing NSView based on parent window closing notifications. #137

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/macos/view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down Expand Up @@ -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];
Expand Down
24 changes: 23 additions & 1 deletion src/macos/window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand Down Expand Up @@ -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,
Expand Down