crates/tui-termion/src/term.rs 8.7 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::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
/// 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
    /// Wrapped terminal writer.
63
    inner: W,
64
}
65
66
impl<W: Write> KeyboardProtocol<W> {
67
    /// Enables the protocol on `inner` and returns the guarding wrapper.
68
    fn new(mut inner: W) -> io::Result<Self> {
69
        inner.write_all(KEYBOARD_PUSH.as_bytes())?;
70
        inner.flush()?;
71
        Ok(Self { inner })
72
    }
73
}
74
75
impl<W: Write> Drop for KeyboardProtocol<W> {
76
    fn drop(&mut self) {
77
        let _ = self.inner.write_all(KEYBOARD_POP.as_bytes());
78
        let _ = self.inner.flush();
79
    }
80
}
81
82
impl<W: Write> Write for KeyboardProtocol<W> {
83
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
84
        self.inner.write(buf)
85
    }
86
87
    fn flush(&mut self) -> io::Result<()> {
88
        self.inner.flush()
89
    }
90
}
91
92
/// Returns typed events from the terminal.
93
pub fn events() -> impl Iterator<Item = io::Result<Event<()>>> {
94
    event_receiver().into_iter()
95
}
96
97
/// Returns typed input events from the terminal device.
98
///
99
/// This stream does not install signal handlers or synthesize resize events.
100
/// Use [`events`] for a full application event stream.
101
fn input_events() -> io::Result<impl Iterator<Item = io::Result<Event<()>>>> {
102
    let terminal = File::open(TTY_DEVICE)
103
        .or_else(|_| File::open(STDOUT_DEVICE))
104
        .or_else(|_| File::open(STDERR_DEVICE))?;
105
106
    Ok(terminal
107
        .events_and_raw()
108
        .map(|event| event.map(TermionEvent::from).map(Event::from)))
109
}
110
111
/// Opens the terminal device used for interactive screen output.
112
fn terminal_screen() -> io::Result<File> {
113
    OpenOptions::new()
114
        .read(true)
115
        .write(true)
116
        .open(TTY_DEVICE)
117
        .or_else(|_| {
118
            OpenOptions::new()
119
                .read(true)
120
                .write(true)
121
                .open(STDOUT_DEVICE)
122
        })
123
        .or_else(|_| {
124
            OpenOptions::new()
125
                .read(true)
126
                .write(true)
127
                .open(STDERR_DEVICE)
128
        })
129
}
130
131
/// Returns the current terminal viewport size.
132
pub fn viewport() -> Option<Size> {
133
    termion::terminal_size()
134
        .map(|(cols, rows)| Size::new(cols as usize, rows as usize))
135
        .ok()
136
}
137
138
/// Writes a widget to stdout under the given constraint.
139
pub fn print_constrained<W: Widget + ?Sized>(
140
    widget: &mut W,
141
    constraints: Constraint,
142
) -> io::Result<()> {
143
    let mut stdout = io::stdout();
144
    for line in widget.display(constraints).lines() {
145
        writeln!(stdout, "{}", line.trim_end())?;
146
    }
147
    Ok(())
148
}
149
150
/// Runs an application on stdout using termion.
151
pub fn run<A>(app: &mut A) -> io::Result<()>
152
where
153
    A: App<Event = ()>,
154
{
155
    let backend = screen()?;
156
    let mut terminal = Terminal::new(backend)?;
157
158
    terminal.clear()?;
159
    terminal.set_cursor_visible(false)?;
160
161
    let result = event_loop(app, &mut terminal);
162
    let cursor = terminal.set_cursor_visible(true);
163
164
    result.and(cursor)
165
}
166
167
/// Runs the application event loop.
168
fn event_loop<A>(
169
    app: &mut A,
170
    terminal: &mut Terminal<TermionBackend<TerminalScreen>>,
171
) -> io::Result<()>
172
where
173
    A: App<Event = ()>,
174
{
175
    terminal.draw(|frame| app.render(frame))?;
176
177
    let events = event_receiver();
178
179
    while let Ok(event) = events.recv() {
180
        let mut redraw = false;
181
        if update(app, event?, &mut redraw) == Control::Quit {
182
            break;
183
        }
184
        while let Ok(event) = events.try_recv() {
185
            if update(app, event?, &mut redraw) == Control::Quit {
186
                return Ok(());
187
            }
188
        }
189
        if redraw {
190
            terminal.draw(|frame| app.render(frame))?;
191
        }
192
    }
193
    Ok(())
194
}
195
196
/// Spawns a blocking terminal reader and returns its event channel.
197
fn event_receiver() -> mpsc::Receiver<io::Result<Event<()>>> {
198
    let (tx, rx) = mpsc::channel();
199
200
    // Spawns a blocking terminal event reader.
201
    thread::spawn({
202
        let tx = tx.clone();
203
        move || match input_events() {
204
            Ok(events) => {
205
                for event in events {
206
                    if tx.send(event).is_err() {
207
                        break;
208
                    }
209
                }
210
            }
211
            Err(error) => {
212
                let _ = tx.send(Err(error));
213
            }
214
        }
215
    });
216
    // Spawns a signal notification reader.
217
    thread::spawn(move || match signals::Signals::install(SIGNALS) {
218
        Ok(signals) => {
219
            while let Ok(signal) = signals.recv() {
220
                match signal {
221
                    signals::Signal::WindowChanged => {
222
                        if tx
223
                            .send(Ok(Event::Resize(viewport().unwrap_or(Size::MAX))))
224
                            .is_err()
225
                        {
226
                            break;
227
                        }
228
                    }
229
                    signals::Signal::Interrupt
230
                    | signals::Signal::Terminate
231
                    | signals::Signal::Hangup => {}
232
                }
233
            }
234
        }
235
        Err(error) => {
236
            let _ = tx.send(Err(error));
237
        }
238
    });
239
240
    rx
241
}
242
243
/// Applies one event and records whether the caller should redraw.
244
fn update<A>(app: &mut A, event: Event<()>, redraw: &mut bool) -> Control
245
where
246
    A: App<Event = ()>,
247
{
248
    let resized = matches!(event, Event::Resize(_));
249
    match app.update(event) {
250
        Control::Continue | Control::Wait => {
251
            *redraw |= resized;
252
            Control::Continue
253
        }
254
        Control::Redraw => {
255
            *redraw = true;
256
            Control::Redraw
257
        }
258
        Control::Quit => Control::Quit,
259
    }
260
}
261
262
#[cfg(test)]
263
#[allow(clippy::unwrap_used)]
264
mod tests {
265
    use super::*;
266
    use rustik_tui_core as tui_core;
267
    use tui_core::Label;
268
269
    #[test]
270
    fn update_redraws_after_resize_even_when_app_continues() {
271
        struct ResizeAware;
272
273
        impl App for ResizeAware {
274
            type Event = ();
275
276
            fn update(&mut self, _: Event<Self::Event>) -> Control {
277
                Control::Continue
278
            }
279
280
            fn render(&mut self, frame: &mut tui_core::Frame<'_>) {
281
                frame.render_widget(Label::new("x"), frame.area);
282
            }
283
        }
284
        let mut app = ResizeAware;
285
        let mut redraw = false;
286
287
        let control = update(&mut app, Event::Resize(Size::new(80, 24)), &mut redraw);
288
289
        assert_eq!(control, Control::Continue);
290
        assert!(redraw);
291
    }
292
}