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

Implements custom async executor for winit event loop #1180

Merged
merged 1 commit into from
Dec 14, 2024
Merged
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
80 changes: 61 additions & 19 deletions gui/src/rt/mod.rs
Original file line number Diff line number Diff line change
@@ -1,35 +1,38 @@
pub use self::context::*;

use self::event::WindowEvent;
use futures::executor::LocalPool;
use futures::task::LocalSpawnExt;
use self::task::TaskList;
use self::waker::Waker;
use std::future::Future;
use std::sync::Arc;
use thiserror::Error;
use winit::application::ApplicationHandler;
use winit::error::EventLoopError;
use winit::event_loop::{ActiveEventLoop, EventLoop};
use winit::event_loop::{ActiveEventLoop, EventLoop, EventLoopProxy};
use winit::window::WindowId;

mod context;
mod event;
mod task;
mod waker;

pub fn block_on(main: impl Future<Output = ()> + 'static) -> Result<(), RuntimeError> {
// Setup winit event loop.
let mut el = EventLoop::<Event>::with_user_event();
let el = el.build().map_err(RuntimeError::CreateEventLoop)?;
let executor = LocalPool::new();

executor
.spawner()
.spawn_local(async move {
main.await;
RuntimeContext::with(|cx| cx.event_loop().exit());
})
.unwrap();
let main = async move {
main.await;
RuntimeContext::with(|cx| cx.event_loop().exit());
};

// Run event loop.
let mut tasks = TaskList::default();
let main: Box<dyn Future<Output = ()>> = Box::new(main);
let main = tasks.insert(Box::into_pin(main));
let mut rt = Runtime {
executor,
el: el.create_proxy(),
tasks,
main,
on_close: WindowEvent::default(),
};

Expand All @@ -38,18 +41,55 @@ pub fn block_on(main: impl Future<Output = ()> + 'static) -> Result<(), RuntimeE

/// Implementation of [`ApplicationHandler`] to drive [`Future`].
struct Runtime {
executor: LocalPool,
el: EventLoopProxy<Event>,
tasks: TaskList,
main: u64,
on_close: WindowEvent<()>,
}

impl ApplicationHandler<Event> for Runtime {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
impl Runtime {
pub fn dispatch(&mut self, el: &ActiveEventLoop, task: u64) -> bool {
// Get target task.
let mut task = match self.tasks.get(task) {
Some(v) => v,
None => {
// It is possible for the waker to wake the same task multiple times. In this case
// the previous wake may complete the task.
return false;
}
};

// Poll the task.
let waker = Arc::new(Waker::new(self.el.clone(), *task.key()));
let mut cx = RuntimeContext {
el: event_loop,
el,
on_close: &mut self.on_close,
};

cx.run(|| self.executor.run_until_stalled());
cx.run(|| {
let waker = std::task::Waker::from(waker);
let mut cx = std::task::Context::from_waker(&waker);

if task.get_mut().as_mut().poll(&mut cx).is_ready() {
drop(task.remove());
}
});

true
}
}

impl ApplicationHandler<Event> for Runtime {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
assert!(self.dispatch(event_loop, self.main));
}

fn user_event(&mut self, event_loop: &ActiveEventLoop, event: Event) {
match event {
Event::TaskReady(task) => {
self.dispatch(event_loop, task);
}
}
}

fn window_event(
Expand All @@ -69,7 +109,9 @@ impl ApplicationHandler<Event> for Runtime {
}

/// Event to wakeup winit event loop.
enum Event {}
enum Event {
TaskReady(u64),
}

/// Represents an error when [`block_on()`] fails.
#[derive(Debug, Error)]
Expand Down
34 changes: 34 additions & 0 deletions gui/src/rt/task.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
use std::collections::hash_map::OccupiedEntry;
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;

/// List of pending tasks.
#[derive(Default)]
pub struct TaskList {
list: HashMap<u64, Pin<Box<dyn Future<Output = ()>>>>,
next: u64,
}

impl TaskList {
pub fn insert(&mut self, f: Pin<Box<dyn Future<Output = ()>>>) -> u64 {
let id = self.next;

assert!(self.list.insert(id, f).is_none());
self.next = self.next.checked_add(1).unwrap();

id
}

pub fn get(
&mut self,
id: u64,
) -> Option<OccupiedEntry<u64, Pin<Box<dyn Future<Output = ()>>>>> {
use std::collections::hash_map::Entry;

match self.list.entry(id) {
Entry::Occupied(e) => Some(e),
Entry::Vacant(_) => None,
}
}
}
26 changes: 26 additions & 0 deletions gui/src/rt/waker.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
use super::Event;
use std::sync::Arc;
use std::task::Wake;
use winit::event_loop::EventLoopProxy;

/// Implementation of [`Wake`].
pub struct Waker {
el: EventLoopProxy<Event>,
task: u64,
}

impl Waker {
pub fn new(el: EventLoopProxy<Event>, task: u64) -> Self {
Self { el, task }
}
}

impl Wake for Waker {
fn wake(self: Arc<Self>) {
self.wake_by_ref();
}

fn wake_by_ref(self: &Arc<Self>) {
drop(self.el.send_event(Event::TaskReady(self.task)));
}
}