//! Termion-backed terminal output. use std::io::{self, Write}; use rustik_tui_core as tui_core; use tui_core::backend::Backend; use tui_core::buffer::DirtyRun; use tui_core::layout::Point; use tui_core::{PaintMode, Size, Style}; /// Termion-backed terminal output. #[derive(Debug)] pub struct TermionBackend { writer: W, paint: PaintMode, } impl TermionBackend { /// Creates a backend that writes ANSI styling escapes. pub fn new(writer: W) -> Self { Self { writer, paint: PaintMode::Styled, } } /// Creates a backend that writes no ANSI styling escapes. pub fn plain(writer: W) -> Self { Self { writer, paint: PaintMode::Plain, } } /// Returns the wrapped writer. pub fn into_inner(self) -> W { self.writer } } impl Backend for TermionBackend { type Error = io::Error; fn size(&mut self) -> Result { let (cols, rows) = termion::terminal_size()?; Ok(Size::new(cols as usize, rows as usize)) } fn draw(&mut self, runs: &[DirtyRun<'_>]) -> Result<(), Self::Error> { for run in runs { write!( self.writer, "{}", termion::cursor::Goto(coord(run.x), coord(run.y)) )?; match self.paint { PaintMode::Plain => self.draw_plain_cells(run.cells)?, PaintMode::Styled => self.draw_styled_cells(run.cells)?, } } Ok(()) } fn clear(&mut self) -> Result<(), Self::Error> { write!(self.writer, "{}", termion::clear::All) } fn flush(&mut self) -> Result<(), Self::Error> { self.writer.flush() } fn set_cursor_position(&mut self, point: Point) -> Result<(), Self::Error> { write!( self.writer, "{}", termion::cursor::Goto(coord(point.x), coord(point.y)) ) } fn set_cursor_visible(&mut self, visible: bool) -> Result<(), Self::Error> { if visible { write!(self.writer, "{}", termion::cursor::Show) } else { write!(self.writer, "{}", termion::cursor::Hide) } } } impl TermionBackend { /// Writes cells without ANSI styling. fn draw_plain_cells(&mut self, cells: &[tui_core::buffer::Cell]) -> io::Result<()> { for cell in cells { if cell.is_continuation() { continue; } self.writer.write_all(cell.glyph().as_bytes())?; } Ok(()) } /// Writes cells while keeping one ANSI style active across matching cells. fn draw_styled_cells(&mut self, cells: &[tui_core::buffer::Cell]) -> io::Result<()> { let mut style = Style::default(); for cell in cells { if cell.is_continuation() { continue; } let next = cell.style(); if next != style { self.write_style_suffix(style)?; self.write_style_prefix(next)?; style = next; } self.writer.write_all(cell.glyph().as_bytes())?; } self.write_style_suffix(style) } /// Writes the ANSI prefix for `style`. fn write_style_prefix(&mut self, style: Style) -> io::Result<()> { let mut text = String::new(); style .fmt_prefix(&mut text) .map_err(|_| io::Error::other("write_style_prefix: failed to format style prefix"))?; self.writer.write_all(text.as_bytes()) } /// Writes the ANSI suffix for `style`. fn write_style_suffix(&mut self, style: Style) -> io::Result<()> { let mut text = String::new(); style .fmt_suffix(&mut text) .map_err(|_| io::Error::other("write_style_suffix: failed to format style suffix"))?; self.writer.write_all(text.as_bytes()) } } /// Converts a zero-based coordinate into a terminal coordinate. fn coord(value: usize) -> u16 { u16::try_from(value.saturating_add(1)).unwrap_or(u16::MAX) } #[cfg(test)] #[allow(clippy::unwrap_used)] mod tests { use super::*; use tui_core::{Buffer, Color, Rect, Style}; #[test] fn termion_backend_writes_dirty_runs_with_one_based_coordinates() { let cells = [tui_core::buffer::Cell::new('x', Style::default())]; let run = DirtyRun { x: 2, y: 3, cells: &cells, }; let mut backend = TermionBackend::new(Vec::new()); backend.draw(&[run]).unwrap(); backend.flush().unwrap(); let out = String::from_utf8(backend.into_inner()).unwrap(); assert!(out.starts_with("\x1B[4;3H")); assert!(out.ends_with('x')); } #[test] fn termion_backend_paint_mode_is_explicit() { let cells = [tui_core::buffer::Cell::new('x', Color::Red.style())]; let run = DirtyRun { x: 0, y: 0, cells: &cells, }; let mut styled = TermionBackend::new(Vec::new()); styled.draw(&[run]).unwrap(); assert!( String::from_utf8(styled.into_inner()) .unwrap() .contains("\x1B[31m") ); let mut plain = TermionBackend::plain(Vec::new()); plain.draw(&[run]).unwrap(); let out = String::from_utf8(plain.into_inner()).unwrap(); assert_eq!(out, "\x1B[1;1Hx"); } #[test] fn termion_backend_keeps_matching_cell_styles_active() { let cells = [ tui_core::buffer::Cell::new('x', Color::Red.style()), tui_core::buffer::Cell::new('y', Color::Red.style()), ]; let run = DirtyRun { x: 0, y: 0, cells: &cells, }; let mut backend = TermionBackend::new(Vec::new()); backend.draw(&[run]).unwrap(); let out = String::from_utf8(backend.into_inner()).unwrap(); assert_eq!(out, "\x1B[1;1H\x1B[31mxy\x1B[0m"); } #[test] fn termion_backend_does_not_write_wide_continuation_cells() { let mut buffer = Buffer::empty(Rect::new(0, 0, 4, 1)); buffer.reset_dirty(); buffer.set_str(0, 0, "🍍a", Style::default()); let runs = buffer.dirty_runs(); let mut backend = TermionBackend::new(Vec::new()); backend.draw(&runs).unwrap(); let out = String::from_utf8(backend.into_inner()).unwrap(); assert!(out.ends_with("🍍a")); assert!(!out.ends_with("🍍 a")); } #[test] fn termion_backend_cursor_and_visibility_commands_are_written() { let mut backend = TermionBackend::new(Vec::new()); backend.set_cursor_visible(false).unwrap(); backend.set_cursor_position(Point::new(1, 2)).unwrap(); backend.set_cursor_visible(true).unwrap(); let out = String::from_utf8(backend.into_inner()).unwrap(); assert!(out.contains("\x1B[?25l")); assert!(out.contains("\x1B[3;2H")); assert!(out.contains("\x1B[?25h")); } }