Skip to main content

infinity_agent_cli/
term_io.rs

1//! Terminal I/O abstraction for the TUI.
2//!
3//! The TUI talks to the terminal exclusively through two traits: [`TermOut`]
4//! (an ANSI byte sink plus the few queries/mode switches we need) and
5//! [`EventSource`] (an async stream of crossterm input events). Production
6//! code uses the crossterm/stdout-backed implementations in this module;
7//! tests substitute a `vt100`-backed virtual terminal and scripted events so
8//! the rendered screen state can be snapshot-tested.
9
10use ratatui::crossterm::{
11    cursor,
12    event::{self, Event},
13    terminal as cterm,
14};
15use std::io::{self, Write};
16
17/// Output half of a terminal: an ANSI escape-sequence sink plus the small
18/// set of queries and mode switches the TUI needs.
19///
20/// Writes may be buffered; implementations must apply all previously written
21/// bytes when [`Write::flush`] is called.
22pub trait TermOut: Write {
23    /// Current terminal size as `(cols, rows)`.
24    fn size(&mut self) -> io::Result<(u16, u16)>;
25
26    /// Current cursor position as `(col, row)`, zero-based.
27    ///
28    /// Implementations must flush pending output before answering so the
29    /// reported position reflects every previous write.
30    fn cursor_position(&mut self) -> io::Result<(u16, u16)>;
31
32    fn enable_raw_mode(&mut self) -> io::Result<()>;
33
34    fn disable_raw_mode(&mut self) -> io::Result<()>;
35}
36
37/// Input half of a terminal: an async source of crossterm [`Event`]s.
38pub trait EventSource {
39    /// Wait until an event might be available from
40    /// [`try_read_event`](EventSource::try_read_event), or until an
41    /// implementation-defined animation tick elapses.
42    ///
43    /// Must be cancel-safe: dropping the returned future must not lose
44    /// events.
45    fn wait_for_event(&mut self) -> impl Future<Output = ()>;
46
47    /// Non-blocking read of the next pending event, if any.
48    fn try_read_event(&mut self) -> io::Result<Option<Event>>;
49}
50
51/// The real terminal: writes to stdout and queries via crossterm.
52pub struct CrosstermTerm {
53    stdout: io::Stdout,
54}
55
56impl CrosstermTerm {
57    pub fn new() -> Self {
58        Self {
59            stdout: io::stdout(),
60        }
61    }
62}
63
64impl Default for CrosstermTerm {
65    fn default() -> Self {
66        Self::new()
67    }
68}
69
70impl Write for CrosstermTerm {
71    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
72        self.stdout.write(buf)
73    }
74
75    fn flush(&mut self) -> io::Result<()> {
76        self.stdout.flush()
77    }
78}
79
80impl TermOut for CrosstermTerm {
81    fn size(&mut self) -> io::Result<(u16, u16)> {
82        cterm::size()
83    }
84
85    fn cursor_position(&mut self) -> io::Result<(u16, u16)> {
86        self.stdout.flush()?;
87        cursor::position()
88    }
89
90    fn enable_raw_mode(&mut self) -> io::Result<()> {
91        cterm::enable_raw_mode()
92    }
93
94    fn disable_raw_mode(&mut self) -> io::Result<()> {
95        cterm::disable_raw_mode()
96    }
97}
98
99/// The real event source: polls crossterm events on the blocking thread
100/// pool, waking up every 16ms even without input so animations (e.g. the
101/// thinking spinner) keep redrawing.
102pub struct CrosstermEvents;
103
104impl EventSource for CrosstermEvents {
105    async fn wait_for_event(&mut self) {
106        tokio::task::spawn_blocking(|| {
107            let _ = event::poll(std::time::Duration::from_millis(16));
108        })
109        .await
110        .ok();
111    }
112
113    fn try_read_event(&mut self) -> io::Result<Option<Event>> {
114        if event::poll(std::time::Duration::ZERO)? {
115            Ok(Some(event::read()?))
116        } else {
117            Ok(None)
118        }
119    }
120}