1use crossterm::event::{Event, EventStream, KeyEvent, KeyEventKind};
2use futures_util::StreamExt as _;
3use tokio::sync::mpsc;
4
5#[derive(Debug, Clone, PartialEq, Eq)]
7pub enum InputEvent {
8 Key(KeyEvent),
10 Paste(String),
12 Resize {
14 width: u16,
16 height: u16,
18 },
19 Focus(bool),
21}
22
23#[derive(Debug)]
25pub struct InputPump {
26 handle: tokio::task::JoinHandle<()>,
27}
28
29impl InputPump {
30 pub async fn shutdown(self) {
32 self.handle.abort();
33 let _ = self.handle.await;
34 }
35}
36
37#[must_use]
43pub fn spawn_input_pump(capacity: usize) -> (InputPump, mpsc::Receiver<InputEvent>) {
44 assert!(capacity > 0, "input capacity must be non-zero");
45 let (sender, receiver) = mpsc::channel(capacity);
46 let handle = tokio::spawn(async move {
47 let mut events = EventStream::new();
48 while let Some(event) = events.next().await {
49 let Ok(event) = event else {
50 break;
51 };
52 let projected = match event {
53 Event::Key(key)
54 if matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat) =>
55 {
56 Some(InputEvent::Key(key))
57 }
58 Event::Paste(text) => Some(InputEvent::Paste(text)),
59 Event::Resize(width, height) => Some(InputEvent::Resize { width, height }),
60 Event::FocusGained => Some(InputEvent::Focus(true)),
61 Event::FocusLost => Some(InputEvent::Focus(false)),
62 Event::Key(_) | Event::Mouse(_) => None,
63 };
64 if let Some(event) = projected
65 && sender.send(event).await.is_err()
66 {
67 break;
68 }
69 }
70 });
71 (InputPump { handle }, receiver)
72}