From bdc634276dbff28a571685d9b4ab89a802a80411 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sat, 17 Aug 2019 23:00:23 -0700 Subject: [PATCH] plumbing for polling std::future::futures on macos --- window/examples/async.rs | 121 ++++++++++++++++++++++++++++++ window/src/lib.rs | 1 + window/src/os/macos/connection.rs | 31 ++++++-- window/src/os/macos/window.rs | 21 +----- window/src/tasks.rs | 95 +++++++++++++++++++++++ 5 files changed, 244 insertions(+), 25 deletions(-) create mode 100644 window/examples/async.rs create mode 100644 window/src/tasks.rs diff --git a/window/examples/async.rs b/window/examples/async.rs new file mode 100644 index 000000000..6fc97d6e8 --- /dev/null +++ b/window/examples/async.rs @@ -0,0 +1,121 @@ +#![feature(async_await)] + +use ::window::*; +use failure::Fallible; +use std::any::Any; + +struct MyWindow { + allow_close: bool, + cursor_pos: (u16, u16), +} + +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 { + true + } else { + self.allow_close = true; + false + } + } + + fn destroy(&mut self) { + eprintln!("destroy was called!"); + Connection::get().unwrap().terminate_message_loop(); + } + + fn paint(&mut self, context: &mut dyn PaintContext) { + // Pick a purple background color + context.clear(Color::rgb(0x40, 0x20, 0x60)); + + // This line doesn't need anti-aliasing + context.draw_line(0, 0, 100, 100, Color::rgb(0xff, 0xff, 0xff), Operator::Over); + + // This shallower line should need some + context.draw_line( + 100, + 0, + 200, + 120, + Color::rgb(0xff, 0x80, 0xff), + Operator::Over, + ); + + context.draw_line( + 0, + 0, + self.cursor_pos.0 as isize, + self.cursor_pos.1 as isize, + Color::rgb(0xff, 0xff, 0x80), + Operator::Over, + ); + } + + fn resize(&mut self, dims: Dimensions) { + eprintln!("resize {:?}", dims); + } + + fn key_event(&mut self, key: &KeyEvent, ctx: &dyn WindowOps) -> bool { + eprintln!("{:?}", key); + ctx.set_cursor(Some(MouseCursor::Text)); + false + } + + fn mouse_event(&mut self, event: &MouseEvent, ctx: &dyn WindowOps) { + self.cursor_pos = (event.x, event.y); + ctx.invalidate(); + ctx.set_cursor(Some(MouseCursor::Arrow)); + + if event.kind == MouseEventKind::Press(MousePress::Left) { + eprintln!("{:?}", event); + } + } + + fn as_any(&mut self) -> &mut dyn Any { + self + } +} + +async fn spawn_window() -> Result<(), Box> { + let win = Window::new_window( + "myclass", + "the title", + 800, + 600, + Box::new(MyWindow { + allow_close: false, + cursor_pos: (100, 200), + }), + )?; + + eprintln!("here I am"); + win.show(); + eprintln!("and here"); + win.apply(|myself, _win| { + eprintln!("doing apply"); + if let Some(myself) = myself.downcast_ref::() { + eprintln!( + "got myself; allow_close={}, cursor_pos:{:?}", + myself.allow_close, myself.cursor_pos + ); + } + }); + eprintln!("done with spawn_window"); + Ok(()) +} + +fn main() -> Fallible<()> { + let conn = Connection::init()?; + conn.spawn_task(async { + eprintln!("running this async block"); + spawn_window().await.ok(); + }); + conn.run_message_loop() +} diff --git a/window/src/lib.rs b/window/src/lib.rs index b54a9a6a1..eab4cb108 100644 --- a/window/src/lib.rs +++ b/window/src/lib.rs @@ -3,6 +3,7 @@ pub mod bitmaps; pub mod color; pub mod input; pub mod os; +mod tasks; pub use bitmaps::BitmapImage; pub use color::Color; diff --git a/window/src/os/macos/connection.rs b/window/src/os/macos/connection.rs index 60b0c0ac6..0d7ce857f 100644 --- a/window/src/os/macos/connection.rs +++ b/window/src/os/macos/connection.rs @@ -1,4 +1,5 @@ use super::window::WindowInner; +use crate::tasks::{Task, Tasks}; use cocoa::appkit::{NSApp, NSApplication, NSApplicationActivationPolicyRegular}; use cocoa::base::{id, nil}; use core_foundation::runloop::*; @@ -16,6 +17,7 @@ pub struct Connection { ns_app: id, pub(crate) windows: RefCell>>>, pub(crate) next_window_id: AtomicUsize, + tasks: Tasks, } struct SpawnQueue { @@ -65,13 +67,16 @@ impl SpawnQueue { } } + // This needs to be a separate function from the loop in `run` + // in order for the lock to be released before we call the + // returned function + fn pop_func(&self) -> Option { + self.spawned_funcs.lock().unwrap().pop_front() + } + fn run(&self) { - loop { - if let Some(func) = self.spawned_funcs.lock().unwrap().pop_front() { - func(); - } else { - return; - } + while let Some(func) = self.pop_func() { + func(); } } } @@ -98,6 +103,7 @@ impl Connection { let conn = Rc::new(Self { ns_app, windows: RefCell::new(HashMap::new()), + tasks: Default::default(), next_window_id: AtomicUsize::new(1), }); CONN.with(|m| *m.borrow_mut() = Some(Rc::clone(&conn))); @@ -115,6 +121,7 @@ impl Connection { unsafe { self.ns_app.run(); } + self.windows.borrow_mut().clear(); Ok(()) } @@ -142,6 +149,18 @@ impl Connection { } })); } + + pub fn spawn_task + 'static>(&self, future: F) { + let id = self.tasks.add_task(Task(Box::pin(future))); + Self::wake_task_by_id(id); + } + + pub(crate) fn wake_task_by_id(slot: usize) { + SpawnQueueExecutor {}.execute(Box::new(move || { + let conn = Connection::get().unwrap(); + conn.tasks.poll_by_slot(slot); + })); + } } struct SpawnQueueExecutor; diff --git a/window/src/os/macos/window.rs b/window/src/os/macos/window.rs index 9cb4c1cfe..04285b4f0 100644 --- a/window/src/os/macos/window.rs +++ b/window/src/os/macos/window.rs @@ -26,8 +26,8 @@ use std::rc::Rc; pub(crate) struct WindowInner { window_id: usize, - window: StrongPtr, view: StrongPtr, + window: StrongPtr, } #[derive(Debug, Clone)] @@ -70,6 +70,7 @@ impl Window { ), ); + window.setReleasedWhenClosed_(NO); window.cascadeTopLeftFromPoint_(NSPoint::new(20.0, 20.0)); window.setTitle_(*nsstring(&name)); window.setAcceptsMouseMovedEvents_(YES); @@ -105,7 +106,6 @@ impl WindowOps for Window { Connection::with_window_inner(self.0, |inner| inner.hide()); } fn show(&self) { - eprintln!("schedule show"); Connection::with_window_inner(self.0, |inner| inner.show()); } fn set_cursor(&self, cursor: Option) { @@ -137,7 +137,6 @@ impl WindowOps for Window { impl WindowOpsMut for WindowInner { fn show(&mut self) { - eprintln!("do show"); unsafe { let current_app = NSRunningApplication::currentApplication(nil); current_app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps); @@ -180,12 +179,6 @@ struct Inner { window_id: usize, } -impl Drop for Inner { - fn drop(&mut self) { - eprintln!("dropping Inner"); - } -} - const CLS_NAME: &str = "WezTermWindowView"; struct WindowView { @@ -193,12 +186,6 @@ struct WindowView { buffer: RefCell, } -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]; @@ -315,7 +302,6 @@ impl WindowView { } extern "C" fn dealloc(this: &mut Object, _sel: Sel) { - eprintln!("WindowView::dealloc"); Self::drop_inner(this); unsafe { let superclass = superclass(this); @@ -349,8 +335,6 @@ impl WindowView { } extern "C" fn window_should_close(this: &mut Object, _sel: Sel, _id: id) -> BOOL { - eprintln!("window_should_close"); - unsafe { let () = msg_send![this, setNeedsDisplay: YES]; } @@ -372,7 +356,6 @@ impl WindowView { } 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.borrow_mut().callbacks.destroy(); diff --git a/window/src/tasks.rs b/window/src/tasks.rs new file mode 100644 index 000000000..487ecb874 --- /dev/null +++ b/window/src/tasks.rs @@ -0,0 +1,95 @@ +use crate::Connection; +use std::cell::{Cell, RefCell}; +use std::future::Future; +use std::task::{Context, RawWaker, RawWakerVTable, Waker}; + +pub struct Task(pub std::pin::Pin>>); + +enum Slot { + Vacant { next_vacant: usize }, + Running(Option), +} + +#[derive(Default)] +pub struct Tasks { + tasks: RefCell>, + next_vacant: Cell, +} + +impl Tasks { + pub fn add_task(&self, task: Task) -> usize { + let idx = self.next_vacant.get(); + let mut tasks = self.tasks.borrow_mut(); + match tasks.get_mut(idx) { + Some(&mut Slot::Vacant { next_vacant }) => { + self.next_vacant.set(next_vacant); + tasks[idx] = Slot::Running(Some(task)); + } + Some(&mut Slot::Running(_)) => panic!("vacant points to running task"), + None => { + assert_eq!(idx, tasks.len()); + tasks.push(Slot::Running(Some(task))); + self.next_vacant.set(idx + 1); + } + } + idx + } + + pub fn poll_by_slot(&self, slot: usize) -> bool { + let mut task = match self.tasks.borrow_mut().get_mut(slot) { + Some(&mut Slot::Running(ref mut task)) => task.take().unwrap(), + Some(&mut Slot::Vacant { .. }) | None => return false, + }; + + let waker = TaskWaker::new_waker(slot); + let mut context = Context::from_waker(&waker); + + let done = task.0.as_mut().poll(&mut context).is_ready(); + + let mut tasks = self.tasks.borrow_mut(); + if done { + tasks[slot] = Slot::Vacant { + next_vacant: self.next_vacant.get(), + }; + self.next_vacant.set(slot); + } else { + tasks[slot] = Slot::Running(Some(task)); + } + + true + } +} + +struct TaskWaker(usize); + +static VTBL: RawWakerVTable = RawWakerVTable::new( + TaskWaker::waker_clone, + TaskWaker::waker_wake, + TaskWaker::waker_wake_by_ref, + TaskWaker::waker_drop, +); + +impl TaskWaker { + fn new_waker(slot: usize) -> Waker { + let raw = RawWaker::new(unsafe { std::mem::transmute(slot) }, &VTBL); + unsafe { Waker::from_raw(raw) } + } + + unsafe fn waker_clone(p: *const ()) -> RawWaker { + RawWaker::new(p, &VTBL) + } + + unsafe fn waker_wake(p: *const ()) { + let id: usize = std::mem::transmute(p); + Connection::wake_task_by_id(id); + } + + unsafe fn waker_wake_by_ref(p: *const ()) { + let id: usize = std::mem::transmute(p); + Connection::wake_task_by_id(id); + } + + unsafe fn waker_drop(p: *const ()) { + /* no action required */ + } +}