1
1
mirror of https://github.com/wez/wezterm.git synced 2024-12-27 15:37:29 +03:00
wezterm/window/src/spawn.rs

275 lines
7.8 KiB
Rust
Raw Normal View History

2019-08-18 18:49:20 +03:00
#[cfg(windows)]
use crate::os::windows::event::EventHandle;
2019-08-18 19:27:41 +03:00
#[cfg(target_os = "macos")]
use core_foundation::runloop::*;
2019-08-18 18:49:20 +03:00
use promise::{BasicExecutor, SpawnFunc};
use std::collections::VecDeque;
use std::sync::{Arc, Mutex};
2020-01-04 19:52:50 +03:00
use std::time::Instant;
2019-08-18 19:30:58 +03:00
#[cfg(all(unix, not(target_os = "macos")))]
use {
filedescriptor::{FileDescriptor, Pipe},
mio::unix::EventedFd,
mio::{Evented, Poll, PollOpt, Ready, Token},
std::os::unix::io::AsRawFd,
};
2019-08-18 18:49:20 +03:00
lazy_static::lazy_static! {
pub(crate) static ref SPAWN_QUEUE: Arc<SpawnQueue> = Arc::new(SpawnQueue::new().expect("failed to create SpawnQueue"));
}
2020-01-04 19:52:50 +03:00
struct InstrumentedSpawnFunc {
func: SpawnFunc,
at: Instant,
}
2019-08-18 18:49:20 +03:00
pub(crate) struct SpawnQueue {
2020-01-04 19:52:50 +03:00
spawned_funcs: Mutex<VecDeque<InstrumentedSpawnFunc>>,
spawned_funcs_low_pri: Mutex<VecDeque<InstrumentedSpawnFunc>>,
2019-08-18 18:57:07 +03:00
#[cfg(windows)]
2019-08-18 18:49:20 +03:00
pub event_handle: EventHandle,
2019-08-18 18:57:07 +03:00
#[cfg(all(unix, not(target_os = "macos")))]
2019-08-18 18:49:20 +03:00
write: Mutex<FileDescriptor>,
2019-08-18 18:57:07 +03:00
#[cfg(all(unix, not(target_os = "macos")))]
2019-08-18 18:49:20 +03:00
read: Mutex<FileDescriptor>,
}
impl SpawnQueue {
2019-12-15 08:43:05 +03:00
pub fn new() -> anyhow::Result<Self> {
2019-08-18 18:49:20 +03:00
Self::new_impl()
}
pub fn spawn(&self, f: SpawnFunc) {
self.spawn_impl(f, true)
2019-08-18 18:49:20 +03:00
}
pub fn run(&self) -> bool {
2019-08-18 18:49:20 +03:00
self.run_impl()
}
2019-08-18 18:57:07 +03:00
// 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> {
if let Some(func) = self.spawned_funcs.lock().unwrap().pop_front() {
2020-01-04 19:52:50 +03:00
metrics::value!("executor.spawn_delay", func.at.elapsed());
Some(func.func)
} else if let Some(func) = self.spawned_funcs_low_pri.lock().unwrap().pop_front() {
metrics::value!("executor.spawn_delay.low_pri", func.at.elapsed());
Some(func.func)
} else {
2020-01-04 19:52:50 +03:00
None
}
}
pub fn spawn_task<F: std::future::Future<Output = ()> + 'static>(
&self,
future: F,
) -> async_task::JoinHandle<(), ()> {
let (task, handle) = async_task::spawn_local(
future,
move |task| SPAWN_QUEUE.spawn(Box::new(move || task.run())),
(),
);
task.schedule();
handle
}
fn queue_func(&self, f: SpawnFunc, high_pri: bool) {
2020-01-04 19:52:50 +03:00
let f = InstrumentedSpawnFunc {
func: f,
at: Instant::now(),
};
if high_pri {
self.spawned_funcs.lock().unwrap()
} else {
self.spawned_funcs_low_pri.lock().unwrap()
}
.push_back(f);
2019-08-18 18:57:07 +03:00
}
fn has_any_queued(&self) -> bool {
2019-11-24 18:20:41 +03:00
!self.spawned_funcs.lock().unwrap().is_empty()
|| !self.spawned_funcs_low_pri.lock().unwrap().is_empty()
}
2019-08-18 18:49:20 +03:00
}
#[cfg(windows)]
impl SpawnQueue {
2019-12-15 08:43:05 +03:00
fn new_impl() -> anyhow::Result<Self> {
2019-08-18 18:49:20 +03:00
let spawned_funcs = Mutex::new(VecDeque::new());
let spawned_funcs_low_pri = Mutex::new(VecDeque::new());
2019-08-18 18:49:20 +03:00
let event_handle = EventHandle::new_manual_reset().expect("EventHandle creation failed");
Ok(Self {
spawned_funcs,
spawned_funcs_low_pri,
2019-08-18 18:49:20 +03:00
event_handle,
})
}
fn spawn_impl(&self, f: SpawnFunc, high_pri: bool) {
self.queue_func(f, high_pri);
2019-08-18 18:49:20 +03:00
self.event_handle.set_event();
}
fn run_impl(&self) -> bool {
2019-08-18 18:49:20 +03:00
self.event_handle.reset_event();
2019-08-18 18:57:07 +03:00
while let Some(func) = self.pop_func() {
func();
2019-08-18 18:49:20 +03:00
}
self.has_any_queued()
2019-08-18 18:49:20 +03:00
}
}
#[cfg(all(unix, not(target_os = "macos")))]
impl SpawnQueue {
2019-12-15 08:43:05 +03:00
fn new_impl() -> anyhow::Result<Self> {
// On linux we have a slightly sloppy wakeup mechanism;
// we have a non-blocking pipe that we can use to get
// woken up after some number of enqueues. We don't
// guarantee a 1:1 enqueue to wakeup with this mechanism
// but in practical terms it does guarantee a wakeup
// if the main thread is asleep and we enqueue some
// number of items.
// We can't affort to use a blocking pipe for the wakeup
// because the write needs to hold a mutex and that
// can block reads as well as other writers.
let mut pipe = Pipe::new()?;
pipe.write.set_non_blocking(true)?;
pipe.read.set_non_blocking(true)?;
2019-08-18 18:49:20 +03:00
Ok(Self {
spawned_funcs: Mutex::new(VecDeque::new()),
spawned_funcs_low_pri: Mutex::new(VecDeque::new()),
2019-08-18 18:49:20 +03:00
write: Mutex::new(pipe.write),
read: Mutex::new(pipe.read),
})
}
fn spawn_impl(&self, f: SpawnFunc, high_pri: bool) {
2019-08-18 18:49:20 +03:00
use std::io::Write;
self.queue_func(f, high_pri);
2019-08-18 18:49:20 +03:00
self.write.lock().unwrap().write(b"x").ok();
}
fn run_impl(&self) -> bool {
// On linux we only ever process one at at time, so that
// we can return to the main loop and process messages
// from the X server
if let Some(func) = self.pop_func() {
2019-08-18 18:49:20 +03:00
func();
}
// try to drain the pipe.
// We do this regardless of whether we popped an item
// so that we avoid being in a perpetually signalled state.
// It is ok if we completely drain the pipe because the
// main loop uses the return value to set the sleep
// interval and will unconditionally call us on each
// iteration.
let mut byte = [0u8; 64];
use std::io::Read;
self.read.lock().unwrap().read(&mut byte).ok();
self.has_any_queued()
2019-08-18 18:49:20 +03:00
}
}
#[cfg(all(unix, not(target_os = "macos")))]
impl Evented for SpawnQueue {
fn register(
&self,
poll: &Poll,
token: Token,
interest: Ready,
opts: PollOpt,
) -> std::io::Result<()> {
EventedFd(&self.read.lock().unwrap().as_raw_fd()).register(poll, token, interest, opts)
}
fn reregister(
&self,
poll: &Poll,
token: Token,
interest: Ready,
opts: PollOpt,
) -> std::io::Result<()> {
EventedFd(&self.read.lock().unwrap().as_raw_fd()).reregister(poll, token, interest, opts)
}
fn deregister(&self, poll: &Poll) -> std::io::Result<()> {
EventedFd(&self.read.lock().unwrap().as_raw_fd()).deregister(poll)
}
}
2019-08-18 18:57:07 +03:00
#[cfg(target_os = "macos")]
impl SpawnQueue {
2019-12-15 08:43:05 +03:00
fn new_impl() -> anyhow::Result<Self> {
2019-08-18 18:57:07 +03:00
let spawned_funcs = Mutex::new(VecDeque::new());
let spawned_funcs_low_pri = Mutex::new(VecDeque::new());
2019-08-18 18:57:07 +03:00
let observer = unsafe {
CFRunLoopObserverCreate(
std::ptr::null(),
kCFRunLoopAllActivities,
1,
0,
SpawnQueue::trigger,
std::ptr::null_mut(),
)
};
unsafe {
CFRunLoopAddObserver(CFRunLoopGetMain(), observer, kCFRunLoopCommonModes);
}
Ok(Self {
spawned_funcs,
spawned_funcs_low_pri,
})
2019-08-18 18:57:07 +03:00
}
2019-11-12 07:23:38 +03:00
extern "C" fn trigger(
_observer: *mut __CFRunLoopObserver,
_: CFRunLoopActivity,
_: *mut std::ffi::c_void,
) {
if SPAWN_QUEUE.run() {
Self::queue_wakeup();
}
2019-08-18 18:57:07 +03:00
}
fn queue_wakeup() {
2019-08-18 18:57:07 +03:00
unsafe {
CFRunLoopWakeUp(CFRunLoopGetMain());
}
}
fn spawn_impl(&self, f: SpawnFunc, high_pri: bool) {
self.queue_func(f, high_pri);
Self::queue_wakeup();
}
fn run_impl(&self) -> bool {
if let Some(func) = self.pop_func() {
2019-08-18 18:57:07 +03:00
func();
}
self.has_any_queued()
2019-08-18 18:57:07 +03:00
}
}
pub struct SpawnQueueExecutor;
impl BasicExecutor for SpawnQueueExecutor {
fn execute(&self, f: SpawnFunc) {
SPAWN_QUEUE.spawn(f)
}
}
pub struct LowPriSpawnQueueExecutor;
impl BasicExecutor for LowPriSpawnQueueExecutor {
fn execute(&self, f: SpawnFunc) {
SPAWN_QUEUE.spawn_impl(f, false)
}
}