From ee203b0b76fd5d484d97d019a3fee199a97e119e Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Fri, 9 Aug 2019 01:25:57 -0700 Subject: [PATCH] improve lifecycle management on macos I'm not totally convinced that the refcounting is right because I've not seen `dealloc` get triggered, but the important thing is that closing the window does cause the rust level objects to be dropped. --- window/examples/basic.rs | 13 +- window/src/os/macos/connection.rs | 15 +-- window/src/os/macos/mod.rs | 6 +- window/src/os/macos/window.rs | 205 ++++++++++++++++++++++++++++-- 4 files changed, 214 insertions(+), 25 deletions(-) diff --git a/window/examples/basic.rs b/window/examples/basic.rs index 8a084412c..76e7fdc62 100644 --- a/window/examples/basic.rs +++ b/window/examples/basic.rs @@ -5,17 +5,27 @@ struct MyWindow { allow_close: bool, } +impl Drop for MyWindow { + fn drop(&mut self) { + eprintln!("MyWindow dropped"); + } +} + impl WindowCallbacks for MyWindow { fn can_close(&mut self) -> bool { eprintln!("can I close?"); if self.allow_close { - Connection::get().unwrap().terminate_message_loop(); true } else { self.allow_close = true; false } } + + fn destroy(&mut self) { + eprintln!("destroy was called!"); + Connection::get().unwrap().terminate_message_loop(); + } } fn main() -> Fallible<()> { @@ -30,6 +40,7 @@ fn main() -> Fallible<()> { )?; win.show(); + drop(win); conn.run_message_loop() } diff --git a/window/src/os/macos/connection.rs b/window/src/os/macos/connection.rs index c93e94676..0e87e69e1 100644 --- a/window/src/os/macos/connection.rs +++ b/window/src/os/macos/connection.rs @@ -1,6 +1,5 @@ use cocoa::appkit::{NSApp, NSApplication, NSApplicationActivationPolicyRegular}; use cocoa::base::{id, nil}; -use cocoa::foundation::NSAutoreleasePool; use failure::Fallible; use objc::*; use std::cell::RefCell; @@ -26,20 +25,18 @@ impl Connection { } pub fn init() -> Fallible> { - let ns_app = unsafe { - let _pool = NSAutoreleasePool::new(nil); + unsafe { let ns_app = NSApp(); ns_app.setActivationPolicy_(NSApplicationActivationPolicyRegular); - ns_app - }; - let conn = Arc::new(Self { ns_app }); - CONN.with(|m| *m.borrow_mut() = Some(Arc::clone(&conn))); - Ok(conn) + let conn = Arc::new(Self { ns_app }); + CONN.with(|m| *m.borrow_mut() = Some(Arc::clone(&conn))); + Ok(conn) + } } pub fn terminate_message_loop(&self) { unsafe { - let () = msg_send![NSApp(), terminate: nil]; + let () = msg_send![NSApp(), stop: nil]; } } diff --git a/window/src/os/macos/mod.rs b/window/src/os/macos/mod.rs index 0a830dc81..80a1fd5af 100644 --- a/window/src/os/macos/mod.rs +++ b/window/src/os/macos/mod.rs @@ -1,5 +1,6 @@ use cocoa::base::nil; use cocoa::foundation::NSString; +use objc::rc::StrongPtr; pub mod connection; pub mod window; @@ -8,7 +9,6 @@ pub use connection::*; pub use window::*; /// Convert a rust string to a cocoa string -fn nsstring(s: &str) -> cocoa::base::id { - // ARC will free this at the appropriate time - unsafe { NSString::alloc(nil).init_str(s) } +fn nsstring(s: &str) -> StrongPtr { + unsafe { StrongPtr::new(NSString::alloc(nil).init_str(s)) } } diff --git a/window/src/os/macos/window.rs b/window/src/os/macos/window.rs index 4949dcad6..0252ca4b6 100644 --- a/window/src/os/macos/window.rs +++ b/window/src/os/macos/window.rs @@ -1,16 +1,28 @@ use super::nsstring; use crate::WindowCallbacks; use cocoa::appkit::{ - NSApplicationActivateIgnoringOtherApps, NSBackingStoreBuffered, NSRunningApplication, NSWindow, - NSWindowStyleMask, + NSApplicationActivateIgnoringOtherApps, NSBackingStoreBuffered, NSRunningApplication, NSView, + NSWindow, NSWindowStyleMask, }; use cocoa::base::*; -use cocoa::foundation::{NSAutoreleasePool, NSPoint, NSRect, NSSize}; +use cocoa::foundation::{NSPoint, NSRect, NSSize}; use failure::Fallible; +use objc::declare::ClassDecl; +use objc::rc::{StrongPtr, WeakPtr}; +use objc::runtime::{Class, Object, Sel}; use objc::*; +use std::ffi::c_void; +use std::sync::{Arc, Mutex}; pub struct Window { - window: id, + window: StrongPtr, + view: StrongPtr, +} + +impl Drop for Window { + fn drop(&mut self) { + eprintln!("drop Window"); + } } impl Window { @@ -31,19 +43,34 @@ impl Window { NSSize::new(width as f64, height as f64), ); - let window = NSWindow::alloc(nil).initWithContentRect_styleMask_backing_defer_( - rect, - style_mask, - NSBackingStoreBuffered, - NO, + let inner = Arc::new(Mutex::new(Inner { + callbacks, + view_id: None, + })); + + let window = StrongPtr::new( + NSWindow::alloc(nil).initWithContentRect_styleMask_backing_defer_( + rect, + style_mask, + NSBackingStoreBuffered, + NO, + ), ); - window.autorelease(); window.cascadeTopLeftFromPoint_(NSPoint::new(20.0, 20.0)); - window.setTitle_(nsstring(&name)); + window.setTitle_(*nsstring(&name)); window.setAcceptsMouseMovedEvents_(YES); - Ok(Self { window }) + let content_view = window.contentView(); + let frame = NSView::frame(content_view); + + let view = WindowView::alloc(&inner)?; + view.initWithFrame_(frame); + content_view.addSubview_(*view); + + let () = msg_send![*window, setDelegate: *view]; + + Ok(Self { window, view }) } } @@ -55,3 +82,157 @@ impl Window { } } } + +struct Inner { + callbacks: Box, + view_id: Option, +} + +impl Drop for Inner { + fn drop(&mut self) { + eprintln!("dropping Inner"); + } +} + +const CLS_NAME: &str = "WezTermWindowView"; + +struct WindowView { + inner: Arc>, +} + +impl Drop for WindowView { + fn drop(&mut self) { + eprintln!("dropping WindowView"); + } +} + +pub fn superclass(this: &Object) -> &'static Class { + unsafe { + let superclass: id = msg_send![this, superclass]; + &*(superclass as *const _) + } +} + +impl WindowView { + fn view_id(&self) -> id { + let inner = self.inner.lock().unwrap(); + inner.view_id.as_ref().map(|w| *w.load()).unwrap_or(nil) + } + + fn window_id(&self) -> id { + unsafe { msg_send![self.view_id(), window] } + } + + extern "C" fn dealloc(this: &mut Object, _sel: Sel) { + eprintln!("WindowView::dealloc"); + Self::drop_inner(this); + unsafe { + let superclass = superclass(this); + let () = msg_send![super(this, superclass), dealloc]; + } + } + + /// `dealloc` is called when our NSView descendant is destroyed. + /// In practice, I've not seen this trigger, which likely means + /// that there is something afoot with reference counting. + /// The cardinality of Window and View objects is low enough + /// that I'm "OK" with this for now. + /// What really matters is that the `Inner` object is dropped + /// in a timely fashion once the window is closed, so we manage + /// that by hooking into `windowWillClose` and routing both + /// `dealloc` and `windowWillClose` to `drop_inner`. + fn drop_inner(this: &mut Object) { + unsafe { + let myself: *mut c_void = *this.get_ivar(CLS_NAME); + this.set_ivar(CLS_NAME, std::ptr::null_mut() as *mut c_void); + + if !myself.is_null() { + let myself = Box::from_raw(myself as *mut Self); + drop(myself); + } + } + } + + extern "C" fn window_should_close(this: &mut Object, _sel: Sel, _id: id) -> BOOL { + eprintln!("window_should_close"); + if let Some(this) = Self::get_this(this) { + if this.inner.lock().unwrap().callbacks.can_close() { + YES + } else { + NO + } + } else { + YES + } + } + + extern "C" fn window_will_close(this: &mut Object, _sel: Sel, _id: id) { + eprintln!("window_will_close"); + if let Some(this) = Self::get_this(this) { + // Advise the window of its impending death + this.inner.lock().unwrap().callbacks.destroy(); + } + + // Release and zero out the inner member + Self::drop_inner(this); + } + + fn get_this(this: &Object) -> Option<&mut Self> { + unsafe { + let myself: *mut c_void = *this.get_ivar(CLS_NAME); + if myself.is_null() { + None + } else { + Some(&mut *(myself as *mut Self)) + } + } + } + + fn alloc(inner: &Arc>) -> Fallible { + let cls = Self::get_class(); + + let view_id: StrongPtr = unsafe { StrongPtr::new(msg_send![cls, new]) }; + + inner.lock().unwrap().view_id.replace(view_id.weak()); + + let view = Box::into_raw(Box::new(Self { + inner: Arc::clone(&inner), + })); + + unsafe { + (**view_id).set_ivar(CLS_NAME, view as *mut c_void); + } + + Ok(view_id) + } + + fn get_class() -> &'static Class { + Class::get(CLS_NAME).unwrap_or_else(Self::define_class) + } + + fn define_class() -> &'static Class { + let mut cls = + ClassDecl::new(CLS_NAME, class!(NSView)).expect("Unable to register WindowView class"); + + cls.add_ivar::<*mut c_void>(CLS_NAME); + + unsafe { + cls.add_method( + sel!(dealloc), + WindowView::dealloc as extern "C" fn(&mut Object, Sel), + ); + + cls.add_method( + sel!(windowWillClose:), + Self::window_will_close as extern "C" fn(&mut Object, Sel, id), + ); + + cls.add_method( + sel!(windowShouldClose:), + Self::window_should_close as extern "C" fn(&mut Object, Sel, id) -> BOOL, + ); + } + + cls.register() + } +}