use std::{
sync::{Arc, mpsc},
time::Duration,
};
use egui::{
Align2, Color32, CornerRadius, FontId, Rect, Response, Sense, Stroke, TextFormat, Ui,
text::LayoutJob, vec2,
};
use libghostty_vt::{
Terminal as Emulator, TerminalOptions,
key::{self, Action},
render::{CellIterator, CursorVisualStyle, Dirty, RenderState, RowIterator},
style::RgbColor,
terminal::ScrollViewport,
};
use crate::{
ColorScheme, Error, Result, TerminalStyle, Tty, TtyStream, colors, keys, links, search,
selection,
};
pub const DEFAULT_SCROLLBACK: usize = 10_000;
const DEFAULT_POLL_INTERVAL: Duration = Duration::from_millis(33);
const BLINK_POLL_INTERVAL: Duration = Duration::from_millis(16);
const MIN_COLS: u16 = 20;
const MIN_ROWS: u16 = 4;
const LEGACY_EDITING_CHORDS: &[(key::Key, key::Mods, &[u8])] = &[
(key::Key::ArrowLeft, key::Mods::CTRL, b"\x1bb"),
(key::Key::ArrowRight, key::Mods::CTRL, b"\x1bf"),
(key::Key::Backspace, key::Mods::CTRL, b"\x17"),
(key::Key::ArrowLeft, key::Mods::SUPER, b"\x01"),
(key::Key::ArrowRight, key::Mods::SUPER, b"\x05"),
(key::Key::Backspace, key::Mods::SUPER, b"\x15"),
];
fn legacy_editing_chord(key: key::Key, mods: key::Mods) -> Option<&'static [u8]> {
LEGACY_EDITING_CHORDS
.iter()
.find(|(chord, with, _)| *chord == key && *with == mods)
.map(|(_, _, bytes)| *bytes)
}
pub struct Terminal {
emulator: Emulator<'static, 'static>,
render_state: RenderState<'static>,
row_iterator: RowIterator<'static>,
cell_iterator: CellIterator<'static>,
encoder: key::Encoder<'static>,
output: mpsc::Receiver<Vec<u8>>,
tty: Arc<dyn Tty>,
cols: u16,
rows: u16,
label: Option<String>,
poll_interval: Duration,
exited: bool,
pending_focus: bool,
blink_clock: f32,
scroll_remainder: f32,
pointer: selection::Pointer,
hovered_link: Option<links::Link>,
colored_for: Option<ColorScheme>,
emulator_colors: Option<colors::Scheme>,
}
impl Terminal {
pub fn new(stream: TtyStream) -> Result<Self> {
Self::with_scrollback(stream, DEFAULT_SCROLLBACK)
}
pub fn with_scrollback(stream: TtyStream, max_scrollback: usize) -> Result<Self> {
let TtyStream { output, tty } = stream;
let cols = 80;
let rows = 24;
let mut emulator = Emulator::new(TerminalOptions {
cols,
rows,
max_scrollback,
})
.map_err(|error| Error::context("failed to create a terminal", error))?;
let reply_to = Arc::clone(&tty);
emulator
.on_pty_write(move |_emulator, data| {
let _ = reply_to.reply(data);
})
.map_err(|error| Error::context("failed to install the terminal reply hook", error))?;
Ok(Self {
emulator,
render_state: RenderState::new()
.map_err(|error| Error::context("failed to create a render state", error))?,
row_iterator: RowIterator::new()
.map_err(|error| Error::context("failed to create a row iterator", error))?,
cell_iterator: CellIterator::new()
.map_err(|error| Error::context("failed to create a cell iterator", error))?,
encoder: key::Encoder::new()
.map_err(|error| Error::context("failed to create a key encoder", error))?,
output,
tty,
cols,
rows,
label: None,
poll_interval: DEFAULT_POLL_INTERVAL,
exited: false,
pending_focus: false,
blink_clock: 0.0,
scroll_remainder: 0.0,
pointer: selection::Pointer::new()?,
hovered_link: None,
colored_for: None,
emulator_colors: None,
})
}
#[must_use]
pub fn with_label(mut self, label: impl Into<String>) -> Self {
self.label = Some(label.into());
self
}
#[must_use]
pub fn with_poll_interval(mut self, interval: Duration) -> Self {
self.poll_interval = interval;
self
}
pub fn request_focus(&mut self) {
self.pending_focus = true;
}
pub fn has_exited(&self) -> bool {
self.exited
}
pub fn size(&self) -> (u16, u16) {
(self.cols, self.rows)
}
pub fn title(&self) -> Option<String> {
self.emulator
.title()
.ok()
.map(str::trim)
.filter(|title| !title.is_empty())
.map(ToOwned::to_owned)
}
pub fn send(&self, bytes: &[u8]) -> Result<()> {
self.tty.write(bytes)
}
pub fn selected_text(&self) -> Option<String> {
selection::selected_text(&self.emulator)
}
pub fn find(&mut self, query: &str, at: usize) -> usize {
let found = search::find_all(&self.emulator, query);
match found.get(at) {
Some(found) => report(search::show(&mut self.emulator, *found, self.rows)),
None => report(
self.emulator
.set_selection(None)
.map(|_| ())
.map_err(|error| Error::context("failed to clear the selection", error)),
),
}
found.len()
}
pub fn visible_text(&mut self) -> Result<String> {
let Self {
emulator,
render_state,
row_iterator,
cell_iterator,
..
} = self;
let snapshot = render_state
.update(emulator)
.map_err(|error| Error::context("failed to read the screen", error))?;
let mut rows = row_iterator
.update(&snapshot)
.map_err(|error| Error::context("failed to walk the rows", error))?;
let mut out = String::new();
let mut cell_text = String::new();
while let Some(row) = rows.next() {
let mut cells = cell_iterator
.update(row)
.map_err(|error| Error::context("failed to walk the cells", error))?;
let mut line = String::new();
while let Some(view) = cells.next() {
cell_text.clear();
if view.graphemes_len().unwrap_or(0) > 0 {
let _ = view.graphemes_utf8(&mut cell_text);
}
line.push_str(if cell_text.is_empty() { " " } else { &cell_text });
}
out.push_str(line.trim_end());
out.push('\n');
}
Ok(out)
}
pub fn drawn_colors(&mut self) -> Result<(Color32, Color32)> {
let Self {
emulator,
render_state,
..
} = self;
let snapshot = render_state
.update(emulator)
.map_err(|error| Error::context("failed to read the screen", error))?;
let colors = snapshot
.colors()
.map_err(|error| Error::context("failed to read the colors", error))?;
Ok((color_of(colors.foreground), color_of(colors.background)))
}
pub fn set_color_scheme(&mut self, scheme: ColorScheme) {
if self.colored_for == Some(scheme) {
return;
}
if self.emulator_colors.is_none() {
let Self {
emulator,
render_state,
..
} = self;
match render_state
.update(emulator)
.and_then(|snapshot| snapshot.colors())
{
Ok(colors) => self.emulator_colors = Some(colors::emulator_scheme(&colors)),
Err(error) => {
report(Err(Error::context(
"failed to read the terminal's own colors",
error,
)));
return;
}
}
}
let Some(emulator) = self.emulator_colors.clone() else {
return;
};
report(colors::apply(&mut self.emulator, &emulator, scheme));
self.colored_for = Some(scheme);
}
pub fn poll(&mut self) -> bool {
let mut received = false;
loop {
match self.output.try_recv() {
Ok(chunk) => {
self.emulator.vt_write(&chunk);
received = true;
}
Err(mpsc::TryRecvError::Empty) => break,
Err(mpsc::TryRecvError::Disconnected) => {
self.exited = true;
break;
}
}
}
if self.tty.has_exited() {
self.exited = true;
}
received
}
pub fn ui(&mut self, ui: &mut Ui, style: &TerminalStyle) -> Response {
self.poll();
self.set_color_scheme(style.scheme);
let padding = style.padding;
let cell = cell_size(ui.painter(), &style.font);
let available = ui.available_size();
let cols = ((available.x - 2.0 * padding) / cell.x)
.floor()
.max(f32::from(MIN_COLS)) as u16;
let rows = ((available.y - 2.0 * padding) / cell.y)
.floor()
.max(f32::from(MIN_ROWS)) as u16;
report(self.resize(cols, rows, cell));
let (response, painter) = ui.allocate_painter(available, Sense::click_and_drag());
if response.clicked()
|| response.drag_started()
|| std::mem::take(&mut self.pending_focus)
{
response.request_focus();
}
let focused = response.has_focus();
if focused {
ui.memory_mut(|memory| {
memory.set_focus_lock_filter(
response.id,
egui::EventFilter {
tab: true,
horizontal_arrows: true,
vertical_arrows: true,
escape: true,
},
)
});
self.handle_input(ui);
self.handle_clipboard(ui);
}
self.handle_scroll(ui, &response, cell);
let origin = response.rect.min + vec2(padding, padding);
self.handle_pointer(ui, &response, origin, cell);
self.blink_clock += ui.input(|input| input.stable_dt).min(0.1);
let cursor_blinking = match self.draw(&painter, origin, cell, style, focused) {
Ok(blinking) => blinking,
Err(error) => {
painter.text(
origin,
Align2::LEFT_TOP,
format!("terminal render failed: {error}"),
style.font.clone(),
style.error_ink,
);
false
}
};
if self.exited {
let what = self.label.as_deref().unwrap_or("the program");
painter.text(
response.rect.left_bottom() + vec2(padding, -padding - cell.y),
Align2::LEFT_TOP,
format!("[{what} exited]"),
FontId::monospace(cell.y * 0.7),
style.notice_ink,
);
} else {
let interval = if cursor_blinking {
self.poll_interval.min(BLINK_POLL_INTERVAL)
} else {
self.poll_interval
};
ui.ctx().request_repaint_after(interval);
}
response
}
fn resize(&mut self, cols: u16, rows: u16, cell: egui::Vec2) -> Result<()> {
if cols == self.cols && rows == self.rows {
return Ok(());
}
self.cols = cols;
self.rows = rows;
self.emulator
.resize(cols, rows, cell.x as u32, cell.y as u32)
.map_err(|error| Error::context("failed to resize the terminal", error))?;
self.tty.resize(cols, rows)
}
fn handle_pointer(
&mut self,
ui: &Ui,
response: &Response,
origin: egui::Pos2,
cell_size: egui::Vec2,
) {
let (pointer_at, pressed, released, now) = ui.input(|input| {
(
input.pointer.interact_pos(),
input.pointer.primary_pressed(),
input.pointer.primary_released(),
Duration::from_secs_f64(input.time.max(0.0)),
)
});
let cell = pointer_at.map(|at| selection::Cell {
x: (((at.x - origin.x) / cell_size.x).floor().max(0.0) as u16).min(self.cols - 1),
y: (((at.y - origin.y) / cell_size.y).floor().max(0.0) as u16).min(self.rows - 1),
});
self.hovered_link = match (response.contains_pointer(), cell) {
(true, Some(cell)) if !self.pointer.dragging => {
links::link_at(&self.emulator, self.cols, cell.x, cell.y)
}
_ => None,
};
if self.hovered_link.is_some() {
ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
}
let Some((cell, at)) = cell.zip(pointer_at) else {
return;
};
let at = (at.x - response.rect.min.x, at.y - response.rect.min.y);
if pressed && response.contains_pointer() {
report(self.pointer.press(&self.emulator, cell, at, now));
} else if self.pointer.dragging && released {
let was_a_click = !self.pointer.dragged(&self.emulator);
report(self.pointer.release(&self.emulator));
if was_a_click
&& let Some(link) = &self.hovered_link
{
ui.ctx().open_url(egui::OpenUrl::new_tab(&link.url));
}
} else if self.pointer.dragging {
let geometry = selection::geometry(
self.cols,
cell_size.x,
origin.x - response.rect.min.x,
response.rect.height().max(1.0),
);
let rectangle = ui.input(|input| input.modifiers.alt);
report(
self.pointer
.drag(&self.emulator, cell, at, geometry, rectangle),
);
}
}
fn handle_clipboard(&mut self, ui: &Ui) {
let events = ui.input(|input| input.events.clone());
for event in &events {
match event {
egui::Event::Copy | egui::Event::Cut => {
match selection::selected_text(&self.emulator) {
Some(text) if !text.is_empty() => ui.ctx().copy_text(text),
_ if COPY_CHORD_IS_ALSO_INTERRUPT => {
report(self.tty.write(&[0x03]));
}
_ => {}
}
}
egui::Event::Paste(text) => match selection::encode_paste(&self.emulator, text) {
Ok(bytes) => report(self.tty.write(&bytes)),
Err(error) => report(Err(error)),
},
_ => {}
}
}
}
fn handle_scroll(&mut self, ui: &Ui, response: &Response, cell_size: egui::Vec2) {
if !response.hovered() {
return;
}
let scroll = ui.input(|input| input.smooth_scroll_delta.y);
if scroll == 0.0 || cell_size.y <= 0.0 {
return;
}
self.scroll_remainder += scroll / cell_size.y;
let lines = self.scroll_remainder.trunc();
self.scroll_remainder -= lines;
if lines != 0.0 {
self.emulator
.scroll_viewport(ScrollViewport::Delta(-(lines as isize)));
}
}
fn handle_input(&mut self, ui: &Ui) {
let events = ui.input(|input| input.events.clone());
let mut pending_text: Vec<String> = events
.iter()
.filter_map(|event| match event {
egui::Event::Text(text) => Some(text.clone()),
_ => None,
})
.collect();
let mut text_index = 0usize;
self.encoder.set_options_from_terminal(&self.emulator);
let mut encoded = Vec::new();
for event in &events {
let egui::Event::Key {
key,
pressed,
repeat,
modifiers,
..
} = event
else {
continue;
};
let Some(vt) = keys::vt_key(*key) else {
continue;
};
if keys::is_modifier_key(vt) {
continue;
}
if !pressed {
continue;
}
let mods = keys::vt_mods(*modifiers);
if !self.reads_the_real_chord()
&& let Some(bytes) = legacy_editing_chord(vt, mods)
{
encoded.extend_from_slice(bytes);
continue;
}
let text = if mods.intersects(key::Mods::CTRL | key::Mods::SUPER) {
None
} else {
let text = pending_text.get(text_index).cloned();
if text.is_some() {
text_index += 1;
}
text
};
report(self.encode_key(vt, mods, text, *repeat, &mut encoded));
}
for text in pending_text.drain(text_index.min(pending_text.len())..) {
encoded.extend_from_slice(text.as_bytes());
}
if !encoded.is_empty() {
report(self.tty.write(&encoded));
}
}
fn reads_the_real_chord(&self) -> bool {
self.emulator
.kitty_keyboard_flags()
.is_ok_and(|flags| !flags.is_empty())
}
fn encode_key(
&mut self,
vt: key::Key,
mods: key::Mods,
text: Option<String>,
repeat: bool,
out: &mut Vec<u8>,
) -> Result<()> {
let mut event = key::Event::new()
.map_err(|error| Error::context("failed to create a key event", error))?;
event.set_action(if repeat { Action::Repeat } else { Action::Press });
event.set_key(vt);
event.set_mods(mods);
let unshifted = keys::unshifted_codepoint(vt);
if let Some(codepoint) = unshifted {
event.set_unshifted_codepoint(codepoint);
}
if keys::shift_was_consumed(mods, unshifted, text.as_deref()) {
event.set_consumed_mods(key::Mods::SHIFT);
}
if let Some(text) = text {
event.set_utf8(Some(text));
}
self.encoder
.encode_to_vec(&event, out)
.map_err(|error| Error::context("failed to encode a keystroke", error))
}
fn draw(
&mut self,
painter: &egui::Painter,
origin: egui::Pos2,
cell: egui::Vec2,
style: &TerminalStyle,
focused: bool,
) -> Result<bool> {
let Self {
emulator,
render_state,
row_iterator,
cell_iterator,
blink_clock,
hovered_link,
..
} = self;
let blink_clock = *blink_clock;
let hovered_link = hovered_link.clone();
let snapshot = render_state
.update(emulator)
.map_err(|error| Error::context("failed to read the screen", error))?;
let colors = snapshot
.colors()
.map_err(|error| Error::context("failed to read the colors", error))?;
let default_fg = color_of(colors.foreground);
let default_bg = color_of(colors.background);
let mut rows = row_iterator
.update(&snapshot)
.map_err(|error| Error::context("failed to walk the rows", error))?;
let mut y = origin.y;
let mut text = String::with_capacity(16);
let mut row_index: u16 = 0;
while let Some(row) = rows.next() {
let underlined = hovered_link
.as_ref()
.filter(|link| link.row == row_index)
.map(|link| link.columns.clone());
let mut column_index: u16 = 0;
let mut cells = cell_iterator
.update(row)
.map_err(|error| Error::context("failed to walk the cells", error))?;
let mut x = origin.x;
let mut job = LayoutJob::default();
let mut run: Option<Run> = None;
while let Some(view) = cells.next() {
let selected = view.is_selected().unwrap_or(false);
let grapheme_count = view.graphemes_len().unwrap_or(0);
let cell_bg = view.bg_color().ok().flatten().map(color_of);
let mut fg = view
.fg_color()
.ok()
.flatten()
.map(color_of)
.unwrap_or(default_fg);
let mut bg = cell_bg;
let mut bold = false;
let mut italic = false;
let mut underline = false;
let mut strikethrough = false;
if view.has_styling().unwrap_or(false)
&& let Ok(cell_style) = view.style()
{
if cell_style.inverse {
let swapped = bg.unwrap_or(default_bg);
bg = Some(fg);
fg = swapped;
}
bold = cell_style.bold;
italic = cell_style.italic;
underline = cell_style.underline != libghostty_vt::style::Underline::None;
strikethrough = cell_style.strikethrough;
}
if selected {
let swapped = bg.unwrap_or(default_bg);
bg = Some(fg);
fg = swapped;
}
if underlined
.as_ref()
.is_some_and(|columns| columns.contains(&column_index))
{
underline = true;
}
if let Some(bg) = bg {
painter.rect_filled(
Rect::from_min_size(egui::pos2(x, y), cell),
CornerRadius::ZERO,
bg,
);
}
text.clear();
if grapheme_count > 0 {
let _ = view.graphemes_utf8(&mut text);
}
let glyph = if text.is_empty() { " " } else { text.as_str() };
let cell_style = CellStyle {
fg,
bold,
italic,
underline,
strikethrough,
};
match &mut run {
Some(current) if current.style == cell_style => current.text.push_str(glyph),
Some(current) => {
current.flush(&mut job, style);
*current = Run::new(cell_style, glyph);
}
None => run = Some(Run::new(cell_style, glyph)),
}
x += cell.x;
column_index += 1;
}
if let Some(mut current) = run.take() {
current.flush(&mut job, style);
}
if !job.sections.is_empty() {
let galley = painter.layout_job(job);
painter.galley(egui::pos2(origin.x, y), galley, default_fg);
}
let _ = row.set_dirty(false);
y += cell.y;
row_index += 1;
}
let mut blinking = false;
if snapshot.cursor_visible().unwrap_or(false)
&& let Ok(Some(viewport)) = snapshot.cursor_viewport()
{
blinking = snapshot.cursor_blinking().unwrap_or(false);
let visible = !blinking || blink_clock.rem_euclid(1.06) < 0.53;
if visible {
let color = colors.cursor.map(color_of).unwrap_or(style.cursor);
let at = egui::pos2(
origin.x + f32::from(viewport.x) * cell.x,
origin.y + f32::from(viewport.y) * cell.y,
);
draw_cursor(
painter,
Rect::from_min_size(at, cell),
snapshot
.cursor_visual_style()
.unwrap_or(CursorVisualStyle::Block),
color,
focused,
);
}
}
let _ = snapshot.set_dirty(Dirty::Clean);
Ok(blinking)
}
}
fn draw_cursor(
painter: &egui::Painter,
rect: Rect,
style: CursorVisualStyle,
color: Color32,
focused: bool,
) {
if !focused || style == CursorVisualStyle::BlockHollow {
painter.rect_stroke(
rect.shrink(0.5),
CornerRadius::ZERO,
Stroke::new(1.0, color),
egui::StrokeKind::Inside,
);
return;
}
let filled = match style {
CursorVisualStyle::Bar => Rect::from_min_size(rect.min, vec2(2.0, rect.height())),
CursorVisualStyle::Underline => Rect::from_min_size(
egui::pos2(rect.min.x, rect.max.y - 2.0),
vec2(rect.width(), 2.0),
),
_ => rect,
};
painter.rect_filled(filled, CornerRadius::ZERO, color);
}
const COPY_CHORD_IS_ALSO_INTERRUPT: bool = !cfg!(target_os = "macos");
fn report(result: Result<()>) {
if let Err(error) = result {
eprintln!("[egui_tty] {error}");
}
}
#[derive(Clone, Copy, PartialEq)]
struct CellStyle {
fg: Color32,
bold: bool,
italic: bool,
underline: bool,
strikethrough: bool,
}
struct Run {
style: CellStyle,
text: String,
}
impl Run {
fn new(style: CellStyle, glyph: &str) -> Self {
Self {
style,
text: glyph.to_string(),
}
}
fn flush(&mut self, job: &mut LayoutJob, style: &TerminalStyle) {
if self.text.is_empty() {
return;
}
let mut format = TextFormat {
font_id: style.font.clone(),
color: self.style.fg,
italics: self.style.italic,
..Default::default()
};
if self.style.underline {
format.underline = Stroke::new(1.0, self.style.fg);
}
if self.style.strikethrough {
format.strikethrough = Stroke::new(1.0, self.style.fg);
}
if self.style.bold {
format.color = mix(self.style.fg, style.bold_ink);
}
job.append(&self.text, 0.0, format);
self.text.clear();
}
}
fn mix(color: Color32, toward: Color32) -> Color32 {
let mix = |a: u8, b: u8| ((u16::from(a) + u16::from(b)) / 2) as u8;
Color32::from_rgb(
mix(color.r(), toward.r()),
mix(color.g(), toward.g()),
mix(color.b(), toward.b()),
)
}
fn color_of(rgb: RgbColor) -> Color32 {
Color32::from_rgb(rgb.r, rgb.g, rgb.b)
}
pub fn cell_size(painter: &egui::Painter, font: &FontId) -> egui::Vec2 {
let galley = painter.layout_no_wrap("M".to_string(), font.clone(), Color32::WHITE);
vec2(galley.size().x.max(1.0), galley.size().y.max(1.0))
}
#[cfg(test)]
mod tests {
use std::sync::{Mutex, mpsc};
use super::*;
#[derive(Default)]
struct Recorder(Mutex<Vec<u8>>);
impl Tty for Recorder {
fn write(&self, bytes: &[u8]) -> Result<()> {
self.0.lock().unwrap().extend_from_slice(bytes);
Ok(())
}
fn resize(&self, _cols: u16, _rows: u16) -> Result<()> {
Ok(())
}
}
fn encoded(key: key::Key, mods: key::Mods, text: Option<&str>) -> Vec<u8> {
encoded_with(key, mods, text, b"")
}
fn encoded_with(
key: key::Key,
mods: key::Mods,
text: Option<&str>,
asked_for: &[u8],
) -> Vec<u8> {
let (writer, output) = mpsc::channel();
let mut terminal = Terminal::new(TtyStream {
output,
tty: Arc::new(Recorder::default()) as Arc<dyn Tty>,
})
.expect("expected a terminal");
if !asked_for.is_empty() {
writer.send(asked_for.to_vec()).expect("expected a listener");
terminal.poll();
}
drop(writer);
terminal.encoder.set_options_from_terminal(&terminal.emulator);
let mut out = Vec::new();
terminal
.encode_key(key, mods, text.map(str::to_string), false, &mut out)
.expect("expected the keystroke to encode");
out
}
#[test]
fn the_editing_chords_are_sent_as_what_a_shell_binds() {
assert_eq!(
legacy_editing_chord(key::Key::ArrowLeft, key::Mods::CTRL),
Some(b"\x1bb".as_slice())
);
assert_eq!(
legacy_editing_chord(key::Key::ArrowRight, key::Mods::CTRL),
Some(b"\x1bf".as_slice())
);
assert_eq!(
legacy_editing_chord(key::Key::ArrowLeft, key::Mods::SUPER),
Some(b"\x01".as_slice())
);
}
#[test]
fn every_other_key_is_left_to_the_encoder() {
assert_eq!(legacy_editing_chord(key::Key::ArrowLeft, key::Mods::empty()), None);
assert_eq!(legacy_editing_chord(key::Key::ArrowUp, key::Mods::CTRL), None);
assert_eq!(legacy_editing_chord(key::Key::A, key::Mods::CTRL), None);
assert_eq!(
legacy_editing_chord(key::Key::ArrowLeft, key::Mods::CTRL | key::Mods::SHIFT),
None
);
}
#[test]
fn a_program_that_asked_for_the_kitty_protocol_reads_the_chord_itself() {
let (writer, output) = mpsc::channel();
let mut terminal = Terminal::new(TtyStream {
output,
tty: Arc::new(Recorder::default()) as Arc<dyn Tty>,
})
.expect("expected a terminal");
assert!(
!terminal.reads_the_real_chord(),
"a shell asks for nothing, and is sent what it binds"
);
writer
.send(b"\x1b[>1u".to_vec())
.expect("expected a listener");
terminal.poll();
assert!(
terminal.reads_the_real_chord(),
"a program that turned the protocol on should be sent the chord"
);
}
#[test]
fn a_plain_letter_is_sent_as_itself() {
assert_eq!(encoded(key::Key::A, key::Mods::empty(), Some("a")), b"a");
}
#[test]
fn a_shifted_letter_is_sent_as_the_capital() {
assert_eq!(encoded(key::Key::A, key::Mods::SHIFT, Some("A")), b"A");
}
#[test]
fn shifted_punctuation_is_sent_as_the_character_it_types() {
assert_eq!(encoded(key::Key::Slash, key::Mods::SHIFT, Some("?")), b"?");
}
#[test]
fn the_kitty_protocol_still_sends_the_character_that_was_typed() {
let bytes = encoded_with(key::Key::Slash, key::Mods::SHIFT, Some("?"), b"\x1b[>1u");
assert_eq!(
String::from_utf8_lossy(&bytes),
"?",
"a question mark should reach the program as a question mark"
);
}
#[test]
fn the_shifted_characters_of_the_number_row_survive_the_kitty_protocol() {
for (key, unshifted, typed) in [
(key::Key::Digit9, '9', "("),
(key::Key::Digit0, '0', ")"),
(key::Key::Digit1, '1', "!"),
(key::Key::Digit8, '8', "*"),
(key::Key::Minus, '-', "_"),
(key::Key::Equal, '=', "+"),
] {
let _ = unshifted;
let bytes = encoded_with(key, key::Mods::SHIFT, Some(typed), b"\x1b[>1u");
assert_eq!(
String::from_utf8_lossy(&bytes),
typed,
"{typed} should reach the program as itself"
);
}
}
#[test]
fn the_kitty_protocol_still_reports_shift_when_it_typed_nothing() {
let bytes = encoded_with(key::Key::Tab, key::Mods::SHIFT, None, b"\x1b[>1u");
let text = String::from_utf8_lossy(&bytes).to_string();
assert!(text.contains(";2"), "shift should still be reported: {text:?}");
}
#[test]
fn a_control_combo_is_a_command_rather_than_text() {
assert_eq!(encoded(key::Key::C, key::Mods::CTRL, None), b"\x03");
}
}