crates/tui-termion/src/term.rs 10.1 KiB raw
1
//! Termion terminal session helpers.
2
//!
3
//! This module owns the raw-screen setup and event iterator plumbing needed to
4
//! run a `rustik-tui` app on a real terminal. Keeping it outside the core crate avoids
5
//! tying widget rendering to termion.
6
7
use std::fs::{File, OpenOptions};
8
use std::io;
9
use std::io::{BufWriter, Write};
10
use std::sync::mpsc;
11
use std::thread;
12
13
use termion::input::{MouseTerminal, TermReadEventsAndRaw};
14
use termion::raw::{IntoRawMode, RawTerminal};
15
use termion::screen::{AlternateScreen, IntoAlternateScreen};
16
17
use rustik_signals as signals;
18
use rustik_tui_core as tui_core;
19
20
use tui_core::app::{App, Control};
21
use tui_core::event::Event;
22
use tui_core::terminal::Terminal;
23
use tui_core::{Constraint, Size, Widget};
24
25
use crate::{TermionBackend, TermionEvent};
26
27
/// Signals observed by terminal applications.
28
const SIGNALS: &[signals::Signal] = &[signals::Signal::WindowChanged];
29
/// Controlling terminal path used when standard input is application data.
30
const TTY_DEVICE: &str = "/dev/tty";
31
/// Sequence enabling the Kitty keyboard protocol's disambiguate-escape-codes
32
/// flag, so modified keys and the Escape key are reported as `CSI u` sequences.
33
const KEYBOARD_PUSH: &str = "\x1B[>1u";
34
/// Sequence restoring the terminal's previous keyboard protocol flags.
35
const KEYBOARD_POP: &str = "\x1B[<u";
36
/// Process stdout descriptor path used as a terminal fallback.
37
const STDOUT_DEVICE: &str = "/proc/self/fd/1";
38
/// Process stderr descriptor path used as a terminal fallback.
39
const STDERR_DEVICE: &str = "/proc/self/fd/2";
40
41
/// Raw alternate terminal-device screen with the enhanced keyboard protocol.
42
pub type TerminalScreen = KeyboardProtocol<AlternateScreen<MouseTerminal<RawTerminal<File>>>>;
43
44
/// Creates a raw alternate-screen backend on the terminal device.
45
pub fn screen() -> io::Result<TermionBackend<TerminalScreen>> {
46
    let terminal = terminal_screen()?;
47
    let raw = terminal.into_raw_mode()?;
48
    let mouse = MouseTerminal::from(raw);
49
    let screen = mouse.into_alternate_screen()?;
50
    let keyboard = KeyboardProtocol::new(screen)?;
51
    Ok(TermionBackend::new(keyboard))
52
}
53
54
/// Buffered output wrapper that enables the enhanced keyboard protocol for its lifetime.
55
///
56
/// The protocol lets the terminal report modified keys unambiguously; terminals that do not
57
/// implement it ignore the enabling sequence, so this degrades to the legacy keyboard encoding. The
58
/// restoring sequence is written when the wrapper is dropped, before the underlying
59
/// raw/alternate-screen guards tear down.
60
#[derive(Debug)]
61
pub struct KeyboardProtocol<W: Write> {
62
    /// Terminal writer that collects output until the frame is flushed.
63
    inner: BufWriter<W>,
64
}
65
66
impl<W: Write> KeyboardProtocol<W> {
67
    /// Enables the protocol on `inner` and returns the guarding wrapper.
68
    fn new(inner: W) -> io::Result<Self> {
69
        let mut inner = BufWriter::new(inner);
70
        inner.write_all(KEYBOARD_PUSH.as_bytes())?;
71
        inner.flush()?;
72
        Ok(Self { inner })
73
    }
74
}
75
76
impl<W: Write> Drop for KeyboardProtocol<W> {
77
    fn drop(&mut self) {
78
        let _ = self.inner.write_all(KEYBOARD_POP.as_bytes());
79
        let _ = self.inner.flush();
80
    }
81
}
82
83
impl<W: Write> Write for KeyboardProtocol<W> {
84
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
85
        self.inner.write(buf)
86
    }
87
88
    fn flush(&mut self) -> io::Result<()> {
89
        self.inner.flush()
90
    }
91
}
92
93
/// Returns typed events from the terminal.
94
pub fn events() -> impl Iterator<Item = io::Result<Event<()>>> {
95
    event_receiver().into_iter()
96
}
97
98
/// Returns typed input events from the terminal device.
99
///
100
/// This stream does not install signal handlers or synthesize resize events.
101
/// Use [`events`] for a full application event stream.
102
fn input_events() -> io::Result<impl Iterator<Item = io::Result<Event<()>>>> {
103
    let terminal = File::open(TTY_DEVICE)
104
        .or_else(|_| File::open(STDOUT_DEVICE))
105
        .or_else(|_| File::open(STDERR_DEVICE))?;
106
107
    Ok(terminal
108
        .events_and_raw()
109
        .map(|event| event.map(TermionEvent::from).map(Event::from)))
110
}
111
112
/// Opens the terminal device used for interactive screen output.
113
fn terminal_screen() -> io::Result<File> {
114
    OpenOptions::new()
115
        .read(true)
116
        .write(true)
117
        .open(TTY_DEVICE)
118
        .or_else(|_| {
119
            OpenOptions::new()
120
                .read(true)
121
                .write(true)
122
                .open(STDOUT_DEVICE)
123
        })
124
        .or_else(|_| {
125
            OpenOptions::new()
126
                .read(true)
127
                .write(true)
128
                .open(STDERR_DEVICE)
129
        })
130
}
131
132
/// Returns the current terminal viewport size.
133
pub fn viewport() -> Option<Size> {
134
    termion::terminal_size()
135
        .map(|(cols, rows)| Size::new(cols as usize, rows as usize))
136
        .ok()
137
}
138
139
/// Writes a widget to stdout under the given constraint.
140
pub fn print_constrained<W: Widget + ?Sized>(
141
    widget: &mut W,
142
    constraints: Constraint,
143
) -> io::Result<()> {
144
    let mut stdout = io::stdout();
145
    for line in widget.display(constraints).lines() {
146
        writeln!(stdout, "{}", line.trim_end())?;
147
    }
148
    Ok(())
149
}
150
151
/// Runs an application on stdout using termion.
152
pub fn run<A>(app: &mut A) -> io::Result<()>
153
where
154
    A: App<Event = ()>,
155
{
156
    let backend = screen()?;
157
    let mut terminal = Terminal::new(backend)?;
158
159
    terminal.clear()?;
160
    terminal.set_cursor_visible(false)?;
161
162
    let result = event_loop(app, &mut terminal);
163
    let cursor = terminal.set_cursor_visible(true);
164
165
    result.and(cursor)
166
}
167
168
/// Runs the application event loop.
169
fn event_loop<A>(
170
    app: &mut A,
171
    terminal: &mut Terminal<TermionBackend<TerminalScreen>>,
172
) -> io::Result<()>
173
where
174
    A: App<Event = ()>,
175
{
176
    terminal.draw(|frame| app.render(frame))?;
177
178
    let events = event_receiver();
179
180
    while let Ok(event) = events.recv() {
181
        let mut redraw = false;
182
        if update(app, event?, &mut redraw) == Control::Quit {
183
            break;
184
        }
185
        while let Ok(event) = events.try_recv() {
186
            if update(app, event?, &mut redraw) == Control::Quit {
187
                return Ok(());
188
            }
189
        }
190
        if redraw {
191
            terminal.draw(|frame| app.render(frame))?;
192
        }
193
    }
194
    Ok(())
195
}
196
197
/// Spawns a blocking terminal reader and returns its event channel.
198
fn event_receiver() -> mpsc::Receiver<io::Result<Event<()>>> {
199
    let (tx, rx) = mpsc::channel();
200
201
    // Spawns a blocking terminal event reader.
202
    thread::spawn({
203
        let tx = tx.clone();
204
        move || match input_events() {
205
            Ok(events) => {
206
                for event in events {
207
                    if tx.send(event).is_err() {
208
                        break;
209
                    }
210
                }
211
            }
212
            Err(error) => {
213
                let _ = tx.send(Err(error));
214
            }
215
        }
216
    });
217
    // Spawns a signal notification reader.
218
    thread::spawn(move || match signals::Signals::install(SIGNALS) {
219
        Ok(signals) => {
220
            while let Ok(signal) = signals.recv() {
221
                match signal {
222
                    signals::Signal::WindowChanged => {
223
                        if tx
224
                            .send(Ok(Event::Resize(viewport().unwrap_or(Size::MAX))))
225
                            .is_err()
226
                        {
227
                            break;
228
                        }
229
                    }
230
                    signals::Signal::Interrupt
231
                    | signals::Signal::Terminate
232
                    | signals::Signal::Hangup => {}
233
                }
234
            }
235
        }
236
        Err(error) => {
237
            let _ = tx.send(Err(error));
238
        }
239
    });
240
241
    rx
242
}
243
244
/// Applies one event and records whether the caller should redraw.
245
fn update<A>(app: &mut A, event: Event<()>, redraw: &mut bool) -> Control
246
where
247
    A: App<Event = ()>,
248
{
249
    let resized = matches!(event, Event::Resize(_));
250
    match app.update(event) {
251
        Control::Continue | Control::Wait => {
252
            *redraw |= resized;
253
            Control::Continue
254
        }
255
        Control::Redraw => {
256
            *redraw = true;
257
            Control::Redraw
258
        }
259
        Control::Quit => Control::Quit,
260
    }
261
}
262
263
#[cfg(test)]
264
#[allow(clippy::unwrap_used)]
265
mod tests {
266
    use super::*;
267
    use rustik_tui_core as tui_core;
268
    use tui_core::Label;
269
270
    /// Records writes to the terminal device.
271
    #[derive(Default)]
272
    struct RecordingWriter {
273
        /// Bytes passed to each device write.
274
        writes: Vec<Vec<u8>>,
275
    }
276
277
    impl Write for RecordingWriter {
278
        fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
279
            self.writes.push(bytes.to_vec());
280
            Ok(bytes.len())
281
        }
282
283
        fn flush(&mut self) -> io::Result<()> {
284
            Ok(())
285
        }
286
    }
287
288
    #[test]
289
    fn terminal_output_flushes_frames_and_protocol_sequences() {
290
        let mut writer = RecordingWriter::default();
291
        {
292
            let mut terminal = KeyboardProtocol::new(&mut writer).unwrap();
293
            assert_eq!(terminal.inner.get_ref().writes, [KEYBOARD_PUSH.as_bytes()]);
294
295
            for byte in b"\x1b[31mhello\x1b[0m" {
296
                terminal.write_all(&[*byte]).unwrap();
297
            }
298
            terminal.flush().unwrap();
299
            assert_eq!(
300
                terminal.inner.get_ref().writes,
301
                [KEYBOARD_PUSH.as_bytes(), b"\x1b[31mhello\x1b[0m"]
302
            );
303
304
            terminal.write_all(b"\x1b[?25h").unwrap();
305
        }
306
        assert_eq!(
307
            writer.writes,
308
            [
309
                KEYBOARD_PUSH.as_bytes(),
310
                b"\x1b[31mhello\x1b[0m",
311
                b"\x1b[?25h\x1b[<u",
312
            ]
313
        );
314
    }
315
316
    #[test]
317
    fn update_redraws_after_resize_even_when_app_continues() {
318
        struct ResizeAware;
319
320
        impl App for ResizeAware {
321
            type Event = ();
322
323
            fn update(&mut self, _: Event<Self::Event>) -> Control {
324
                Control::Continue
325
            }
326
327
            fn render(&mut self, frame: &mut tui_core::Frame<'_>) {
328
                frame.render_widget(Label::new("x"), frame.area);
329
            }
330
        }
331
        let mut app = ResizeAware;
332
        let mut redraw = false;
333
334
        let control = update(&mut app, Event::Resize(Size::new(80, 24)), &mut redraw);
335
336
        assert_eq!(control, Control::Continue);
337
        assert!(redraw);
338
    }
339
}