Skip to main content

tea_cli/tui/
input.rs

1use crossterm::event::{Event, EventStream, KeyEvent, KeyEventKind};
2use futures_util::StreamExt as _;
3use tokio::sync::mpsc;
4
5/// Bounded terminal input projected into the interactive application loop.
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub enum InputEvent {
8    /// Key press or repeat; release events are discarded by the input pump.
9    Key(KeyEvent),
10    /// One bracketed paste payload.
11    Paste(String),
12    /// New terminal dimensions.
13    Resize {
14        /// Display-cell columns.
15        width: u16,
16        /// Terminal rows.
17        height: u16,
18    },
19    /// Terminal focus changed.
20    Focus(bool),
21}
22
23/// Owned cancellable crossterm input task.
24#[derive(Debug)]
25pub struct InputPump {
26    handle: tokio::task::JoinHandle<()>,
27}
28
29impl InputPump {
30    /// Cancels and awaits the owned input reader.
31    pub async fn shutdown(self) {
32        self.handle.abort();
33        let _ = self.handle.await;
34    }
35}
36
37/// Starts one bounded crossterm input reader.
38///
39/// # Panics
40///
41/// Panics when `capacity` is zero.
42#[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}