plumbing for polling std::future::futures on macos
This commit is contained in:
1 parent
6047229bf2
commit
bdc634276d
5 files changed
+244
-25
No files matched your search
@@ -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<dyn std::error::Error>> {
|
||||
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::<MyWindow>() {
|
||||
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()
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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<HashMap<usize, Rc<RefCell<WindowInner>>>>,
|
||||
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<SpawnFunc> {
|
||||
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<F: std::future::Future<Output = ()> + '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;
|
||||
|
||||
@@ -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<MouseCursor>) {
|
||||
@@ -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<Image>,
|
||||
}
|
||||
|
||||
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();
|
||||
|
||||
@@ -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<Box<dyn Future<Output = ()>>>);
|
||||
|
||||
enum Slot {
|
||||
Vacant { next_vacant: usize },
|
||||
Running(Option<Task>),
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Tasks {
|
||||
tasks: RefCell<Vec<Slot>>,
|
||||
next_vacant: Cell<usize>,
|
||||
}
|
||||
|
||||
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 */
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user