#![forbid(unsafe_code)]
#![warn(missing_docs, clippy::doc_markdown)]
mod colors;
mod error;
mod keys;
mod links;
mod search;
mod selection;
mod style;
mod terminal;
pub use error::{Error, Result};
pub use style::{ColorScheme, TerminalStyle};
pub use terminal::{DEFAULT_SCROLLBACK, Terminal, cell_size};
use std::sync::{Arc, mpsc};
pub trait Tty: Send + Sync {
fn write(&self, bytes: &[u8]) -> Result<()>;
fn reply(&self, bytes: &[u8]) -> Result<()> {
self.write(bytes)
}
fn resize(&self, cols: u16, rows: u16) -> Result<()>;
fn has_exited(&self) -> bool {
false
}
}
pub struct TtyStream {
pub output: mpsc::Receiver<Vec<u8>>,
pub tty: Arc<dyn Tty>,
}
#[cfg(test)]
mod tests {
use std::sync::{Arc, Mutex, mpsc};
use super::*;
#[derive(Default)]
struct Recorder {
written: Mutex<Vec<u8>>,
size: Mutex<(u16, u16)>,
}
impl Tty for Recorder {
fn write(&self, bytes: &[u8]) -> Result<()> {
self.written.lock().unwrap().extend_from_slice(bytes);
Ok(())
}
fn resize(&self, cols: u16, rows: u16) -> Result<()> {
*self.size.lock().unwrap() = (cols, rows);
Ok(())
}
}
fn terminal() -> (Terminal, mpsc::Sender<Vec<u8>>, Arc<Recorder>) {
let (writer, output) = mpsc::channel();
let recorder = Arc::new(Recorder::default());
let terminal = Terminal::new(TtyStream {
output,
tty: Arc::clone(&recorder) as Arc<dyn Tty>,
})
.expect("expected a terminal");
(terminal, writer, recorder)
}
#[test]
fn output_from_the_program_lands_on_the_screen() {
let (mut terminal, writer, _) = terminal();
writer
.send(b"hello\r\nworld\r\n".to_vec())
.expect("expected the terminal to be listening");
assert!(terminal.poll(), "the terminal read what was written");
let screen = terminal.visible_text().expect("expected the screen");
let lines: Vec<&str> = screen.lines().take(2).collect();
assert_eq!(lines, vec!["hello", "world"]);
}
#[test]
fn escape_sequences_are_interpreted_rather_than_printed() {
let (mut terminal, writer, _) = terminal();
writer
.send(b"\x1b]0;a title\x07\x1b[31mred\x1b[0m".to_vec())
.expect("expected the terminal to be listening");
terminal.poll();
assert_eq!(terminal.title().as_deref(), Some("a title"));
assert_eq!(
terminal.visible_text().expect("expected the screen").lines().next(),
Some("red")
);
}
#[test]
fn keystrokes_reach_the_program() {
let (terminal, _writer, recorder) = terminal();
terminal.send(b"ls\r").expect("expected the write to land");
assert_eq!(&*recorder.written.lock().unwrap(), b"ls\r");
}
fn typed(terminal: &mut Terminal, key: egui::Key, modifiers: egui::Modifiers) {
let ctx = egui::Context::default();
terminal.request_focus();
ctx.run_ui(egui::RawInput::default(), |ui| {
terminal.ui(ui, &TerminalStyle::from_visuals(ui.visuals()));
})
.drop_without_applying_deltas();
let input = egui::RawInput {
events: vec![egui::Event::Key {
key,
physical_key: Some(key),
pressed: true,
repeat: false,
modifiers,
}],
..Default::default()
};
ctx.run_ui(input, |ui| {
terminal.ui(ui, &TerminalStyle::from_visuals(ui.visuals()));
})
.drop_without_applying_deltas();
}
#[test]
fn a_shell_is_sent_the_word_motion_it_binds() {
let (mut terminal, _writer, recorder) = terminal();
typed(
&mut terminal,
egui::Key::ArrowLeft,
egui::Modifiers {
ctrl: true,
..Default::default()
},
);
assert_eq!(&*recorder.written.lock().unwrap(), b"\x1bb");
}
#[test]
fn a_program_on_the_kitty_protocol_is_sent_the_chord() {
let (mut terminal, writer, recorder) = terminal();
writer
.send(b"\x1b[>1u".to_vec())
.expect("expected the terminal to be listening");
terminal.poll();
typed(
&mut terminal,
egui::Key::ArrowLeft,
egui::Modifiers {
ctrl: true,
..Default::default()
},
);
let written = recorder.written.lock().unwrap().clone();
assert_ne!(written, b"\x1bb", "the chord should not have been rewritten");
assert!(
String::from_utf8_lossy(&written).contains("[1;5"),
"expected the chord itself, got {:?}",
String::from_utf8_lossy(&written)
);
}
#[test]
fn a_closed_output_channel_means_the_program_has_gone() {
let (mut terminal, writer, _) = terminal();
assert!(!terminal.has_exited());
drop(writer);
terminal.poll();
assert!(terminal.has_exited());
}
fn scrollable() -> (Terminal, egui::Context, mpsc::Sender<Vec<u8>>) {
let (mut terminal, writer, _) = terminal();
let mut output = String::new();
for index in 0..80 {
output.push_str(&format!("line {index}\r\n"));
}
writer
.send(output.into_bytes())
.expect("expected the terminal to be listening");
terminal.poll();
(terminal, egui::Context::default(), writer)
}
fn wheeled(terminal: &mut Terminal, ctx: &egui::Context, points: f32) {
let input = egui::RawInput {
events: vec![
egui::Event::PointerMoved(egui::pos2(80.0, 80.0)),
egui::Event::MouseWheel {
unit: egui::MouseWheelUnit::Point,
delta: egui::vec2(0.0, points),
phase: egui::TouchPhase::Move,
modifiers: Default::default(),
},
],
screen_rect: Some(egui::Rect::from_min_size(
egui::Pos2::ZERO,
egui::vec2(400.0, 160.0),
)),
..Default::default()
};
ctx.run_ui(input, |ui| {
terminal.ui(ui, &TerminalStyle::from_visuals(ui.visuals()));
})
.drop_without_applying_deltas();
}
fn top_line(terminal: &mut Terminal) -> String {
terminal
.visible_text()
.expect("expected the screen")
.lines()
.next()
.unwrap_or_default()
.trim_end()
.to_string()
}
#[test]
fn a_gesture_of_sub_line_steps_scrolls_as_far_as_it_asks_for() {
let (mut terminal, ctx, _writer) = scrollable();
wheeled(&mut terminal, &ctx, 0.0);
let before = top_line(&mut terminal);
for _ in 0..20 {
wheeled(&mut terminal, &ctx, 4.0);
}
assert_ne!(
top_line(&mut terminal),
before,
"a trackpad gesture should scroll the terminal"
);
}
#[test]
fn output_arriving_does_not_yank_the_view_back_to_the_bottom() {
let (mut terminal, ctx, writer) = scrollable();
wheeled(&mut terminal, &ctx, 0.0);
for _ in 0..20 {
wheeled(&mut terminal, &ctx, 4.0);
}
let scrolled_to = top_line(&mut terminal);
writer
.send(b"more output\r\n".to_vec())
.expect("expected the terminal to be listening");
terminal.poll();
assert_eq!(top_line(&mut terminal), scrolled_to);
}
#[test]
fn searching_finds_matches_in_the_scrollback() {
let (mut terminal, writer, _) = terminal();
let mut output = String::new();
for index in 0..60 {
output.push_str(&format!("line {index}\r\n"));
}
output.push_str("the needle\r\n");
writer
.send(output.into_bytes())
.expect("expected the terminal to be listening");
terminal.poll();
assert_eq!(terminal.find("needle", 0), 1);
assert_eq!(terminal.selected_text().as_deref(), Some("needle"));
assert_eq!(terminal.find("line", 0), 60, "the scrollback counts too");
}
#[test]
fn the_light_scheme_is_readable_where_the_dark_one_is_not() {
let (mut terminal, _writer, _) = terminal();
terminal.set_color_scheme(ColorScheme::Dark);
let (dark_fg, dark_bg) = terminal.drawn_colors().expect("expected colors");
terminal.set_color_scheme(ColorScheme::Light);
let (light_fg, light_bg) = terminal.drawn_colors().expect("expected colors");
assert!(dark_bg.r() < light_bg.r(), "the light background is paper");
assert!(light_fg.r() < dark_fg.r(), "and its text is ink");
}
}