//! Termion terminal session helpers. //! //! This module owns the raw-screen setup and event iterator plumbing needed to //! run a `rustik-tui` app on a real terminal. Keeping it outside the core crate avoids //! tying widget rendering to termion. use std::fs::{File, OpenOptions}; use std::io; use std::io::{BufWriter, Write}; use std::sync::mpsc; use std::thread; use termion::input::{MouseTerminal, TermReadEventsAndRaw}; use termion::raw::{IntoRawMode, RawTerminal}; use termion::screen::{AlternateScreen, IntoAlternateScreen}; use rustik_signals as signals; use rustik_tui_core as tui_core; use tui_core::app::{App, Control}; use tui_core::event::Event; use tui_core::terminal::Terminal; use tui_core::{Constraint, Size, Widget}; use crate::{TermionBackend, TermionEvent}; /// Signals observed by terminal applications. const SIGNALS: &[signals::Signal] = &[signals::Signal::WindowChanged]; /// Controlling terminal path used when standard input is application data. const TTY_DEVICE: &str = "/dev/tty"; /// Sequence enabling the Kitty keyboard protocol's disambiguate-escape-codes /// flag, so modified keys and the Escape key are reported as `CSI u` sequences. const KEYBOARD_PUSH: &str = "\x1B[>1u"; /// Sequence restoring the terminal's previous keyboard protocol flags. const KEYBOARD_POP: &str = "\x1B[>>>; /// Creates a raw alternate-screen backend on the terminal device. pub fn screen() -> io::Result> { let terminal = terminal_screen()?; let raw = terminal.into_raw_mode()?; let mouse = MouseTerminal::from(raw); let screen = mouse.into_alternate_screen()?; let keyboard = KeyboardProtocol::new(screen)?; Ok(TermionBackend::new(keyboard)) } /// Buffered output wrapper that enables the enhanced keyboard protocol for its lifetime. /// /// The protocol lets the terminal report modified keys unambiguously; terminals that do not /// implement it ignore the enabling sequence, so this degrades to the legacy keyboard encoding. The /// restoring sequence is written when the wrapper is dropped, before the underlying /// raw/alternate-screen guards tear down. #[derive(Debug)] pub struct KeyboardProtocol { /// Terminal writer that collects output until the frame is flushed. inner: BufWriter, } impl KeyboardProtocol { /// Enables the protocol on `inner` and returns the guarding wrapper. fn new(inner: W) -> io::Result { let mut inner = BufWriter::new(inner); inner.write_all(KEYBOARD_PUSH.as_bytes())?; inner.flush()?; Ok(Self { inner }) } } impl Drop for KeyboardProtocol { fn drop(&mut self) { let _ = self.inner.write_all(KEYBOARD_POP.as_bytes()); let _ = self.inner.flush(); } } impl Write for KeyboardProtocol { fn write(&mut self, buf: &[u8]) -> io::Result { self.inner.write(buf) } fn flush(&mut self) -> io::Result<()> { self.inner.flush() } } /// Returns typed events from the terminal. pub fn events() -> impl Iterator>> { event_receiver().into_iter() } /// Returns typed input events from the terminal device. /// /// This stream does not install signal handlers or synthesize resize events. /// Use [`events`] for a full application event stream. fn input_events() -> io::Result>>> { let terminal = File::open(TTY_DEVICE) .or_else(|_| File::open(STDOUT_DEVICE)) .or_else(|_| File::open(STDERR_DEVICE))?; Ok(terminal .events_and_raw() .map(|event| event.map(TermionEvent::from).map(Event::from))) } /// Opens the terminal device used for interactive screen output. fn terminal_screen() -> io::Result { OpenOptions::new() .read(true) .write(true) .open(TTY_DEVICE) .or_else(|_| { OpenOptions::new() .read(true) .write(true) .open(STDOUT_DEVICE) }) .or_else(|_| { OpenOptions::new() .read(true) .write(true) .open(STDERR_DEVICE) }) } /// Returns the current terminal viewport size. pub fn viewport() -> Option { termion::terminal_size() .map(|(cols, rows)| Size::new(cols as usize, rows as usize)) .ok() } /// Writes a widget to stdout under the given constraint. pub fn print_constrained( widget: &mut W, constraints: Constraint, ) -> io::Result<()> { let mut stdout = io::stdout(); for line in widget.display(constraints).lines() { writeln!(stdout, "{}", line.trim_end())?; } Ok(()) } /// Runs an application on stdout using termion. pub fn run(app: &mut A) -> io::Result<()> where A: App, { let backend = screen()?; let mut terminal = Terminal::new(backend)?; terminal.clear()?; terminal.set_cursor_visible(false)?; let result = event_loop(app, &mut terminal); let cursor = terminal.set_cursor_visible(true); result.and(cursor) } /// Runs the application event loop. fn event_loop( app: &mut A, terminal: &mut Terminal>, ) -> io::Result<()> where A: App, { terminal.draw(|frame| app.render(frame))?; let events = event_receiver(); while let Ok(event) = events.recv() { let mut redraw = false; if update(app, event?, &mut redraw) == Control::Quit { break; } while let Ok(event) = events.try_recv() { if update(app, event?, &mut redraw) == Control::Quit { return Ok(()); } } if redraw { terminal.draw(|frame| app.render(frame))?; } } Ok(()) } /// Spawns a blocking terminal reader and returns its event channel. fn event_receiver() -> mpsc::Receiver>> { let (tx, rx) = mpsc::channel(); // Spawns a blocking terminal event reader. thread::spawn({ let tx = tx.clone(); move || match input_events() { Ok(events) => { for event in events { if tx.send(event).is_err() { break; } } } Err(error) => { let _ = tx.send(Err(error)); } } }); // Spawns a signal notification reader. thread::spawn(move || match signals::Signals::install(SIGNALS) { Ok(signals) => { while let Ok(signal) = signals.recv() { match signal { signals::Signal::WindowChanged => { if tx .send(Ok(Event::Resize(viewport().unwrap_or(Size::MAX)))) .is_err() { break; } } signals::Signal::Interrupt | signals::Signal::Terminate | signals::Signal::Hangup => {} } } } Err(error) => { let _ = tx.send(Err(error)); } }); rx } /// Applies one event and records whether the caller should redraw. fn update(app: &mut A, event: Event<()>, redraw: &mut bool) -> Control where A: App, { let resized = matches!(event, Event::Resize(_)); match app.update(event) { Control::Continue | Control::Wait => { *redraw |= resized; Control::Continue } Control::Redraw => { *redraw = true; Control::Redraw } Control::Quit => Control::Quit, } } #[cfg(test)] #[allow(clippy::unwrap_used)] mod tests { use super::*; use rustik_tui_core as tui_core; use tui_core::Label; /// Records writes to the terminal device. #[derive(Default)] struct RecordingWriter { /// Bytes passed to each device write. writes: Vec>, } impl Write for RecordingWriter { fn write(&mut self, bytes: &[u8]) -> io::Result { self.writes.push(bytes.to_vec()); Ok(bytes.len()) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } #[test] fn terminal_output_flushes_frames_and_protocol_sequences() { let mut writer = RecordingWriter::default(); { let mut terminal = KeyboardProtocol::new(&mut writer).unwrap(); assert_eq!(terminal.inner.get_ref().writes, [KEYBOARD_PUSH.as_bytes()]); for byte in b"\x1b[31mhello\x1b[0m" { terminal.write_all(&[*byte]).unwrap(); } terminal.flush().unwrap(); assert_eq!( terminal.inner.get_ref().writes, [KEYBOARD_PUSH.as_bytes(), b"\x1b[31mhello\x1b[0m"] ); terminal.write_all(b"\x1b[?25h").unwrap(); } assert_eq!( writer.writes, [ KEYBOARD_PUSH.as_bytes(), b"\x1b[31mhello\x1b[0m", b"\x1b[?25h\x1b[) -> Control { Control::Continue } fn render(&mut self, frame: &mut tui_core::Frame<'_>) { frame.render_widget(Label::new("x"), frame.area); } } let mut app = ResizeAware; let mut redraw = false; let control = update(&mut app, Event::Resize(Size::new(80, 24)), &mut redraw); assert_eq!(control, Control::Continue); assert!(redraw); } }