use std::io::{stdout, BufWriter, Stdout, Write};
use std::time::Duration;
use crossterm::event::{self, Event};
use crossterm::style::{
Attribute, Color, Print, SetAttribute, SetBackgroundColor, SetForegroundColor,
};
use crossterm::{cursor, execute, queue, terminal};
use crate::buffer::{CellDiff, Intensity};
pub struct Terminal {
out: BufWriter<Stdout>,
}
impl Terminal {
pub fn new() -> std::io::Result<Self> {
terminal::enable_raw_mode()?;
let mut out = BufWriter::new(stdout());
execute!(
out,
terminal::EnterAlternateScreen,
cursor::Hide,
event::EnableMouseCapture
)?;
Ok(Terminal { out })
}
pub fn size(&self) -> std::io::Result<(u16, u16)> {
terminal::size()
}
pub fn draw_diff(&mut self, diffs: &[CellDiff]) -> std::io::Result<()> {
render_diff(&mut self.out, diffs)?;
self.out.flush()
}
pub fn next_event(&self, timeout: Duration) -> std::io::Result<Option<Event>> {
let deadline = std::time::Instant::now() + timeout;
loop {
let remaining = deadline.saturating_duration_since(std::time::Instant::now());
if remaining.is_zero() {
return Ok(None);
}
if !event::poll(remaining)? {
return Ok(None);
}
let event = event::read()?;
if !is_ignorable_mouse_motion(&event) {
return Ok(Some(event));
}
}
}
}
fn is_ignorable_mouse_motion(event: &Event) -> bool {
matches!(
event,
Event::Mouse(m) if matches!(m.kind, event::MouseEventKind::Moved | event::MouseEventKind::Drag(_))
)
}
pub fn render_diff(writer: &mut impl Write, diffs: &[CellDiff]) -> std::io::Result<()> {
let mut last_pos: Option<(u16, u16)> = None;
let mut last_fg: Option<Color> = None;
let mut last_bg: Option<Color> = None;
let mut last_intensity: Option<Intensity> = None;
let mut last_underline: Option<bool> = None;
let mut last_italic: Option<bool> = None;
let mut last_reverse: Option<bool> = None;
let mut last_strikethrough: Option<bool> = None;
for d in diffs {
let contiguous =
matches!(last_pos, Some((px, py)) if py == d.y && d.x.checked_sub(1) == Some(px));
if !contiguous {
queue!(writer, cursor::MoveTo(d.x, d.y))?;
}
let intensity = d.cell.style.intensity;
if last_intensity != Some(intensity) {
let attr = match intensity {
Intensity::Normal => Attribute::NormalIntensity,
Intensity::Bold => Attribute::Bold,
Intensity::Dim => Attribute::Dim,
};
queue!(writer, SetAttribute(attr))?;
last_intensity = Some(intensity);
}
let underline = d.cell.style.underline;
if last_underline != Some(underline) {
let attr = if underline {
Attribute::Underlined
} else {
Attribute::NoUnderline
};
queue!(writer, SetAttribute(attr))?;
last_underline = Some(underline);
}
let italic = d.cell.style.italic;
if last_italic != Some(italic) {
let attr = if italic {
Attribute::Italic
} else {
Attribute::NoItalic
};
queue!(writer, SetAttribute(attr))?;
last_italic = Some(italic);
}
let reverse = d.cell.style.reverse;
if last_reverse != Some(reverse) {
let attr = if reverse {
Attribute::Reverse
} else {
Attribute::NoReverse
};
queue!(writer, SetAttribute(attr))?;
last_reverse = Some(reverse);
}
let strikethrough = d.cell.style.strikethrough;
if last_strikethrough != Some(strikethrough) {
let attr = if strikethrough {
Attribute::CrossedOut
} else {
Attribute::NotCrossedOut
};
queue!(writer, SetAttribute(attr))?;
last_strikethrough = Some(strikethrough);
}
if last_fg != Some(d.cell.fg) {
queue!(writer, SetForegroundColor(d.cell.fg))?;
last_fg = Some(d.cell.fg);
}
if last_bg != Some(d.cell.bg) {
queue!(writer, SetBackgroundColor(d.cell.bg))?;
last_bg = Some(d.cell.bg);
}
queue!(writer, Print(d.cell.symbol))?;
last_pos = Some((d.x, d.y));
}
Ok(())
}
impl Drop for Terminal {
fn drop(&mut self) {
let _ = execute!(self.out, SetAttribute(Attribute::Reset));
let _ = execute!(self.out, event::DisableMouseCapture);
let _ = terminal::disable_raw_mode();
let _ = execute!(self.out, terminal::LeaveAlternateScreen, cursor::Show);
}
}
pub fn install_panic_hook() {
let default_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
let _ = execute!(stdout(), SetAttribute(Attribute::Reset));
let _ = execute!(stdout(), event::DisableMouseCapture);
let _ = terminal::disable_raw_mode();
let _ = execute!(stdout(), terminal::LeaveAlternateScreen, cursor::Show);
default_hook(info);
}));
}
#[cfg(test)]
mod render_diff_tests {
use super::*;
use crate::buffer::{Cell, CellDiff, CellStyle, Intensity};
use crossterm::style::Color;
fn d(x: u16, y: u16, symbol: char, fg: Color, bg: Color, intensity: Intensity) -> CellDiff {
CellDiff {
x,
y,
cell: Cell {
symbol,
fg,
bg,
style: CellStyle {
intensity,
..Default::default()
},
alpha: 1.0,
},
}
}
fn styled(x: u16, y: u16, symbol: char, style: CellStyle) -> CellDiff {
CellDiff {
x,
y,
cell: Cell {
symbol,
fg: Color::Reset,
bg: Color::Reset,
style,
alpha: 1.0,
},
}
}
fn render(diffs: &[CellDiff]) -> Vec<u8> {
let mut buf = Vec::new();
render_diff(&mut buf, diffs).unwrap();
buf
}
fn encode<C: crossterm::Command>(cmd: C) -> Vec<u8> {
let mut v = Vec::new();
crossterm::queue!(&mut v, cmd).unwrap();
v
}
fn count(hay: &[u8], needle: &[u8]) -> usize {
if needle.is_empty() || needle.len() > hay.len() {
return 0;
}
hay.windows(needle.len()).filter(|w| *w == needle).count()
}
fn move_count(out: &[u8]) -> usize {
count(out, b"H")
}
#[test]
fn empty_diffs_produce_no_output() {
assert!(render(&[]).is_empty());
}
#[test]
fn single_diff_emits_move_colors_intensity_and_glyph() {
let out = render(&[d(3, 2, 'A', Color::Reset, Color::Reset, Intensity::Normal)]);
assert_eq!(move_count(&out), 1);
assert!(out.contains(&b'A'));
assert_eq!(count(&out, &encode(SetForegroundColor(Color::Reset))), 1);
assert_eq!(count(&out, &encode(SetBackgroundColor(Color::Reset))), 1);
assert_eq!(
count(&out, &encode(SetAttribute(Attribute::NormalIntensity))),
1
);
}
#[test]
fn contiguous_same_styled_run_moves_once_and_sets_style_once() {
let out = render(&[
d(3, 2, 'A', Color::Reset, Color::Reset, Intensity::Normal),
d(4, 2, 'B', Color::Reset, Color::Reset, Intensity::Normal),
]);
assert_eq!(move_count(&out), 1, "contiguous run needs one MoveTo");
assert_eq!(count(&out, &encode(SetForegroundColor(Color::Reset))), 1);
assert_eq!(count(&out, &encode(SetBackgroundColor(Color::Reset))), 1);
assert_eq!(
count(&out, &encode(SetAttribute(Attribute::NormalIntensity))),
1
);
assert!(out.contains(&b'A') && out.contains(&b'B'));
}
#[test]
fn positional_gap_forces_a_second_move() {
let out = render(&[
d(3, 2, 'A', Color::Reset, Color::Reset, Intensity::Normal),
d(6, 2, 'B', Color::Reset, Color::Reset, Intensity::Normal),
]);
assert_eq!(move_count(&out), 2);
}
#[test]
fn new_row_forces_a_second_move() {
let out = render(&[
d(3, 2, 'A', Color::Reset, Color::Reset, Intensity::Normal),
d(4, 3, 'B', Color::Reset, Color::Reset, Intensity::Normal),
]);
assert_eq!(move_count(&out), 2);
}
#[test]
fn color_change_mid_run_re_emits_that_color_only() {
let out = render(&[
d(3, 2, 'A', Color::Reset, Color::Reset, Intensity::Normal),
d(4, 2, 'B', Color::Red, Color::Reset, Intensity::Normal),
]);
assert_eq!(move_count(&out), 1, "still contiguous");
assert_eq!(count(&out, &encode(SetForegroundColor(Color::Reset))), 1);
assert_eq!(count(&out, &encode(SetForegroundColor(Color::Red))), 1);
assert_eq!(
count(&out, &encode(SetBackgroundColor(Color::Reset))),
1,
"bg unchanged, emitted once"
);
}
#[test]
fn bold_toggle_emits_intensity_transitions() {
let out = render(&[
d(3, 2, 'A', Color::Reset, Color::Reset, Intensity::Normal),
d(4, 2, 'B', Color::Reset, Color::Reset, Intensity::Bold),
d(5, 2, 'C', Color::Reset, Color::Reset, Intensity::Normal),
]);
assert_eq!(count(&out, &encode(SetAttribute(Attribute::Bold))), 1);
assert_eq!(
count(&out, &encode(SetAttribute(Attribute::NormalIntensity))),
2,
"first cell + bold-off transition"
);
}
#[test]
fn intensity_cycles_through_all_three_states() {
let out = render(&[
d(3, 2, 'A', Color::Reset, Color::Reset, Intensity::Normal),
d(4, 2, 'B', Color::Reset, Color::Reset, Intensity::Bold),
d(5, 2, 'C', Color::Reset, Color::Reset, Intensity::Dim),
d(6, 2, 'D', Color::Reset, Color::Reset, Intensity::Normal),
]);
assert_eq!(
count(&out, &encode(SetAttribute(Attribute::NormalIntensity))),
2,
"first cell (Normal) + final Normal transition"
);
assert_eq!(count(&out, &encode(SetAttribute(Attribute::Bold))), 1);
assert_eq!(count(&out, &encode(SetAttribute(Attribute::Dim))), 1);
}
#[test]
fn underline_toggle_emits_underlined_and_no_underline() {
let out = render(&[
styled(3, 2, 'A', CellStyle::default()),
styled(
4,
2,
'B',
CellStyle {
underline: true,
..Default::default()
},
),
styled(5, 2, 'C', CellStyle::default()),
]);
assert_eq!(count(&out, &encode(SetAttribute(Attribute::Underlined))), 1);
assert_eq!(
count(&out, &encode(SetAttribute(Attribute::NoUnderline))),
2,
"first cell + underline-off transition"
);
}
#[test]
fn italic_toggle_emits_italic_and_no_italic() {
let out = render(&[
styled(3, 2, 'A', CellStyle::default()),
styled(
4,
2,
'B',
CellStyle {
italic: true,
..Default::default()
},
),
styled(5, 2, 'C', CellStyle::default()),
]);
assert_eq!(count(&out, &encode(SetAttribute(Attribute::Italic))), 1);
assert_eq!(
count(&out, &encode(SetAttribute(Attribute::NoItalic))),
2,
"first cell + italic-off transition"
);
}
#[test]
fn reverse_toggle_emits_reverse_and_no_reverse() {
let out = render(&[
styled(3, 2, 'A', CellStyle::default()),
styled(
4,
2,
'B',
CellStyle {
reverse: true,
..Default::default()
},
),
styled(5, 2, 'C', CellStyle::default()),
]);
assert_eq!(count(&out, &encode(SetAttribute(Attribute::Reverse))), 1);
assert_eq!(
count(&out, &encode(SetAttribute(Attribute::NoReverse))),
2,
"first cell + reverse-off transition"
);
}
#[test]
fn strikethrough_toggle_emits_crossed_out_and_not_crossed_out() {
let out = render(&[
styled(3, 2, 'A', CellStyle::default()),
styled(
4,
2,
'B',
CellStyle {
strikethrough: true,
..Default::default()
},
),
styled(5, 2, 'C', CellStyle::default()),
]);
assert_eq!(count(&out, &encode(SetAttribute(Attribute::CrossedOut))), 1);
assert_eq!(
count(&out, &encode(SetAttribute(Attribute::NotCrossedOut))),
2,
"first cell + strikethrough-off transition"
);
}
#[test]
fn all_five_style_axes_combine_independently_in_one_cell() {
let out = render(&[styled(
3,
2,
'A',
CellStyle {
intensity: Intensity::Bold,
underline: true,
italic: true,
reverse: true,
strikethrough: true,
},
)]);
assert_eq!(count(&out, &encode(SetAttribute(Attribute::Bold))), 1);
assert_eq!(count(&out, &encode(SetAttribute(Attribute::Underlined))), 1);
assert_eq!(count(&out, &encode(SetAttribute(Attribute::Italic))), 1);
assert_eq!(count(&out, &encode(SetAttribute(Attribute::Reverse))), 1);
assert_eq!(count(&out, &encode(SetAttribute(Attribute::CrossedOut))), 1);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crossterm::event::{KeyCode, KeyEvent, MouseButton, MouseEvent, MouseEventKind};
use crossterm::terminal;
fn mouse_event(kind: MouseEventKind) -> Event {
Event::Mouse(MouseEvent {
kind,
column: 0,
row: 0,
modifiers: crossterm::event::KeyModifiers::NONE,
})
}
#[test]
fn moved_mouse_events_are_ignorable() {
assert!(is_ignorable_mouse_motion(&mouse_event(
MouseEventKind::Moved
)));
}
#[test]
fn drag_mouse_events_are_ignorable() {
assert!(is_ignorable_mouse_motion(&mouse_event(
MouseEventKind::Drag(MouseButton::Left)
)));
}
#[test]
fn click_mouse_events_are_not_ignorable() {
assert!(!is_ignorable_mouse_motion(&mouse_event(
MouseEventKind::Down(MouseButton::Left)
)));
}
#[test]
fn key_events_are_not_ignorable() {
assert!(!is_ignorable_mouse_motion(&Event::Key(KeyEvent::from(
KeyCode::Char('a')
))));
}
#[test]
#[ignore = "requires a real terminal (TTY); run with `cargo test -- --ignored`"]
fn enter_and_drop_restores_raw_mode() {
assert!(!terminal::is_raw_mode_enabled().unwrap());
{
let _term = Terminal::new().unwrap();
assert!(terminal::is_raw_mode_enabled().unwrap());
}
assert!(!terminal::is_raw_mode_enabled().unwrap());
}
#[test]
#[ignore = "requires a real terminal (TTY); run with `cargo test -- --ignored`"]
fn panic_hook_disables_raw_mode_before_unwinding() {
install_panic_hook();
terminal::enable_raw_mode().unwrap();
assert!(terminal::is_raw_mode_enabled().unwrap());
let result = std::panic::catch_unwind(|| {
panic!("simulated crash");
});
assert!(result.is_err());
assert!(!terminal::is_raw_mode_enabled().unwrap());
}
}