diff --git a/src/futurecore.rs b/src/futurecore.rs index c204cde6a..e7e6a1102 100644 --- a/src/futurecore.rs +++ b/src/futurecore.rs @@ -15,11 +15,15 @@ use futures::executor::{self, Notify, Spawn}; use futures::future::{ExecuteError, Executor}; use futures::{Async, Future}; use std::cell::{Cell, RefCell}; +use std::collections::VecDeque; use std::sync::mpsc; use std::sync::{Arc, Mutex}; +const EXTERNAL_SPAWN: usize = !0usize; + pub trait CoreSender: Send { fn send(&self, idx: usize) -> Result<(), Error>; + fn clone_sender(&self) -> Box; } pub trait CoreReceiver { @@ -35,6 +39,34 @@ pub struct Core { // future is ready to get polled. tasks: RefCell>, next_vacant: Cell, + external_spawn: Arc, +} + +#[derive(Default)] +struct SpawningFromAnotherThread { + futures: Mutex + Send>>>, +} + +pub struct Spawner { + tx: Box, + external_spawn: Arc, +} + +impl Spawner { + pub fn spawn(&self, future: Box + Send>) { + let mut futures = self.external_spawn.futures.lock().unwrap(); + futures.push_back(future); + self.tx.send(EXTERNAL_SPAWN).unwrap(); + } +} + +impl Clone for Spawner { + fn clone(&self) -> Spawner { + Spawner { + tx: self.tx.clone_sender(), + external_spawn: Arc::clone(&self.external_spawn), + } + } } enum Slot { @@ -43,7 +75,8 @@ enum Slot { } impl Core { - pub fn new(tx: Box, tx2: Box, rx: Box) -> Self { + pub fn new(tx: Box, rx: Box) -> Self { + let tx2 = tx.clone_sender(); Self { notify: Arc::new(Notifier { tx: Mutex::new(tx2), @@ -52,6 +85,14 @@ impl Core { rx, next_vacant: Cell::new(0), tasks: RefCell::new(Vec::new()), + external_spawn: Arc::new(SpawningFromAnotherThread::default()), + } + } + + pub fn get_spawner(&self) -> Spawner { + Spawner { + tx: self.tx.clone_sender(), + external_spawn: Arc::clone(&self.external_spawn), } } @@ -62,6 +103,10 @@ impl Core { where F: Future + 'static, { + self.spawn_impl(Box::new(f), true); + } + + fn spawn_impl(&self, f: Box + 'static>, do_tx: bool) -> usize { let idx = self.next_vacant.get(); let mut tasks = self.tasks.borrow_mut(); match tasks.get_mut(idx) { @@ -76,7 +121,19 @@ impl Core { } } tasks[idx] = Slot::RunningFuture(Some(executor::spawn(Box::new(f)))); - self.tx.send(idx).unwrap(); + if do_tx { + self.tx.send(idx).unwrap(); + } + idx + } + + fn spawn_external(&self) -> Option { + let mut futures = self.external_spawn.futures.lock().unwrap(); + if let Some(future) = futures.pop_front() { + Some(self.spawn_impl(future, false)) + } else { + None + } } /// "Turns" this event loop one tick. @@ -84,6 +141,10 @@ impl Core { /// Returns `false` if there were no futures in a known-ready state. pub fn turn(&self) -> bool { let task_id = match self.rx.try_recv() { + Ok(task_id) if task_id == EXTERNAL_SPAWN => match self.spawn_external() { + Some(task_id) => task_id, + _ => return false, + }, Ok(task_id) => task_id, Err(mpsc::TryRecvError::Empty) => return false, Err(mpsc::TryRecvError::Disconnected) => panic!("futurecore rx Disconnected"), @@ -132,10 +193,6 @@ where } struct Notifier { - // TODO: it's pretty unfortunate to use a `Mutex` here where the `Sender` - // itself is basically `Sync` as-is. Ideally this'd use something like - // an off-the-shelf mpsc queue as well as `thread::park` and - // `Thread::unpark`. tx: Mutex>, } diff --git a/src/guiloop/glutinloop.rs b/src/guiloop/glutinloop.rs index 0ee5693d7..40285f8dd 100644 --- a/src/guiloop/glutinloop.rs +++ b/src/guiloop/glutinloop.rs @@ -42,6 +42,9 @@ impl futurecore::CoreSender for GuiSender { fn send(&self, idx: usize) -> Result<(), Error> { GuiSender::send(self, idx) } + fn clone_sender(&self) -> Box { + Box::new(GuiSender::clone(self)) + } } impl PtyEventSender for GuiSender { @@ -154,8 +157,8 @@ impl GuiEventLoop { let event_loop = glium::glutin::EventsLoop::new(); let (fut_tx, fut_rx) = channel(event_loop.create_proxy()); - let fut_tx2 = fut_tx.clone(); - let core = futurecore::Core::new(Box::new(fut_tx), Box::new(fut_tx2), Box::new(fut_rx)); + let core = futurecore::Core::new(Box::new(fut_tx), Box::new(fut_rx)); + mux.set_spawner(core.get_spawner()); let (poll_tx, poll_rx) = channel(event_loop.create_proxy()); diff --git a/src/guiloop/x11.rs b/src/guiloop/x11.rs index cbc2cf79c..6ecd6f9cd 100644 --- a/src/guiloop/x11.rs +++ b/src/guiloop/x11.rs @@ -25,6 +25,9 @@ impl futurecore::CoreSender for GuiSender { fn send(&self, idx: usize) -> Result<(), Error> { GuiSender::send(self, idx).map_err(|e| format_err!("send: {}", e)) } + fn clone_sender(&self) -> Box { + Box::new(GuiSender::clone(self)) + } } impl PtyEventSender for GuiSender { @@ -103,8 +106,8 @@ impl GuiEventLoop { Ready::readable(), PollOpt::level(), )?; - let fut_tx2 = fut_tx.clone(); - let core = futurecore::Core::new(Box::new(fut_tx), Box::new(fut_tx2), Box::new(fut_rx)); + let core = futurecore::Core::new(Box::new(fut_tx), Box::new(fut_rx)); + mux.set_spawner(core.get_spawner()); let (pty_tx, pty_rx) = channel(); poll.register(&pty_rx, Token(TOK_PTY), Ready::readable(), PollOpt::level())?; diff --git a/src/mux/mod.rs b/src/mux/mod.rs index a996580a1..dd938f221 100644 --- a/src/mux/mod.rs +++ b/src/mux/mod.rs @@ -1,3 +1,4 @@ +use crate::futurecore::Spawner; use crate::guicommon::tabs::{Tab, TabId}; use failure::Error; use std::cell::RefCell; @@ -13,6 +14,7 @@ pub mod renderable; #[derive(Default)] pub struct Mux { tabs: RefCell>>, + spawner: RefCell>, } #[derive(Clone)] @@ -25,7 +27,12 @@ pub trait PtyEventSender: Send { fn send(&self, event: PtyEvent) -> Result<(), Error>; } -fn read_from_tab_pty(sender: Box, tab_id: TabId, mut reader: Box) { +fn read_from_tab_pty( + spawner: Spawner, + sender: Box, + tab_id: TabId, + mut reader: Box, +) { const BUFSIZE: usize = 32 * 1024; let mut buf = [0; BUFSIZE]; loop { @@ -36,6 +43,10 @@ fn read_from_tab_pty(sender: Box, tab_id: TabId, mut reader: Box return; } Ok(size) => { + spawner.spawn(Box::new(futures::future::lazy(|| { + eprintln!("I was spawned from a pty thread"); + futures::future::ok(()) + }))); if sender .send(PtyEvent::Data { tab_id, @@ -88,6 +99,10 @@ impl<'a> TerminalHost for Host<'a> { } impl Mux { + pub fn set_spawner(&self, spawner: Spawner) { + *self.spawner.borrow_mut() = Some(spawner); + } + pub fn get_tab(&self, tab_id: TabId) -> Option> { self.tabs.borrow().get(&tab_id).map(Rc::clone) } @@ -97,7 +112,8 @@ impl Mux { let reader = tab.reader()?; let tab_id = tab.tab_id(); - thread::spawn(move || read_from_tab_pty(sender, tab_id, reader)); + let spawner = self.spawner.borrow().as_ref().unwrap().clone(); + thread::spawn(move || read_from_tab_pty(spawner, sender, tab_id, reader)); Ok(()) }