use std::cell::RefCell;
use std::sync::{Arc, Mutex};
use super::*;
use crate::event::{ProgramStatusCapabilities, SettingReport};
use crate::text::TextSurface;
#[cfg(any(unix, windows))]
fn null_input() -> std::io::PipeReader {
let (reader, _writer) = std::io::pipe().unwrap();
reader
}
#[derive(Clone, Copy)]
struct TestOut<'a>(&'a RefCell<Vec<u8>>);
impl Write for TestOut<'_> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.borrow_mut().extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
fn written(buf: &RefCell<Vec<u8>>) -> String {
String::from_utf8_lossy(&buf.borrow()).into_owned()
}
#[test]
fn extended_cursor_position_request_flushes() {
let out = RefCell::new(Vec::new());
let mut program = Program::for_test(&out, (80, 24));
program.request_extended_cursor_position().unwrap();
assert_eq!(written(&out), "\x1b[?6n");
program.request_cursor_position().unwrap();
assert_eq!(written(&out), "\x1b[?6n\x1b[6n");
}
impl<'a> Program<std::io::PipeReader, TestOut<'a>> {
fn for_test(buf: &'a RefCell<Vec<u8>>, size: (u16, u16)) -> Self {
Self::for_test_with_input(buf, size, null_input())
}
fn for_test_with_input(
buf: &'a RefCell<Vec<u8>>,
size: (u16, u16),
input: std::io::PipeReader,
) -> Self {
let env = crate::terminal::EnvList::from_process();
let writer = TestOut(buf);
let terminal = crate::terminal::Terminal::from_parts(null_input(), writer, env);
let color_profile = crate::color::Profile::detect_from(terminal.env(), true);
let optimizations = Optimizations::from_env(terminal.env());
let mut screen = Screen::new(writer, size);
screen.set_color_profile(color_profile);
screen.set_optimizations(optimizations);
let source = Arc::new(Mutex::new(crate::event::EventSource::new(input).unwrap()));
#[cfg(windows)]
let source_waker = source.lock().unwrap().waker();
Self {
terminal,
screen,
source,
#[cfg(windows)]
source_waker,
unread: VecDeque::new(),
state: state::State::default(),
caps: Capabilities::default(),
options: ProgramOptions::default(),
window_cells: None,
window_pixels: None,
cell_pixels: None,
origin: Position::ORIGIN,
origin_queries_pending: 0,
}
}
}
#[test]
fn decoder_flags_delegate_without_changing_options_or_terminal_modes() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (20, 1));
program.options.legacy_keys = DecoderFlags::CTRL_M;
program
.event_source()
.lock()
.unwrap()
.set_decoder_flags(DecoderFlags::CTRL_M);
assert_eq!(program.decoder_flags(), DecoderFlags::CTRL_M);
for flags in [
DecoderFlags::CTRL_I | DecoderFlags::LF_IS_ENTER,
DecoderFlags::empty(),
DecoderFlags::all(),
] {
program.set_decoder_flags(flags);
assert_eq!(program.decoder_flags(), flags);
assert_eq!(program.source.lock().unwrap().decoder_flags(), flags);
assert_eq!(program.options.legacy_keys, DecoderFlags::CTRL_M);
assert!(program.state.chosen.is_empty());
assert!(!program.backspace_mode());
program.screen.flush().unwrap();
assert!(buf.borrow().is_empty());
}
}
#[cfg(unix)]
#[test]
fn shared_source_paste_timeout_can_change_during_a_paste() {
let buf = RefCell::new(Vec::new());
let (reader, mut writer) = std::io::pipe().unwrap();
let mut program = Program::for_test_with_input(&buf, (20, 1), reader);
let source = program.event_source();
source
.lock()
.unwrap()
.set_paste_idle_timeout(Some(Duration::ZERO));
assert!(!program.poll_event(Some(Duration::ZERO)).unwrap());
writer.write_all(b"\x1b[200~hello\x1b[20").unwrap();
assert_eq!(program.read_event().unwrap(), Event::PasteStart);
assert_eq!(
program.read_event().unwrap(),
Event::PasteChunk(b"hello".to_vec()),
);
source.lock().unwrap().set_paste_idle_timeout(None);
assert!(!program.poll_event(Some(Duration::ZERO)).unwrap());
source
.lock()
.unwrap()
.set_paste_idle_timeout(Some(Duration::from_secs(60)));
assert!(!program.poll_event(Some(Duration::ZERO)).unwrap());
source
.lock()
.unwrap()
.set_paste_idle_timeout(Some(Duration::ZERO));
assert_eq!(
program.read_event().unwrap(),
Event::PasteChunk(b"\x1b[20".to_vec()),
);
assert_eq!(
program.read_event().unwrap(),
Event::PasteEnd { complete: false }
);
writer.write_all(b"x").unwrap();
assert!(matches!(
program.read_event().unwrap(),
Event::KeyPress(key) if key.code == crate::event::KeyCode::Char('x')
));
}
#[cfg(unix)]
#[test]
fn runtime_decoder_flags_apply_only_to_future_decoding() {
use crate::event::KeyCode;
let buf = RefCell::new(Vec::new());
let (reader, mut writer) = std::io::pipe().unwrap();
let mut program = Program::for_test_with_input(&buf, (20, 1), reader);
writer.write_all(b"\t\t").unwrap();
assert!(program.poll_event(Some(Duration::from_secs(1))).unwrap());
let tab = program.read_event().unwrap();
assert!(matches!(&tab, Event::KeyPress(key) if key.code == KeyCode::Tab));
program.unread_event(tab.clone());
program.set_decoder_flags(DecoderFlags::CTRL_I);
assert_eq!(program.try_read_event().unwrap(), Some(tab.clone()));
assert_eq!(program.try_read_event().unwrap(), Some(tab.clone()));
assert_eq!(program.try_read_event().unwrap(), None);
writer.write_all(b"\t").unwrap();
assert!(matches!(program.read_event().unwrap(), Event::KeyPress(key) if key.matches("ctrl+i")));
program.set_decoder_flags(DecoderFlags::empty());
writer.write_all(b"\t").unwrap();
assert_eq!(program.read_event().unwrap(), tab);
assert!(program.options.legacy_keys.is_empty());
assert!(buf.borrow().is_empty());
}
#[test]
fn backspace_mode_setter_and_lifecycle() {
use crate::ansi::mode::Mode;
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (20, 1));
assert!(!program.backspace_mode());
assert!(!program.options.query_backspace_mode);
for enabled in [true, false] {
buf.borrow_mut().clear();
program.set_backspace_mode(enabled).unwrap();
assert_eq!(program.backspace_mode(), enabled);
assert_eq!(
written(&buf),
if enabled { "\x1b[?67h" } else { "\x1b[?67l" }
);
assert_eq!(program.state.backspace_mode, enabled);
assert!(program.state.chosen.contains(&Mode::BACKARROW_KEY));
assert!(!program.options.query_backspace_mode);
assert!(program.options.legacy_keys.is_empty());
buf.borrow_mut().clear();
program.reset().unwrap();
program.screen.flush().unwrap();
assert!(written(&buf).contains("\x1b[?67l"));
assert!(!program.backspace_mode());
assert_eq!(program.state.backspace_mode, enabled);
buf.borrow_mut().clear();
program.restore().unwrap();
program.screen.flush().unwrap();
assert!(written(&buf).contains(if enabled { "\x1b[?67h" } else { "\x1b[?67l" }));
assert_eq!(program.backspace_mode(), enabled);
}
}
#[test]
fn backspace_mode_query_is_optional_and_preserves_options() {
use crate::terminal::{EnvList, Terminal};
for apple in [false, true] {
for query in [false, true] {
let buf = RefCell::new(Vec::new());
let input = null_input();
let terminal = Terminal::from_parts(
&input,
TestOut(&buf),
EnvList::from_pairs([(
"TERM_PROGRAM",
if apple { "Apple_Terminal" } else { "xterm" },
)]),
);
let mut program = Program::with_render(terminal, (20, 1)).unwrap();
program.options.query_backspace_mode = query;
program.options.legacy_keys = DecoderFlags::CTRL_BACKSPACE;
program.query_capabilities(b"extra").unwrap();
let output = written(&buf);
assert_eq!(
output.matches("\x1b[?67$p").count(),
usize::from(query && !apple)
);
assert!(output.ends_with("extra\x1b[c"));
assert!(!output.contains("\x1b[?67h"));
assert!(!output.contains("\x1b[?67l"));
assert_eq!(program.options.query_backspace_mode, query);
assert_eq!(program.options.legacy_keys, DecoderFlags::CTRL_BACKSPACE);
}
}
}
#[cfg(all(unix, not(target_os = "l4re")))]
#[test]
fn query_options_do_not_query_during_init() {
use crate::terminal::{EnvList, Terminal};
use crate::testutil::{drain, open_pty_pair};
let Some((master, slave)) = open_pty_pair() else {
return;
};
let terminal = Terminal::new(&slave, &slave, EnvList::new());
let mut program = Program::new(terminal).unwrap();
program
.init_with(ProgramOptions {
query_backspace_mode: true,
query_foreground_color: true,
query_background_color: true,
query_cursor_color: true,
query_palette_colors: vec![0, 15, 255],
query_program_status: true,
legacy_keys: DecoderFlags::CTRL_BACKSPACE,
..ProgramOptions::default()
})
.unwrap();
assert!(program.options.query_backspace_mode);
assert!(program.options.query_foreground_color);
assert!(program.options.query_background_color);
assert!(program.options.query_cursor_color);
assert_eq!(program.options.query_palette_colors, [0, 15, 255]);
assert!(program.options.query_program_status);
assert_eq!(program.options.legacy_keys, DecoderFlags::CTRL_BACKSPACE);
assert!(!program.backspace_mode());
let output = drain(&master);
let output = String::from_utf8_lossy(&output);
for query in [
"\x1b[?67",
"\x1b]10;?",
"\x1b]11;?",
"\x1b]12;?",
"\x1b]4;",
"\x1b]7501;",
] {
assert!(!output.contains(query));
}
program.finish().unwrap();
}
#[test]
fn color_queries_are_optional_and_preserve_options() {
use crate::terminal::{EnvList, Terminal};
let defaults = ProgramOptions::default();
assert!(!defaults.query_foreground_color);
assert!(!defaults.query_background_color);
assert!(!defaults.query_cursor_color);
assert!(defaults.query_palette_colors.is_empty());
for apple in [false, true] {
for mask in 0..8 {
for indices in [vec![], vec![255, 0, 15, 15]] {
let buf = RefCell::new(Vec::new());
let input = null_input();
let terminal = Terminal::from_parts(
&input,
TestOut(&buf),
EnvList::from_pairs([(
"TERM_PROGRAM",
if apple { "Apple_Terminal" } else { "xterm" },
)]),
);
let mut program = Program::with_render(terminal, (20, 1)).unwrap();
program.options.query_foreground_color = mask & 1 != 0;
program.options.query_background_color = mask & 2 != 0;
program.options.query_cursor_color = mask & 4 != 0;
program.options.query_palette_colors = indices.clone();
program.query_capabilities(b"extra").unwrap();
let output = written(&buf);
let mut expected = String::new();
for (enabled, query) in [
(mask & 1 != 0, "\x1b]10;?\x07"),
(mask & 2 != 0, "\x1b]11;?\x07"),
(mask & 4 != 0, "\x1b]12;?\x07"),
] {
assert_eq!(output.matches(query).count(), usize::from(enabled));
if enabled {
expected.push_str(query);
}
}
for index in &indices {
expected.push_str(&format!("\x1b]4;{index};?\x07"));
}
assert_eq!(output.matches("\x1b]4;").count(), indices.len());
assert!(output.ends_with(&format!("{expected}extra\x1b[c")));
assert_eq!(program.options.query_foreground_color, mask & 1 != 0);
assert_eq!(program.options.query_background_color, mask & 2 != 0);
assert_eq!(program.options.query_cursor_color, mask & 4 != 0);
assert_eq!(program.options.query_palette_colors, indices);
}
}
}
}
#[cfg(unix)]
#[test]
fn backspace_mode_reports_do_not_rewind_or_own_the_mode() {
use crate::ansi::mode::{Mode, ModeSetting};
let buf = RefCell::new(Vec::new());
let (reader, mut writer) = std::io::pipe().unwrap();
let mut program = Program::for_test_with_input(&buf, (20, 1), reader);
writer
.write_all(b"\x1b[?67;1$y\x08\x1b[?67;2$y\x08")
.unwrap();
assert!(program.poll_event(Some(Duration::from_secs(1))).unwrap());
assert!(!program.backspace_mode());
let report = program.read_event().unwrap();
assert_eq!(
program.capabilities().mode(Mode::BACKARROW_KEY),
Some(ModeSetting::Set)
);
assert!(
program.backspace_mode(),
"only the first report was applied"
);
assert!(
matches!(program.read_event().unwrap(), Event::KeyPress(k) if k.code == crate::event::KeyCode::Char('h')),
"already queued keys keep their decoded values"
);
program.read_event().unwrap();
program.read_event().unwrap();
program.unread_event(report);
program.read_event().unwrap();
assert!(!program.backspace_mode());
writer.write_all(b"\x1b[?67;1$y").unwrap();
program.read_event().unwrap();
assert!(program.backspace_mode());
writer.write_all(b"\x08").unwrap();
assert!(
matches!(program.read_event().unwrap(), Event::KeyPress(k) if k.code == crate::event::KeyCode::Backspace)
);
assert!(!program.state.chosen.contains(&Mode::BACKARROW_KEY));
program.reset().unwrap();
program.restore().unwrap();
program.screen.flush().unwrap();
assert!(!written(&buf).contains("\x1b[?67"));
assert!(
program.backspace_mode(),
"discovery alone must not reset the mode"
);
program.set_backspace_mode(false).unwrap();
writer.write_all(b"\x1b[?67;1$y").unwrap();
program.read_event().unwrap();
assert!(
program.backspace_mode(),
"later reports still update decoding"
);
assert!(
!program.state.backspace_mode,
"the explicit selection remains"
);
program.restore().unwrap();
assert!(!program.backspace_mode());
}
#[test]
fn backspace_mode_observation_applies_only_recognized_backarrow_reports() {
use crate::ansi::mode::{Mode, ModeSetting};
for initial in [false, true] {
for mode in [Mode::BACKARROW_KEY, Mode::Ansi(67), Mode::Dec(66)] {
for setting in [
ModeSetting::NotRecognized,
ModeSetting::Set,
ModeSetting::Reset,
ModeSetting::PermanentlySet,
ModeSetting::PermanentlyReset,
] {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (20, 1));
program.source.lock().unwrap().set_backspace_mode(initial);
program
.observe_event(&Event::ModeReport { mode, setting })
.unwrap();
let expected = if mode == Mode::BACKARROW_KEY && setting.is_recognized() {
setting.is_set()
} else {
initial
};
assert_eq!(program.backspace_mode(), expected);
assert_eq!(program.capabilities().mode(mode), Some(setting));
assert!(!program.state.chosen.contains(&Mode::BACKARROW_KEY));
assert!(buf.borrow().is_empty());
}
}
}
}
#[test]
fn reset_and_restore_round_trip_grapheme_clusters() {
let buf = RefCell::new(Vec::new());
{
let mut program = Program::for_test(&buf, (20, 1));
program.enable_grapheme_clusters().unwrap();
assert!(program.screen().grapheme_clusters());
program.reset().unwrap();
assert!(program.screen().grapheme_clusters());
program.restore().unwrap();
program.screen_mut().flush().unwrap();
}
let out = written(&buf);
assert!(out.matches("\x1b[?2027h").count() >= 2);
assert!(out.contains("\x1b[?2027l"));
}
#[cfg(all(unix, not(target_os = "l4re")))]
#[test]
fn autoresize_at_the_same_size_does_not_repaint() {
use std::os::fd::AsRawFd;
let Some((master, slave)) = crate::testutil::open_pty_pair() else {
return;
};
assert_eq!(
unsafe { libc::fcntl(master.as_raw_fd(), libc::F_SETFL, libc::O_NONBLOCK) },
0,
"set O_NONBLOCK on the pty master: {}",
std::io::Error::last_os_error()
);
let drain = || {
let mut out = Vec::new();
let mut buf = [0u8; 8192];
loop {
let n = unsafe { libc::read(master.as_raw_fd(), buf.as_mut_ptr().cast(), buf.len()) };
if n > 0 {
out.extend_from_slice(&buf[..n as usize]);
continue;
}
if n == 0 {
break;
}
let err = std::io::Error::last_os_error();
match err.kind() {
std::io::ErrorKind::WouldBlock => break,
std::io::ErrorKind::Interrupted => continue,
_ => panic!("read from the pty master: {err}"),
}
}
String::from_utf8_lossy(&out).into_owned()
};
let set_size = |rows: u16, cols: u16| {
let ws = libc::winsize {
ws_row: rows,
ws_col: cols,
ws_xpixel: 0,
ws_ypixel: 0,
};
assert_eq!(
unsafe { libc::ioctl(slave.as_raw_fd(), libc::TIOCSWINSZ, &ws) },
0,
"TIOCSWINSZ on a fresh pty slave: {}",
std::io::Error::last_os_error()
);
};
set_size(24, 80);
let term = crate::terminal::Terminal::new(&slave, &slave, crate::terminal::EnvList::new());
let mut program = Program::new(term).expect("Program::new over a pty slave");
program.screen_mut().set_fullscreen(true);
program.autoresize().expect("initial autoresize");
program
.screen_mut()
.set_str((0, 0), "hello", crate::style::Style::default());
program.screen_mut().render().expect("first render");
program.screen_mut().flush().expect("first flush");
assert!(
drain().contains("hello"),
"the first frame must draw the tracked contents"
);
program.autoresize().expect("same-size autoresize");
program.screen_mut().render().expect("second render");
program.screen_mut().flush().expect("second flush");
assert_eq!(drain(), "", "a same-size report must not repaint");
set_size(25, 80);
program.autoresize().expect("taller autoresize");
program.screen_mut().render().expect("third render");
program.screen_mut().flush().expect("third flush");
assert!(
drain().contains("hello"),
"a taller terminal must redraw the tracked contents"
);
set_size(25, 100);
program.autoresize().expect("wider autoresize");
assert_eq!(program.screen().size(), Size::new(100, 25));
program.screen_mut().render().expect("fourth render");
program.screen_mut().flush().expect("fourth flush");
assert!(
drain().contains("hello"),
"a wider terminal must redraw the tracked contents"
);
}
#[cfg(all(unix, not(target_os = "l4re")))]
#[test]
fn autoresize_refits_after_the_report_was_already_observed() {
use std::os::fd::AsRawFd;
let Some((_master, slave)) = crate::testutil::open_pty_pair() else {
return;
};
let set_size = |rows: u16, cols: u16| {
let ws = libc::winsize {
ws_row: rows,
ws_col: cols,
ws_xpixel: 0,
ws_ypixel: 0,
};
assert_eq!(
unsafe { libc::ioctl(slave.as_raw_fd(), libc::TIOCSWINSZ, &ws) },
0,
"TIOCSWINSZ on a fresh pty slave: {}",
std::io::Error::last_os_error()
);
};
set_size(24, 80);
let term = crate::terminal::Terminal::new(&slave, &slave, crate::terminal::EnvList::new());
let mut program = Program::new(term).expect("Program::new over a pty slave");
program.screen_mut().set_fullscreen(true);
program.autoresize().expect("initial autoresize");
assert_eq!(program.screen().size(), Size::new(80, 24));
set_size(30, 80);
program
.observe_event(&Event::Resize(crate::terminal::Winsize {
row: 30,
col: 80,
xpixel: 0,
ypixel: 0,
}))
.expect("observe the in-band resize report");
assert_eq!(
program.window_cells(),
Some(Size::new(80, 30)),
"observing the report refreshes the cache"
);
program.autoresize().expect("autoresize after the report");
assert_eq!(
program.screen().size(),
Size::new(80, 30),
"autoresize must still refit the managed area"
);
}
#[test]
fn set_title_emits_osc_0() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (80, 24));
program.set_title("hi").unwrap();
assert_eq!(written(&buf), "\x1b]0;hi\x1b\\");
}
#[test]
fn set_window_title_emits_osc_2() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (80, 24));
program.set_window_title("hi").unwrap();
assert_eq!(written(&buf), "\x1b]2;hi\x1b\\");
}
#[test]
fn set_icon_title_emits_osc_1() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (80, 24));
program.set_icon_title("hi").unwrap();
assert_eq!(written(&buf), "\x1b]1;hi\x1b\\");
}
#[test]
fn reset_coalesces_equal_titles_into_single_osc_0() {
let buf = RefCell::new(Vec::new());
{
let mut program = Program::for_test(&buf, (80, 24));
program.set_title("App").unwrap();
buf.borrow_mut().clear();
program.reset().unwrap();
program.screen_mut().flush().unwrap();
}
let out = written(&buf);
assert!(
out.contains("\x1b]0;\x1b\\"),
"missing OSC 0 reset: {out:?}"
);
assert!(
!out.contains("\x1b]2;\x1b\\"),
"unexpected OSC 2 reset: {out:?}"
);
assert!(
!out.contains("\x1b]1;\x1b\\"),
"unexpected OSC 1 reset: {out:?}"
);
}
#[test]
fn reset_uses_separate_osc_for_differing_titles() {
let buf = RefCell::new(Vec::new());
{
let mut program = Program::for_test(&buf, (80, 24));
program.set_window_title("Win").unwrap();
program.set_icon_title("Icon").unwrap();
buf.borrow_mut().clear();
program.reset().unwrap();
program.screen_mut().flush().unwrap();
}
let out = written(&buf);
assert!(
out.contains("\x1b]2;\x1b\\"),
"missing OSC 2 reset: {out:?}"
);
assert!(
out.contains("\x1b]1;\x1b\\"),
"missing OSC 1 reset: {out:?}"
);
assert!(
!out.contains("\x1b]0;\x1b\\"),
"unexpected OSC 0 reset: {out:?}"
);
}
#[test]
fn restore_coalesces_equal_titles_into_single_osc_0() {
let buf = RefCell::new(Vec::new());
{
let mut program = Program::for_test(&buf, (80, 24));
program.set_title("App").unwrap();
buf.borrow_mut().clear();
program.restore().unwrap();
program.screen_mut().flush().unwrap();
}
let out = written(&buf);
assert!(
out.contains("\x1b]0;App\x1b\\"),
"missing OSC 0 restore: {out:?}"
);
assert!(
!out.contains("\x1b]2;App"),
"unexpected OSC 2 restore: {out:?}"
);
assert!(
!out.contains("\x1b]1;App"),
"unexpected OSC 1 restore: {out:?}"
);
}
#[test]
fn empty_title_clears_state_and_is_not_restored() {
let buf = RefCell::new(Vec::new());
{
let mut program = Program::for_test(&buf, (80, 24));
program.set_title("App").unwrap();
program.set_title("").unwrap();
buf.borrow_mut().clear();
program.restore().unwrap();
program.screen_mut().flush().unwrap();
}
let out = written(&buf);
assert!(
!out.contains("\x1b]0;"),
"title should not be restored: {out:?}"
);
assert!(
!out.contains("\x1b]1;"),
"icon should not be restored: {out:?}"
);
assert!(
!out.contains("\x1b]2;"),
"window should not be restored: {out:?}"
);
}
#[test]
fn set_progress_state_emits_osc_9_4() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (80, 24));
program
.set_progress_state(ProgressState::Normal(42))
.unwrap();
assert_eq!(written(&buf), "\x1b]9;4;1;42\x07");
}
#[test]
fn program_status_reports_flush_and_survive_reset_restore() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (20, 1));
for state in [
ProgramStatusState::IDLE,
ProgramStatusState::WORKING,
ProgramStatusState::BLOCKED,
ProgramStatusState::DONE,
ProgramStatusState::ERROR,
] {
let mut report = ProgramStatus::new(state);
report.message = Some("Build");
program.set_program_status(&report).unwrap();
assert!(written(&buf).ends_with(":msg=QnVpbGQ=\x1b\\"));
assert!(program.capabilities().program_status().is_none());
buf.borrow_mut().clear();
program.reset().unwrap();
program.restore().unwrap();
program.teardown().unwrap();
assert!(!written(&buf).contains("7501"));
}
program
.set_program_status(&ProgramStatus::new(ProgramStatusState::CLEAR))
.unwrap();
assert!(written(&buf).ends_with("\x1b]7501;state=clear\x1b\\"));
}
#[test]
fn program_status_query_is_explicit_and_observation_records_support() {
let buf = RefCell::new(Vec::new());
let input = null_input();
let terminal = Terminal::from_parts(&input, TestOut(&buf), crate::terminal::EnvList::new());
let mut program = Program::with_render(terminal, (20, 1)).unwrap();
program.query_capabilities(&[]).unwrap();
assert!(!written(&buf).contains("7501"));
buf.borrow_mut().clear();
program.request_program_status().unwrap();
assert_eq!(written(&buf), "\x1b]7501;?\x1b\\");
assert!(program.capabilities().program_status().is_none());
buf.borrow_mut().clear();
program
.observe_event(&Event::ProgramStatus(ProgramStatusCapabilities {
states: vec![],
kinds: vec![],
}))
.unwrap();
assert!(program.capabilities().program_status().is_some());
assert!(buf.borrow().is_empty());
program
.query_capabilities(crate::ansi::program_status::REQUEST_PROGRAM_STATUS)
.unwrap();
assert!(written(&buf).ends_with("\x1b]7501;?\x1b\\\x1b[c"));
}
#[test]
fn program_status_query_option_preserves_options_and_reply_observation() {
use crate::terminal::EnvList;
assert!(!ProgramOptions::default().query_program_status);
for apple in [false, true] {
for query in [false, true] {
let buf = RefCell::new(Vec::new());
let input = null_input();
let terminal = Terminal::from_parts(
&input,
TestOut(&buf),
EnvList::from_pairs([(
"TERM_PROGRAM",
if apple { "Apple_Terminal" } else { "xterm" },
)]),
);
let mut program = Program::with_render(terminal, (20, 1)).unwrap();
program.options.query_program_status = query;
for _ in 0..2 {
program.query_capabilities(b"extra").unwrap();
let output = written(&buf);
assert_eq!(
output.matches("\x1b]7501;?\x1b\\").count(),
usize::from(query)
);
let suffix = if query {
"\x1b]7501;?\x1b\\extra\x1b[c"
} else {
"extra\x1b[c"
};
assert!(output.ends_with(suffix));
assert_eq!(program.options.query_program_status, query);
buf.borrow_mut().clear();
}
assert!(program.capabilities().program_status().is_none());
program
.observe_event(&Event::ProgramStatus(ProgramStatusCapabilities {
states: vec![],
kinds: vec![],
}))
.unwrap();
assert!(program.capabilities().program_status().is_some());
assert_eq!(program.options.query_program_status, query);
assert!(buf.borrow().is_empty());
}
}
}
#[test]
fn program_status_observation_replaces_both_lists() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (20, 1));
assert_eq!(program.capabilities().program_status(), None);
for (states, kinds) in [
(
vec!["idle".to_owned(), "paused".to_owned()],
vec!["confirm".to_owned()],
),
(vec!["done".to_owned()], vec![]),
(vec![], vec![]),
] {
let event = Event::ProgramStatus(ProgramStatusCapabilities {
states: states.clone(),
kinds: kinds.clone(),
});
program.observe_event(&event).unwrap();
assert_eq!(
program.capabilities().program_status(),
Some(&ProgramStatusCapabilities { states, kinds })
);
assert!(buf.borrow().is_empty());
}
}
#[test]
fn invalid_program_status_emits_nothing() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (20, 1));
let mut report = ProgramStatus::new(ProgramStatusState::WORKING);
report.id = Some("bad:id");
assert_eq!(
program.set_program_status(&report).unwrap_err().kind(),
io::ErrorKind::InvalidInput
);
assert!(buf.borrow().is_empty());
}
#[test]
fn program_status_sends_discovered_extension_names() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (20, 1));
let mut decoder = crate::event::decode::Decoder::new(DecoderFlags::empty());
let events = decoder.parse(b"\x1b]7501;?:states=paused:kinds=confirm\x1b\\");
program.observe_event(&events[0]).unwrap();
let caps = program.capabilities().program_status().unwrap().clone();
let mut report = ProgramStatus::new(ProgramStatusState::new(&caps.states[0]));
program.set_program_status(&report).unwrap();
assert_eq!(written(&buf), "\x1b]7501;state=paused\x1b\\");
buf.borrow_mut().clear();
report.state = ProgramStatusState::BLOCKED;
report.kind = Some(ProgramStatusKind::new(&caps.kinds[0]));
program.set_program_status(&report).unwrap();
assert_eq!(written(&buf), "\x1b]7501;state=blocked:kind=confirm\x1b\\");
buf.borrow_mut().clear();
report.kind = Some(ProgramStatusKind::new("bad:kind"));
assert_eq!(
program.set_program_status(&report).unwrap_err().kind(),
io::ErrorKind::InvalidInput
);
assert!(buf.borrow().is_empty());
}
#[test]
fn program_status_propagates_output_and_flush_errors() {
#[derive(Clone, Copy)]
struct FailingOutput {
fail_write: bool,
}
impl Write for FailingOutput {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
if self.fail_write {
Err(io::ErrorKind::BrokenPipe.into())
} else {
Ok(bytes.len())
}
}
fn flush(&mut self) -> io::Result<()> {
Err(io::ErrorKind::BrokenPipe.into())
}
}
for fail_write in [false, true] {
for query in [false, true] {
let input = null_input();
let terminal = Terminal::from_parts(
&input,
FailingOutput { fail_write },
crate::terminal::EnvList::new(),
);
let mut program = Program::with_render(terminal, (20, 1)).unwrap();
let result = if query {
program.request_program_status()
} else {
program.set_program_status(&ProgramStatus::new(ProgramStatusState::WORKING))
};
assert_eq!(result.unwrap_err().kind(), io::ErrorKind::BrokenPipe);
}
}
}
#[cfg(unix)]
#[test]
fn program_status_synchronous_read_observes_support() {
let (reader, mut writer) = std::io::pipe().unwrap();
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test_with_input(&buf, (20, 1), reader);
writer.write_all(b"\x1b]7501;?\x1b\\").unwrap();
assert_eq!(
program.read_event().unwrap(),
Event::ProgramStatus(ProgramStatusCapabilities {
states: ["idle", "working", "done", "blocked", "error"]
.map(String::from)
.to_vec(),
kinds: ["permission", "question", "auth"]
.map(String::from)
.to_vec(),
})
);
assert!(program.capabilities().program_status().is_some());
assert_eq!(
program.capabilities().program_status().unwrap().states,
["idle", "working", "done", "blocked", "error"]
);
assert_eq!(
program.capabilities().program_status().unwrap().kinds,
["permission", "question", "auth"]
);
writer
.write_all(b"\x1b]7501;?:states=done,paused:kinds=\x07")
.unwrap();
program.read_event().unwrap();
assert_eq!(
program.capabilities().program_status().unwrap().states,
["done", "paused"]
);
assert!(
program
.capabilities()
.program_status()
.unwrap()
.kinds
.is_empty()
);
}
#[test]
fn set_progress_state_clamps_and_maps_each_state() {
for (state, want) in [
(ProgressState::Normal(0), "\x1b]9;4;1;0\x07"),
(ProgressState::Normal(200), "\x1b]9;4;1;100\x07"),
(ProgressState::Error(7), "\x1b]9;4;2;7\x07"),
(ProgressState::Warning(99), "\x1b]9;4;4;99\x07"),
(ProgressState::Indeterminate, "\x1b]9;4;3\x07"),
] {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (80, 24));
program.set_progress_state(state).unwrap();
assert_eq!(written(&buf), want, "wrong bytes for {state:?}");
}
}
#[test]
fn reset_progress_state_emits_removal() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (80, 24));
program
.set_progress_state(ProgressState::Indeterminate)
.unwrap();
program.reset_progress_state().unwrap();
assert!(written(&buf).ends_with("\x1b]9;4;0\x07"));
}
#[test]
fn reset_removes_progress_and_restore_reports_it_again() {
let buf = RefCell::new(Vec::new());
{
let mut program = Program::for_test(&buf, (80, 24));
program
.set_progress_state(ProgressState::Error(64))
.unwrap();
buf.borrow_mut().clear();
program.reset().unwrap();
program.screen_mut().flush().unwrap();
let reset_out = written(&buf);
assert!(
reset_out.contains("\x1b]9;4;0\x07"),
"progress not removed on reset: {reset_out:?}"
);
buf.borrow_mut().clear();
program.restore().unwrap();
program.screen_mut().flush().unwrap();
}
let restore_out = written(&buf);
assert!(
restore_out.contains("\x1b]9;4;2;64\x07"),
"progress not restored: {restore_out:?}"
);
}
#[test]
fn untouched_progress_is_not_reset_or_restored() {
let buf = RefCell::new(Vec::new());
{
let mut program = Program::for_test(&buf, (80, 24));
program.reset().unwrap();
program.restore().unwrap();
program.screen_mut().flush().unwrap();
}
assert!(
!written(&buf).contains("\x1b]9;4"),
"unexpected progress sequence: {:?}",
written(&buf)
);
}
#[test]
fn empty_window_title_clears_only_window_state() {
let buf = RefCell::new(Vec::new());
{
let mut program = Program::for_test(&buf, (80, 24));
program.set_window_title("Win").unwrap();
program.set_icon_title("Icon").unwrap();
program.set_window_title("").unwrap();
buf.borrow_mut().clear();
program.restore().unwrap();
program.screen_mut().flush().unwrap();
}
let out = written(&buf);
assert!(
out.contains("\x1b]1;Icon\x1b\\"),
"icon should be restored: {out:?}"
);
assert!(
!out.contains("\x1b]2;"),
"window should not be restored: {out:?}"
);
assert!(!out.contains("\x1b]0;"), "no OSC 0 expected: {out:?}");
}
#[test]
fn reset_lnm_emits_ansi_mode_20_reset() {
let buf = RefCell::new(Vec::new());
{
let mut program = Program::for_test(&buf, (20, 1));
program.reset_lnm().unwrap();
}
assert_eq!(written(&buf), "\x1b[20l");
}
#[test]
fn reset_tab_stops_uses_terminal_env_with_tabs_enabled_or_disabled() {
let portable = "\r\x1b[3g\x1b[8C\x1bH\x1b[8C\x1bH\r";
for (term, expected) in [
("xterm-kitty", "\x1b[?5W"),
("tmux-256color", portable),
("screen-256color", portable),
] {
for tabs in [false, true] {
let buf = RefCell::new(Vec::new());
let input = null_input();
let terminal = Terminal::from_parts(
&input,
TestOut(&buf),
crate::terminal::EnvList::from_pairs([("TERM", term), ("KITTY_WINDOW_ID", "1")]),
);
let mut program = Program::with_render(terminal, (20, 1)).unwrap();
program
.screen_mut()
.set_optimizations(Optimizations::from_term(term).with_tabs(tabs));
program.reset_tab_stops().unwrap();
assert_eq!(written(&buf), expected, "TERM={term}, tabs={tabs}");
}
}
}
#[test]
fn reset_moves_cursor_to_last_row_inline() {
let buf = RefCell::new(Vec::new());
{
let mut program = Program::for_test(&buf, (20, 5));
program
.screen_mut()
.set_str((0, 0), "hi", crate::style::Style::default());
program.screen_mut().render().unwrap();
program
.screen_mut()
.move_cursor_to(Position::ORIGIN)
.unwrap();
buf.borrow_mut().clear();
program.reset().unwrap();
program.screen_mut().flush().unwrap();
}
let out = written(&buf);
assert!(
out.contains("\x1b[4B") || out.matches('\n').count() >= 4,
"expected reset to walk cursor down 4 rows, got {out:?}"
);
}
#[test]
fn reset_moves_cursor_to_last_row_alt_screen() {
let buf = RefCell::new(Vec::new());
{
let mut program = Program::for_test(&buf, (20, 5));
program.set_alt_screen(true).unwrap();
program
.screen_mut()
.set_str((0, 0), "hi", crate::style::Style::default());
program.screen_mut().render().unwrap();
program.reset().unwrap();
program.screen_mut().flush().unwrap();
}
let out = written(&buf);
let leave = out.find("\x1b[?1049l").expect("alt-program leave");
let head = &out[..leave];
assert!(
head.contains("\x1b[5;1H")
|| head.contains("\x1b[5H")
|| head.contains("\x1b[4B")
|| head.matches('\n').count() >= 4,
"expected cursor move to last row before alt-program leave, head={head:?}"
);
}
#[test]
fn reset_uses_front_buf_height_not_live_height_after_resize() {
let buf = RefCell::new(Vec::new());
{
let mut program = Program::for_test(&buf, (20, 5));
program.set_alt_screen(true).unwrap();
program
.screen_mut()
.set_str((0, 0), "hi", crate::style::Style::default());
program.screen_mut().render().unwrap();
program.screen_mut().resize((20, 50));
program.reset().unwrap();
program.screen_mut().flush().unwrap();
}
let out = written(&buf);
let leave = out.find("\x1b[?1049l").expect("alt-program leave");
let head = &out[..leave];
assert!(
!head.contains("\x1b[50;1H") && !head.contains("\x1b[50H"),
"reset targeted live height instead of front-buf height: head={head:?}"
);
}
#[test]
fn set_kitty_keyboard_flags_always_emits_set() {
use crate::ansi::kitty::KittyKeyboardFlags;
let buf = RefCell::new(Vec::new());
{
let mut program = Program::for_test(&buf, (20, 1));
program
.set_kitty_keyboard(Some(KittyKeyboardFlags::DISAMBIGUATE_ESCAPE_CODES))
.unwrap();
program
.set_kitty_keyboard(Some(KittyKeyboardFlags::DISAMBIGUATE_ESCAPE_CODES))
.unwrap();
program
.set_kitty_keyboard(Some(KittyKeyboardFlags::empty()))
.unwrap();
program.screen_mut().flush().unwrap();
}
let out = written(&buf);
let bits = KittyKeyboardFlags::DISAMBIGUATE_ESCAPE_CODES.bits();
assert_eq!(out.matches(&format!("\x1b[={bits};1u")).count(), 2);
assert!(out.contains("\x1b[=0;1u"));
}
#[test]
fn kitty_keyboard_reapplies_on_alt_screen_toggle() {
use crate::ansi::kitty::KittyKeyboardFlags;
let buf = RefCell::new(Vec::new());
{
let mut program = Program::for_test(&buf, (20, 1));
program
.set_kitty_keyboard(Some(KittyKeyboardFlags::DISAMBIGUATE_ESCAPE_CODES))
.unwrap();
program.set_alt_screen(true).unwrap();
program.set_alt_screen(false).unwrap();
program.screen_mut().flush().unwrap();
}
let out = written(&buf);
let bits = KittyKeyboardFlags::DISAMBIGUATE_ESCAPE_CODES.bits();
assert_eq!(out.matches(&format!("\x1b[={bits};1u")).count(), 3);
}
#[test]
fn reset_clears_kitty_keyboard_on_both_buffers_when_alt_active() {
use crate::ansi::kitty::KittyKeyboardFlags;
let buf = RefCell::new(Vec::new());
{
let mut program = Program::for_test(&buf, (20, 1));
program
.set_kitty_keyboard(Some(KittyKeyboardFlags::DISAMBIGUATE_ESCAPE_CODES))
.unwrap();
program.set_alt_screen(true).unwrap();
program.reset().unwrap();
assert_eq!(
program.state.kitty_keyboard,
KittyKeyboardFlags::DISAMBIGUATE_ESCAPE_CODES
);
program.screen_mut().flush().unwrap();
}
let out = written(&buf);
let leave = out.find("\x1b[?1049l").expect("alt-program leave");
let head = &out[..leave];
let tail = &out[leave..];
assert!(
head.contains("\x1b[=0;1u"),
"alt clear missing: head={head:?}"
);
assert!(
tail.contains("\x1b[=0;1u"),
"main clear missing: tail={tail:?}"
);
}
#[test]
fn restore_reapplies_kitty_keyboard_on_both_buffers_when_alt_active() {
let buf = RefCell::new(Vec::new());
use crate::ansi::kitty::KittyKeyboardFlags;
{
let mut program = Program::for_test(&buf, (20, 1));
program
.set_kitty_keyboard(Some(KittyKeyboardFlags::DISAMBIGUATE_ESCAPE_CODES))
.unwrap();
program.set_alt_screen(true).unwrap();
program.reset().unwrap();
buf.borrow_mut().clear();
program.restore().unwrap();
program.screen_mut().flush().unwrap();
}
let out = written(&buf);
let bits = KittyKeyboardFlags::DISAMBIGUATE_ESCAPE_CODES.bits();
let enter = out.find("\x1b[?1049h").expect("alt-program enter");
let head = &out[..enter];
let tail = &out[enter..];
assert!(
head.contains(&format!("\x1b[={bits};1u")),
"main set missing: head={head:?}"
);
assert!(
tail.contains(&format!("\x1b[={bits};1u")),
"alt set missing: tail={tail:?}"
);
}
#[test]
fn origin_defaults_to_zero_and_maps_mouse() {
let buf = RefCell::new(Vec::new());
use crate::event::{KeyModifiers, Mouse, MouseButton};
let program = Program::for_test(&buf, (10, 3));
assert_eq!(program.origin(), Position::ORIGIN);
let m = Mouse::new(5, 7, MouseButton::Left, KeyModifiers::empty());
let mapped = program.mouse_to_origin(m);
assert_eq!((mapped.x, mapped.y), (5, 7));
}
#[test]
fn origin_maps_mouse_relative_to_stored_origin() {
let buf = RefCell::new(Vec::new());
use crate::event::{KeyModifiers, Mouse, MouseButton};
let mut program = Program::for_test(&buf, (10, 3));
program.origin = Position::new(2, 3);
let m = Mouse::new(6, 5, MouseButton::Left, KeyModifiers::empty());
let mapped = program.mouse_to_origin(m);
assert_eq!((mapped.x, mapped.y), (4, 2));
let above = Mouse::new(1, 1, MouseButton::Left, KeyModifiers::empty());
let mapped = program.mouse_to_origin(above);
assert_eq!((mapped.x, mapped.y), (0, 0));
}
#[test]
fn alt_screen_origin_is_zero() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (10, 3));
program.origin = Position::new(4, 9);
program.screen_mut().set_fullscreen(true);
assert_eq!(program.origin(), Position::ORIGIN);
let m = crate::event::Mouse::new(
6,
11,
crate::event::MouseButton::Left,
crate::event::KeyModifiers::empty(),
);
let mapped = program.mouse_to_origin(m);
assert_eq!((mapped.x, mapped.y), (6, 11));
}
#[test]
fn origin_captured_from_cursor_position_reply() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (10, 3));
program.window_cells = Some(Size::new(10, 8));
program.origin_queries_pending = 1;
program
.observe_event(&Event::CursorPosition {
position: Position::new(2, 7),
page: 0,
})
.unwrap();
assert_eq!(program.origin_queries_pending, 0);
assert_eq!(program.origin(), Position::new(2, 5));
program
.observe_event(&Event::CursorPosition {
position: Position::new(0, 0),
page: 0,
})
.unwrap();
assert_eq!(program.origin(), Position::new(2, 5));
}
#[test]
fn a_burst_of_origin_requests_keeps_the_last_reply() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (10, 3));
program.window_cells = Some(Size::new(10, 20));
program.request_origin().unwrap();
program.request_origin().unwrap();
assert_eq!(program.origin_queries_pending, 2);
program
.observe_event(&Event::CursorPosition {
position: Position::new(0, 4),
page: 0,
})
.unwrap();
program
.observe_event(&Event::CursorPosition {
position: Position::new(0, 9),
page: 0,
})
.unwrap();
assert_eq!(program.origin_queries_pending, 0);
assert_eq!(program.origin(), Position::new(0, 9));
}
#[test]
fn an_unread_event_is_not_observed_a_second_time() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (10, 3));
program.window_cells = Some(Size::new(10, 20));
program.request_origin().unwrap();
program
.observe_event(&Event::CursorPosition {
position: Position::new(0, 4),
page: 0,
})
.unwrap();
assert_eq!(program.origin_queries_pending, 0);
program.request_origin().unwrap();
program.unread_event(Event::CursorPosition {
position: Position::new(0, 4),
page: 0,
});
assert!(program.poll_event(Some(Duration::ZERO)).unwrap());
assert!(matches!(
program.read_event().unwrap(),
Event::CursorPosition { .. }
));
assert_eq!(program.origin_queries_pending, 1);
}
#[cfg(unix)]
#[test]
fn unread_events_preserve_wakes_in_poll_and_read() {
for use_poll in [false, true] {
let (reader, _writer) = std::io::pipe().unwrap();
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test_with_input(&buf, (10, 3), reader);
program.unread_event(Event::PasteStart);
program.source.lock().unwrap().waker().wake().unwrap();
let event = if use_poll {
assert!(program.poll_event(Some(Duration::ZERO)).unwrap());
program.try_read_event().unwrap().unwrap()
} else {
program.read_event().unwrap()
};
assert_eq!(event, Event::PasteStart);
assert_eq!(
program.read_event().unwrap_err().kind(),
io::ErrorKind::Interrupted,
);
assert!(!program.poll_event(Some(Duration::ZERO)).unwrap());
}
}
#[cfg(unix)]
#[test]
fn mode_changes_keep_interrupting_retrying_and_competing_readers() {
use std::sync::mpsc;
for use_poll in [false, true] {
for competing in [false, true] {
let (input, mut output) = std::io::pipe().unwrap();
let source = Arc::new(Mutex::new(EventSource::new(input).unwrap()));
let waker = source.lock().unwrap().waker();
let (started, waiting) = mpsc::sync_channel(0);
let (acquired, finished) = mpsc::sync_channel(0);
std::thread::scope(|scope| {
let reader = scope.spawn(|| {
let mut source = source.lock().unwrap();
started.send(()).unwrap();
let mut results = Vec::new();
for _ in 0..2 {
let result = if use_poll {
source.poll(None).map(|ready| !ready)
} else {
source.read().map(|_| false).or_else(|error| {
if error.kind() == io::ErrorKind::Interrupted {
Ok(true)
} else {
Err(error)
}
})
};
results.push(result.unwrap());
}
results
});
waiting.recv_timeout(Duration::from_secs(2)).unwrap();
let competitor = competing.then(|| {
scope.spawn(|| {
for _ in 0..2 {
if let Err(error) = source.lock().unwrap().read() {
assert_eq!(error.kind(), io::ErrorKind::Interrupted);
}
}
})
});
let transition = scope.spawn(|| {
let _source = lock_source_for_mode_change(&source, &waker).unwrap();
acquired.send(()).unwrap();
});
let result = finished.recv_timeout(Duration::from_secs(2));
output.write_all(b"xxxx").unwrap();
let interrupted = reader.join().unwrap();
if let Some(competitor) = competitor {
competitor.join().unwrap();
}
if result.is_err() {
finished.recv_timeout(Duration::from_secs(2)).unwrap();
}
transition.join().unwrap();
assert!(
result.is_ok(),
"mode change blocked after a reader consumed its wake"
);
assert_eq!(interrupted, [true, true]);
});
}
}
}
#[test]
fn mouse_pixels_map_to_cells_without_running_past_the_grid() {
use crate::event::KeyModifiers;
use crate::event::{Mouse, MouseButton};
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (80, 25));
program.window_pixels = Some(Size::new(1000, 500));
program.window_cells = Some(Size::new(80, 25));
let at = |x, y| {
program
.mouse_pixels_to_cells(Mouse::new(x, y, MouseButton::Left, KeyModifiers::empty()))
.unwrap()
};
assert_eq!((at(999, 499).x, at(999, 499).y), (79, 24));
assert_eq!((at(0, 0).x, at(0, 0).y), (0, 0));
assert_eq!(at(500, 250).x, 40);
}
#[cfg(unix)]
#[test]
fn a_synchronous_read_observes_without_a_second_call() {
for (wire, expected_page) in [
(b"\x1b[5;3R".as_slice(), 0),
(b"\x1b[?5;3R", 0),
(b"\x1b[?5;3;2R", 2),
] {
let (reader, mut writer) = std::io::pipe().unwrap();
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test_with_input(&buf, (10, 3), reader);
program.window_cells = Some(Size::new(10, 20));
program.request_origin().unwrap();
writer.write_all(wire).unwrap();
drop(writer);
let ev = program.read_event().unwrap();
assert!(
matches!(ev, Event::CursorPosition { position, page }
if position == Position::new(2, 4) && page == expected_page),
"{ev:?}"
);
assert_eq!(
program.origin_queries_pending, 0,
"the read did not observe"
);
assert_eq!(program.origin(), Position::new(2, 4));
}
}
#[test]
fn clip_origin_keeps_area_on_screen() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (10, 3));
program.window_cells = Some(Size::new(10, 8));
assert_eq!(
program.clip_origin(Position::new(2, 7)),
Position::new(2, 5)
);
assert_eq!(
program.clip_origin(Position::new(2, 4)),
Position::new(2, 4)
);
program.window_cells = Some(Size::new(10, 3));
assert_eq!(
program.clip_origin(Position::new(0, 6)),
Position::new(0, 0)
);
}
#[test]
fn observing_a_resize_records_the_size_without_writing() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (10, 3));
program.enable_mouse(MouseTracking::empty()).unwrap();
buf.borrow_mut().clear();
let ws = crate::terminal::Winsize {
col: 40,
row: 12,
xpixel: 0,
ypixel: 0,
};
program.observe_event(&Event::Resize(ws)).unwrap();
assert_eq!(program.window_cells, Some(Size::new(40, 12)));
assert_eq!(program.origin_queries_pending, 0);
assert!(written(&buf).is_empty(), "{:?}", written(&buf));
}
#[test]
fn enabling_the_mouse_does_not_query_the_origin() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (10, 3));
program.enable_mouse(MouseTracking::empty()).unwrap();
assert_eq!(program.origin_queries_pending, 0);
assert!(!written(&buf).contains("\x1b[6n"), "{:?}", written(&buf));
}
#[test]
fn request_origin_parks_the_cursor_and_asks_where_it_landed() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (10, 3));
program.window_cells = Some(Size::new(10, 20));
program.request_origin().unwrap();
let out = written(&buf);
assert!(out.ends_with("\x1b[6n"), "{out:?}");
assert_eq!(program.origin_queries_pending, 1);
buf.borrow_mut().clear();
program
.observe_event(&Event::CursorPosition {
position: Position::new(2, 5),
page: 0,
})
.unwrap();
assert_eq!(program.origin(), Position::new(2, 5));
assert_eq!(program.origin_queries_pending, 0);
assert!(written(&buf).is_empty());
}
#[test]
fn request_origin_is_a_no_op_in_fullscreen() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (10, 3));
program.screen_mut().set_fullscreen(true);
program.request_origin().unwrap();
assert_eq!(program.origin_queries_pending, 0);
assert!(written(&buf).is_empty(), "{:?}", written(&buf));
}
#[cfg(all(unix, not(target_os = "l4re")))]
#[test]
fn init_carries_the_legacy_key_choice_to_the_decoder() {
use crate::event::DecoderFlags;
let Some((_master, slave)) = crate::testutil::open_pty_pair() else {
return;
};
let term = crate::terminal::Terminal::new(&slave, &slave, crate::terminal::EnvList::new());
let mut program = Program::new(term).expect("Program::new over a pty slave");
assert!(
program.source.lock().unwrap().decoder_flags().is_empty(),
"each byte reads as the named key until an application says otherwise"
);
program
.init_with(ProgramOptions {
legacy_keys: DecoderFlags::CTRL_M,
..ProgramOptions::default()
})
.expect("init over a pty slave");
assert_eq!(
program.source.lock().unwrap().decoder_flags(),
DecoderFlags::CTRL_M
);
}
#[cfg(all(unix, not(target_os = "l4re")))]
#[test]
fn init_grants_tabs_and_bs_after_entering_raw_mode() {
use std::os::fd::AsRawFd;
let Some((_master, slave)) = crate::testutil::open_pty_pair() else {
return;
};
let mut cooked: libc::termios = unsafe { std::mem::zeroed() };
assert_eq!(
unsafe { libc::tcgetattr(slave.as_raw_fd(), &mut cooked) },
0,
"tcgetattr on a fresh pty slave: {}",
std::io::Error::last_os_error()
);
cooked.c_oflag |= libc::OPOST | libc::ONLCR;
assert_eq!(
unsafe { libc::tcsetattr(slave.as_raw_fd(), libc::TCSANOW, &cooked) },
0,
"tcsetattr on a fresh pty slave: {}",
std::io::Error::last_os_error()
);
let term = crate::terminal::Terminal::new(&slave, &slave, crate::terminal::EnvList::new());
let mut program = Program::new(term).expect("Program::new over a pty slave");
let primed = Optimizations::modern()
.with_tabs(false)
.with_bs(false)
.with_onlcr(true);
program.screen_mut().set_optimizations(primed);
program
.init_with(ProgramOptions::default())
.expect("init over a pty slave");
assert_tabs_and_bs_granted(program.screen().optimizations(), primed, "init");
program.pause().expect("pause");
assert_eq!(
unsafe { libc::tcsetattr(slave.as_raw_fd(), libc::TCSANOW, &cooked) },
0,
"restoring cooked mode while paused: {}",
std::io::Error::last_os_error()
);
program.screen_mut().set_optimizations(primed);
program.resume().expect("resume");
assert_tabs_and_bs_granted(program.screen().optimizations(), primed, "resume");
}
#[cfg(windows)]
#[test]
fn failed_raw_mode_entry_does_not_enable_vt_input() {
let (reader, writer) = std::io::pipe().unwrap();
for resume in [false, true] {
let terminal = Terminal::new(&reader, &writer, crate::terminal::EnvList::new());
let mut program = Program::with_render(terminal, (80, 24)).unwrap();
let result = if resume {
program.resume()
} else {
program.init()
};
assert!(result.is_err());
assert!(!program.source.lock().unwrap().vt_input());
}
}
#[cfg(all(unix, not(target_os = "l4re")))]
fn assert_tabs_and_bs_granted(got: Optimizations, primed: Optimizations, phase: &str) {
assert_eq!(
got,
primed.with_tabs(true).with_bs(true),
"{phase} must grant TABS and BS and change nothing else"
);
}
#[cfg(all(unix, not(target_os = "l4re")))]
mod lnm {
use super::*;
use crate::terminal::{EnvList, Terminal};
use crate::testutil::{drain, open_pty_pair};
fn init_bytes_over_pty(f: impl FnOnce(&mut Program<&std::fs::File, &std::fs::File>)) -> String {
let (Some((_ma, input)), Some((mb, out))) = (open_pty_pair(), open_pty_pair()) else {
return String::new();
};
let terminal = Terminal::new(&input, &out, EnvList::from_pairs([("TERM", "xterm")]));
let mut program = Program::new(terminal).expect("program over two ptys");
f(&mut program);
String::from_utf8_lossy(&drain(&mb)).into_owned()
}
#[test]
fn init_resets_lnm() {
let out = init_bytes_over_pty(|program| {
program.init_with(ProgramOptions::default()).expect("init");
});
if out.is_empty() {
return; }
assert!(out.contains("\x1b[20l"), "init must reset LNM: {out:?}");
}
#[test]
fn resume_resets_lnm() {
let out = init_bytes_over_pty(|program| {
program.init_with(ProgramOptions::default()).expect("init");
program.pause().expect("pause");
program.resume().expect("resume");
});
if out.is_empty() {
return; }
assert_eq!(
out.matches("\x1b[20l").count(),
2,
"init and resume must each reset LNM: {out:?}"
);
}
}
#[cfg(all(unix, not(target_os = "l4re")))]
mod teardown_failure {
use super::*;
use crate::terminal::{EnvList, Terminal};
use crate::testutil::{open_pty_pair, opost, prime};
use std::cell::Cell;
use std::fs::File;
use std::os::fd::{AsFd, BorrowedFd};
#[derive(Clone, Copy)]
struct Breakable<'a> {
tty: &'a File,
broken: &'a Cell<bool>,
fail_on_flush: bool,
}
impl io::Write for Breakable<'_> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
if self.broken.get() && !self.fail_on_flush {
return Err(io::Error::from(io::ErrorKind::BrokenPipe));
}
(&*self.tty).write(buf)
}
fn flush(&mut self) -> io::Result<()> {
if self.broken.get() {
return Err(io::Error::from(io::ErrorKind::BrokenPipe));
}
(&*self.tty).flush()
}
}
impl AsFd for Breakable<'_> {
fn as_fd(&self) -> BorrowedFd<'_> {
self.tty.as_fd()
}
}
#[test]
fn backspace_mode_write_failure_preserves_selection() {
let Some((_master, tty)) = open_pty_pair() else {
return;
};
for fail_on_flush in [false, true] {
let broken = Cell::new(true);
let output = Breakable {
tty: &tty,
broken: &broken,
fail_on_flush,
};
let terminal = Terminal::new(&tty, output, EnvList::new());
let mut program = Program::new(terminal).unwrap();
let error = program.set_backspace_mode(true).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::BrokenPipe);
assert!(!program.backspace_mode());
assert!(!program.state.backspace_mode);
assert!(
!program
.state
.chosen
.contains(&crate::ansi::mode::Mode::BACKARROW_KEY)
);
}
}
#[test]
fn finish_restores_the_terminal_even_when_teardown_fails() {
let (Some((_ma, input)), Some((_mb, out))) = (open_pty_pair(), open_pty_pair()) else {
return;
};
prime(&input, true);
prime(&out, true);
let broken = Cell::new(false);
let output = Breakable {
tty: &out,
broken: &broken,
fail_on_flush: false,
};
let terminal = Terminal::new(&input, output, EnvList::from_pairs([("TERM", "xterm")]));
let mut program = Program::new(terminal).expect("program over two ptys");
program.init().expect("init");
assert!(!opost(&input) && !opost(&out), "both halves must be raw");
broken.set(true);
let err = program.finish().expect_err("the teardown flush must fail");
assert_eq!(err.kind(), io::ErrorKind::BrokenPipe);
assert!(
opost(&input) && opost(&out),
"finish must hand the terminal back even when teardown fails"
);
}
}
#[test]
fn enter_and_exit_alt_screen_emit_1049_and_retarget_the_screen() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (80, 24));
program.enter_alt_screen().unwrap();
assert!(program.screen().fullscreen());
assert!(written(&buf).contains("\x1b[?1049h"));
buf.borrow_mut().clear();
program.exit_alt_screen().unwrap();
assert!(!program.screen().fullscreen());
assert!(written(&buf).contains("\x1b[?1049l"));
}
#[test]
fn alt_screen_switch_reasserts_cursor_visibility() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (80, 24));
program.hide_cursor().unwrap();
assert!(!program.screen().cursor_visible());
buf.borrow_mut().clear();
program.enter_alt_screen().unwrap();
let out = written(&buf);
let enter = out.find("\x1b[?1049h").expect("missing DECSET 1049");
assert!(
out[enter..].contains("\x1b[?25l"),
"cursor not re-hidden on the alt buffer: {out:?}"
);
buf.borrow_mut().clear();
program.exit_alt_screen().unwrap();
let out = written(&buf);
let exit = out.find("\x1b[?1049l").expect("missing DECRST 1049");
assert!(
out[exit..].contains("\x1b[?25l"),
"cursor not re-hidden on the normal buffer: {out:?}"
);
}
#[test]
fn redundant_alt_screen_switch_skips_the_per_buffer_fixups() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (80, 24));
program.enter_alt_screen().unwrap();
buf.borrow_mut().clear();
program.enter_alt_screen().unwrap();
assert_eq!(written(&buf), "\x1b[?1049h");
}
#[test]
fn reset_ignores_render_properties_the_program_never_emitted() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (80, 24));
program.screen_mut().set_fullscreen(true);
program.screen_mut().set_cursor_visible(false);
program.screen_mut().set_grapheme_clusters(true);
buf.borrow_mut().clear();
program.reset().unwrap();
program.screen_mut().flush().unwrap();
let out = written(&buf);
assert!(
!out.contains("\x1b[?1049"),
"left a buffer it never entered: {out:?}"
);
assert!(
!out.contains("\x1b[?25h"),
"showed a cursor it never hid: {out:?}"
);
assert!(
!out.contains("\x1b[?2027"),
"reset a mode it never set: {out:?}"
);
}
#[test]
fn reset_undoes_emitted_modes_even_when_render_properties_disagree() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (80, 24));
program.enter_alt_screen().unwrap();
program.hide_cursor().unwrap();
program.enable_grapheme_clusters().unwrap();
program.screen_mut().set_fullscreen(false);
program.screen_mut().set_cursor_visible(true);
program.screen_mut().set_grapheme_clusters(false);
buf.borrow_mut().clear();
program.reset().unwrap();
program.screen_mut().flush().unwrap();
let out = written(&buf);
assert!(
out.contains("\x1b[?1049l"),
"stuck on the alt screen: {out:?}"
);
assert!(out.contains("\x1b[?25h"), "left the cursor hidden: {out:?}");
assert!(
out.contains("\x1b[?2027l"),
"left grapheme mode on: {out:?}"
);
}
#[test]
fn restore_reapplies_the_emitted_render_coupled_modes() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (80, 24));
program.enter_alt_screen().unwrap();
program.hide_cursor().unwrap();
program.enable_grapheme_clusters().unwrap();
buf.borrow_mut().clear();
program.restore().unwrap();
program.screen_mut().flush().unwrap();
let out = written(&buf);
assert!(
out.contains("\x1b[?1049h"),
"did not re-enter the alt screen: {out:?}"
);
assert!(
out.contains("\x1b[?25l"),
"did not re-hide the cursor: {out:?}"
);
assert!(
out.contains("\x1b[?2027h"),
"did not re-enable grapheme mode: {out:?}"
);
}
#[test]
fn prefer_grapheme_clusters_enables_the_mode_when_the_terminal_reports_it() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (20, 1));
assert!(program.options.prefer_grapheme_clusters);
assert!(!program.screen().grapheme_clusters());
program
.observe_event(&Event::ModeReport {
mode: crate::ansi::mode::Mode::UNICODE_CORE,
setting: crate::ansi::mode::ModeSetting::Reset,
})
.unwrap();
program.screen_mut().flush().unwrap();
assert!(
program
.capabilities()
.supports(crate::ansi::mode::Mode::UNICODE_CORE)
);
assert!(program.screen().grapheme_clusters());
assert!(written(&buf).contains("\x1b[?2027h"));
}
#[test]
fn prefer_in_band_resize_enables_the_mode_when_the_terminal_reports_it() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (20, 1));
assert!(program.options.prefer_in_band_resize);
program
.observe_event(&Event::ModeReport {
mode: crate::ansi::mode::Mode::IN_BAND_RESIZE,
setting: crate::ansi::mode::ModeSetting::Reset,
})
.unwrap();
program.screen_mut().flush().unwrap();
assert!(
program
.capabilities()
.supports(crate::ansi::mode::Mode::IN_BAND_RESIZE)
);
assert!(program.state.in_band_resize);
assert!(written(&buf).contains("\x1b[?2048h"));
}
#[test]
fn prefer_flags_off_records_the_capability_without_emitting() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (20, 1));
program.options.prefer_grapheme_clusters = false;
program.options.prefer_in_band_resize = false;
for mode in [
crate::ansi::mode::Mode::UNICODE_CORE,
crate::ansi::mode::Mode::IN_BAND_RESIZE,
] {
program
.observe_event(&Event::ModeReport {
mode,
setting: crate::ansi::mode::ModeSetting::Reset,
})
.unwrap();
}
program.screen_mut().flush().unwrap();
assert!(
program
.capabilities()
.supports(crate::ansi::mode::Mode::UNICODE_CORE)
);
assert!(
program
.capabilities()
.supports(crate::ansi::mode::Mode::IN_BAND_RESIZE)
);
assert!(!program.screen().grapheme_clusters());
assert!(!program.state.in_band_resize);
let out = written(&buf);
assert!(
!out.contains("2027h"),
"emitted 2027 with the flag off: {out:?}"
);
assert!(
!out.contains("2048h"),
"emitted 2048 with the flag off: {out:?}"
);
}
#[test]
fn a_repeated_mode_report_does_not_re_emit_the_mode() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (20, 1));
for _ in 0..3 {
for mode in [
crate::ansi::mode::Mode::UNICODE_CORE,
crate::ansi::mode::Mode::IN_BAND_RESIZE,
] {
program
.observe_event(&Event::ModeReport {
mode,
setting: crate::ansi::mode::ModeSetting::Reset,
})
.unwrap();
}
}
program.screen_mut().flush().unwrap();
let out = written(&buf);
assert_eq!(out.matches("\x1b[?2027h").count(), 1, "{out:?}");
assert_eq!(out.matches("\x1b[?2048h").count(), 1, "{out:?}");
}
#[test]
fn an_unavailable_mode_report_enables_nothing() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (20, 1));
for mode in [
crate::ansi::mode::Mode::UNICODE_CORE,
crate::ansi::mode::Mode::IN_BAND_RESIZE,
] {
program
.observe_event(&Event::ModeReport {
mode,
setting: crate::ansi::mode::ModeSetting::NotRecognized,
})
.unwrap();
}
program.screen_mut().flush().unwrap();
assert!(
!program
.capabilities()
.supports(crate::ansi::mode::Mode::UNICODE_CORE)
);
assert!(
!program
.capabilities()
.supports(crate::ansi::mode::Mode::IN_BAND_RESIZE)
);
assert!(!program.screen().grapheme_clusters());
let out = written(&buf);
assert!(!out.contains("2027h") && !out.contains("2048h"), "{out:?}");
}
#[test]
fn a_preferred_mode_enabled_by_discovery_is_undone_by_reset() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (20, 1));
for mode in [
crate::ansi::mode::Mode::UNICODE_CORE,
crate::ansi::mode::Mode::IN_BAND_RESIZE,
] {
program
.observe_event(&Event::ModeReport {
mode,
setting: crate::ansi::mode::ModeSetting::Reset,
})
.unwrap();
}
buf.borrow_mut().clear();
program.reset().unwrap();
program.screen_mut().flush().unwrap();
let out = written(&buf);
assert!(out.contains("\x1b[?2027l"), "{out:?}");
assert!(out.contains("\x1b[?2048l"), "{out:?}");
}
#[test]
fn capabilities_keep_the_reported_mode_setting_not_just_availability() {
use crate::ansi::mode::{Mode, ModeSetting};
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (20, 1));
for (mode, setting) in [
(Mode::SYNCHRONIZED_OUTPUT, ModeSetting::PermanentlySet),
(Mode::MOUSE_SGR_PIXEL, ModeSetting::Reset),
(Mode::COLUMN_132, ModeSetting::NotRecognized),
] {
program
.observe_event(&Event::ModeReport { mode, setting })
.unwrap();
}
let caps = program.capabilities();
assert_eq!(
caps.mode(Mode::SYNCHRONIZED_OUTPUT),
Some(ModeSetting::PermanentlySet)
);
assert_eq!(caps.mode(Mode::MOUSE_SGR_PIXEL), Some(ModeSetting::Reset));
assert_eq!(
caps.mode(Mode::COLUMN_132),
Some(ModeSetting::NotRecognized)
);
assert_eq!(caps.mode(Mode::AUTO_WRAP), None);
assert!(caps.supports(Mode::SYNCHRONIZED_OUTPUT));
assert!(caps.supports(Mode::MOUSE_SGR_PIXEL));
assert!(!caps.supports(Mode::COLUMN_132));
assert!(!caps.supports(Mode::AUTO_WRAP));
}
#[test]
fn capabilities_record_a_mode_the_program_does_not_act_on() {
use crate::ansi::mode::{Mode, ModeSetting};
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (20, 1));
program
.observe_event(&Event::ModeReport {
mode: Mode::CURSOR_KEYS,
setting: ModeSetting::Set,
})
.unwrap();
assert_eq!(
program.capabilities().mode(Mode::CURSOR_KEYS),
Some(ModeSetting::Set)
);
}
#[test]
fn capabilities_keep_the_raw_primary_da_attributes() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (20, 1));
program
.observe_event(&Event::PrimaryDeviceAttributes(vec![
Some(62),
Some(4),
None,
Some(52),
]))
.unwrap();
let caps = program.capabilities();
assert_eq!(
caps.primary_device_attributes(),
Some([Some(62), Some(4), None, Some(52)].as_slice())
);
}
#[test]
fn primary_device_attributes_are_none_until_the_terminal_answers() {
let buf = RefCell::new(Vec::new());
let program = Program::for_test(&buf, (20, 1));
let caps = program.capabilities();
assert_eq!(caps.primary_device_attributes(), None);
assert_eq!(caps.kitty_keyboard(), None);
assert_eq!(caps.modify_other_keys(), None);
assert_eq!(caps.terminal_name(), None);
assert!(caps.termcap_reports().is_empty());
}
#[test]
fn capabilities_keep_the_reported_kitty_flags_and_modify_other_keys() {
use crate::ansi::kitty::KittyKeyboardFlags;
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (20, 1));
let flags =
KittyKeyboardFlags::DISAMBIGUATE_ESCAPE_CODES | KittyKeyboardFlags::REPORT_EVENT_TYPES;
program
.observe_event(&Event::KittyKeyboardEnhancements(flags))
.unwrap();
program
.observe_event(&Event::ModifyOtherKeys(
crate::event::ModifyOtherKeysMode::Mode2,
))
.unwrap();
let caps = program.capabilities();
assert_eq!(caps.kitty_keyboard(), Some(flags));
assert_eq!(
caps.modify_other_keys(),
Some(crate::event::ModifyOtherKeysMode::Mode2)
);
}
#[test]
fn an_empty_kitty_reply_still_proves_support() {
use crate::ansi::kitty::KittyKeyboardFlags;
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (20, 1));
program
.observe_event(&Event::KittyKeyboardEnhancements(
KittyKeyboardFlags::empty(),
))
.unwrap();
assert_eq!(
program.capabilities().kitty_keyboard(),
Some(KittyKeyboardFlags::empty())
);
}
#[test]
fn a_disabled_modify_other_keys_reply_still_proves_support() {
use crate::event::ModifyOtherKeysMode;
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (20, 1));
program
.observe_event(&Event::ModifyOtherKeys(ModifyOtherKeysMode::Disabled))
.unwrap();
assert_eq!(
program.capabilities().modify_other_keys(),
Some(ModifyOtherKeysMode::Disabled)
);
}
#[test]
fn the_terminal_name_lands_in_capabilities() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (20, 1));
program
.observe_event(&Event::TerminalName("XTerm(380)".to_string()))
.unwrap();
assert_eq!(program.capabilities().terminal_name(), Some("XTerm(380)"));
assert_eq!(program.terminal_name(), Some("XTerm(380)"));
}
#[test]
fn a_later_mode_report_replaces_an_earlier_one() {
use crate::ansi::mode::{Mode, ModeSetting};
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (20, 1));
for setting in [ModeSetting::Reset, ModeSetting::Set] {
program
.observe_event(&Event::ModeReport {
mode: Mode::MOUSE_ANY,
setting,
})
.unwrap();
}
assert_eq!(
program.capabilities().mode(Mode::MOUSE_ANY),
Some(ModeSetting::Set)
);
assert_eq!(program.capabilities().modes().len(), 1);
}
#[test]
fn capabilities_keep_the_raw_secondary_and_tertiary_device_attributes() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (10, 3));
program
.observe_event(&Event::SecondaryDeviceAttributes(vec![
Some(0),
Some(95),
None,
]))
.unwrap();
program
.observe_event(&Event::TertiaryDeviceAttributes("00000000".to_string()))
.unwrap();
let caps = program.capabilities();
assert_eq!(
caps.secondary_device_attributes(),
Some(&[Some(0), Some(95), None][..]),
"DA2 is reported unparsed, empty parameters included"
);
assert_eq!(caps.tertiary_device_attributes(), Some("00000000"));
}
#[test]
fn capabilities_record_the_terminals_own_colors_not_the_overrides() {
use crate::color::Color;
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (10, 3));
let reported = Color::Rgb(0x1e, 0x1e, 0x2e);
program
.observe_event(&Event::BackgroundColor(reported))
.unwrap();
program
.observe_event(&Event::ForegroundColor(Color::Rgb(0xcd, 0xd6, 0xf4)))
.unwrap();
program
.observe_event(&Event::CursorColor(Color::Rgb(0xf5, 0xe0, 0xdc)))
.unwrap();
program
.observe_event(&Event::PaletteColor {
index: 4,
color: Color::Rgb(0, 0, 0xff),
})
.unwrap();
program
.set_background_color(Color::Rgb(0xff, 0, 0))
.unwrap();
let caps = program.capabilities();
assert_eq!(caps.background_color(), Some(reported));
assert_eq!(caps.foreground_color(), Some(Color::Rgb(0xcd, 0xd6, 0xf4)));
assert_eq!(caps.cursor_color(), Some(Color::Rgb(0xf5, 0xe0, 0xdc)));
assert_eq!(caps.palette_color(4), Some(Color::Rgb(0, 0, 0xff)));
assert_eq!(caps.palette_color(5), None);
}
#[test]
fn capabilities_track_the_latest_color_scheme() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (10, 3));
assert_eq!(program.capabilities().color_scheme(), None);
program
.observe_event(&Event::ColorScheme(crate::event::ColorScheme::Dark))
.unwrap();
assert_eq!(
program.capabilities().color_scheme(),
Some(crate::event::ColorScheme::Dark)
);
program
.observe_event(&Event::ColorScheme(crate::event::ColorScheme::Light))
.unwrap();
assert_eq!(
program.capabilities().color_scheme(),
Some(crate::event::ColorScheme::Light)
);
}
#[test]
fn capabilities_keep_termcap_values_and_distinguish_a_no_from_silence() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (10, 3));
program
.observe_event(&Event::Termcap {
recognized: true,
entries: vec![
("TN".to_string(), Some("xterm".to_string())),
("Co".to_string(), Some("256".to_string())),
("kb".to_string(), None),
("kf13".to_string(), Some("\x1b[1;2P".to_string())),
],
})
.unwrap();
program
.observe_event(&Event::Termcap {
recognized: false,
entries: vec![("RGB".to_string(), None)],
})
.unwrap();
let caps = program.capabilities();
assert_eq!(caps.termcap("TN"), Some("xterm"));
assert_eq!(caps.termcap("Co"), Some("256"));
assert_eq!(caps.termcap("kb"), Some(""));
assert!(caps.supports_termcap("kb"));
assert!(!caps.supports_termcap("RGB"));
assert_eq!(caps.termcap_reports().get("RGB"), Some(&None));
assert_eq!(caps.termcap_reports().get("Tc"), None);
assert_eq!(caps.termcap("kf13"), Some("\x1b[1;2P"));
assert_eq!(caps.termcap_reports().len(), 5);
}
#[test]
fn a_decrqss_setting_report_is_not_recorded() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (80, 24));
let before = program.capabilities().clone();
for report in [
SettingReport::Raw("0;1m".into()),
SettingReport::Raw(">4;2m".into()),
SettingReport::Unrecognized,
] {
program
.observe_event(&Event::SettingReport(report))
.unwrap();
}
assert_eq!(program.capabilities(), &before);
}
#[test]
fn a_truecolor_termcap_reply_upgrades_the_color_profile() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (10, 3));
program.screen_mut().set_color_profile(Profile::Ansi256);
program
.observe_event(&Event::Termcap {
recognized: true,
entries: vec![("Tc".to_string(), None)],
})
.unwrap();
assert!(program.capabilities().supports_termcap("Tc"));
assert_eq!(program.screen().color_profile(), Profile::TrueColor);
}
#[test]
fn a_kitty_graphics_response_records_graphics_support() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (10, 3));
assert!(!program.capabilities().kitty_graphics());
program
.observe_event(&Event::KittyGraphics {
options: vec![("i".to_string(), "1".to_string())],
payload: b"OK".to_vec(),
})
.unwrap();
assert!(program.capabilities().kitty_graphics());
}
#[test]
#[cfg(unix)]
fn drag_drop_support_is_observed_without_consuming_the_reply() {
let buf = RefCell::new(Vec::new());
let (reader, mut writer) = std::io::pipe().unwrap();
let terminal = Terminal::from_parts(&reader, TestOut(&buf), crate::terminal::EnvList::new());
let mut program = Program::with_render(terminal, (10, 3)).unwrap();
assert!(!program.capabilities().drag_drop());
writer.write_all(b"\x1b]72;t=m;x\x1b\\").unwrap();
assert!(matches!(
program.read_event().unwrap(),
Event::DragDrop { .. }
));
assert!(!program.capabilities().drag_drop());
program
.query_capabilities(crate::ansi::drag_drop::REQUEST_DRAG_DROP)
.unwrap();
assert!(buf.borrow().ends_with(b"\x1b]72;t=q\x1b\\\x1b[c"));
writer
.write_all(b"\x1b]72;t=q:i=42;future=1\x1b\\")
.unwrap();
assert_eq!(
program.read_event().unwrap(),
Event::DragDrop {
options: vec![("t".into(), "q".into()), ("i".into(), "42".into())],
payload: b"future=1".to_vec(),
}
);
assert!(program.capabilities().drag_drop());
}
#[test]
fn a_reported_cell_size_beats_dividing_the_window_sizes() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (10, 3));
assert_eq!(program.cell_pixels(), None);
program
.observe_event(&Event::WindowCellSize {
width: 10,
height: 4,
})
.unwrap();
program
.observe_event(&Event::WindowPixelSize {
width: 84,
height: 68,
})
.unwrap();
assert_eq!(program.cell_pixels(), Some(Size::new(8, 17)));
program
.observe_event(&Event::CellPixelSize {
width: 8,
height: 16,
})
.unwrap();
assert_eq!(
program.cell_pixels(),
Some(Size::new(8, 16)),
"the terminal's own reply wins over the derived approximation"
);
let mouse = crate::event::Mouse::new(
24,
32,
crate::event::MouseButton::Left,
crate::event::KeyModifiers::empty(),
);
let cells = program.mouse_pixels_to_cells(mouse).unwrap();
assert_eq!((cells.x, cells.y), (3, 2));
}
#[test]
fn a_later_mode_report_does_not_undo_an_explicit_disable() {
use crate::ansi::mode::{Mode, ModeSetting};
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (20, 5));
let report = Event::ModeReport {
mode: Mode::UNICODE_CORE,
setting: ModeSetting::Set,
};
program.observe_event(&report).unwrap();
assert!(program.state.grapheme_clusters, "adopted on discovery");
program.disable_grapheme_clusters().unwrap();
buf.borrow_mut().clear();
program.observe_event(&report).unwrap();
assert!(
!program.state.grapheme_clusters,
"the explicit disable must stand"
);
assert!(
written(&buf).is_empty(),
"and nothing may be written behind the app's back"
);
assert!(
program.options.prefer_grapheme_clusters,
"observing must not rewrite the caller's options"
);
}
#[test]
fn a_first_mode_report_does_not_undo_an_earlier_explicit_disable() {
use crate::ansi::mode::{Mode, ModeSetting};
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (20, 5));
program.disable_grapheme_clusters().unwrap();
program.disable_in_band_resize().unwrap();
program.options.prefer_synchronized_output = false;
program.screen_mut().set_synchronized_output(false);
buf.borrow_mut().clear();
for mode in [
Mode::UNICODE_CORE,
Mode::IN_BAND_RESIZE,
Mode::SYNCHRONIZED_OUTPUT,
] {
program
.observe_event(&Event::ModeReport {
mode,
setting: ModeSetting::Set,
})
.unwrap();
}
program.screen_mut().flush().unwrap();
let out = written(&buf);
assert!(out.is_empty(), "wrote behind the app's back: {out:?}");
assert!(!program.state.grapheme_clusters);
assert!(!program.state.in_band_resize);
assert!(!program.screen().synchronized_output());
assert!(program.capabilities().supports(Mode::UNICODE_CORE));
assert!(program.capabilities().supports(Mode::SYNCHRONIZED_OUTPUT));
}
#[test]
fn reset_and_restore_round_trip_visibility_reports() {
let buf = RefCell::new(Vec::new());
{
let mut program = Program::for_test(&buf, (20, 1));
program.enable_visibility_reports().unwrap();
program.reset().unwrap();
program.restore().unwrap();
program.screen_mut().flush().unwrap();
}
let out = written(&buf);
assert!(
out.matches("\x1b[?2033h").count() >= 2,
"expected enable and restore: {out:?}"
);
assert!(out.contains("\x1b[?2033l"), "expected teardown: {out:?}");
}
#[test]
fn disabled_visibility_reports_are_not_reset_or_restored() {
let buf = RefCell::new(Vec::new());
{
let mut program = Program::for_test(&buf, (20, 1));
program.enable_visibility_reports().unwrap();
program.disable_visibility_reports().unwrap();
buf.borrow_mut().clear();
program.reset().unwrap();
program.restore().unwrap();
program.screen_mut().flush().unwrap();
}
let out = written(&buf);
assert!(
!out.contains("\x1b[?2033"),
"unexpected 2033 traffic: {out:?}"
);
}
#[test]
fn request_visibility_is_a_one_shot_query() {
let buf = RefCell::new(Vec::new());
{
let mut program = Program::for_test(&buf, (80, 24));
program.request_visibility().unwrap();
}
let out = written(&buf);
assert_eq!(out, "\x1b[?998n");
}
#[test]
fn visibility_support_comes_from_the_generic_mode_report() {
use crate::ansi::mode::{Mode, ModeSetting};
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (80, 24));
assert!(!program.capabilities().supports(Mode::VISIBILITY_REPORTS));
program
.observe_event(&Event::ModeReport {
mode: Mode::VISIBILITY_REPORTS,
setting: ModeSetting::Reset,
})
.unwrap();
assert!(program.capabilities().supports(Mode::VISIBILITY_REPORTS));
for setting in [ModeSetting::NotRecognized, ModeSetting::PermanentlyReset] {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (80, 24));
program
.observe_event(&Event::ModeReport {
mode: Mode::VISIBILITY_REPORTS,
setting,
})
.unwrap();
assert!(
!program.capabilities().supports(Mode::VISIBILITY_REPORTS),
"{setting:?} must not count as support"
);
}
}
#[test]
fn request_cursor_style_asks_decrqss_for_decscusr() {
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (10, 3));
program.request_cursor_style().unwrap();
assert_eq!(buf.borrow().as_slice(), b"\x1bP$q q\x1b\\");
}
#[test]
fn reset_cursor_style_hands_the_cursor_back() {
use crate::ansi::cursor::CursorShape;
let buf = RefCell::new(Vec::new());
let mut program = Program::for_test(&buf, (10, 3));
program.set_cursor_style(CursorShape::Bar, true).unwrap();
buf.borrow_mut().clear();
program.reset_cursor_style().unwrap();
assert_eq!(buf.borrow().as_slice(), b"\x1b[0 q");
buf.borrow_mut().clear();
program.reset().unwrap();
program.screen_mut().flush().unwrap();
let out = String::from_utf8_lossy(&buf.borrow()).into_owned();
assert!(!out.contains(" q"), "teardown repeated the reset: {out:?}");
}