use crossterm::event::{Event, EventStream, KeyEvent, KeyEventKind};
use futures_util::StreamExt as _;
use tokio::sync::mpsc;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InputEvent {
Key(KeyEvent),
Paste(String),
Resize {
width: u16,
height: u16,
},
Focus(bool),
}
#[derive(Debug)]
pub struct InputPump {
handle: tokio::task::JoinHandle<()>,
}
impl InputPump {
pub async fn shutdown(self) {
self.handle.abort();
let _ = self.handle.await;
}
}
#[must_use]
pub fn spawn_input_pump(capacity: usize) -> (InputPump, mpsc::Receiver<InputEvent>) {
assert!(capacity > 0, "input capacity must be non-zero");
let (sender, receiver) = mpsc::channel(capacity);
let handle = tokio::spawn(async move {
let mut events = EventStream::new();
while let Some(event) = events.next().await {
let Ok(event) = event else {
break;
};
let projected = match event {
Event::Key(key)
if matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat) =>
{
Some(InputEvent::Key(key))
}
Event::Paste(text) => Some(InputEvent::Paste(text)),
Event::Resize(width, height) => Some(InputEvent::Resize { width, height }),
Event::FocusGained => Some(InputEvent::Focus(true)),
Event::FocusLost => Some(InputEvent::Focus(false)),
Event::Key(_) | Event::Mouse(_) => None,
};
if let Some(event) = projected
&& sender.send(event).await.is_err()
{
break;
}
}
});
(InputPump { handle }, receiver)
}