use alacritty_terminal::Term;
use alacritty_terminal::event::{Event as AlacEvent, EventListener};
use alacritty_terminal::grid::{Dimensions, Scroll};
use alacritty_terminal::index::{Column, Line, Point, Side};
use alacritty_terminal::selection::{Selection as TracerSelection, SelectionType};
use alacritty_terminal::sync::FairMutex;
use alacritty_terminal::term::cell::Flags;
use alacritty_terminal::term::test::TermSize;
use alacritty_terminal::term::{Config, TermMode};
use alacritty_terminal::vte::ansi::{Color as AnsiColor, NamedColor, Processor, StdSyncHandler};
use anyhow::{Context, Result};
use portable_pty::{CommandBuilder, MasterPty, PtySize, native_pty_system};
use ratatui::{
buffer::Buffer,
layout::Rect,
style::{Color, Modifier, Style},
widgets::{Block, Borders, Widget},
};
use std::io::{Read, Write};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
const SCROLLBACK_LINES: usize = 5000;
#[derive(Clone, Copy, PartialEq)]
pub enum MouseButtonKind {
Left,
Middle,
Right,
WheelUp,
WheelDown,
}
#[derive(Clone, Copy, PartialEq)]
pub enum MouseAction {
Press,
Release,
Motion,
}
#[derive(Clone, Copy, Default)]
pub struct MouseMods {
pub shift: bool,
pub alt: bool,
pub ctrl: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Selection {
pub anchor: (i32, u16),
pub head: (i32, u16),
pub block: bool,
}
struct AltSelAnchor {
rows: Vec<String>,
top: i32,
text: String,
dormant: bool,
visible: Option<Vec<(i32, u16, u16)>>,
ctx_above: Option<String>,
ctx_below: Option<String>,
}
impl Selection {
pub fn new(line: i32, col: u16) -> Self {
Self {
anchor: (line, col),
head: (line, col),
block: false,
}
}
pub fn normalised(&self) -> (i32, u16, i32, u16) {
let (a_l, a_c) = self.anchor;
let (b_l, b_c) = self.head;
if (a_l, a_c) <= (b_l, b_c) {
(a_l, a_c, b_l, b_c)
} else {
(b_l, b_c, a_l, a_c)
}
}
pub fn block_bounds(&self) -> (i32, u16, i32, u16) {
let (a_l, a_c) = self.anchor;
let (b_l, b_c) = self.head;
(a_l.min(b_l), a_c.min(b_c), a_l.max(b_l), a_c.max(b_c))
}
pub fn has_area(&self) -> bool {
self.anchor != self.head
}
}
#[derive(Clone, Default)]
pub struct VoidListener {
pty_response_tx: Option<std::sync::mpsc::Sender<String>>,
size: Option<Arc<std::sync::Mutex<(u16, u16)>>>,
bell: Option<Arc<AtomicBool>>,
}
impl EventListener for VoidListener {
fn send_event(&self, event: AlacEvent) {
match event {
AlacEvent::Bell => {
if let Some(bell) = self.bell.as_ref() {
bell.store(true, Ordering::Release);
}
}
AlacEvent::PtyWrite(text) => {
if let Some(tx) = self.pty_response_tx.as_ref() {
let _ = tx.send(text);
}
}
AlacEvent::TextAreaSizeRequest(cb) => {
let (Some(tx), Some(size)) = (self.pty_response_tx.as_ref(), self.size.as_ref())
else {
return;
};
let (cols, rows) = *size.lock().unwrap();
let ws = alacritty_terminal::event::WindowSize {
num_lines: rows,
num_cols: cols,
cell_width: 1,
cell_height: 1,
};
let _ = tx.send(cb(ws));
}
_ => {}
}
}
}
const STALL_GAP_MS: u64 = 60_000;
#[derive(Clone, Debug)]
struct ScrollClock {
base: i64,
planted: Option<i32>,
hist: i64,
}
impl ScrollClock {
fn new() -> Self {
Self {
base: 0,
planted: None,
hist: 0,
}
}
fn plant_tracer(term: &mut Term<VoidListener>, line: i32) {
let point = Point::new(Line(line), Column(0));
let mut tracer = TracerSelection::new(SelectionType::Simple, point, Side::Left);
tracer.update(point, Side::Right);
term.selection = Some(tracer);
}
fn tracer_line(term: &Term<VoidListener>) -> Option<i32> {
let range = term.selection.as_ref()?.to_range(term)?;
Some(range.start.line.0)
}
fn now(&self, term: &Term<VoidListener>) -> i64 {
if term.mode().contains(TermMode::ALT_SCREEN) {
return self.base;
}
match (self.planted, Self::tracer_line(term)) {
(Some(planted), Some(cur)) => self.base + i64::from(planted - cur),
_ => {
let growth = term.grid().history_size() as i64 - self.hist;
self.base + growth.max(0)
}
}
}
fn tick(&mut self, term: &mut Term<VoidListener>) -> i64 {
let now = self.now(term);
if !term.mode().contains(TermMode::ALT_SCREEN) {
self.base = now;
self.hist = term.grid().history_size() as i64;
let park = if self.hist > 0 { -1 } else { 0 };
Self::plant_tracer(term, park);
self.planted = Some(park);
}
now
}
}
#[derive(Default)]
struct WipeSniffer {
carry: Vec<u8>,
}
const WIPE_CARRY_MAX: usize = 64;
impl WipeSniffer {
fn scan(&mut self, chunk: &[u8], mut alt: bool) -> (bool, bool) {
let mut data = std::mem::take(&mut self.carry);
data.extend_from_slice(chunk);
let mut screen = false;
let mut hist = false;
let mut i = 0;
while i < data.len() {
if data[i] != 0x1b {
i += 1;
continue;
}
let Some(&next) = data.get(i + 1) else {
self.carry = data.split_off(i);
return (screen, hist);
};
match next {
b'c' => {
screen = true;
hist = true;
alt = false;
i += 2;
}
b'[' => {
let mut j = i + 2;
while j < data.len()
&& !(0x40..=0x7e).contains(&data[j])
&& !matches!(data[j], 0x18 | 0x1a | 0x1b)
{
j += 1;
}
if j >= data.len() {
if data.len() - i <= WIPE_CARRY_MAX {
self.carry = data.split_off(i);
}
return (screen, hist);
}
if matches!(data[j], 0x18 | 0x1a | 0x1b) {
i = if data[j] == 0x1b { j } else { j + 1 };
continue;
}
let params = &data[i + 2..j];
match data[j] {
b'J' if params == b"2" && !alt => screen = true,
b'J' if params == b"3" && !alt => hist = true,
fin @ (b'h' | b'l') if params.first() == Some(&b'?') => {
for p in params[1..].split(|&c| c == b';') {
if p == b"47" || p == b"1047" || p == b"1049" {
alt = fin == b'h';
}
}
}
_ => {}
}
i = j + 1;
}
_ => i += 2,
}
}
(screen, hist)
}
}
fn stamp_chunk(
term: &mut Term<VoidListener>,
clock: &mut ScrollClock,
lt: &mut std::collections::BTreeMap<i64, u64>,
prev_id: &mut i64,
now_ms: u64,
) {
if term.mode().contains(TermMode::ALT_SCREEN) {
return;
}
let now = clock.tick(term);
let cur_id = now + i64::from(term.grid().cursor.point.line.0);
let from = (*prev_id).min(cur_id);
for a in from..=cur_id {
lt.insert(a, now_ms);
}
*prev_id = cur_id;
while lt.len() > 210_000 {
lt.pop_first();
}
}
struct PaneAnnotation {
line_rec: i32,
clock_rec: i64,
start: u16,
len: u16,
text: String,
}
pub struct PtyTerminal {
term: Arc<FairMutex<Term<VoidListener>>>,
pty_dirty: Arc<AtomicBool>,
pty_pending_bytes: Arc<AtomicUsize>,
bracketed_paste_enabled: Arc<AtomicBool>,
port_rx: std::sync::mpsc::Receiver<crate::port_detect::PortHit>,
master: Box<dyn MasterPty + Send>,
writer: Arc<std::sync::Mutex<Box<dyn Write + Send>>>,
_child: Box<dyn portable_pty::Child + Send + Sync>,
reader_thread: Option<std::thread::JoinHandle<()>>,
reader_shutdown: Option<std::io::PipeWriter>,
shell_pid: Option<i32>,
uid: u64,
input_seen: bool,
run_pane: bool,
manual_name_seen: bool,
cols: u16,
rows: u16,
size_shared: Arc<std::sync::Mutex<(u16, u16)>>,
pub focused: bool,
pub broadcast_excluded: bool,
pub focus_gradient: bool,
pub theme: crate::theme::Theme,
pub last_area: Rect,
pub last_inner: Rect,
selection: Option<Selection>,
copy_cursor: Option<(i32, u16)>,
sel_scrolled: i64,
clock: Arc<std::sync::Mutex<ScrollClock>>,
alt_sel: Option<AltSelAnchor>,
drag_selecting: bool,
manual_name: Option<String>,
auto_label: String,
search_needle: Option<String>,
search_opts: crate::widgets::search::SearchOpts,
current_match: Option<(i64, i32, usize, usize)>,
bell: Arc<AtomicBool>,
marks: Arc<std::sync::Mutex<Vec<StoredMark>>>,
osc7_cwd: Arc<std::sync::Mutex<Option<std::path::PathBuf>>>,
osc7_host: Arc<std::sync::Mutex<Option<String>>>,
pub accent: Option<(u8, u8, u8)>,
pub accent_badge: Option<String>,
notifications: Arc<std::sync::Mutex<Vec<String>>>,
progress: Arc<std::sync::Mutex<Option<(u8, u8)>>>,
line_times: Arc<std::sync::Mutex<std::collections::BTreeMap<i64, u64>>>,
pub show_timestamps: bool,
annotations: Vec<PaneAnnotation>,
finished_rx: std::sync::mpsc::Receiver<FinishedCommand>,
hints: Option<(i64, Vec<HintSpan>)>,
triggers: Arc<std::sync::Mutex<std::sync::Arc<crate::triggers::TriggerSet>>>,
trigger_rx: std::sync::mpsc::Receiver<crate::triggers::TriggerHit>,
palette: [(u8, u8, u8); 16],
images: Arc<std::sync::Mutex<Vec<StoredImage>>>,
#[cfg(test)]
written_for_test: Arc<std::sync::Mutex<Vec<u8>>>,
}
struct StoredImage {
seq: u64,
data: std::sync::Arc<Vec<u8>>,
line_rec: i32,
clock_rec: i64,
}
#[derive(Clone)]
pub struct PaneImage {
pub seq: u64,
pub data: std::sync::Arc<Vec<u8>>,
pub line: i32,
}
const IMAGES_MAX: usize = 4;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HintSpan {
pub line: i32,
pub start: usize,
pub len: usize,
pub label: String,
pub typed: usize,
}
struct StoredMark {
kind: crate::shell_integration::OscEvent,
line_rec: i32,
clock_rec: i64,
col_rec: usize,
dur: Option<std::time::Duration>,
}
#[derive(Clone, Debug)]
pub struct FinishedCommand {
pub exit: Option<i32>,
pub dur: std::time::Duration,
pub cmd: String,
pub cwd: Option<std::path::PathBuf>,
pub host: Option<String>,
pub output: String,
}
pub const FINISHED_OUTPUT_CAP_LINES: usize = 5000;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CommandDecoration {
pub line: i32,
pub exit: Option<i32>,
pub duration: Option<std::time::Duration>,
pub input: Option<(i32, usize)>,
pub output_start: i32,
pub output_end: i32,
}
pub fn pair_decorations(
marks: &[(
crate::shell_integration::OscEvent,
i32,
usize,
Option<std::time::Duration>,
)],
) -> Vec<CommandDecoration> {
use crate::shell_integration::OscEvent as E;
let mut out = Vec::new();
let mut prompt: Option<i32> = None;
let mut input: Option<(i32, usize)> = None;
let mut started: Option<i32> = None;
for (kind, line, col, dur) in marks {
match kind {
E::PromptStart => {
prompt = Some(*line);
input = None;
}
E::PromptEnd => input = Some((*line, *col)),
E::CommandStart => started = Some(*line),
E::CommandEnd(exit) => {
if let Some(output_start) = started.take() {
out.push(CommandDecoration {
line: prompt.unwrap_or(output_start),
exit: *exit,
duration: *dur,
input,
output_start,
output_end: *line,
});
}
}
_ => {}
}
}
out
}
pub fn human_duration(d: std::time::Duration) -> String {
let secs = d.as_secs_f64();
if secs < 1.0 {
format!("{}ms", d.as_millis())
} else if secs < 60.0 {
format!("{secs:.1}s")
} else {
format!("{}m {:02}s", d.as_secs() / 60, d.as_secs() % 60)
}
}
const MARKS_MAX: usize = 2000;
pub fn pick_prompt_jump(prompt_lines: &[i32], current_top: i32, forward: bool) -> Option<i32> {
if forward {
prompt_lines
.iter()
.copied()
.filter(|&l| l > current_top)
.min()
} else {
prompt_lines
.iter()
.copied()
.filter(|&l| l < current_top)
.max()
}
}
fn apply_shell_integration_env(
cmd: &mut CommandBuilder,
shell_path: &str,
config_dir: &std::path::Path,
) -> Vec<String> {
if std::env::var("CROFT_SHELL_INTEGRATION").as_deref() == Ok("0") {
return Vec::new();
}
let base = std::path::Path::new(shell_path)
.file_name()
.and_then(|s| s.to_str())
.unwrap_or("");
match base {
"zsh" => {
let Ok(shim) = crate::shell_integration::ensure_zsh_shim(config_dir) else {
return Vec::new();
};
let inherited = std::env::var_os("ZDOTDIR").map(std::path::PathBuf::from);
let home = std::env::var_os("HOME")
.map(std::path::PathBuf::from)
.unwrap_or_default();
if home.as_os_str().is_empty() {
return Vec::new();
}
let user_zdotdir = crate::shell_integration::resolve_user_zdotdir(
inherited.as_deref(),
&config_dir.join("shell-integration"),
&home,
);
cmd.env("CROFT_USER_ZDOTDIR", user_zdotdir);
cmd.env("ZDOTDIR", &shim);
Vec::new()
}
"bash" => {
if !bash_env_injection_supported(shell_path) {
return Vec::new();
}
let Ok(shim) = crate::shell_integration::ensure_bash_shim(config_dir) else {
return Vec::new();
};
if let Ok(env) = std::env::var("ENV") {
cmd.env("CROFT_BASH_ENV", env);
}
cmd.env("ENV", &shim);
cmd.env("CROFT_BASH_INJECT", "1");
if std::env::var_os("HISTFILE").is_none()
&& let Some(home) = std::env::var_os("HOME")
{
cmd.env(
"HISTFILE",
std::path::Path::new(&home).join(".bash_history"),
);
cmd.env("CROFT_BASH_UNEXPORT_HISTFILE", "1");
}
vec!["--posix".to_string()]
}
"fish" => {
let Ok(dir) = crate::shell_integration::ensure_fish_integration(config_dir) else {
return Vec::new();
};
let inherited = std::env::var("XDG_DATA_DIRS").ok();
cmd.env(
"XDG_DATA_DIRS",
crate::shell_integration::fish_xdg_data_dirs(&dir, inherited.as_deref()),
);
cmd.env("CROFT_FISH_XDG_DATA_DIR", &dir);
Vec::new()
}
_ => Vec::new(),
}
}
fn bash_env_injection_supported(shell_path: &str) -> bool {
let Ok(out) = std::process::Command::new(shell_path)
.args(["-c", "echo \"${BASH_VERSINFO[0]}.${BASH_VERSINFO[1]}\""])
.output()
else {
return false;
};
parse_bash_version_supported(&String::from_utf8_lossy(&out.stdout))
}
fn parse_bash_version_supported(s: &str) -> bool {
let mut it = s.trim().split('.');
let (Some(maj), Some(min)) = (
it.next().and_then(|v| v.parse::<u32>().ok()),
it.next().and_then(|v| v.parse::<u32>().ok()),
) else {
return false;
};
maj > 4 || (maj == 4 && min >= 4)
}
pub fn interactive_shell_invocation(shell_path: &str) -> (String, Vec<String>) {
let basename = std::path::Path::new(shell_path)
.file_name()
.and_then(|s| s.to_str())
.unwrap_or(shell_path);
let supports_login_flag = matches!(
basename,
"zsh" | "bash" | "fish" | "ksh" | "mksh" | "dash" | "tcsh" | "sh"
);
let args = if supports_login_flag {
vec!["-l".to_string()]
} else {
Vec::new()
};
(shell_path.to_string(), args)
}
pub fn parse_shells(contents: &str) -> Vec<(String, String)> {
let mut out: Vec<(String, String)> = Vec::new();
for line in contents.lines() {
let line = line.trim();
if line.is_empty() || !line.starts_with('/') {
continue;
}
let base = std::path::Path::new(line)
.file_name()
.and_then(|s| s.to_str())
.unwrap_or(line)
.to_string();
if out.iter().any(|(_, b)| *b == base) {
continue;
}
out.push((line.to_string(), base));
}
out
}
pub fn process_name(pid: i32) -> Option<String> {
use sysinfo::{Pid, ProcessesToUpdate, System};
if pid <= 0 {
return None;
}
let p = Pid::from(pid as usize);
let mut sys = System::new();
sys.refresh_processes(ProcessesToUpdate::Some(&[p]), true);
sys.process(p)
.map(|pr| pr.name().to_string_lossy().to_string())
.filter(|n| !n.is_empty())
}
#[cfg(target_os = "linux")]
pub fn cwd_of_pid(pid: u32) -> Option<std::path::PathBuf> {
std::fs::read_link(format!("/proc/{pid}/cwd")).ok()
}
#[cfg(target_os = "macos")]
pub fn cwd_of_pid(pid: u32) -> Option<std::path::PathBuf> {
use std::ffi::OsString;
use std::os::raw::{c_int, c_void};
use std::os::unix::ffi::OsStringExt;
const PROC_PIDVNODEPATHINFO: c_int = 9;
const MAXPATHLEN: usize = 1024;
#[repr(C)]
#[derive(Default, Clone, Copy)]
struct VinfoStat {
vst_dev: u32,
vst_mode: u16,
vst_nlink: u16,
vst_ino: u64,
vst_uid: u32,
vst_gid: u32,
vst_atime: i64,
vst_atimensec: i64,
vst_mtime: i64,
vst_mtimensec: i64,
vst_ctime: i64,
vst_ctimensec: i64,
vst_birthtime: i64,
vst_birthtimensec: i64,
vst_size: i64,
vst_blocks: i64,
vst_blksize: i32,
vst_flags: u32,
vst_gen: u32,
vst_rdev: u32,
vst_qspare: [i64; 2],
}
#[repr(C)]
#[derive(Clone, Copy)]
struct VnodeInfo {
vi_stat: VinfoStat,
vi_type: i32,
vi_pad: i32,
vi_fsid: [i32; 2],
}
#[repr(C)]
#[derive(Clone, Copy)]
struct VnodeInfoPath {
vip_vi: VnodeInfo,
vip_path: [u8; MAXPATHLEN],
}
#[repr(C)]
#[derive(Clone, Copy)]
struct ProcVnodePathInfo {
pvi_cdir: VnodeInfoPath,
pvi_rdir: VnodeInfoPath,
}
unsafe extern "C" {
fn proc_pidinfo(
pid: c_int,
flavor: c_int,
arg: u64,
buffer: *mut c_void,
buffersize: c_int,
) -> c_int;
}
let mut info: ProcVnodePathInfo = unsafe { std::mem::zeroed() };
let size = std::mem::size_of::<ProcVnodePathInfo>() as c_int;
let ret = unsafe {
proc_pidinfo(
pid as c_int,
PROC_PIDVNODEPATHINFO,
0,
&mut info as *mut _ as *mut c_void,
size,
)
};
if ret <= 0 {
return None;
}
let path = &info.pvi_cdir.vip_path;
let len = path.iter().position(|&b| b == 0).unwrap_or(0);
if len == 0 {
return None;
}
Some(std::path::PathBuf::from(OsString::from_vec(
path[..len].to_vec(),
)))
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
pub fn cwd_of_pid(_pid: u32) -> Option<std::path::PathBuf> {
None
}
pub fn pick_pane_label<'a>(manual: Option<&'a str>, auto: &'a str) -> &'a str {
manual.unwrap_or(auto)
}
impl PtyTerminal {
pub fn new(cwd: &std::path::Path) -> Result<Self> {
let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/bash".to_string());
Self::new_shell(&shell, cwd)
}
pub fn new_shell(shell_path: &str, cwd: &std::path::Path) -> Result<Self> {
let (program, args) = interactive_shell_invocation(shell_path);
let mut cmd = CommandBuilder::new(&program);
let pre = apply_shell_integration_env(&mut cmd, shell_path, &crate::prefs::config_dir());
for a in pre.iter().chain(args.iter()) {
cmd.arg(a);
}
cmd.cwd(cwd);
Self::spawn_with(cmd, None)
}
pub fn new_running(program: &str, args: &[String], cwd: &std::path::Path) -> Result<Self> {
let mut cmd = CommandBuilder::new(program);
for a in args {
cmd.arg(a);
}
cmd.cwd(cwd);
let label = if args.is_empty() {
program.to_string()
} else {
format!("{program} {}", args.join(" "))
};
Self::spawn_with(cmd, Some(label))
}
pub fn visible_text(&self) -> String {
let term = self.term.lock();
let rows = term.screen_lines();
let cols = term.columns();
if rows == 0 || cols == 0 {
return String::new();
}
let off = term.grid().display_offset() as i32;
extract_selection_text(&term, -off, 0, rows as i32 - 1 - off, cols - 1)
}
pub fn grid_lines(&self) -> (Vec<String>, i32) {
let term = self.term.lock();
if term.columns() == 0 {
return (Vec::new(), 0);
}
let top = term.grid().topmost_line().0;
let bottom = term.screen_lines() as i32 - 1;
let mut lines = Vec::new();
let mut l = top;
while l <= bottom {
let (s, _cols) = row_text_and_cols(&term, l);
lines.push(s.trim_end().to_string());
l += 1;
}
(lines, top)
}
pub fn grid_lines_and_clock(&self) -> (Vec<String>, i32, i64) {
let term = self.term.lock();
if term.columns() == 0 {
return (Vec::new(), 0, self.clock_now(&term));
}
let top = term.grid().topmost_line().0;
let bottom = term.screen_lines() as i32 - 1;
let mut lines = Vec::new();
let mut l = top;
while l <= bottom {
let (s, _cols) = row_text_and_cols(&term, l);
lines.push(s.trim_end().to_string());
l += 1;
}
(lines, top, self.clock_now(&term))
}
pub fn hyperlink_at(&self, row: usize, col: usize) -> Option<String> {
let term = self.term.lock();
if col >= term.columns() {
return None;
}
let line_idx = row as i32 - term.grid().display_offset() as i32;
if line_idx < term.grid().topmost_line().0 || line_idx >= term.screen_lines() as i32 {
return None;
}
term.grid()[Point::new(Line(line_idx), Column(col))]
.hyperlink()
.map(|h| h.uri().to_string())
}
pub fn set_search(&mut self, needle: Option<String>, opts: crate::widgets::search::SearchOpts) {
self.search_needle = needle.filter(|s| !s.is_empty());
self.search_opts = opts;
self.pty_dirty.store(true, Ordering::Release);
}
pub fn set_current_match(&mut self, m: Option<(i32, usize, usize)>, clock: i64) {
self.current_match = m.map(|(line, col, len)| (clock, line, col, len));
self.pty_dirty.store(true, Ordering::Release);
}
pub fn set_hints(&mut self, hints: Option<Vec<HintSpan>>, clock: i64) {
self.hints = hints.map(|h| (clock, h));
self.pty_dirty.store(true, Ordering::Release);
}
pub fn visible_lines(&self) -> (Vec<String>, i32) {
let term = self.term.lock();
if term.columns() == 0 {
return (Vec::new(), 0);
}
let off = term.grid().display_offset() as i32;
let rows = term.screen_lines() as i32;
let mut lines = Vec::new();
for l in -off..rows - off {
let (s, _cols) = row_text_and_cols(&term, l);
lines.push(s.trim_end().to_string());
}
(lines, -off)
}
pub fn visible_lines_and_clock(&mut self) -> (Vec<String>, Vec<bool>, i32, i64) {
let mut term = self.term.lock();
let clock = self.clock.lock().unwrap().tick(&mut term);
if term.columns() == 0 {
return (Vec::new(), Vec::new(), 0, clock);
}
let off = term.grid().display_offset() as i32;
let rows = term.screen_lines() as i32;
let cols = term.columns();
let mut lines = Vec::new();
let mut wraps = Vec::new();
for l in -off..rows - off {
let (s, _cols) = row_text_and_cols(&term, l);
let wrapped = term.grid()[Point::new(Line(l), Column(cols - 1))]
.flags
.contains(Flags::WRAPLINE);
lines.push(if wrapped { s } else { s.trim_end().to_string() });
wraps.push(wrapped);
}
(lines, wraps, -off, clock)
}
pub fn set_triggers(&self, set: std::sync::Arc<crate::triggers::TriggerSet>) {
let mut cur = self.triggers.lock().unwrap();
if std::sync::Arc::ptr_eq(&cur, &set) {
return;
}
*cur = set;
drop(cur);
self.pty_dirty.store(true, Ordering::Release);
}
pub fn drain_trigger_hits(&self) -> Vec<crate::triggers::TriggerHit> {
self.trigger_rx.try_iter().collect()
}
pub fn set_palette(&mut self, palette: [(u8, u8, u8); 16]) {
if self.palette != palette {
self.palette = palette;
self.pty_dirty.store(true, Ordering::Release);
}
}
pub fn pane_images(&self) -> Vec<PaneImage> {
let mut term = self.term.lock();
let now = self.clock.lock().unwrap().tick(&mut term);
let floor = term.grid().topmost_line().0;
drop(term);
let mut imgs = self.images.lock().unwrap();
imgs.retain(|m| m.line_rec - (now - m.clock_rec) as i32 >= floor);
imgs.iter()
.map(|m| PaneImage {
seq: m.seq,
data: m.data.clone(),
line: m.line_rec - (now - m.clock_rec) as i32,
})
.collect()
}
pub fn alt_screen(&self) -> bool {
self.term.lock().mode().contains(TermMode::ALT_SCREEN)
}
pub fn app_cursor_keys(&self) -> bool {
self.term.lock().mode().contains(TermMode::APP_CURSOR)
}
pub fn scroll_display_offset(&self) -> i32 {
self.display_offset()
}
pub fn scroll_to_line(&mut self, abs_line: i32) {
let mut term = self.term.lock();
if term.mode().contains(TermMode::ALT_SCREEN) {
return;
}
let rows = term.screen_lines() as i32;
let max_off = (-term.grid().topmost_line().0).max(0);
let cur = term.grid().display_offset() as i32;
let desired = scroll_offset_for_line(rows, max_off, abs_line);
let delta = desired - cur;
if delta != 0 {
term.scroll_display(Scroll::Delta(delta));
}
drop(term);
self.pty_dirty.store(true, Ordering::Release);
}
fn spawn_with(mut cmd: CommandBuilder, run_label: Option<String>) -> Result<Self> {
let pty_system = native_pty_system();
let cols = 80u16;
let rows = 24u16;
let pair = pty_system
.openpty(PtySize {
cols,
rows,
pixel_width: 0,
pixel_height: 0,
})
.context("openpty")?;
cmd.env("TERM", "xterm-256color");
cmd.env("COLORTERM", "truecolor");
let child = pair.slave.spawn_command(cmd).context("spawn child")?;
let shell_pid = child.process_id().map(|p| p as i32);
drop(pair.slave);
let writer: Arc<std::sync::Mutex<Box<dyn Write + Send>>> = Arc::new(std::sync::Mutex::new(
pair.master.take_writer().context("take writer")?,
));
let mut reader = pair.master.try_clone_reader().context("clone reader")?;
let term_size = TermSize::new(cols as usize, rows as usize);
let cfg = Config {
scrolling_history: crate::prefs::terminal_scrollback_lines(
crate::prefs::Prefs::load_or_default().terminal_scrollback,
SCROLLBACK_LINES,
),
..Config::default()
};
let size_shared = Arc::new(std::sync::Mutex::new((cols, rows)));
let (response_tx, response_rx) = std::sync::mpsc::channel::<String>();
let bell = Arc::new(AtomicBool::new(false));
let listener = VoidListener {
pty_response_tx: Some(response_tx),
size: Some(size_shared.clone()),
bell: Some(bell.clone()),
};
let term = Term::new(cfg, &term_size, listener);
let term = Arc::new(FairMutex::new(term));
let term_for_thread = term.clone();
let writer_for_responder = writer.clone();
std::thread::spawn(move || {
while let Ok(text) = response_rx.recv() {
let Ok(mut w) = writer_for_responder.lock() else {
break;
};
if w.write_all(text.as_bytes()).is_err() {
break;
}
if w.flush().is_err() {
break;
}
}
});
let pty_dirty = Arc::new(AtomicBool::new(true));
let pty_dirty_for_thread = pty_dirty.clone();
let pty_pending_bytes = Arc::new(AtomicUsize::new(0));
let pty_pending_bytes_for_thread = pty_pending_bytes.clone();
let bracketed_paste_enabled = Arc::new(AtomicBool::new(false));
let bracketed_paste_for_thread = bracketed_paste_enabled.clone();
let (port_tx, port_rx) = std::sync::mpsc::channel::<crate::port_detect::PortHit>();
if let Some(label) = run_label.as_deref() {
let header = format!("\x1b[2m▶ {label}\x1b[22m\r\n");
let mut p = Processor::<StdSyncHandler>::new();
let mut t = term.lock();
p.advance(&mut *t, header.as_bytes());
}
let script_mode = run_label.is_some();
let marks = Arc::new(std::sync::Mutex::new(Vec::<StoredMark>::new()));
let marks_for_thread = marks.clone();
let images = Arc::new(std::sync::Mutex::new(Vec::<StoredImage>::new()));
let images_for_thread = images.clone();
let (finished_tx, finished_rx) = std::sync::mpsc::channel::<FinishedCommand>();
let osc7_cwd = Arc::new(std::sync::Mutex::new(Option::<std::path::PathBuf>::None));
let osc7_for_thread = osc7_cwd.clone();
let notifications = Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
let notifications_for_thread = notifications.clone();
let progress = Arc::new(std::sync::Mutex::new(None::<(u8, u8)>));
let progress_for_thread = progress.clone();
let line_times = Arc::new(std::sync::Mutex::new(
std::collections::BTreeMap::<i64, u64>::new(),
));
let line_times_for_thread = line_times.clone();
let clock = Arc::new(std::sync::Mutex::new(ScrollClock::new()));
let clock_for_thread = clock.clone();
let osc7_host = Arc::new(std::sync::Mutex::new(None::<String>));
let osc7_host_for_thread = osc7_host.clone();
let triggers = Arc::new(std::sync::Mutex::new(std::sync::Arc::new(
crate::triggers::TriggerSet::default(),
)));
let triggers_for_thread = triggers.clone();
let (trigger_tx, trigger_rx) = std::sync::mpsc::channel::<crate::triggers::TriggerHit>();
let (shutdown_r, shutdown_w) = std::io::pipe().context("shutdown pipe")?;
let pty_fd = pair
.master
.as_raw_fd()
.context("pty master has no raw fd")?;
let reader_thread = std::thread::spawn(move || {
let mut processor = Processor::<StdSyncHandler>::new();
let mut port_sniffer = crate::port_detect::PortSniffer::new();
let mut osc_sniffer = crate::shell_integration::OscSniffer::default();
let mut wipe_sniffer = WipeSniffer::default();
let mut trigger_scanner = crate::triggers::TriggerScanner::new();
let mut trigger_hits = Vec::new();
let mut image_seq = 0u64;
let mut prev_stamp_id: i64 = 0;
let mut cmd_start: Option<std::time::Instant> = None;
let mut buf = [0u8; 65536];
loop {
if !wait_pty_readable(pty_fd, &shutdown_r) {
break;
}
match reader.read(&mut buf) {
Ok(0) => break,
Ok(n) => {
sniff_bracketed_paste_mode(&buf[..n], &bracketed_paste_for_thread);
port_sniffer.sniff(&buf[..n], &port_tx);
let osc_events = osc_sniffer.scan(&buf[..n]);
let mut t = term_for_thread.lock();
let (screen_wiped, hist_wiped) =
wipe_sniffer.scan(&buf[..n], t.mode().contains(TermMode::ALT_SCREEN));
let mut done = 0usize;
for (end, ev) in osc_events {
processor.advance(&mut *t, &buf[done..end]);
done = end;
use crate::shell_integration::OscEvent as E;
match ev {
E::Cwd(p, host) => {
*osc7_for_thread.lock().unwrap() = Some(p);
*osc7_host_for_thread.lock().unwrap() = host;
}
E::Notify(msg) => {
notifications_for_thread.lock().unwrap().push(msg);
}
E::Progress(state, pct) => {
*progress_for_thread.lock().unwrap() =
(state != 0).then_some((state, pct));
}
E::InlineImage(data) => {
let line_rec = t.grid().cursor.point.line.0;
let clock_rec = clock_for_thread.lock().unwrap().tick(&mut t);
let mut imgs = images_for_thread.lock().unwrap();
if imgs.len() >= IMAGES_MAX {
let drop_n = imgs.len() + 1 - IMAGES_MAX;
imgs.drain(..drop_n);
}
image_seq += 1;
imgs.push(StoredImage {
seq: image_seq,
data: std::sync::Arc::new(data),
line_rec,
clock_rec,
});
}
kind @ (E::PromptStart
| E::PromptEnd
| E::CommandStart
| E::CommandEnd(_)) => {
let dur = match &kind {
E::CommandStart => {
cmd_start = Some(std::time::Instant::now());
None
}
E::CommandEnd(exit) => {
*progress_for_thread.lock().unwrap() = None;
let dur = cmd_start.take().map(|s| s.elapsed());
if let Some(d) = dur {
let (cmd, output) = {
let now = clock_for_thread
.lock()
.unwrap()
.tick(&mut t);
let ms = marks_for_thread.lock().unwrap();
(
last_command_input_text(&t, &ms, now),
last_command_output_text(&t, &ms, now),
)
};
let cwd = osc7_for_thread.lock().unwrap().clone();
let host =
osc7_host_for_thread.lock().unwrap().clone();
let _ = finished_tx.send(FinishedCommand {
exit: *exit,
dur: d,
cmd,
cwd,
host,
output,
});
}
dur
}
_ => None,
};
let line_rec = t.grid().cursor.point.line.0;
let clock_rec = clock_for_thread.lock().unwrap().tick(&mut t);
let col_rec = t.grid().cursor.point.column.0;
let mut ms = marks_for_thread.lock().unwrap();
if ms.len() >= MARKS_MAX {
let drop_n = ms.len() + 1 - MARKS_MAX;
ms.drain(..drop_n);
}
ms.push(StoredMark {
kind,
line_rec,
clock_rec,
col_rec,
dur,
});
}
}
}
processor.advance(&mut *t, &buf[done..n]);
if screen_wiped || hist_wiped {
let now = clock_for_thread.lock().unwrap().tick(&mut t);
let erased = |line_rec: i32, clock_rec: i64| {
let line = line_rec - (now - clock_rec) as i32;
if line >= 0 { screen_wiped } else { hist_wiped }
};
images_for_thread
.lock()
.unwrap()
.retain(|m| !erased(m.line_rec, m.clock_rec));
marks_for_thread
.lock()
.unwrap()
.retain(|m| !erased(m.line_rec, m.clock_rec));
}
{
let now_ms = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
let mut clock = clock_for_thread.lock().unwrap();
let mut lt = line_times_for_thread.lock().unwrap();
stamp_chunk(&mut t, &mut clock, &mut lt, &mut prev_stamp_id, now_ms);
}
let trig = triggers_for_thread.lock().unwrap().clone();
trigger_scanner.scan(&buf[..n], &trig, &mut trigger_hits);
for h in trigger_hits.drain(..) {
let _ = trigger_tx.send(h);
}
drop(t);
pty_pending_bytes_for_thread.fetch_add(n, Ordering::Relaxed);
pty_dirty_for_thread.store(true, Ordering::Release);
}
Err(_) => break,
}
}
if script_mode {
let footer = b"\r\n\x1b[2m[Process exited]\x1b[22m\r\n";
let mut t = term_for_thread.lock();
processor.advance(&mut *t, footer);
drop(t);
pty_dirty_for_thread.store(true, Ordering::Release);
}
});
Ok(Self {
term,
pty_dirty,
pty_pending_bytes,
bracketed_paste_enabled,
port_rx,
master: pair.master,
writer,
_child: child,
reader_thread: Some(reader_thread),
reader_shutdown: Some(shutdown_w),
shell_pid,
uid: {
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
},
input_seen: false,
run_pane: script_mode,
manual_name_seen: false,
cols,
rows,
size_shared,
focused: false,
broadcast_excluded: false,
focus_gradient: false,
theme: crate::theme::Theme::default(),
last_area: Rect::default(),
last_inner: Rect::default(),
selection: None,
copy_cursor: None,
sel_scrolled: 0,
clock,
alt_sel: None,
drag_selecting: false,
manual_name: None,
auto_label: String::new(),
search_needle: None,
search_opts: crate::widgets::search::SearchOpts::default(),
current_match: None,
bell,
marks,
osc7_cwd,
osc7_host,
accent: None,
accent_badge: None,
notifications,
progress,
line_times,
show_timestamps: false,
annotations: Vec::new(),
finished_rx,
hints: None,
triggers,
trigger_rx,
palette: crate::theme::VSCODE_ANSI,
images,
#[cfg(test)]
written_for_test: Arc::new(std::sync::Mutex::new(Vec::new())),
})
}
pub fn command_marks(&self) -> Vec<(crate::shell_integration::OscEvent, i32)> {
self.marks_snapshot()
.into_iter()
.map(|(kind, line, _, _)| (kind, line))
.collect()
}
fn marks_snapshot(
&self,
) -> Vec<(
crate::shell_integration::OscEvent,
i32,
usize,
Option<std::time::Duration>,
)> {
let mut term = self.term.lock();
let now = self.clock.lock().unwrap().tick(&mut term);
let floor = term.grid().topmost_line().0;
drop(term);
let mut marks = self.marks.lock().unwrap();
marks.retain(|m| m.line_rec - (now - m.clock_rec) as i32 >= floor);
marks
.iter()
.map(|m| {
(
m.kind.clone(),
m.line_rec - (now - m.clock_rec) as i32,
m.col_rec,
m.dur,
)
})
.collect()
}
pub fn command_decorations(&self) -> Vec<CommandDecoration> {
pair_decorations(&self.marks_snapshot())
}
pub fn drain_finished_commands(&self) -> Vec<FinishedCommand> {
self.finished_rx.try_iter().collect()
}
pub fn command_output_text(&self, d: &CommandDecoration) -> String {
if d.output_end <= d.output_start {
return String::new();
}
let term = self.term.lock();
extract_selection_text(
&term,
d.output_start,
0,
d.output_end - 1,
term.columns().saturating_sub(1),
)
}
pub fn command_input_text(&self, d: &CommandDecoration) -> String {
let Some((line, col)) = d.input else {
return String::new();
};
if d.output_start <= line {
return String::new();
}
let term = self.term.lock();
extract_selection_text(
&term,
line,
col,
d.output_start - 1,
term.columns().saturating_sub(1),
)
}
pub fn select_command_output(&mut self, d: &CommandDecoration) {
if d.output_end <= d.output_start {
return;
}
self.selection = Some(Selection {
anchor: (d.output_start, 0),
head: (d.output_end - 1, self.cols.saturating_sub(1)),
block: false,
});
self.stamp_selection_clock();
self.scroll_to_line(d.output_start);
}
pub fn decoration_at_screen(&self, col: u16, row: u16) -> Option<CommandDecoration> {
let inner = self.last_inner;
if col != self.last_area.x || row < inner.y || row >= inner.y + inner.height {
return None;
}
let term = self.term.lock();
if term.mode().contains(TermMode::ALT_SCREEN) {
return None;
}
let display_offset = term.grid().display_offset() as i32;
drop(term);
let line = i32::from(row - inner.y) - display_offset;
self.command_decorations()
.into_iter()
.find(|d| d.line == line)
}
pub fn prompt_lines(&self) -> Vec<i32> {
self.command_marks()
.into_iter()
.filter(|(kind, _)| *kind == crate::shell_integration::OscEvent::PromptStart)
.map(|(_, line)| line)
.collect()
}
pub fn shell_cwd(&self) -> Option<std::path::PathBuf> {
self.osc7_cwd.lock().unwrap().clone()
}
pub fn kernel_shell_cwd(&self) -> Option<std::path::PathBuf> {
cwd_of_pid(u32::try_from(self.shell_pid?).ok()?)
}
pub fn drain_notifications(&self) -> Vec<String> {
std::mem::take(&mut *self.notifications.lock().unwrap())
}
pub fn viewport_top_line(&self) -> i32 {
-(self.term.lock().grid().display_offset() as i32)
}
pub fn scroll_line_to_top(&mut self, abs_line: i32) {
let mut term = self.term.lock();
if term.mode().contains(TermMode::ALT_SCREEN) {
return;
}
let max_off = (-term.grid().topmost_line().0).max(0);
let desired = (-abs_line).clamp(0, max_off);
let delta = desired - term.grid().display_offset() as i32;
if delta != 0 {
term.scroll_display(Scroll::Delta(delta));
}
drop(term);
self.pty_dirty.store(true, Ordering::Release);
}
pub fn take_bell(&self) -> bool {
self.bell.swap(false, Ordering::AcqRel)
}
pub fn foreground_pid(&self) -> Option<i32> {
self.master.process_group_leader()
}
pub fn shell_pid(&self) -> Option<i32> {
self.shell_pid
}
pub fn label(&self) -> &str {
pick_pane_label(self.manual_name.as_deref(), &self.auto_label)
}
pub fn set_auto_label(&mut self, label: String) {
self.auto_label = label;
}
pub fn manual_name(&self) -> Option<&str> {
self.manual_name.as_deref()
}
pub fn set_manual_name(&mut self, name: Option<String>) {
self.manual_name = name.filter(|n| !n.trim().is_empty());
if self.manual_name.is_some() {
self.manual_name_seen = true;
}
}
pub fn take_dirty(&self) -> bool {
self.pty_pending_bytes.store(0, Ordering::Relaxed);
self.pty_dirty.swap(false, Ordering::AcqRel)
}
pub fn progress(&self) -> Option<(u8, u8)> {
*self.progress.lock().unwrap()
}
pub fn prompt_click_arrows(&self, col: u16, row: u16) -> Option<Vec<u8>> {
let (vr, vc) = self.cell_at(col, row)?;
let term = self.term.lock();
if term.mode().contains(TermMode::ALT_SCREEN) {
return None;
}
let off = term.grid().display_offset() as i32;
let line = vr as i32 - off;
let cursor = term.grid().cursor.point;
if line != cursor.line.0 {
return None;
}
let now = self.clock_now(&term);
let ms = self.marks.lock().unwrap();
let last = ms.last()?;
if !matches!(last.kind, crate::shell_integration::OscEvent::PromptEnd) {
return None;
}
if last.line_rec - (now - last.clock_rec) as i32 != line {
return None;
}
let b_col = last.col_rec as u16;
let (text, colmap) = row_text_and_cols(&term, line);
let chars = text.trim_end().chars().count();
let end_col = if chars == 0 {
b_col
} else {
colmap
.get(chars - 1)
.map(|&c| c as u16 + 1)
.unwrap_or(b_col)
};
let cur = cursor.column.0 as u16;
let hi = end_col.max(cur);
let target = vc.clamp(b_col.min(hi), hi);
if target == cur {
return None;
}
let (seq, n) = if target > cur {
(b"\x1b[C".as_slice(), target - cur)
} else {
(b"\x1b[D".as_slice(), cur - target)
};
Some(seq.repeat(n as usize))
}
pub fn shell_host(&self) -> Option<String> {
self.osc7_host.lock().unwrap().clone()
}
pub fn local_shell_cwd(&self) -> Option<std::path::PathBuf> {
let host = self.shell_host().unwrap_or_default();
if !crate::command_history::is_local_host(&host) {
return None;
}
let claim = self.shell_cwd()?;
let real = cwd_of_pid(self.pid()?)?;
(claim.canonicalize().ok()? == real.canonicalize().ok()?).then_some(claim)
}
pub fn scroll_clock(&mut self) -> i64 {
self.tick_clock()
}
pub fn add_annotation(&mut self, line: i32, clock: i64, start: u16, len: u16, text: String) {
self.annotations.push(PaneAnnotation {
line_rec: line,
clock_rec: clock,
start,
len: len.max(1),
text,
});
self.pty_dirty.store(true, Ordering::Release);
}
pub fn annotations_current(&mut self) -> Vec<(i32, u16, u16, String)> {
let now = self.tick_clock();
let top = self.term.lock().grid().topmost_line().0;
self.annotations
.retain(|a| a.line_rec - (now - a.clock_rec) as i32 >= top);
self.annotations
.iter()
.map(|a| {
(
a.line_rec - (now - a.clock_rec) as i32,
a.start,
a.len,
a.text.clone(),
)
})
.collect()
}
pub fn find_captured_line(&self, needle: &str) -> Option<i32> {
if needle.is_empty() {
return None;
}
let term = self.term.lock();
let cols = term.columns();
let wraps = |line: i32| {
cols > 0
&& term.grid()[Point::new(Line(line), Column(cols - 1))]
.flags
.contains(Flags::WRAPLINE)
};
let top = term.grid().topmost_line().0;
let bottom = term.screen_lines() as i32 - 1;
for line in (top..=bottom).rev() {
if line > top && wraps(line - 1) {
continue;
}
let (text, _) = row_text_and_cols(&term, line);
let t = text.trim_end();
if t.is_empty() {
continue;
}
if t.starts_with(needle) || (wraps(line) && needle.starts_with(t)) {
return Some(line);
}
}
None
}
pub fn annotations_at_clock(&self, clock: i64) -> Vec<(i32, u16, u16, String)> {
self.annotations
.iter()
.map(|a| {
(
a.line_rec - (clock - a.clock_rec) as i32,
a.start,
a.len,
a.text.clone(),
)
})
.collect()
}
pub fn annotation_at(&self, col: u16, row: u16) -> Option<(usize, String)> {
let (vr, vc) = self.cell_at(col, row)?;
let term = self.term.lock();
if term.mode().contains(TermMode::ALT_SCREEN) {
return None;
}
let off = term.grid().display_offset() as i32;
let now = self.clock_now(&term);
drop(term);
let line = vr as i32 - off;
self.annotations
.iter()
.enumerate()
.find(|(_, a)| {
a.line_rec - (now - a.clock_rec) as i32 == line
&& vc >= a.start
&& vc < a.start + a.len
})
.map(|(i, a)| (i, a.text.clone()))
}
pub fn remove_annotation(&mut self, idx: usize) {
if idx < self.annotations.len() {
self.annotations.remove(idx);
self.pty_dirty.store(true, Ordering::Release);
}
}
pub fn set_annotation_text(&mut self, idx: usize, text: String) {
if let Some(a) = self.annotations.get_mut(idx) {
a.text = text;
self.pty_dirty.store(true, Ordering::Release);
}
}
pub fn row_time(&self, line: i32) -> Option<u64> {
let term = self.term.lock();
let now = self.clock_now(&term);
drop(term);
self.line_times
.lock()
.unwrap()
.get(&(i64::from(line) + now))
.copied()
}
pub fn drain_ports(&self) -> Vec<crate::port_detect::PortHit> {
self.port_rx.try_iter().collect()
}
pub fn peek_pending_bytes(&self) -> usize {
self.pty_pending_bytes.load(Ordering::Relaxed)
}
pub fn pid(&self) -> Option<u32> {
self._child.process_id()
}
pub fn peek_dirty(&self) -> bool {
self.pty_dirty.load(Ordering::Acquire)
}
pub fn cell_at(&self, col: u16, row: u16) -> Option<(u16, u16)> {
let inner = self.last_inner;
if inner.width == 0 || inner.height == 0 {
return None;
}
if col < inner.x || col >= inner.x + inner.width {
return None;
}
if row < inner.y || row >= inner.y + inner.height {
return None;
}
Some((row - inner.y, col - inner.x))
}
fn display_offset(&self) -> i32 {
self.term.lock().grid().display_offset() as i32
}
pub fn line_text_at(&self, col: u16, row: u16) -> Option<(String, usize)> {
let (r, c) = self.cell_at(col, row)?;
let term = self.term.lock();
let line = r as i32 - term.grid().display_offset() as i32;
let (text, cols_map) = row_text_and_cols(&term, line);
let idx = cols_map.iter().rposition(|&gc| gc <= c as usize)?;
Some((text, idx))
}
pub fn hyperlink_at_screen(&self, col: u16, row: u16) -> Option<String> {
let (r, c) = self.cell_at(col, row)?;
self.hyperlink_at(r as usize, c as usize)
}
fn clock_now(&self, term: &Term<VoidListener>) -> i64 {
self.clock.lock().unwrap().now(term)
}
fn tick_clock(&mut self) -> i64 {
let mut term = self.term.lock();
self.clock.lock().unwrap().tick(&mut term)
}
fn stamp_selection_clock(&mut self) {
self.sel_scrolled = self.tick_clock();
let term = self.term.lock();
self.alt_sel = if term.mode().contains(TermMode::ALT_SCREEN) {
self.selection.and_then(|s| capture_alt_anchor(&term, s))
} else {
None
};
}
fn rebase_alt_selection(&mut self) {
if self.selection.is_none() {
self.alt_sel = None;
return;
}
let Some(mut anchor) = self.alt_sel.take() else {
return;
};
let term = self.term.lock();
let rows_vis = term.screen_lines() as i32;
let old_top = anchor.top;
let k = anchor.rows.len() as i32;
let grid_rows: Vec<(String, Vec<usize>)> =
(0..rows_vis).map(|l| row_text_and_cols(&term, l)).collect();
let k_rows = anchor.rows.len();
let min_exact = k_rows.min(2);
let mut best: Option<(i32, usize, usize)> = None;
for top in 1 - k..rows_vis {
let (mut exact, mut nonblank) = (0usize, false);
for (i, want) in anchor.rows.iter().enumerate() {
let line = top + i as i32;
if (0..rows_vis).contains(&line) && grid_rows[line as usize].0 == *want {
exact += 1;
nonblank |= !want.trim().is_empty();
}
}
let mut ctx = 0usize;
for (want, line) in [
(anchor.ctx_above.as_ref(), top - 1),
(anchor.ctx_below.as_ref(), top + k),
] {
if let Some(want) = want
&& (0..rows_vis).contains(&line)
&& grid_rows[line as usize].0 == *want
{
ctx += 1;
}
}
if exact >= min_exact
&& nonblank
&& best.is_none_or(|(btop, bexact, bctx)| {
exact > bexact
|| (exact == bexact && ctx > bctx)
|| (exact == bexact
&& ctx == bctx
&& (top - old_top).abs() < (btop - old_top).abs())
})
{
best = Some((top, exact, ctx));
}
}
match best {
Some((top, _, _)) => {
let d = top - old_top;
anchor.top = top;
if d != 0
&& let Some(s) = self.selection.as_mut()
{
s.anchor.0 += d;
s.head.0 += d;
}
anchor.dormant = false;
let mut clips: Vec<(i32, u16, u16)> = Vec::new();
let mut all_exact = true;
for (i, want) in anchor.rows.iter().enumerate() {
let line = top + i as i32;
if !(0..rows_vis).contains(&line) {
all_exact = false;
continue;
}
let (got, colmap) = &grid_rows[line as usize];
if got == want {
clips.push((line, 0, u16::MAX));
} else {
all_exact = false;
for (lo, hi) in partial_overlap_cols(want, got, colmap) {
clips.push((line, lo, hi));
}
}
}
anchor.visible = (!all_exact).then_some(clips);
if all_exact && let Some(fresh) = capture_alt_anchor(&term, self.selection.unwrap())
{
anchor = fresh;
}
}
None if self.drag_selecting => {
anchor.dormant = false;
anchor.visible = None;
if let Some(fresh) = capture_alt_anchor(&term, self.selection.unwrap()) {
anchor = fresh;
}
}
None => anchor.dormant = true,
}
drop(term);
self.alt_sel = Some(anchor);
}
fn rebase_selection(&mut self) {
if self.selection.is_none() && self.copy_cursor.is_none() {
return;
}
if self.term.lock().mode().contains(TermMode::ALT_SCREEN) {
self.rebase_alt_selection();
return;
}
if self.alt_sel.take().is_some() {
self.selection = None;
self.copy_cursor = None;
return;
}
let now = self.tick_clock();
let top = self.term.lock().grid().topmost_line().0;
let delta = (now - self.sel_scrolled) as i32;
self.sel_scrolled = now;
if delta != 0 {
if let Some(sel) = self.selection.as_mut() {
sel.anchor.0 -= delta;
sel.head.0 -= delta;
}
if let Some(cur) = self.copy_cursor.as_mut() {
cur.0 -= delta;
}
}
if self
.selection
.is_some_and(|s| s.anchor.0 < top && s.head.0 < top)
{
self.selection = None;
} else if let Some(sel) = self.selection.as_mut() {
sel.anchor.0 = sel.anchor.0.max(top);
sel.head.0 = sel.head.0.max(top);
}
if let Some(cur) = self.copy_cursor.as_mut() {
cur.0 = cur.0.max(top);
}
}
pub fn start_selection_at(&mut self, col: u16, row: u16) {
if let Some((r, c)) = self.cell_at(col, row) {
let line = r as i32 - self.display_offset();
self.selection = Some(Selection::new(line, c));
self.drag_selecting = true;
self.stamp_selection_clock();
}
}
#[cfg(test)]
pub fn feed_bytes_for_test(&self, bytes: &[u8]) {
let mut p = Processor::<StdSyncHandler>::new();
let mut term = self.term.lock();
p.advance(&mut *term, bytes);
}
#[cfg(test)]
pub fn stamp_chunk_for_test(&self, prev_id: &mut i64, now_ms: u64) {
let mut term = self.term.lock();
let mut clock = self.clock.lock().unwrap();
let mut lt = self.line_times.lock().unwrap();
stamp_chunk(&mut term, &mut clock, &mut lt, prev_id, now_ms);
}
#[cfg(test)]
pub fn line_time_entries_for_test(&self) -> Vec<(i64, u64)> {
self.line_times
.lock()
.unwrap()
.iter()
.map(|(&k, &v)| (k, v))
.collect()
}
#[cfg(test)]
pub fn push_mark_for_test(&self, kind: crate::shell_integration::OscEvent, col_rec: usize) {
let mut term = self.term.lock();
let line_rec = term.grid().cursor.point.line.0;
let clock_rec = self.clock.lock().unwrap().tick(&mut term);
drop(term);
self.marks.lock().unwrap().push(StoredMark {
kind,
line_rec,
clock_rec,
col_rec,
dur: None,
});
}
#[cfg(test)]
pub fn push_image_for_test(&self, data: Vec<u8>) {
let mut term = self.term.lock();
let line_rec = term.grid().cursor.point.line.0;
let clock_rec = self.clock.lock().unwrap().tick(&mut term);
drop(term);
let mut imgs = self.images.lock().unwrap();
let seq = imgs.last().map_or(0, |m| m.seq) + 1;
imgs.push(StoredImage {
seq,
data: std::sync::Arc::new(data),
line_rec,
clock_rec,
});
}
#[cfg(test)]
pub fn has_hints_for_test(&self) -> bool {
self.hints.is_some()
}
#[cfg(test)]
pub fn has_search_for_test(&self) -> bool {
self.search_needle.is_some()
}
#[cfg(test)]
pub fn debug_sel_state(&self) -> (Option<Selection>, i64, i64, Option<i32>, bool) {
(
self.selection,
self.sel_scrolled,
self.clock.lock().unwrap().base,
self.alt_sel.as_ref().map(|a| a.top),
self.term.lock().mode().contains(TermMode::ALT_SCREEN),
)
}
pub fn end_drag(&mut self) {
if self.drag_selecting {
self.drag_selecting = false;
self.stamp_selection_clock();
}
}
pub fn extend_selection_to(&mut self, col: u16, row: u16) {
self.drag_selecting = true;
self.rebase_selection();
let cell = self.cell_at(col, row);
let off = self.display_offset();
if let (Some(sel), Some((r, c))) = (self.selection.as_mut(), cell) {
sel.head = (r as i32 - off, c);
}
}
pub fn drag_select_to(&mut self, col: u16, row: u16) -> i32 {
let inner = self.last_inner;
if inner.width == 0 || inner.height == 0 {
return 0;
}
self.drag_selecting = true;
let top = inner.y;
let bottom = inner.y + inner.height - 1;
let (vp_row, dir) = if row < top {
(0u16, -1)
} else if row > bottom {
(inner.height - 1, 1)
} else {
(row - inner.y, 0)
};
let max_x = inner.x + inner.width - 1;
let c = col.clamp(inner.x, max_x) - inner.x;
self.rebase_selection();
let off = self.display_offset();
if let Some(sel) = self.selection.as_mut() {
sel.head = (vp_row as i32 - off, c);
}
dir
}
pub fn autoscroll_select(&mut self, dir: i32, col: u16) {
if dir == 0 {
return;
}
if self.term.lock().mode().contains(TermMode::ALT_SCREEN) {
let inner = self.last_inner;
if inner.width == 0 || inner.height == 0 || !self.mouse_reporting() {
return;
}
let edge_row = if dir < 0 {
inner.y
} else {
inner.y + inner.height - 1
};
let ccol = col.clamp(inner.x, inner.x + inner.width - 1);
let button = if dir < 0 {
MouseButtonKind::WheelUp
} else {
MouseButtonKind::WheelDown
};
self.report_mouse(
button,
MouseAction::Press,
ccol,
edge_row,
MouseMods::default(),
);
self.rebase_selection();
if let Some(sel) = self.selection.as_mut() {
sel.head = (i32::from(edge_row - inner.y), ccol - inner.x);
}
return;
}
let scrolled = if dir < 0 {
self.scroll_up(1)
} else {
self.scroll_down(1)
};
if !scrolled {
return;
}
let inner = self.last_inner;
if inner.width == 0 || inner.height == 0 {
return;
}
let max_x = inner.x + inner.width - 1;
let c = col.clamp(inner.x, max_x) - inner.x;
let vp_row = if dir < 0 { 0u16 } else { inner.height - 1 };
self.rebase_selection();
let off = self.display_offset();
if let Some(sel) = self.selection.as_mut() {
sel.head = (vp_row as i32 - off, c);
}
}
pub fn clear_selection(&mut self) {
self.selection = None;
self.alt_sel = None;
}
pub fn select_word_at(&mut self, col: u16, row: u16) {
let Some((r, c)) = self.cell_at(col, row) else {
return;
};
let term = self.term.lock();
let display_offset = term.grid().display_offset();
let Some((anchor, head)) =
select_word_at_in_term(&term, display_offset, r as usize, c as usize)
else {
return;
};
drop(term);
let off = display_offset as i32;
let to_abs = |(vr, vc): (u16, u16)| (vr as i32 - off, vc);
self.selection = Some(Selection {
anchor: to_abs(anchor),
head: to_abs(head),
block: false,
});
self.stamp_selection_clock();
}
pub fn selection(&self) -> Option<Selection> {
let mut sel = self.selection?;
let delta = (self.clock_now(&self.term.lock()) - self.sel_scrolled) as i32;
sel.anchor.0 -= delta;
sel.head.0 -= delta;
Some(sel)
}
pub fn set_selection(&mut self, sel: Option<Selection>) {
self.rebase_selection();
self.selection = sel;
self.stamp_selection_clock();
self.pty_dirty.store(true, Ordering::Release);
}
pub fn set_copy_cursor(&mut self, cur: Option<(i32, u16)>) {
self.rebase_selection();
self.copy_cursor = cur;
self.stamp_selection_clock();
self.pty_dirty.store(true, Ordering::Release);
}
pub fn cursor_line_col(&self) -> (i32, u16) {
let term = self.term.lock();
let p = term.grid().cursor.point;
(p.line.0, p.column.0 as u16)
}
pub fn selection_and_clock(&mut self) -> (Option<Selection>, i64) {
let mut term = self.term.lock();
let now = self.clock.lock().unwrap().tick(&mut term);
let sel = self.selection.map(|mut s| {
let delta = (now - self.sel_scrolled) as i32;
s.anchor.0 -= delta;
s.head.0 -= delta;
s
});
(sel, now)
}
#[allow(clippy::type_complexity)]
pub fn cursor_bounds_and_clock(&mut self) -> ((i32, u16), (i32, i32, u16, u16), i64) {
let mut term = self.term.lock();
let now = self.clock.lock().unwrap().tick(&mut term);
let p = term.grid().cursor.point;
let top = term.grid().topmost_line().0;
let bottom = term.screen_lines() as i32 - 1;
(
(p.line.0, p.column.0 as u16),
(top, bottom, self.cols, self.rows),
now,
)
}
pub fn row_text(&self, line: i32) -> (String, Vec<usize>) {
let term = self.term.lock();
row_text_and_cols(&term, line)
}
pub fn grid_bounds(&self) -> (i32, i32, u16, u16) {
let term = self.term.lock();
let top = term.grid().topmost_line().0;
let bottom = term.screen_lines() as i32 - 1;
(top, bottom, self.cols, self.rows)
}
pub fn selection_text(&self) -> String {
if let Some(anchor) = self
.alt_sel
.as_ref()
.filter(|a| a.dormant || a.visible.is_some())
{
return anchor.text.clone();
}
let Some(mut sel) = self.selection else {
return String::new();
};
let term = self.term.lock();
let delta = (self.clock_now(&term) - self.sel_scrolled) as i32;
sel.anchor.0 -= delta;
sel.head.0 -= delta;
if sel.block {
let (rl, cl, rh, ch) = sel.block_bounds();
return block_selection_text(&term, rl, cl as usize, rh, ch as usize);
}
let (sr, sc, er, ec) = sel.normalised();
extract_selection_text(&term, sr, sc as usize, er, ec as usize)
}
pub fn uid(&self) -> u64 {
self.uid
}
pub fn write_input(&mut self, data: &[u8]) {
self.reset_scrollback();
self.input_seen = true;
#[cfg(test)]
self.written_for_test
.lock()
.unwrap()
.extend_from_slice(data);
if let Ok(mut w) = self.writer.lock() {
let _ = w.write_all(data);
let _ = w.flush();
}
self.pty_dirty.store(true, Ordering::Release);
}
#[cfg(test)]
pub fn written_bytes_for_test(&self) -> Vec<u8> {
self.written_for_test.lock().unwrap().clone()
}
pub fn mouse_reporting(&self) -> bool {
self.term.lock().mode().intersects(TermMode::MOUSE_MODE)
}
pub fn report_mouse(
&mut self,
button: MouseButtonKind,
action: MouseAction,
col: u16,
row: u16,
mods: MouseMods,
) -> bool {
let Some((r, c)) = self.cell_at(col, row) else {
return false;
};
let mode = *self.term.lock().mode();
if !mode.intersects(TermMode::MOUSE_MODE) {
return false;
}
if action == MouseAction::Motion
&& !mode.intersects(TermMode::MOUSE_DRAG | TermMode::MOUSE_MOTION)
{
return false;
}
let report = encode_mouse_report(
mode.contains(TermMode::SGR_MOUSE),
button,
action,
c,
r,
mods,
);
if let Ok(mut w) = self.writer.lock() {
let _ = w.write_all(&report);
let _ = w.flush();
}
self.input_seen = true;
self.pty_dirty.store(true, Ordering::Release);
true
}
pub fn change_cwd(&mut self, path: &std::path::Path) {
self.write_input(&format_cd_command(path));
}
pub fn paste_input(&mut self, payload: &[u8]) {
if self.bracketed_paste_enabled.load(Ordering::Acquire) {
self.write_input(b"\x1b[200~");
self.write_input(payload);
self.write_input(b"\x1b[201~");
} else {
self.write_input(payload);
}
}
pub fn foreground_is_shell(&self) -> bool {
match (self.master.process_group_leader(), self.shell_pid) {
(Some(fg), Some(pid)) => fg == pid,
_ if self.input_seen => {
std::thread::sleep(std::time::Duration::from_millis(5));
match (self.master.process_group_leader(), self.shell_pid) {
(Some(fg), Some(pid)) => fg == pid,
_ => false,
}
}
_ => true,
}
}
pub fn cwd_seed_is_safe(&self) -> bool {
self.foreground_is_shell() || (!self.input_seen && self.marks.lock().unwrap().is_empty())
}
#[cfg(test)]
pub fn foreground_resolved_for_test(&self) -> Option<bool> {
match (self.master.process_group_leader(), self.shell_pid) {
(Some(fg), Some(pid)) => Some(fg == pid),
_ => None,
}
}
pub fn is_pristine(&self) -> bool {
!self.run_pane && !self.input_seen && !self.manual_name_seen
}
pub fn scroll_up(&mut self, n: usize) -> bool {
let mut term = self.term.lock();
if term.mode().contains(TermMode::ALT_SCREEN) {
return false;
}
term.scroll_display(Scroll::Delta(n as i32));
self.pty_dirty.store(true, Ordering::Release);
true
}
pub fn scroll_down(&mut self, n: usize) -> bool {
let mut term = self.term.lock();
if term.mode().contains(TermMode::ALT_SCREEN) {
return false;
}
term.scroll_display(Scroll::Delta(-(n as i32)));
self.pty_dirty.store(true, Ordering::Release);
true
}
pub fn scroll_to_top(&mut self) -> bool {
let mut term = self.term.lock();
if term.mode().contains(TermMode::ALT_SCREEN) {
return false;
}
term.scroll_display(Scroll::Top);
drop(term);
self.pty_dirty.store(true, Ordering::Release);
true
}
pub fn reset_scrollback(&mut self) -> bool {
let mut term = self.term.lock();
if term.mode().contains(TermMode::ALT_SCREEN) {
return false;
}
term.scroll_display(Scroll::Bottom);
self.pty_dirty.store(true, Ordering::Release);
true
}
pub fn clear_screen_and_scrollback(&mut self) {
let mut processor = Processor::<StdSyncHandler>::new();
{
let mut term = self.term.lock();
processor.advance(&mut *term, b"\x1b[2J\x1b[3J\x1b[H");
term.scroll_display(Scroll::Bottom);
}
self.images.lock().unwrap().clear();
self.marks.lock().unwrap().clear();
self.pty_dirty.store(true, Ordering::Release);
}
pub fn resize(&mut self, cols: u16, rows: u16) {
let (cols, rows) = (cols.max(2), rows.max(2));
if cols == self.cols && rows == self.rows {
return;
}
self.cols = cols;
self.rows = rows;
*self.size_shared.lock().unwrap() = (cols, rows);
let _ = self.master.resize(PtySize {
cols,
rows,
pixel_width: 0,
pixel_height: 0,
});
let mut term = self.term.lock();
let size = TermSize::new(cols as usize, rows as usize);
term.resize(size);
self.pty_dirty.store(true, Ordering::Release);
}
}
fn wait_pty_readable(pty_fd: std::os::fd::RawFd, shutdown: &std::io::PipeReader) -> bool {
use std::os::fd::AsRawFd;
let mut fds = [
libc::pollfd {
fd: pty_fd,
events: libc::POLLIN,
revents: 0,
},
libc::pollfd {
fd: shutdown.as_raw_fd(),
events: libc::POLLIN,
revents: 0,
},
];
loop {
let n = unsafe { libc::poll(fds.as_mut_ptr(), 2, -1) };
if n < 0 {
if std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted {
continue;
}
return false;
}
if fds[1].revents != 0 {
return false;
}
if fds[0].revents != 0 {
return true;
}
}
}
impl Drop for PtyTerminal {
fn drop(&mut self) {
let _ = self._child.kill();
let _ = self._child.wait();
drop(self.reader_shutdown.take());
if let Some(handle) = self.reader_thread.take() {
let _ = handle.join();
}
}
}
pub fn row_text_and_cols(term: &Term<VoidListener>, line_idx: i32) -> (String, Vec<usize>) {
let ncols = term.columns();
let mut s = String::with_capacity(ncols);
let mut cols = Vec::with_capacity(ncols);
for c in 0..ncols {
let cell = &term.grid()[Point::new(Line(line_idx), Column(c))];
if cell
.flags
.intersects(Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER)
{
continue;
}
s.push(if cell.c == '\0' { ' ' } else { cell.c });
cols.push(c);
}
(s, cols)
}
fn last_command_input_text(
term: &Term<VoidListener>,
marks: &[StoredMark],
clock_now: i64,
) -> String {
use crate::shell_integration::OscEvent as E;
let cur = |m: &StoredMark| m.line_rec - (clock_now - m.clock_rec) as i32;
let Some(ci) = marks
.iter()
.rposition(|m| matches!(m.kind, E::CommandStart))
else {
return String::new();
};
let Some(b) = marks[..ci]
.iter()
.rev()
.find(|m| matches!(m.kind, E::PromptEnd))
else {
return String::new();
};
let bl = cur(b);
let cl = cur(&marks[ci]);
if cl <= bl {
return String::new();
}
extract_selection_text(
term,
bl,
b.col_rec,
cl - 1,
term.columns().saturating_sub(1),
)
}
fn last_command_output_text(
term: &Term<VoidListener>,
marks: &[StoredMark],
clock_now: i64,
) -> String {
use crate::shell_integration::OscEvent as E;
let Some(c) = marks
.iter()
.rev()
.find(|m| matches!(m.kind, E::CommandStart))
else {
return String::new();
};
let start = c.line_rec - (clock_now - c.clock_rec) as i32;
let end = term.grid().cursor.point.line.0;
if end < start {
return String::new();
}
let text = extract_selection_text(term, start, 0, end, term.columns().saturating_sub(1));
let text = text.trim_end_matches('\n');
let lines: Vec<&str> = text.lines().collect();
if lines.len() > FINISHED_OUTPUT_CAP_LINES {
lines[lines.len() - FINISHED_OUTPUT_CAP_LINES..].join("\n")
} else {
text.to_string()
}
}
fn hhmmss(millis: u64) -> String {
#[allow(deprecated)]
let secs = (millis / 1000) as libc::time_t;
let mut tm: libc::tm = unsafe { std::mem::zeroed() };
if unsafe { libc::localtime_r(&secs, &mut tm) }.is_null() {
return String::from("--:--:--");
}
format!("{:02}:{:02}:{:02}", tm.tm_hour, tm.tm_min, tm.tm_sec)
}
fn partial_overlap_cols(want: &str, got: &str, colmap: &[usize]) -> Vec<(u16, u16)> {
let want = want.trim_end();
let got = got.trim_end();
let want_n = want.chars().count();
let got_n = got.chars().count();
if want_n == 0 || got_n == 0 {
return Vec::new();
}
let prefix = want
.chars()
.zip(got.chars())
.take_while(|(a, b)| a == b)
.count();
let suffix = want
.chars()
.rev()
.zip(got.chars().rev())
.take_while(|(a, b)| a == b)
.count();
let solid =
|chars: &mut dyn Iterator<Item = char>| chars.filter(|c| !c.is_whitespace()).count() >= 4;
let good_prefix = prefix > 0 && solid(&mut want.chars().take(prefix));
let good_suffix = suffix > 0 && solid(&mut want.chars().rev().take(suffix));
let mut spans = Vec::new();
if good_prefix && good_suffix && prefix + suffix >= got_n {
spans.push((colmap[0] as u16, colmap[got_n - 1] as u16));
} else {
if good_prefix {
spans.push((colmap[0] as u16, colmap[prefix - 1] as u16));
}
if good_suffix {
spans.push((colmap[got_n - suffix] as u16, colmap[got_n - 1] as u16));
}
}
spans
}
fn capture_alt_anchor(term: &Term<VoidListener>, sel: Selection) -> Option<AltSelAnchor> {
let rows_vis = term.screen_lines() as i32;
let (lo, hi) = (sel.anchor.0.min(sel.head.0), sel.anchor.0.max(sel.head.0));
if lo < 0 || hi >= rows_vis {
return None;
}
let rows = (lo..=hi).map(|l| row_text_and_cols(term, l).0).collect();
let ctx_above = (lo > 0).then(|| row_text_and_cols(term, lo - 1).0);
let ctx_below = (hi + 1 < rows_vis).then(|| row_text_and_cols(term, hi + 1).0);
let text = if sel.block {
let (rl, cl, rh, ch) = sel.block_bounds();
block_selection_text(term, rl, cl as usize, rh, ch as usize)
} else {
let (sr, sc, er, ec) = sel.normalised();
extract_selection_text(term, sr, sc as usize, er, ec as usize)
};
Some(AltSelAnchor {
rows,
top: lo,
text,
dormant: false,
visible: None,
ctx_above,
ctx_below,
})
}
pub fn extract_selection_text(
term: &Term<VoidListener>,
sr: i32,
sc: usize,
er: i32,
ec: usize,
) -> String {
let cols = term.columns();
let max_line = term.screen_lines() as i32 - 1;
let min_line = term.grid().topmost_line().0;
let sr = sr.max(min_line);
let er = er.min(max_line);
let mut out = String::new();
let mut line_idx = sr;
while line_idx <= er {
let row_start = if line_idx == sr { sc } else { 0 };
let row_end = if line_idx == er {
ec.min(cols.saturating_sub(1))
} else {
cols.saturating_sub(1)
};
let mut line = String::new();
for col in row_start..=row_end {
let p = Point::new(Line(line_idx), Column(col));
let cell = &term.grid()[p];
if cell
.flags
.intersects(Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER)
{
continue;
}
let c = cell.c;
if c == '\0' {
line.push(' ');
} else {
line.push(c);
}
}
let trimmed = line.trim_end();
out.push_str(trimmed);
if line_idx != er {
let wrapped = cols > 0
&& term.grid()[Point::new(Line(line_idx), Column(cols - 1))]
.flags
.contains(Flags::WRAPLINE);
if !wrapped {
out.push('\n');
}
}
line_idx += 1;
}
out
}
pub fn select_word_at_in_term(
term: &Term<VoidListener>,
display_offset: usize,
row: usize,
col: usize,
) -> Option<((u16, u16), (u16, u16))> {
let cols = term.columns();
if col >= cols {
return None;
}
let row_idx = row as i32 - display_offset as i32;
let cell_char = |c: usize| -> char {
let p = Point::new(Line(row_idx), Column(c));
let ch = term.grid()[p].c;
if ch == '\0' { ' ' } else { ch }
};
if !is_terminal_word_char(cell_char(col)) {
return None;
}
let mut start = col;
while start > 0 && is_terminal_word_char(cell_char(start - 1)) {
start -= 1;
}
let mut end = col;
while end + 1 < cols && is_terminal_word_char(cell_char(end + 1)) {
end += 1;
}
Some(((row as u16, start as u16), (row as u16, end as u16)))
}
pub fn is_terminal_word_char(c: char) -> bool {
c.is_alphanumeric() || c == '_'
}
pub fn encode_mouse_report(
sgr: bool,
button: MouseButtonKind,
action: MouseAction,
local_col: u16,
local_row: u16,
mods: MouseMods,
) -> Vec<u8> {
let mut cb: u8 = match button {
MouseButtonKind::Left => 0,
MouseButtonKind::Middle => 1,
MouseButtonKind::Right => 2,
MouseButtonKind::WheelUp => 64,
MouseButtonKind::WheelDown => 65,
};
if action == MouseAction::Motion {
cb += 32;
}
if mods.shift {
cb += 4;
}
if mods.alt {
cb += 8;
}
if mods.ctrl {
cb += 16;
}
let cx = local_col + 1;
let cy = local_row + 1;
if sgr {
let terminator = if action == MouseAction::Release {
'm'
} else {
'M'
};
format!("\x1b[<{cb};{cx};{cy}{terminator}").into_bytes()
} else {
if action == MouseAction::Release {
cb = (cb & !0b11) | 0b11;
}
let enc = |v: u16| (v.min(223) as u8).wrapping_add(32);
vec![0x1b, b'[', b'M', cb.wrapping_add(32), enc(cx), enc(cy)]
}
}
pub fn format_cd_command(path: &std::path::Path) -> Vec<u8> {
let s = path.to_string_lossy();
let mut out = Vec::with_capacity(s.len() + 8);
out.extend_from_slice(b"\x05\x15cd '");
for c in s.chars() {
if c == '\'' {
out.extend_from_slice(b"'\\''");
} else {
let mut buf = [0u8; 4];
out.extend_from_slice(c.encode_utf8(&mut buf).as_bytes());
}
}
out.extend_from_slice(b"'\n");
out
}
pub fn sniff_bracketed_paste_mode(chunk: &[u8], flag: &AtomicBool) {
let needle_set: &[u8] = b"\x1b[?2004h";
let needle_reset: &[u8] = b"\x1b[?2004l";
let mut i = 0;
while i < chunk.len() {
if chunk[i..].starts_with(needle_set) {
flag.store(true, Ordering::Release);
i += needle_set.len();
} else if chunk[i..].starts_with(needle_reset) {
flag.store(false, Ordering::Release);
i += needle_reset.len();
} else {
i += 1;
}
}
}
pub fn osc52_copy_seq(text: &str) -> Vec<u8> {
use base64::Engine;
let encoded = base64::engine::general_purpose::STANDARD.encode(text.as_bytes());
let mut out = Vec::with_capacity(encoded.len() + 8);
out.extend_from_slice(b"\x1b]52;c;");
out.extend_from_slice(encoded.as_bytes());
out.push(0x07);
out
}
fn ansi_to_ratatui(c: AnsiColor, palette: &[(u8, u8, u8); 16]) -> Option<Color> {
match c {
AnsiColor::Spec(rgb) => Some(Color::Rgb(rgb.r, rgb.g, rgb.b)),
AnsiColor::Indexed(i) if i < 16 => Some(pal(palette, i as usize)),
AnsiColor::Indexed(i) => Some(Color::Indexed(i)),
AnsiColor::Named(named) => named_to_ratatui(named, palette),
}
}
fn pal(palette: &[(u8, u8, u8); 16], i: usize) -> Color {
let (r, g, b) = palette[i];
Color::Rgb(r, g, b)
}
fn named_to_ratatui(n: NamedColor, palette: &[(u8, u8, u8); 16]) -> Option<Color> {
use NamedColor::*;
match n {
Foreground | Background | Cursor | DimForeground => None,
Black | DimBlack => Some(pal(palette, 0)),
Red | DimRed => Some(pal(palette, 1)),
Green | DimGreen => Some(pal(palette, 2)),
Yellow | DimYellow => Some(pal(palette, 3)),
Blue | DimBlue => Some(pal(palette, 4)),
Magenta | DimMagenta => Some(pal(palette, 5)),
Cyan | DimCyan => Some(pal(palette, 6)),
White | DimWhite => Some(pal(palette, 7)),
BrightBlack => Some(pal(palette, 8)),
BrightRed => Some(pal(palette, 9)),
BrightGreen => Some(pal(palette, 10)),
BrightYellow => Some(pal(palette, 11)),
BrightBlue => Some(pal(palette, 12)),
BrightMagenta => Some(pal(palette, 13)),
BrightCyan => Some(pal(palette, 14)),
BrightWhite => Some(pal(palette, 15)),
BrightForeground => None,
}
}
impl Widget for &mut PtyTerminal {
fn render(self, area: Rect, buf: &mut Buffer) {
let block_style = if let Some((r, g, b)) = self.accent {
Style::default().fg(Color::Rgb(r, g, b))
} else if self.focused {
Style::default().fg(self.theme.ui(Color::Rgb(0x4e, 0x9a, 0xff)))
} else {
Style::default().fg(Color::DarkGray)
};
let block = Block::default()
.borders(Borders::ALL)
.border_style(block_style);
let inner = block.inner(area);
block.render(area, buf);
if self.focused && self.focus_gradient && self.accent.is_none() {
crate::gradient::paint_gradient_box(buf, area);
}
self.last_area = area;
self.last_inner = inner;
self.rebase_selection();
let dormant = self.alt_sel.as_ref().is_some_and(|a| a.dormant);
let sel_clip = self.alt_sel.as_ref().and_then(|a| a.visible.clone());
let sel_paint = self.selection.filter(|_| !dormant).map(|s| {
if s.block {
(true, s.block_bounds())
} else {
(false, s.normalised())
}
});
let cols = inner.width;
let rows = inner.height;
self.resize(cols, rows);
let decorations = self.command_decorations();
let trigger_set = self.triggers.lock().unwrap().clone();
let term = self.term.lock();
let ann_spans: Vec<(i32, u16, u16)> = if term.mode().contains(TermMode::ALT_SCREEN) {
Vec::new()
} else {
let ann_now = self.clock_now(&term);
self.annotations
.iter()
.map(|a| (a.line_rec - (ann_now - a.clock_rec) as i32, a.start, a.len))
.collect()
};
let display_offset = term.grid().display_offset();
let cursor_visible = term.mode().contains(TermMode::SHOW_CURSOR) && self.focused;
let alt_screen = term.mode().contains(TermMode::ALT_SCREEN);
let cursor_point = term.grid().cursor.point;
let cursor_row_in_viewport = if alt_screen {
cursor_point.line.0
} else {
cursor_point.line.0 + display_offset as i32
};
let cursor_col_in_viewport = cursor_point.column.0 as i32;
let hint_drift: i32 = self
.hints
.as_ref()
.map_or(0, |(c0, _)| (self.clock_now(&term) - c0) as i32);
let active_match: Option<(i32, usize, usize)> = self
.current_match
.map(|(c0, l, c, n)| (l - (self.clock_now(&term) - c0) as i32, c, n));
for y in 0..rows {
let row_line_idx = (y as i32) - (display_offset as i32);
let row_paint: Option<Vec<u8>> = self.search_needle.as_deref().map(|needle| {
let (text, colmap) = row_text_and_cols(&term, row_line_idx);
let mut paint = vec![0u8; cols as usize];
for (mc, ml) in
crate::widgets::editor_find::line_matches(&text, self.search_opts, needle)
{
let active = active_match == Some((row_line_idx, mc, ml));
for k in mc..mc + ml {
if let Some(&col) = colmap.get(k) {
paint[col] = if active { 2 } else { 1 };
}
}
}
paint
});
let hint_paint: Option<(Vec<u8>, Vec<char>)> =
self.hints.as_ref().and_then(|(_, hints)| {
let row_hints: Vec<&HintSpan> = hints
.iter()
.filter(|h| h.line - hint_drift == row_line_idx)
.collect();
if row_hints.is_empty() {
return None;
}
let (_text, colmap) = row_text_and_cols(&term, row_line_idx);
let mut span = vec![0u8; cols as usize];
let mut label = vec!['\0'; cols as usize];
for h in row_hints {
for k in h.start..h.start + h.len {
if let Some(&col) = colmap.get(k) {
span[col] = 1;
}
}
for (j, c) in h.label.chars().skip(h.typed).enumerate() {
if let Some(&col) = colmap.get(h.start + j) {
span[col] = 2;
label[col] = c;
}
}
}
Some((span, label))
});
let trig_paint: Option<TrigRowPaint> = trigger_set.has_highlights().then(|| {
let (text, colmap) = row_text_and_cols(&term, row_line_idx);
let mut paint: TrigRowPaint = vec![None; cols as usize];
for s in crate::triggers::highlight_spans(&text, &trigger_set) {
let fg = s.fg.map(|(r, g, b)| Color::Rgb(r, g, b));
let bg = s.bg.map(|(r, g, b)| Color::Rgb(r, g, b));
for k in s.start..s.start + s.len {
if let Some(&col) = colmap.get(k) {
paint[col] = Some((fg, bg));
}
}
}
paint
});
for x in 0..cols {
let line_idx = (y as i32) - (display_offset as i32);
let p = Point::new(Line(line_idx), Column(x as usize));
let cell = &term.grid()[p];
let mut display_char = if cell.c == '\0' { ' ' } else { cell.c };
let mut style = Style::default();
if let Some(c) = ansi_to_ratatui(cell.fg, &self.palette) {
style = style.fg(c);
}
if let Some(c) = ansi_to_ratatui(cell.bg, &self.palette) {
style = style.bg(c);
}
let flags = cell.flags;
if flags.contains(Flags::BOLD) {
style = style.add_modifier(Modifier::BOLD);
}
if flags.contains(Flags::ITALIC) {
style = style.add_modifier(Modifier::ITALIC);
}
if flags.contains(Flags::DIM) {
style = style.add_modifier(Modifier::DIM);
}
if flags.intersects(Flags::ALL_UNDERLINES) {
style = style.add_modifier(Modifier::UNDERLINED);
}
if flags.contains(Flags::INVERSE) {
style = style.add_modifier(Modifier::REVERSED);
}
if let Some(paint) = trig_paint.as_ref()
&& let Some(Some((fg, bg))) = paint.get(x as usize)
{
if let Some(c) = fg {
style = style.fg(*c);
}
if let Some(c) = bg {
style = style.bg(*c);
}
}
if ann_spans
.iter()
.any(|&(l, s0, ln)| l == line_idx && x >= s0 && x < s0 + ln)
{
style = style
.fg(self.theme.ui(Color::Rgb(0xe5, 0xc0, 0x7b)))
.add_modifier(Modifier::UNDERLINED);
}
if cursor_visible
&& (y as i32) == cursor_row_in_viewport
&& (x as i32) == cursor_col_in_viewport
{
style = style.add_modifier(Modifier::REVERSED);
}
if let Some((block, (sr, sc, er, ec))) = sel_paint
&& sel_clip.as_ref().is_none_or(|clips| {
clips
.iter()
.any(|&(l, lo, hi)| l == line_idx && x >= lo && x <= hi)
})
&& if block {
cell_in_block_selection(line_idx, x, sr, sc, er, ec)
} else {
cell_in_selection(line_idx, x, sr, sc, er, ec)
}
{
style = style.bg(self.theme.ui(Color::Rgb(0x26, 0x4f, 0x78)));
}
if let Some(paint) = row_paint.as_ref() {
match paint.get(x as usize) {
Some(1) => {
style = style
.fg(Color::Black)
.bg(self.theme.ui(Color::Rgb(0xff, 0xd7, 0x4a)))
.add_modifier(Modifier::BOLD);
}
Some(2) => {
style = style
.fg(Color::Black)
.bg(self.theme.ui(Color::Rgb(0xff, 0x8c, 0x2a)))
.add_modifier(Modifier::BOLD);
}
_ => {}
}
}
if let Some((span, labels)) = hint_paint.as_ref() {
match span.get(x as usize) {
Some(1) => {
style = style
.fg(self.theme.ui(Color::Rgb(0x66, 0xcc, 0x66)))
.add_modifier(Modifier::BOLD);
}
Some(2) => {
if let Some(&lc) = labels.get(x as usize)
&& lc != '\0'
{
display_char = lc;
}
style = Style::default()
.fg(Color::Black)
.bg(self.theme.ui(Color::Rgb(0xff, 0xd7, 0x4a)))
.add_modifier(Modifier::BOLD);
}
_ => {}
}
}
if let Some((cl, cc)) = self.copy_cursor
&& line_idx == cl
&& x == cc
{
style = Style::default()
.fg(Color::Black)
.bg(self.theme.ui(Color::Rgb(0x66, 0xcc, 0x66)))
.add_modifier(Modifier::BOLD);
}
let target_x = inner.x + x;
let target_y = inner.y + y;
let target = &mut buf[(target_x, target_y)];
let mut tmp = [0u8; 4];
target.set_symbol(display_char.encode_utf8(&mut tmp));
target.set_style(style);
}
}
if let Some((state, pct)) = *self.progress.lock().unwrap()
&& area.height >= 2
&& inner.width > 0
{
let w = inner.width as u32;
let (fill_from, fill_len) = if state == 3 {
let seg = (w / 5).max(1);
let span = (w - seg).max(1);
let ms = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u32)
.unwrap_or(0);
((ms / 80) % span, seg)
} else {
(0, w * u32::from(pct.min(100)) / 100)
};
let color = match state {
2 => self.theme.ui(Color::Rgb(0xf1, 0x4c, 0x4c)),
4 => self.theme.ui(Color::Rgb(0xe5, 0xc0, 0x7b)),
_ => self.theme.ui(Color::Rgb(0x1b, 0x81, 0xa8)),
};
let by = area.y + area.height - 1;
for i in 0..fill_len.min(w) {
let x = inner.x + (fill_from + i) as u16;
let cell = &mut buf[(x, by)];
cell.set_symbol("━");
cell.set_style(Style::default().fg(color));
}
}
if self.show_timestamps && !alt_screen && inner.width > 14 {
let clock_now = self.clock_now(&term);
let lt = self.line_times.lock().unwrap();
for y in 0..rows {
let abs = clock_now + (y as i32 - display_offset as i32) as i64;
let Some(&ms) = lt.get(&abs) else { continue };
let prev = lt.range(..abs).next_back().map(|(_, &v)| v);
let stalled = prev.is_some_and(|p| ms.saturating_sub(p) >= STALL_GAP_MS);
let mut text = hhmmss(ms);
if stalled {
text = format!("\u{26a0} {text}");
}
let tw = text.chars().count() as u16;
if tw >= inner.width {
continue;
}
let x0 = inner.x + inner.width - tw;
let fg = if stalled {
self.theme.ui(Color::Rgb(0xe5, 0xc0, 0x7b))
} else {
self.theme.ui(Color::Rgb(0x5b, 0x64, 0x72))
};
for (j, c) in text.chars().enumerate() {
let cell = &mut buf[(x0 + j as u16, inner.y + y)];
let mut tmpc = [0u8; 4];
cell.set_symbol(c.encode_utf8(&mut tmpc));
cell.set_style(Style::default().fg(fg));
}
}
}
if let (Some((r, g, b)), Some(badge)) = (self.accent, self.accent_badge.as_deref())
&& !badge.is_empty()
{
let bw = badge.chars().count() as u16;
if bw + 2 < inner.width {
let x0 = inner.x + inner.width - bw - 1;
for (j, c) in badge.chars().enumerate() {
let cell = &mut buf[(x0 + j as u16, inner.y)];
let mut tmpc = [0u8; 4];
cell.set_symbol(c.encode_utf8(&mut tmpc));
cell.set_style(
Style::default()
.fg(Color::Rgb(r, g, b))
.add_modifier(Modifier::DIM | Modifier::BOLD),
);
}
}
}
if display_offset > 0 && !alt_screen && rows > 0 && inner.width > 4 {
let top_row = -(display_offset as i32);
let cols_last = term.columns().saturating_sub(1);
let header = decorations
.iter()
.find(|d| d.line < top_row && d.output_start <= top_row && top_row < d.output_end)
.and_then(|d| {
let (l, c) = d.input?;
(d.output_start > l)
.then(|| extract_selection_text(&term, l, c, d.output_start - 1, cols_last))
})
.or_else(|| {
let ms = self.marks.lock().unwrap();
let running = ms.last().is_some_and(|m| {
matches!(m.kind, crate::shell_integration::OscEvent::CommandStart)
});
if !running {
return None;
}
let now = self.clock_now(&term);
let last = ms.last().unwrap();
let c_line = last.line_rec - (now - last.clock_rec) as i32;
(c_line < top_row).then(|| last_command_input_text(&term, &ms, now))
})
.filter(|t| !t.trim().is_empty());
if let Some(text) = header {
let bg = self.theme.ui(Color::Rgb(0x25, 0x2b, 0x36));
for x in 0..inner.width {
let cell = &mut buf[(inner.x + x, inner.y)];
cell.set_symbol(" ");
cell.set_style(Style::default().bg(bg));
}
let label: String = format!("\u{25b6} {}", text.trim())
.chars()
.map(|c| if c.is_control() { ' ' } else { c })
.collect();
let mut xw = inner.x + 1;
for ch in label.chars() {
if xw + 1 >= inner.x + inner.width {
break;
}
let cell = &mut buf[(xw, inner.y)];
let mut tmpc = [0u8; 4];
cell.set_symbol(ch.encode_utf8(&mut tmpc));
cell.set_style(
Style::default()
.fg(self.theme.ui(Color::Rgb(0xec, 0xf0, 0xf4)))
.bg(bg)
.add_modifier(Modifier::BOLD),
);
xw += 1;
}
let right = format!(" \u{2191} {display_offset} ");
let rw = right.chars().count() as u16;
if xw + rw < inner.x + inner.width {
let x0 = inner.x + inner.width - rw;
for (j, ch) in right.chars().enumerate() {
let cell = &mut buf[(x0 + j as u16, inner.y)];
let mut tmpc = [0u8; 4];
cell.set_symbol(ch.encode_utf8(&mut tmpc));
cell.set_style(
Style::default()
.fg(self.theme.ui(Color::Rgb(0x8b, 0x93, 0xa1)))
.bg(bg),
);
}
}
}
}
if !alt_screen {
for d in &decorations {
let vp = d.line + display_offset as i32;
if (0..rows as i32).contains(&vp) {
let ok = d.exit.unwrap_or(0) == 0;
let cell = &mut buf[(area.x, inner.y + vp as u16)];
cell.set_symbol("●");
cell.set_style(Style::default().fg(if ok {
self.theme.ui(Color::Rgb(0x1b, 0x81, 0xa8))
} else {
self.theme.ui(Color::Rgb(0xf1, 0x4c, 0x4c))
}));
}
}
}
}
}
type TrigRowPaint = Vec<Option<(Option<Color>, Option<Color>)>>;
pub fn scroll_offset_for_line(rows: i32, max_off: i32, abs_line: i32) -> i32 {
(rows / 2 - abs_line).clamp(0, max_off.max(0))
}
pub fn block_selection_text(
term: &Term<VoidListener>,
rl: i32,
cl: usize,
rh: i32,
ch: usize,
) -> String {
let max_line = term.screen_lines() as i32 - 1;
let min_line = term.grid().topmost_line().0;
let rl = rl.max(min_line);
let rh = rh.min(max_line);
let mut rows = Vec::new();
for line in rl..=rh {
rows.push(extract_selection_text(term, line, cl, line, ch));
}
rows.join("\n")
}
pub fn cell_in_block_selection(row: i32, col: u16, rl: i32, cl: u16, rh: i32, ch: u16) -> bool {
row >= rl && row <= rh && col >= cl && col <= ch
}
pub fn cell_in_selection(row: i32, col: u16, sr: i32, sc: u16, er: i32, ec: u16) -> bool {
if row < sr || row > er {
return false;
}
if row == sr && col < sc {
return false;
}
if row == er && col > ec {
return false;
}
true
}
#[cfg(test)]
mod tests {
use super::*;
fn zsh_or_skip() -> Option<&'static str> {
let zsh = "/bin/zsh";
if std::path::Path::new(zsh).exists() {
Some(zsh)
} else {
eprintln!("SKIPPED: {zsh} not installed on this machine");
None
}
}
fn fresh_term(cols: usize, rows: usize) -> Term<VoidListener> {
let cfg = Config {
scrolling_history: 1000,
..Config::default()
};
let size = TermSize::new(cols, rows);
Term::new(cfg, &size, VoidListener::default())
}
fn feed(term: &mut Term<VoidListener>, bytes: &[u8]) {
let mut p = Processor::<StdSyncHandler>::new();
p.advance(term, bytes);
}
#[test]
fn block_selection_highlights_and_extracts_a_rectangle() {
let mut term = fresh_term(20, 5);
feed(&mut term, b"alpha1\r\nbravo2\r\ncharlie3\r\n");
let sel = Selection {
anchor: (2, 3),
head: (0, 1),
block: true,
};
let (rl, cl, rh, ch) = sel.block_bounds();
assert_eq!((rl, cl, rh, ch), (0, 1, 2, 3));
assert!(cell_in_block_selection(1, 2, rl, cl, rh, ch));
assert!(!cell_in_block_selection(1, 0, rl, cl, rh, ch));
assert!(!cell_in_block_selection(1, 4, rl, cl, rh, ch));
assert!(!cell_in_block_selection(3, 2, rl, cl, rh, ch));
assert_eq!(
block_selection_text(&term, rl, cl as usize, rh, ch as usize),
"lph\nrav\nhar",
"a block selection copies the same column slice from every row"
);
}
#[test]
fn annotations_anchor_to_content_and_ride_the_scrollback() {
let tmp = tempfile::tempdir().unwrap();
let script = "n=note; echo ${n}-worthy-line; read x; i=0; while [ $i -lt 30 ]; do echo fill-$i; i=$((i+1)); done; sleep 30";
let mut term =
PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
.unwrap();
term.last_inner = Rect {
x: 0,
y: 0,
width: 80,
height: 24,
};
let mut waited = 0u32;
while !term
.grid_lines()
.0
.iter()
.any(|l| l.starts_with("note-worthy-line"))
{
assert!(waited < 8000, "line never arrived");
std::thread::sleep(std::time::Duration::from_millis(20));
waited += 20;
}
let (lines, top) = term.grid_lines();
let line = top
+ lines
.iter()
.position(|l| l.starts_with("note-worthy-line"))
.unwrap() as i32;
let clock = term.scroll_clock();
term.add_annotation(line, clock, 0, 16, String::from("this is where it broke"));
let (idx, text) = term
.annotation_at(3, line as u16)
.expect("the annotated cell must resolve");
assert_eq!(idx, 0);
assert_eq!(text, "this is where it broke");
assert!(
term.annotation_at(30, line as u16).is_none(),
"cells past the span carry no note"
);
term.write_input(b"\n");
let mut waited = 0u32;
while !term.grid_lines().0.iter().any(|l| l.starts_with("fill-29")) {
assert!(waited < 8000, "filler never arrived");
std::thread::sleep(std::time::Duration::from_millis(20));
waited += 20;
}
let (lines, top) = term.grid_lines();
let expect_line = top
+ lines
.iter()
.position(|l| l.starts_with("note-worthy-line"))
.unwrap() as i32;
let cur = term.annotations_current();
assert_eq!(cur.len(), 1);
assert_eq!(
cur[0].0, expect_line,
"the annotation must still sit on its content line"
);
assert_eq!(cur[0].3, "this is where it broke");
}
#[test]
fn prompt_click_arrows_map_a_click_to_cursor_motion() {
let tmp = tempfile::tempdir().unwrap();
let script = "h=hello; printf '\\033]133;A\\007$ \\033]133;B\\007'; printf \"${h}-world\"; read x; sleep 30";
let mut term =
PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
.unwrap();
term.last_inner = Rect {
x: 1,
y: 1,
width: 80,
height: 24,
};
let mut waited = 0u32;
while !term
.grid_lines()
.0
.iter()
.any(|l| l.contains("hello-world"))
{
assert!(waited < 8000, "prompt text never arrived");
std::thread::sleep(std::time::Duration::from_millis(20));
waited += 20;
}
let (lines, top) = term.grid_lines();
let vrow = (lines
.iter()
.position(|l| l.contains("hello-world"))
.unwrap() as i32
+ top) as u16; let bytes = term
.prompt_click_arrows(1 + 2, 1 + vrow)
.expect("a prompt-row click must produce motion");
assert_eq!(bytes, b"\x1b[D".repeat(11));
let bytes = term.prompt_click_arrows(1, 1 + vrow).unwrap();
assert_eq!(bytes, b"\x1b[D".repeat(11), "clamps to the 133;B column");
assert!(term.prompt_click_arrows(1 + 13, 1 + vrow).is_none());
assert!(term.prompt_click_arrows(1 + 2, 1 + vrow + 1).is_none());
}
#[test]
fn row_times_record_when_each_line_arrived() {
let (_tmp, t) = quiet_pty();
let mut prev = 0i64;
feed_pty(&t, b"first-marker\r\n");
t.stamp_chunk_for_test(&mut prev, 1000);
feed_pty(&t, b"second-marker\r\n");
t.stamp_chunk_for_test(&mut prev, 1400);
let (lines, top) = t.grid_lines();
let a = lines
.iter()
.position(|l| l.starts_with("first-marker"))
.expect("first line on the grid");
let b = lines
.iter()
.position(|l| l.starts_with("second-marker"))
.expect("second line on the grid");
let ta = t
.row_time(top + a as i32)
.expect("the first line must be stamped");
let tb = t
.row_time(top + b as i32)
.expect("the second line must be stamped");
assert_eq!(ta, 1000, "first row keeps its own chunk's arrival time");
assert_eq!(tb, 1400, "second row gets the later chunk's arrival time");
}
#[test]
fn reader_thread_stamps_arriving_rows() {
let tmp = tempfile::tempdir().unwrap();
let script = "a=first; echo ${a}-marker; sleep 30";
let term =
PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
.unwrap();
let mut waited = 0u32;
loop {
let (lines, top) = term.grid_lines();
if let Some(a) = lines.iter().position(|l| l.starts_with("first-marker")) {
assert!(
term.row_time(top + a as i32).is_some(),
"the reader thread must stamp rows it delivers"
);
break;
}
assert!(waited < 8000, "marker never arrived");
std::thread::sleep(std::time::Duration::from_millis(20));
waited += 20;
}
}
#[test]
fn resize_reflows_long_lines_instead_of_truncating() {
let mut term = fresh_term(30, 5);
feed(&mut term, b"abcdefghijklmnopqrstuvwxyz1234\r\n");
term.resize(TermSize::new(10, 5));
let top = term.grid().topmost_line().0;
let bottom = term.screen_lines() as i32 - 1;
let mut all = String::new();
for l in top..=bottom {
let (s, _) = row_text_and_cols(&term, l);
all.push_str(s.trim_end());
}
assert!(
all.contains("abcdefghijklmnopqrstuvwxyz1234"),
"text must survive a narrowing resize by reflowing: {all:?}"
);
term.resize(TermSize::new(40, 5));
let joined: Vec<String> = (term.grid().topmost_line().0..term.screen_lines() as i32)
.map(|l| row_text_and_cols(&term, l).0.trim_end().to_string())
.collect();
assert!(
joined
.iter()
.any(|r| r.contains("abcdefghijklmnopqrstuvwxyz1234")),
"widening must re-join the reflowed rows: {joined:?}"
);
}
#[test]
fn scroll_offset_centers_a_scrollback_match_and_clamps_to_the_range() {
assert_eq!(scroll_offset_for_line(24, 100, -80), 92);
assert_eq!(scroll_offset_for_line(24, 100, 20), 0);
assert_eq!(scroll_offset_for_line(24, 100, -200), 100);
assert_eq!(scroll_offset_for_line(24, 0, -5), 0);
}
#[test]
fn mouse_report_encoding_matches_the_xterm_wire_format() {
let none = MouseMods::default();
let shift = MouseMods {
shift: true,
..MouseMods::default()
};
assert_eq!(
encode_mouse_report(true, MouseButtonKind::Left, MouseAction::Press, 0, 0, none),
b"\x1b[<0;1;1M"
);
assert_eq!(
encode_mouse_report(
true,
MouseButtonKind::Left,
MouseAction::Release,
4,
2,
none
),
b"\x1b[<0;5;3m"
);
assert_eq!(
encode_mouse_report(
true,
MouseButtonKind::WheelDown,
MouseAction::Press,
9,
9,
none
),
b"\x1b[<65;10;10M"
);
assert_eq!(
encode_mouse_report(
true,
MouseButtonKind::Left,
MouseAction::Motion,
0,
0,
shift
),
b"\x1b[<36;1;1M"
);
assert_eq!(
encode_mouse_report(false, MouseButtonKind::Left, MouseAction::Press, 0, 0, none),
&[0x1b, b'[', b'M', 32, 33, 33]
);
assert_eq!(
encode_mouse_report(
false,
MouseButtonKind::Left,
MouseAction::Release,
0,
0,
none
),
&[0x1b, b'[', b'M', 35, 33, 33]
);
}
#[test]
fn dsr_cursor_position_query_round_trips_into_the_pty_response_channel() {
let (tx, rx) = std::sync::mpsc::channel::<String>();
let listener = VoidListener {
pty_response_tx: Some(tx),
size: Some(Arc::new(std::sync::Mutex::new((80, 24)))),
bell: None,
};
let cfg = Config::default();
let size = TermSize::new(80, 24);
let mut term = Term::new(cfg, &size, listener);
let mut processor = Processor::<StdSyncHandler>::new();
processor.advance(&mut term, b"\x1b[6n");
let response = rx
.recv_timeout(std::time::Duration::from_millis(500))
.expect("DSR cursor-position query must produce a PtyWrite event");
assert_eq!(
response, "\x1b[1;1R",
"a fresh terminal's cursor is at row 1, column 1 (1-based), so the reply must be ESC[1;1R"
);
}
#[test]
fn text_area_size_request_replies_with_the_current_grid_geometry() {
let (tx, rx) = std::sync::mpsc::channel::<String>();
let size = Arc::new(std::sync::Mutex::new((120u16, 40u16)));
let listener = VoidListener {
pty_response_tx: Some(tx),
size: Some(size),
bell: None,
};
let cfg = Config::default();
let term_size = TermSize::new(120, 40);
let mut term = Term::new(cfg, &term_size, listener);
let mut processor = Processor::<StdSyncHandler>::new();
processor.advance(&mut term, b"\x1b[18t");
let response = rx
.recv_timeout(std::time::Duration::from_millis(500))
.expect("CSI 18 t must produce a TextAreaSizeRequest reply on the channel");
assert_eq!(
response, "\x1b[8;40;120t",
"CSI 18 t reply format is ESC[8;<rows>;<cols>t per xterm convention"
);
}
#[test]
fn interactive_shell_invocation_passes_login_flag_for_zsh() {
let (program, args) = interactive_shell_invocation("/bin/zsh");
assert_eq!(program, "/bin/zsh");
assert_eq!(
args,
vec!["-l".to_string()],
"zsh must be spawned as a login shell so ~/.zprofile is sourced and the embedded terminal inherits the same env / keybindings as the user's native iTerm2 shell"
);
}
#[test]
fn interactive_shell_invocation_passes_login_flag_for_bash_fish_ksh() {
for path in [
"/bin/bash",
"/usr/local/bin/fish",
"/bin/ksh",
"/usr/bin/tcsh",
] {
let (_, args) = interactive_shell_invocation(path);
assert_eq!(
args,
vec!["-l".to_string()],
"{} must be spawned with -l so its login-shell rc files are sourced",
path
);
}
}
#[test]
fn interactive_shell_invocation_skips_login_flag_for_unknown_shells() {
let (_, args) = interactive_shell_invocation("/opt/exotic/myshell");
assert!(
args.is_empty(),
"an unknown shell must be spawned without -l in case the flag means something else there"
);
}
#[test]
fn sniff_bracketed_paste_mode_toggles_on_set_and_reset() {
let flag = AtomicBool::new(false);
sniff_bracketed_paste_mode(b"prompt> \x1b[?2004h", &flag);
assert!(flag.load(Ordering::Acquire));
sniff_bracketed_paste_mode(b"\x1b[?2004l\nbye", &flag);
assert!(!flag.load(Ordering::Acquire));
}
#[test]
fn sniff_bracketed_paste_mode_ignores_unrelated_dec_modes() {
let flag = AtomicBool::new(false);
sniff_bracketed_paste_mode(b"\x1b[?25h\x1b[?1049h", &flag);
assert!(!flag.load(Ordering::Acquire));
}
#[test]
fn pty_starts_dirty_so_first_frame_renders() {
let tmp = tempfile::tempdir().unwrap();
let term = PtyTerminal::new(tmp.path()).unwrap();
assert!(
term.take_dirty(),
"first take_dirty must be true so we draw the initial state"
);
}
#[test]
fn take_dirty_clears_the_flag() {
let tmp = tempfile::tempdir().unwrap();
let term = PtyTerminal::new(tmp.path()).unwrap();
let _ = term.take_dirty();
assert!(
!term.take_dirty(),
"second take_dirty without new bytes must be false"
);
}
#[test]
fn write_input_marks_dirty() {
let tmp = tempfile::tempdir().unwrap();
let mut term = PtyTerminal::new(tmp.path()).unwrap();
let _ = term.take_dirty();
term.write_input(b"echo hi\r");
assert!(
term.take_dirty(),
"write_input must mark the terminal dirty"
);
}
#[test]
fn dropping_a_terminal_reaps_a_hup_ignoring_shell() {
let tmp = tempfile::tempdir().unwrap();
let mut term = PtyTerminal::new(tmp.path()).unwrap();
let pid = term.pid().expect("spawned shell has a pid") as i32;
term.write_input(b"trap '' HUP; echo TRAP_$(echo armed)\n");
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while !term.visible_text().contains("TRAP_armed") {
assert!(
std::time::Instant::now() < deadline,
"staging: the shell never confirmed the HUP trap"
);
std::thread::sleep(std::time::Duration::from_millis(20));
}
drop(term);
let mut status = 0i32;
let r = unsafe { libc::waitpid(pid, &mut status, libc::WNOHANG) };
assert!(
r < 0,
"the shell was left as an unreaped zombie (waitpid still found it: r={r})"
);
}
#[test]
fn a_background_job_cannot_stall_a_dropped_pane() {
let tmp = tempfile::tempdir().unwrap();
let mut term = PtyTerminal::new(tmp.path()).unwrap();
term.write_input(b"sleep 30 &\n");
std::thread::sleep(std::time::Duration::from_millis(1500));
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
drop(term);
let _ = tx.send(());
});
assert!(
rx.recv_timeout(std::time::Duration::from_secs(10)).is_ok(),
"drop hung: the reader never woke while a background job held the pty slave"
);
}
#[test]
fn format_cd_command_single_quotes_plain_path() {
let bytes = format_cd_command(std::path::Path::new("/tmp/foo"));
assert_eq!(
bytes,
b"\x05\x15cd '/tmp/foo'\n".to_vec(),
"Ctrl-E + Ctrl-U must precede the cd so a half-typed prompt line is cleared first, then the path is single-quoted and newline-terminated to fire immediately"
);
}
#[test]
fn format_cd_command_escapes_embedded_apostrophe() {
let bytes = format_cd_command(std::path::Path::new("/tmp/it's a dir"));
assert_eq!(
bytes,
b"\x05\x15cd '/tmp/it'\\''s a dir'\n".to_vec(),
"embedded ' must be escaped as '\\'' so the cd does not break out of single quotes when the path contains an apostrophe (POSIX-standard quoting)"
);
}
#[test]
fn format_cd_command_quotes_paths_with_spaces() {
let bytes = format_cd_command(std::path::Path::new("/tmp/a b/c d"));
assert_eq!(
bytes,
b"\x05\x15cd '/tmp/a b/c d'\n".to_vec(),
"single-quoting must preserve spaces verbatim so cd lands at the right directory"
);
}
#[test]
fn foreground_is_shell_flips_false_while_a_foreground_command_runs() {
let tmp = tempfile::tempdir().unwrap();
let mut term = PtyTerminal::new(tmp.path()).unwrap();
let mut waited = 0u32;
while waited < 4000 && !term.foreground_is_shell() {
std::thread::sleep(std::time::Duration::from_millis(20));
waited += 20;
}
assert!(
term.foreground_is_shell(),
"a shell at its prompt is the tty's foreground process group, so a cd is safe to inject"
);
term.write_input(b"sleep 10\n");
let mut waited = 0u32;
while waited < 4000 && term.foreground_is_shell() {
std::thread::sleep(std::time::Duration::from_millis(20));
waited += 20;
}
assert!(
!term.foreground_is_shell(),
"while a foreground command owns the tty, the foreground group is the command not the shell, so a cd must not be injected"
);
}
fn startup_owned_pane(tmp: &tempfile::TempDir) -> PtyTerminal {
let script = tmp.path().join("slow-startup.sh");
std::fs::write(&script, "#!/bin/bash\nset -m\nsleep 30\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
}
let term = PtyTerminal::new_running(script.to_str().unwrap(), &[], tmp.path()).unwrap();
let mut waited = 0u32;
while waited < 4000 && term.foreground_is_shell() {
std::thread::sleep(std::time::Duration::from_millis(20));
waited += 20;
}
assert!(
!term.foreground_is_shell(),
"precondition: the startup child must own the foreground group"
);
term
}
#[test]
fn cwd_seed_stays_safe_through_startup_until_a_prompt_mark_arrives() {
let tmp = tempfile::tempdir().unwrap();
let term = startup_owned_pane(&tmp);
assert!(
term.cwd_seed_is_safe(),
"an untouched pane whose foreground group is shell startup must stay seedable: the seed queues as type-ahead for the first prompt"
);
term.push_mark_for_test(crate::shell_integration::OscEvent::PromptStart, 0);
assert!(
!term.cwd_seed_is_safe(),
"after the first prompt mark, a non-shell foreground group must suppress the seed"
);
}
#[test]
fn cwd_seed_turns_unsafe_once_the_pane_has_received_input() {
let tmp = tempfile::tempdir().unwrap();
let mut term = startup_owned_pane(&tmp);
term.write_input(b"q");
assert!(
!term.cwd_seed_is_safe(),
"after input has been written, a non-shell foreground group must suppress the seed"
);
}
#[test]
fn a_foreground_process_cannot_impersonate_a_local_cwd_report() {
let out = std::process::Command::new("hostname").output().unwrap();
let local = String::from_utf8_lossy(&out.stdout).trim().to_string();
if local.is_empty() {
return;
}
let tmp = tempfile::tempdir().unwrap();
let mut term = PtyTerminal::new(tmp.path()).unwrap();
let mut waited = 0u32;
while waited < 4000 && !term.foreground_is_shell() {
std::thread::sleep(std::time::Duration::from_millis(20));
waited += 20;
}
let mut waited = 0u32;
while waited < 4000 && term.shell_cwd().is_none() {
std::thread::sleep(std::time::Duration::from_millis(20));
waited += 20;
}
term.write_input(
format!("sleep 0.5; printf '\\033]7;file://{local}/tmp\\007'; sleep 10\n").as_bytes(),
);
let mut waited = 0u32;
while waited < 4000 && term.foreground_is_shell() {
std::thread::sleep(std::time::Duration::from_millis(20));
waited += 20;
}
assert!(!term.foreground_is_shell(), "staging: a job owns the tty");
let claim = std::path::PathBuf::from("/tmp");
let mut waited = 0u32;
while waited < 6000 && term.shell_cwd().as_deref() != Some(claim.as_path()) {
std::thread::sleep(std::time::Duration::from_millis(20));
waited += 20;
}
assert_eq!(
term.shell_cwd(),
Some(claim),
"staging: the claim was captured"
);
assert_eq!(
term.local_shell_cwd(),
None,
"a tty-owning foreground process must not place local splits by claim"
);
}
#[test]
fn a_claim_parsed_only_after_its_job_died_is_still_untrusted() {
let Some(zsh) = zsh_or_skip() else { return };
let tmp = tempfile::tempdir().unwrap();
let mut term =
PtyTerminal::new_running(zsh, &[String::from("-f"), String::from("-i")], tmp.path())
.unwrap();
let mut waited = 0u32;
while waited < 4000 && !term.foreground_is_shell() {
std::thread::sleep(std::time::Duration::from_millis(20));
waited += 20;
}
let term_arc = term.term.clone();
term.write_input(
b"/bin/sh -c 'sleep 1; printf \"\\033]7;file://localhost/tmp\\007\"; sleep 1'\n",
);
let mut waited = 0u32;
while waited < 4000 && term.foreground_is_shell() {
std::thread::sleep(std::time::Duration::from_millis(20));
waited += 20;
}
assert!(!term.foreground_is_shell(), "staging: the job took the tty");
std::thread::sleep(std::time::Duration::from_millis(150));
let guard = term_arc.lock();
let mut waited = 0u32;
while waited < 8000 && !term.foreground_is_shell() {
std::thread::sleep(std::time::Duration::from_millis(20));
waited += 20;
}
assert!(
term.foreground_is_shell(),
"staging: the job is gone and the shell owns the tty again"
);
std::thread::sleep(std::time::Duration::from_millis(300));
drop(guard);
let mut waited = 0u32;
while waited < 4000 && term.shell_cwd() != Some(std::path::PathBuf::from("/tmp")) {
std::thread::sleep(std::time::Duration::from_millis(20));
waited += 20;
}
assert_eq!(
term.shell_cwd(),
Some(std::path::PathBuf::from("/tmp")),
"staging: the claim was captured after the job died"
);
assert_eq!(
term.local_shell_cwd(),
None,
"a claim whose bytes were parsed after its job died must not be trusted"
);
}
#[test]
fn a_stale_claim_from_a_dead_foreground_job_stays_untrusted() {
let Some(zsh) = zsh_or_skip() else { return };
let tmp = tempfile::tempdir().unwrap();
let mut term =
PtyTerminal::new_running(zsh, &[String::from("-f"), String::from("-i")], tmp.path())
.unwrap();
let mut waited = 0u32;
while waited < 4000 && !term.foreground_is_shell() {
std::thread::sleep(std::time::Duration::from_millis(20));
waited += 20;
}
term.write_input(
b"/bin/sh -c 'sleep 1; printf \"\\033]7;file://localhost/tmp\\007\"; sleep 1'\n",
);
let mut waited = 0u32;
while waited < 8000
&& !(term.foreground_is_shell()
&& term.shell_cwd() == Some(std::path::PathBuf::from("/tmp")))
{
std::thread::sleep(std::time::Duration::from_millis(20));
waited += 20;
}
assert_eq!(
term.shell_cwd(),
Some(std::path::PathBuf::from("/tmp")),
"staging: the claim was captured"
);
assert!(
term.foreground_is_shell(),
"staging: the job is gone and the shell owns the tty again"
);
assert_eq!(
term.local_shell_cwd(),
None,
"a claim captured while a job owned the tty must never become trusted"
);
}
#[test]
fn clear_screen_and_scrollback_wipes_the_grid() {
fn dump(term: &PtyTerminal) -> String {
let t = term.term.lock();
let rows = t.screen_lines();
let cols = t.columns();
let off = t.grid().display_offset() as i32;
extract_selection_text(&t, -off, 0, rows as i32 - 1 - off, cols.saturating_sub(1))
}
let tmp = tempfile::tempdir().unwrap();
let mut term = PtyTerminal::new_running(
"/bin/sh",
&[String::from("-c"), String::from("echo CLEAR-PROBE-\"\"XYZ")],
tmp.path(),
)
.unwrap();
let mut waited = 0u32;
while waited < 4000 && !dump(&term).contains("CLEAR-PROBE-XYZ") {
std::thread::sleep(std::time::Duration::from_millis(20));
waited += 20;
}
assert!(
dump(&term).contains("CLEAR-PROBE-XYZ"),
"probe present before clear"
);
term.clear_screen_and_scrollback();
assert!(
!dump(&term).contains("CLEAR-PROBE-XYZ"),
"clear wipes the screen and scrollback"
);
}
#[test]
fn change_cwd_writes_cd_command_to_pty() {
let tmp = tempfile::tempdir().unwrap();
let mut term = PtyTerminal::new(tmp.path()).unwrap();
let _ = term.take_dirty();
let target = tempfile::tempdir().unwrap();
term.change_cwd(target.path());
assert!(
term.take_dirty(),
"change_cwd must mark the terminal dirty so the next frame paints the new prompt"
);
}
#[test]
fn new_running_spawns_program_directly_and_produces_output() {
let tmp = tempfile::tempdir().unwrap();
let term = PtyTerminal::new_running(
"/bin/echo",
&[String::from("croft-direct-spawn")],
tmp.path(),
)
.unwrap();
let mut waited_ms = 0u32;
while waited_ms < 4000 && !term.peek_dirty() {
std::thread::sleep(std::time::Duration::from_millis(20));
waited_ms += 20;
}
assert!(
term.peek_dirty(),
"direct-spawned /bin/echo must produce output without any write_input"
);
}
#[test]
fn pristine_covers_only_an_untouched_interactive_shell() {
let tmp = tempfile::tempdir().unwrap();
let mut shell = PtyTerminal::new(tmp.path()).unwrap();
assert!(
shell.is_pristine(),
"a freshly spawned shell with no input and no name is pristine"
);
shell.write_input(b"echo touched\n");
assert!(
!shell.is_pristine(),
"any input byte permanently clears pristineness"
);
let mut named = PtyTerminal::new(tmp.path()).unwrap();
named.set_manual_name(Some(String::from("srv")));
assert!(
!named.is_pristine(),
"a manual name is user state; the pane must not be replaceable"
);
named.set_manual_name(None);
assert!(
!named.is_pristine(),
"a rename latches: clearing the name back must not make the pane replaceable"
);
let run = PtyTerminal::new_running(
"/bin/sh",
&[String::from("-c"), String::from("sleep 1")],
tmp.path(),
)
.unwrap();
assert!(
!run.is_pristine(),
"a launched-program pane is doing user work despite having seen no input"
);
}
fn wait_for_grid<F: Fn(&[String]) -> bool>(term: &PtyTerminal, pred: F) -> Vec<String> {
let mut waited_ms = 0u32;
loop {
let (lines, _top) = term.grid_lines();
if pred(&lines) {
return lines;
}
assert!(
waited_ms < 4000,
"expected output never reached the grid; grid was: {lines:?}"
);
std::thread::sleep(std::time::Duration::from_millis(20));
waited_ms += 20;
}
}
#[test]
fn ansi_named_colors_render_through_the_theme_palette() {
let tmp = tempfile::tempdir().unwrap();
let mut term = PtyTerminal::new_running(
"/bin/sh",
&[
String::from("-c"),
String::from("s=QQ; printf \"\\033[31m${s}RED\\033[0m\\n\"; sleep 30"),
],
tmp.path(),
)
.unwrap();
wait_for_grid(&term, |ls| ls.iter().any(|l| l.contains("QQRED")));
let area = Rect::new(0, 0, 60, 10);
let find_q_fg = |term: &mut PtyTerminal| -> Option<Color> {
let mut buf = Buffer::empty(area);
Widget::render(term, area, &mut buf);
for y in 0..area.height {
for x in 1..area.width - 2 {
if buf[(x, y)].symbol() == "Q"
&& buf[(x + 1, y)].symbol() == "Q"
&& buf[(x + 2, y)].symbol() == "R"
{
return Some(buf[(x, y)].fg);
}
}
}
None
};
assert_eq!(
find_q_fg(&mut term),
Some(Color::Rgb(0xcd, 0x31, 0x31)),
"SGR red must map through the default palette"
);
let mut palette = crate::theme::VSCODE_ANSI;
palette[1] = (0x12, 0x34, 0x56);
term.set_palette(palette);
assert_eq!(
find_q_fg(&mut term),
Some(Color::Rgb(0x12, 0x34, 0x56)),
"a palette swap must repaint SGR red with the new color"
);
}
#[test]
fn faint_cells_render_with_the_dim_modifier() {
let tmp = tempfile::tempdir().unwrap();
let mut term = PtyTerminal::new_running(
"/bin/sh",
&[
String::from("-c"),
String::from("s=QQ; printf \"\\033[2m${s}GHOST\\033[0m\\n\"; sleep 30"),
],
tmp.path(),
)
.unwrap();
wait_for_grid(&term, |ls| ls.iter().any(|l| l.contains("QQGHOST")));
let area = Rect::new(0, 0, 60, 10);
let mut buf = Buffer::empty(area);
Widget::render(&mut term, area, &mut buf);
for y in 0..area.height {
for x in 1..area.width - 2 {
if buf[(x, y)].symbol() == "Q"
&& buf[(x + 1, y)].symbol() == "Q"
&& buf[(x + 2, y)].symbol() == "G"
{
assert!(
buf[(x, y)].modifier.contains(Modifier::DIM),
"SGR 2 (faint) cells must carry Modifier::DIM"
);
return;
}
}
}
panic!("the faint sentinel never appeared in the rendered buffer");
}
#[test]
fn imgcat_style_inline_images_are_captured_with_a_grid_anchor() {
use base64::Engine;
let mut png_buf = Vec::new();
image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255]))
.write_to(
&mut std::io::Cursor::new(&mut png_buf),
image::ImageFormat::Png,
)
.expect("encode test png");
let png: &[u8] = &png_buf;
let b64 = base64::engine::general_purpose::STANDARD.encode(png);
let tmp = tempfile::tempdir().unwrap();
let script = format!(
"printf 'before\\n'; printf '\\033]1337;File=inline=1:{b64}\\007\\n'; printf 'after\\n'; sleep 30"
);
let term =
PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script], tmp.path()).unwrap();
wait_for_grid(&term, |ls| ls.iter().any(|l| l.contains("after")));
let mut waited = 0u32;
let imgs = loop {
let imgs = term.pane_images();
if !imgs.is_empty() {
break imgs;
}
assert!(waited < 8000, "inline image never captured");
std::thread::sleep(std::time::Duration::from_millis(40));
waited += 40;
};
assert_eq!(imgs.len(), 1);
assert_eq!(imgs[0].data.as_slice(), png, "payload must round-trip");
let (lines, top) = term.grid_lines();
let before_row = lines
.iter()
.rposition(|l| l.trim_end() == "before")
.expect("the before line must be on the grid") as i32
+ top;
assert_eq!(
imgs[0].line,
before_row + 1,
"anchor must sit on the image's grid row; grid: {lines:?}"
);
}
#[test]
fn wide_chars_read_back_without_phantom_spacer_spaces() {
let tmp = tempfile::tempdir().unwrap();
let term = PtyTerminal::new_running("/bin/echo", &[String::from("日本語 ok")], tmp.path())
.unwrap();
let lines = wait_for_grid(&term, |ls| ls.iter().any(|l| l.contains('日')));
assert!(
lines.iter().any(|l| l.contains("日本語 ok")),
"wide chars must read back contiguously (no spacer-cell spaces); grid was: {lines:?}"
);
}
#[test]
fn wide_chars_render_the_glyph_once_with_a_blank_spacer_cell() {
let tmp = tempfile::tempdir().unwrap();
let mut term =
PtyTerminal::new_running("/bin/echo", &[String::from("日X")], tmp.path()).unwrap();
wait_for_grid(&term, |ls| ls.iter().any(|l| l.contains('日')));
let area = Rect::new(0, 0, 40, 10);
let mut buf = Buffer::empty(area);
Widget::render(&mut term, area, &mut buf);
let mut found = false;
for y in 0..area.height {
for x in 0..area.width.saturating_sub(2) {
if buf[(x, y)].symbol() == "日" {
assert_eq!(
buf[(x + 1, y)].symbol(),
" ",
"the spacer cell after a wide glyph must stay blank"
);
assert_eq!(
buf[(x + 2, y)].symbol(),
"X",
"the next glyph must land two columns after the wide char"
);
found = true;
}
}
}
assert!(found, "the wide glyph must appear in the rendered buffer");
}
#[test]
fn hyperlink_at_returns_the_osc8_uri_under_the_cell() {
let tmp = tempfile::tempdir().unwrap();
let script =
"printf '\\033]8;;https://example.com/doc\\033\\\\CLICK-ME\\033]8;;\\033\\\\\\n'";
let term =
PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
.unwrap();
let is_output = |l: &String| l.contains("CLICK-ME") && !l.contains("printf");
let lines = wait_for_grid(&term, |ls| ls.iter().any(is_output));
let row = lines.iter().position(is_output).unwrap();
let col = lines[row].find("CLICK-ME").unwrap();
assert_eq!(
term.hyperlink_at(row, col).as_deref(),
Some("https://example.com/doc"),
"the cell under the linked text must expose the OSC 8 URI"
);
assert_eq!(
term.hyperlink_at(0, 0),
None,
"cells outside the link (the header row) carry no URI"
);
}
#[test]
fn osc133_marks_record_kind_exit_code_and_grid_line() {
let tmp = tempfile::tempdir().unwrap();
let script = "printf 'before\\n\\033]133;A\\007PROMPT-LINE\\n\\033]133;C\\007out\\n\\033]133;D;3\\007'";
let term =
PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
.unwrap();
let is_output = |l: &String| l.contains("PROMPT-LINE") && !l.contains("printf");
let lines = wait_for_grid(&term, |ls| {
ls.iter().any(is_output) && !term.command_marks().is_empty()
});
let (_, top) = term.grid_lines();
let prompt_row = lines.iter().position(is_output).unwrap();
let marks = term.command_marks();
let prompt_line = marks
.iter()
.find(|(kind, _)| *kind == crate::shell_integration::OscEvent::PromptStart)
.map(|(_, line)| *line)
.expect("a PromptStart mark must be recorded");
assert_eq!(
prompt_line,
top + prompt_row as i32,
"the prompt mark must sit on the line where PROMPT-LINE was printed"
);
assert!(
marks
.iter()
.any(|(kind, _)| *kind == crate::shell_integration::OscEvent::CommandEnd(Some(3))),
"the finished mark must carry exit code 3; marks: {marks:?}"
);
}
#[test]
fn marks_follow_their_content_into_scrollback() {
let tmp = tempfile::tempdir().unwrap();
let script = "printf '\\033]133;A\\007MARKED-PROMPT\\n'; i=0; while [ $i -lt 40 ]; do echo filler-$i; i=$((i+1)); done";
let term =
PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
.unwrap();
wait_for_grid(&term, |ls| ls.iter().any(|l| l.contains("filler-39")));
let (lines, top) = {
let mut prev = term.grid_lines();
let mut waited = 0u32;
loop {
std::thread::sleep(std::time::Duration::from_millis(40));
let cur = term.grid_lines();
if cur == prev || waited >= 4000 {
break cur;
}
prev = cur;
waited += 40;
}
};
let content_row = lines
.iter()
.position(|l| l.contains("MARKED-PROMPT") && !l.contains("printf"))
.expect("the marked line must still be in scrollback");
let marks = term.command_marks();
let prompt_line = marks
.iter()
.find(|(kind, _)| *kind == crate::shell_integration::OscEvent::PromptStart)
.map(|(_, line)| *line)
.expect("the mark must survive the scroll");
assert_eq!(
prompt_line,
top + content_row as i32,
"the mark must move with its content into history (negative grid lines)"
);
assert!(
prompt_line < 0,
"after 40 filler lines the mark is in scrollback"
);
}
#[test]
fn osc7_updates_the_shell_cwd() {
let tmp = tempfile::tempdir().unwrap();
let script = "printf '\\033]7;file://anyhost/tmp/croft%%20dir\\007ok\\n'";
let term =
PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
.unwrap();
wait_for_grid(&term, |ls| {
ls.iter().any(|l| l.contains("ok") && !l.contains("printf"))
});
assert_eq!(
term.shell_cwd(),
Some(std::path::PathBuf::from("/tmp/croft dir")),
"OSC 7 must update the pane's live cwd"
);
}
#[test]
fn a_remote_reported_cwd_is_not_trusted_for_local_use() {
let tmp = tempfile::tempdir().unwrap();
let script = "printf '\\033]7;file://prod-db-1/tmp\\007ok\\n'; sleep 30";
let term =
PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
.unwrap();
wait_for_grid(&term, |ls| {
ls.iter().any(|l| l.contains("ok") && !l.contains("printf"))
});
assert_eq!(
term.shell_cwd(),
Some(std::path::PathBuf::from("/tmp")),
"staging: the raw report is visible"
);
assert_eq!(
term.local_shell_cwd(),
None,
"a path reported by another machine must not be reused locally"
);
let script = "printf '\\033]7;file://localhost/tmp\\007ok\\n'; sleep 30";
let term2 = PtyTerminal::new_running(
"/bin/sh",
&[String::from("-c"), script.into()],
std::path::Path::new("/tmp"),
)
.unwrap();
wait_for_grid(&term2, |ls| {
ls.iter().any(|l| l.contains("ok") && !l.contains("printf"))
});
assert_eq!(
term2.local_shell_cwd(),
Some(std::path::PathBuf::from("/tmp")),
"a localhost report IS this machine (RFC 8089)"
);
}
#[test]
fn osc9_notifications_drain_once() {
let tmp = tempfile::tempdir().unwrap();
let script = "printf '\\033]9;build done\\007ok\\n'";
let term =
PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
.unwrap();
wait_for_grid(&term, |ls| {
ls.iter().any(|l| l.contains("ok") && !l.contains("printf"))
});
assert_eq!(term.drain_notifications(), vec![String::from("build done")]);
assert!(
term.drain_notifications().is_empty(),
"a second drain returns nothing"
);
}
#[test]
fn notify_triggers_fire_on_completed_output_lines() {
let tmp = tempfile::tempdir().unwrap();
let script = "read x; echo deploy failed; sleep 30";
let mut term =
PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
.unwrap();
let set = crate::triggers::TriggerSet::from_json(
r#"[ { "regex": "deploy (\\w+)", "action": "notify", "message": "deploy went \\1" } ]"#,
);
assert!(set.has_events());
term.set_triggers(std::sync::Arc::new(set));
term.write_input(b"\n");
let mut waited = 0u32;
let hits = loop {
let hits = term.drain_trigger_hits();
if !hits.is_empty() {
break hits;
}
assert!(waited < 8000, "trigger never fired");
std::thread::sleep(std::time::Duration::from_millis(40));
waited += 40;
};
assert_eq!(hits.len(), 1, "{hits:?}");
assert_eq!(hits[0].action, crate::triggers::TriggerAction::Notify);
assert_eq!(hits[0].message, "deploy went failed");
}
#[test]
fn a_trigger_fires_for_primary_text_that_shares_a_chunk_with_alt_entry() {
let tmp = tempfile::tempdir().unwrap();
let script = "read x; printf 'deploy failed\\n\\033[?1049h'; sleep 1; printf '\\033[?1049lok\\n'; sleep 30";
let mut term =
PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
.unwrap();
let set = crate::triggers::TriggerSet::from_json(
r#"[ { "regex": "deploy (\\w+)", "action": "notify", "message": "deploy went \\1" } ]"#,
);
assert!(set.has_events());
term.set_triggers(std::sync::Arc::new(set));
term.write_input(b"\n");
let mut waited = 0u32;
let hits = loop {
let hits = term.drain_trigger_hits();
if !hits.is_empty() {
break hits;
}
assert!(
waited < 8000,
"the primary-screen line before the alt entry never fired"
);
std::thread::sleep(std::time::Duration::from_millis(40));
waited += 40;
};
assert_eq!(hits.len(), 1, "{hits:?}");
assert_eq!(hits[0].message, "deploy went failed");
}
#[test]
fn poisoned_zdotdir_from_a_nested_croft_still_loads_the_user_rc() {
let Some(zsh) = zsh_or_skip() else { return };
let home = tempfile::tempdir().unwrap();
std::fs::write(
home.path().join(".zshrc"),
"USER_RC_SENTINEL=loaded\nexport USER_RC_SENTINEL\n",
)
.unwrap();
let cfg_dir = tempfile::tempdir().unwrap();
let shim = crate::shell_integration::ensure_zsh_shim(cfg_dir.path()).unwrap();
let mut cmd = CommandBuilder::new(zsh);
cmd.arg("-i");
cmd.cwd(home.path());
cmd.env("HOME", home.path());
cmd.env("ZDOTDIR", &shim);
cmd.env("CROFT_USER_ZDOTDIR", &shim);
let mut term = PtyTerminal::spawn_with(cmd, None).unwrap();
let mut waited = 0u32;
while term.prompt_lines().is_empty() {
assert!(
waited < 8000,
"no prompt mark; grid: {:?}",
term.grid_lines().0
);
std::thread::sleep(std::time::Duration::from_millis(40));
waited += 40;
}
term.write_input(b"echo SENTINEL_IS=$USER_RC_SENTINEL\r");
let mut waited = 0u32;
loop {
let (lines, _) = term.grid_lines();
assert!(
!lines.iter().any(|l| l.contains("recursion limit")),
"the shim must never source itself; grid: {lines:?}"
);
if lines
.iter()
.any(|l| l.contains("SENTINEL_IS=loaded") && !l.contains("echo"))
{
break;
}
assert!(
waited < 8000,
"user rc never ran under a poisoned ZDOTDIR; grid: {lines:?}"
);
std::thread::sleep(std::time::Duration::from_millis(40));
waited += 40;
}
}
#[test]
fn pair_decorations_matches_prompts_with_exits() {
use crate::shell_integration::OscEvent as E;
let ms = std::time::Duration::from_millis;
let marks = [
(E::PromptStart, -10, 0, None),
(E::PromptEnd, -10, 5, None),
(E::CommandStart, -9, 0, None),
(E::CommandEnd(Some(0)), -7, 0, Some(ms(2400))),
(E::PromptStart, -7, 0, None),
(E::PromptEnd, -7, 5, None),
(E::CommandStart, -6, 0, None),
(E::CommandEnd(Some(3)), -2, 0, Some(ms(150))),
(E::PromptStart, -2, 0, None),
];
assert_eq!(
pair_decorations(&marks),
vec![
CommandDecoration {
line: -10,
exit: Some(0),
duration: Some(ms(2400)),
input: Some((-10, 5)),
output_start: -9,
output_end: -7,
},
CommandDecoration {
line: -7,
exit: Some(3),
duration: Some(ms(150)),
input: Some((-7, 5)),
output_start: -6,
output_end: -2,
},
]
);
let dup = [
(E::PromptStart, -5, 0, None),
(E::CommandStart, -5, 0, None),
(E::CommandEnd(Some(0)), -4, 0, Some(ms(90))),
(E::CommandEnd(Some(0)), -4, 0, None),
];
assert_eq!(pair_decorations(&dup).len(), 1);
let running = [(E::PromptStart, 0, 0, None), (E::CommandStart, 0, 0, None)];
assert!(pair_decorations(&running).is_empty());
}
#[test]
fn command_output_and_input_extract_and_select() {
let tmp = tempfile::tempdir().unwrap();
let script = "printf '\\033]133;A\\007$ \\033]133;B\\007cmd --flag\\n\\033]133;C\\007out1\\nout2\\n\\033]133;D;0\\007'";
let mut term =
PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
.unwrap();
let mut waited = 0u32;
while term.command_decorations().is_empty() {
assert!(
waited < 8000,
"no decoration; marks: {:?}",
term.command_marks()
);
std::thread::sleep(std::time::Duration::from_millis(40));
waited += 40;
}
let deco = term.command_decorations()[0];
assert_eq!(term.command_input_text(&deco), "cmd --flag");
assert_eq!(term.command_output_text(&deco), "out1\nout2");
term.select_command_output(&deco);
let sel = term.selection().expect("output must be selected");
let (sr, _, er, _) = sel.normalised();
assert_eq!(
(sr, er),
(deco.output_start, deco.output_end - 1),
"selection covers exactly the output rows"
);
assert_eq!(term.selection_text(), "out1\nout2");
}
#[test]
fn human_duration_formats_ms_seconds_minutes() {
let d = std::time::Duration::from_millis;
assert_eq!(human_duration(d(480)), "480ms");
assert_eq!(human_duration(d(3400)), "3.4s");
assert_eq!(human_duration(d(59_940)), "59.9s");
assert_eq!(human_duration(d(125_000)), "2m 05s");
}
#[test]
fn osc133_decorations_carry_exit_and_duration_end_to_end() {
let tmp = tempfile::tempdir().unwrap();
let script = "printf '\\033]133;A\\007$ cmd\\n\\033]133;B\\007\\033]133;C\\007'; sleep 1; printf 'out\\n\\033]133;D;2\\007'";
let term =
PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
.unwrap();
let mut waited = 0u32;
loop {
let decos = term.command_decorations();
if let Some(d) = decos.first() {
assert_eq!(d.exit, Some(2), "exit code from 133;D;2");
let dur = d.duration.expect("duration must be measured");
assert!(
dur >= std::time::Duration::from_millis(500),
"duration must cover the sleep; got {dur:?}"
);
break;
}
assert!(
waited < 8000,
"no decoration appeared; marks: {:?}",
term.command_marks()
);
std::thread::sleep(std::time::Duration::from_millis(40));
waited += 40;
}
let finished = term.drain_finished_commands();
assert_eq!(finished.len(), 1, "one completion in the drain");
assert_eq!(finished[0].exit, Some(2));
assert!(finished[0].dur >= std::time::Duration::from_millis(500));
assert!(
term.drain_finished_commands().is_empty(),
"a second drain returns nothing"
);
}
#[test]
fn decoration_dot_paints_on_the_left_border_and_hit_tests() {
let tmp = tempfile::tempdir().unwrap();
let script = "printf '\\033]133;A\\007$ cmd\\n\\033]133;B\\007\\033]133;C\\007out\\n\\033]133;D;2\\007'";
let mut term =
PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
.unwrap();
let mut waited = 0u32;
while term.command_decorations().is_empty() {
assert!(
waited < 8000,
"no decoration; marks: {:?}",
term.command_marks()
);
std::thread::sleep(std::time::Duration::from_millis(40));
waited += 40;
}
let area = Rect::new(0, 0, 40, 12);
let mut buf = Buffer::empty(area);
(&mut term).render(area, &mut buf);
let deco = term.command_decorations()[0];
let y = 1 + u16::try_from(deco.line).unwrap();
let cell = &buf[(0, y)];
assert_eq!(
cell.symbol(),
"●",
"dot on the left border at the prompt row"
);
assert_eq!(
cell.style().fg,
Some(Color::Rgb(0xf1, 0x4c, 0x4c)),
"non-zero exit paints the error red"
);
assert_eq!(buf[(0, y - 1)].symbol(), "│");
assert_eq!(
term.decoration_at_screen(0, y),
Some(deco),
"clicking the dot resolves the record"
);
assert_eq!(
term.decoration_at_screen(0, y - 1),
None,
"no record on a bare border row"
);
}
#[test]
fn foreign_terminal_shim_zdotdir_chains_to_the_user_rc() {
let Some(zsh) = zsh_or_skip() else { return };
let home = tempfile::tempdir().unwrap();
std::fs::write(
home.path().join(".zshrc"),
"USER_RC_SENTINEL=loaded\nexport USER_RC_SENTINEL\n",
)
.unwrap();
let foreign = tempfile::tempdir().unwrap();
std::fs::write(
foreign.path().join(".zshenv"),
"builtin unset ZDOTDIR\n[[ -r \"$HOME/.zshenv\" ]] && builtin source \"$HOME/.zshenv\"\n",
)
.unwrap();
let cfg_dir = tempfile::tempdir().unwrap();
let shim = crate::shell_integration::ensure_zsh_shim(cfg_dir.path()).unwrap();
let mut cmd = CommandBuilder::new(zsh);
cmd.arg("-i");
cmd.cwd(home.path());
cmd.env("HOME", home.path());
cmd.env("ZDOTDIR", &shim);
cmd.env("CROFT_USER_ZDOTDIR", foreign.path());
let mut term = PtyTerminal::spawn_with(cmd, None).unwrap();
let mut waited = 0u32;
while term.prompt_lines().is_empty() {
assert!(
waited < 8000,
"no prompt mark; grid: {:?}",
term.grid_lines().0
);
std::thread::sleep(std::time::Duration::from_millis(40));
waited += 40;
}
term.write_input(b"echo SENTINEL_IS=$USER_RC_SENTINEL\r");
let mut waited = 0u32;
loop {
let (lines, _) = term.grid_lines();
if lines
.iter()
.any(|l| l.contains("SENTINEL_IS=loaded") && !l.contains("echo"))
{
break;
}
assert!(
waited < 8000,
"user rc never ran behind a foreign terminal shim; grid: {lines:?}"
);
std::thread::sleep(std::time::Duration::from_millis(40));
waited += 40;
}
}
#[test]
fn zsh_shim_emits_prompt_marks_end_to_end() {
let Some(zsh) = zsh_or_skip() else { return };
let user_dir = tempfile::tempdir().unwrap();
let cfg_dir = tempfile::tempdir().unwrap();
let shim = crate::shell_integration::ensure_zsh_shim(cfg_dir.path()).unwrap();
let mut cmd = CommandBuilder::new(zsh);
cmd.arg("-i");
cmd.cwd(user_dir.path());
cmd.env("ZDOTDIR", &shim);
cmd.env("CROFT_USER_ZDOTDIR", user_dir.path());
let term = PtyTerminal::spawn_with(cmd, None).unwrap();
let mut waited_ms = 0u32;
while term.prompt_lines().is_empty() {
assert!(
waited_ms < 8000,
"zsh never emitted a prompt mark; grid: {:?}",
term.grid_lines().0
);
std::thread::sleep(std::time::Duration::from_millis(40));
waited_ms += 40;
}
assert!(
term.shell_cwd().is_some(),
"the shim's precmd must also report the cwd via OSC 7"
);
}
#[test]
fn a_percent_directory_round_trips_through_the_zsh_shim() {
let Some(zsh) = zsh_or_skip() else { return };
let user_dir = tempfile::tempdir().unwrap();
let odd = user_dir.path().join("a%41b");
std::fs::create_dir(&odd).unwrap();
let cfg_dir = tempfile::tempdir().unwrap();
let shim = crate::shell_integration::ensure_zsh_shim(cfg_dir.path()).unwrap();
let mut cmd = CommandBuilder::new(zsh);
cmd.arg("-i");
cmd.cwd(&odd);
cmd.env("ZDOTDIR", &shim);
cmd.env("CROFT_USER_ZDOTDIR", user_dir.path());
let term = PtyTerminal::spawn_with(cmd, None).unwrap();
let mut waited = 0u32;
while term.prompt_lines().is_empty() {
assert!(
waited < 20_000,
"zsh never emitted a prompt mark; grid: {:?}",
term.grid_lines().0
);
std::thread::sleep(std::time::Duration::from_millis(40));
waited += 40;
}
let mut waited = 0u32;
let cwd = loop {
if let Some(c) = term.shell_cwd() {
break c;
}
assert!(
waited < 4000,
"the shim's precmd ran (prompt mark present) but never reported a cwd; grid: {:?}",
term.grid_lines().0
);
std::thread::sleep(std::time::Duration::from_millis(40));
waited += 40;
};
assert!(
cwd.ends_with("a%41b"),
"the literal directory name must survive the OSC 7 round trip, got {cwd:?}"
);
}
fn modern_bash() -> Option<&'static str> {
["/opt/homebrew/bin/bash", "/usr/local/bin/bash", "/bin/bash"]
.into_iter()
.find(|b| bash_env_injection_supported(b))
}
#[test]
fn an_empty_enter_with_an_array_prompt_command_fabricates_no_command() {
let Some(bash) = modern_bash() else {
return;
};
let out = std::process::Command::new(bash)
.args(["-c", "echo ${BASH_VERSINFO[0]}${BASH_VERSINFO[1]}"])
.output()
.unwrap();
let v: u32 = String::from_utf8_lossy(&out.stdout)
.trim()
.parse()
.unwrap_or(0);
if v < 51 {
return;
}
let home = tempfile::tempdir().unwrap();
std::fs::write(
home.path().join(".bashrc"),
"mytheme() { :; }\nPROMPT_COMMAND=(mytheme)\n",
)
.unwrap();
let cfg = tempfile::tempdir().unwrap();
let mut cmd = CommandBuilder::new(bash);
cmd.cwd(home.path());
cmd.env("HOME", home.path());
let args = apply_shell_integration_env(&mut cmd, bash, cfg.path());
for a in &args {
cmd.arg(a);
}
cmd.arg("-i");
let mut term = PtyTerminal::spawn_with(cmd, None).unwrap();
let mut waited = 0u32;
while term.prompt_lines().is_empty() {
assert!(waited < 8000, "bash never emitted a prompt mark");
std::thread::sleep(std::time::Duration::from_millis(40));
waited += 40;
}
let prompts_before = term.prompt_lines().len();
term.write_input(b"\n");
let mut waited = 0u32;
while term.prompt_lines().len() <= prompts_before {
assert!(waited < 8000, "the empty Enter never produced a new prompt");
std::thread::sleep(std::time::Duration::from_millis(40));
waited += 40;
}
assert!(
pair_decorations(&term.marks_snapshot()).is_empty(),
"an empty Enter must not fabricate a finished command"
);
}
#[test]
fn shell_integration_env_prepends_posix_for_modern_bash_only() {
let cfg = tempfile::tempdir().unwrap();
if let Some(bash) = modern_bash() {
let mut cmd = CommandBuilder::new(bash);
assert_eq!(
apply_shell_integration_env(&mut cmd, bash, cfg.path()),
vec!["--posix".to_string()]
);
}
assert!(!parse_bash_version_supported("3.2"));
assert!(!parse_bash_version_supported("4.3"));
assert!(!parse_bash_version_supported("garbage"));
assert!(parse_bash_version_supported("4.4"));
assert!(parse_bash_version_supported("5.2"));
assert!(parse_bash_version_supported("10.0"));
if std::path::Path::new("/bin/bash").exists() && !bash_env_injection_supported("/bin/bash")
{
let mut cmd = CommandBuilder::new("/bin/bash");
assert!(
apply_shell_integration_env(&mut cmd, "/bin/bash", cfg.path()).is_empty(),
"bash 3.2 must spawn clean, without posix injection"
);
}
for shell in ["/bin/zsh", "/usr/bin/fish", "/bin/dash"] {
let mut cmd = CommandBuilder::new(shell);
assert!(
apply_shell_integration_env(&mut cmd, shell, cfg.path()).is_empty(),
"{shell} must not gain args"
);
}
}
#[test]
fn zsh_shim_marks_the_prompt_end_for_input_extraction() {
let Some(zsh) = zsh_or_skip() else { return };
let user_dir = tempfile::tempdir().unwrap();
let cfg_dir = tempfile::tempdir().unwrap();
let shim = crate::shell_integration::ensure_zsh_shim(cfg_dir.path()).unwrap();
let mut cmd = CommandBuilder::new(zsh);
cmd.arg("-i");
cmd.cwd(user_dir.path());
cmd.env("ZDOTDIR", &shim);
cmd.env("CROFT_USER_ZDOTDIR", user_dir.path());
let term = PtyTerminal::spawn_with(cmd, None).unwrap();
let mut waited = 0u32;
loop {
let marks = term.command_marks();
if marks
.iter()
.any(|(k, _)| *k == crate::shell_integration::OscEvent::PromptEnd)
{
break;
}
assert!(
waited < 8000,
"zsh never emitted a PromptEnd mark; marks: {marks:?}, grid: {:?}",
term.grid_lines().0
);
std::thread::sleep(std::time::Duration::from_millis(40));
waited += 40;
}
}
#[test]
fn bash_shim_via_posix_env_emits_marks_and_sources_the_user_profile() {
let Some(bash) = modern_bash() else {
return;
};
let home = tempfile::tempdir().unwrap();
std::fs::write(
home.path().join(".bash_profile"),
"USER_RC_SENTINEL=loaded\nexport USER_RC_SENTINEL\n",
)
.unwrap();
let cfg_dir = tempfile::tempdir().unwrap();
let shim = crate::shell_integration::ensure_bash_shim(cfg_dir.path()).unwrap();
let mut cmd = CommandBuilder::new(bash);
cmd.arg("--posix");
cmd.arg("-l");
cmd.cwd(home.path());
cmd.env("HOME", home.path());
cmd.env("ENV", &shim);
cmd.env("CROFT_BASH_INJECT", "1");
let mut term = PtyTerminal::spawn_with(cmd, None).unwrap();
let mut waited = 0u32;
while term.prompt_lines().is_empty() {
assert!(
waited < 8000,
"bash never emitted a prompt mark; grid: {:?}",
term.grid_lines().0
);
std::thread::sleep(std::time::Duration::from_millis(40));
waited += 40;
}
assert!(
term.shell_cwd().is_some(),
"the shim's precmd must report cwd via OSC 7"
);
term.write_input(b"echo SENTINEL_IS=$USER_RC_SENTINEL\r");
let mut waited = 0u32;
loop {
let (lines, _) = term.grid_lines();
if lines
.iter()
.any(|l| l.contains("SENTINEL_IS=loaded") && !l.contains("echo"))
{
break;
}
assert!(
waited < 8000,
"user .bash_profile never ran through the shim; grid: {lines:?}"
);
std::thread::sleep(std::time::Duration::from_millis(40));
waited += 40;
}
term.write_input(b"false\r");
let mut waited = 0u32;
loop {
use crate::shell_integration::OscEvent as E;
let marks = term.command_marks();
if marks.iter().any(|(k, _)| *k == E::CommandEnd(Some(1))) {
assert!(
marks.iter().any(|(k, _)| *k == E::PromptEnd),
"bash PS1 must carry the 133;B input-start mark; marks: {marks:?}"
);
break;
}
assert!(
waited < 8000,
"no CommandEnd(1) after `false`; marks: {marks:?}, grid: {:?}",
term.grid_lines().0
);
std::thread::sleep(std::time::Duration::from_millis(40));
waited += 40;
}
}
fn find_fish() -> Option<String> {
let fixed = [
"/opt/homebrew/bin/fish",
"/usr/local/bin/fish",
"/usr/bin/fish",
];
if let Some(f) = fixed.iter().find(|f| std::path::Path::new(f).exists()) {
return Some((*f).to_string());
}
let path = std::env::var("PATH").ok()?;
path.split(':')
.map(|d| std::path::Path::new(d).join("fish"))
.find(|p| p.is_file())
.map(|p| p.display().to_string())
}
#[test]
fn fish_integration_restores_xdg_dirs_and_yields_single_native_marks() {
let Some(fish) = find_fish() else {
return;
};
let home = tempfile::tempdir().unwrap();
let cfg_dir = tempfile::tempdir().unwrap();
let dir = crate::shell_integration::ensure_fish_integration(cfg_dir.path()).unwrap();
let mut cmd = CommandBuilder::new(&fish);
cmd.arg("-i");
cmd.arg("-l");
cmd.cwd(home.path());
cmd.env("HOME", home.path());
cmd.env(
"XDG_DATA_DIRS",
crate::shell_integration::fish_xdg_data_dirs(&dir, None),
);
cmd.env("CROFT_FISH_XDG_DATA_DIR", &dir);
let mut term = PtyTerminal::spawn_with(cmd, None).unwrap();
let mut waited = 0u32;
while term.prompt_lines().is_empty() {
assert!(
waited < 8000,
"fish never emitted a prompt mark; grid: {:?}",
term.grid_lines().0
);
std::thread::sleep(std::time::Duration::from_millis(40));
waited += 40;
}
term.write_input(b"false\r");
let mut waited = 0u32;
loop {
use crate::shell_integration::OscEvent as E;
let marks = term.command_marks();
if marks.iter().any(|(k, _)| *k == E::CommandEnd(Some(1))) {
break;
}
assert!(
waited < 8000,
"no CommandEnd(1) after `false`; marks: {marks:?}, grid: {:?}",
term.grid_lines().0
);
std::thread::sleep(std::time::Duration::from_millis(40));
waited += 40;
}
let failing: Vec<_> = term
.command_decorations()
.into_iter()
.filter(|d| d.exit == Some(1))
.collect();
assert_eq!(failing.len(), 1, "duplicate decorations: {failing:?}");
term.write_input(b"echo DIRS=$XDG_DATA_DIRS; set -q CROFT_FISH_XDG_DATA_DIR; and echo SI_LEAKED; or echo SI_CLEAN\r");
let needle = format!("{}", dir.display());
let mut waited = 0u32;
loop {
let (lines, _) = term.grid_lines();
if lines
.iter()
.any(|l| l.contains("SI_CLEAN") && !l.contains("echo"))
{
assert!(
!lines
.iter()
.any(|l| l.contains("SI_LEAKED") && !l.contains("echo")),
"grid: {lines:?}"
);
let dirs_line = lines
.iter()
.find(|l| l.contains("DIRS=") && !l.contains("echo"))
.cloned()
.unwrap_or_default();
assert!(
!dirs_line.contains(&needle),
"XDG_DATA_DIRS still carries the injection dir: {dirs_line}"
);
break;
}
assert!(
waited < 8000,
"env scrub probe never answered; grid: {lines:?}"
);
std::thread::sleep(std::time::Duration::from_millis(40));
waited += 40;
}
}
#[test]
fn prompt_jump_targets_walk_previous_and_next() {
let prompts = [-30, -12, 0];
assert_eq!(pick_prompt_jump(&prompts, 0, false), Some(-12));
assert_eq!(pick_prompt_jump(&prompts, -12, false), Some(-30));
assert_eq!(pick_prompt_jump(&prompts, -30, false), None);
assert_eq!(pick_prompt_jump(&prompts, -30, true), Some(-12));
assert_eq!(pick_prompt_jump(&prompts, -12, true), Some(0));
assert_eq!(pick_prompt_jump(&prompts, 0, true), None);
}
#[test]
fn bell_sets_a_flag_the_app_can_drain() {
let tmp = tempfile::tempdir().unwrap();
let script = "printf 'DONE\\007\\n'";
let term =
PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
.unwrap();
wait_for_grid(&term, |ls| {
ls.iter()
.any(|l| l.contains("DONE") && !l.contains("printf"))
});
assert!(
term.take_bell(),
"BEL from the child must set the bell flag for the app to drain"
);
assert!(
!term.take_bell(),
"take_bell drains the flag — a second read is false"
);
}
#[test]
fn grid_lines_exposes_output_for_terminal_find() {
let tmp = tempfile::tempdir().unwrap();
let needle = "croft-find-needle-42";
let term =
PtyTerminal::new_running("/bin/echo", &[String::from(needle)], tmp.path()).unwrap();
let mut waited_ms = 0u32;
loop {
let (lines, top) = term.grid_lines();
if let Some(row) = lines.iter().position(|l| l.contains(needle)) {
let hit = crate::widgets::editor_find::find_next_match(
&lines,
needle,
crate::widgets::search::SearchOpts::default(),
0,
0,
false,
)
.expect("search must find the printed needle");
assert_eq!(hit.row, row, "match row must line up with the grid row");
assert!(top + hit.row as i32 >= top);
break;
}
assert!(waited_ms < 4000, "echo output never reached the grid");
std::thread::sleep(std::time::Duration::from_millis(20));
waited_ms += 20;
}
}
#[test]
fn pending_bytes_counts_advanced_output_and_resets_on_take_dirty() {
let tmp = tempfile::tempdir().unwrap();
let term = PtyTerminal::new_running(
"/bin/echo",
&[String::from("croft-pending-bytes-probe")],
tmp.path(),
)
.unwrap();
let mut waited_ms = 0u32;
while waited_ms < 4000 && term.peek_pending_bytes() == 0 {
std::thread::sleep(std::time::Duration::from_millis(20));
waited_ms += 20;
}
assert!(
term.peek_pending_bytes() > 0,
"the reader thread must accumulate the bytes it advanced so the main loop can tell echo from a bulk stream"
);
assert!(
term.peek_pending_bytes() <= 4096,
"a one-line echo must stay under the small-update threshold so it bypasses the redraw cap"
);
let _ = term.take_dirty();
assert_eq!(
term.peek_pending_bytes(),
0,
"take_dirty must reset the byte accumulator so the next window starts from zero"
);
}
#[test]
fn new_running_renders_running_header_in_term_immediately() {
let tmp = tempfile::tempdir().unwrap();
let term = PtyTerminal::new_running(
"/bin/echo",
&[String::from("croft-header-probe")],
tmp.path(),
)
.unwrap();
let snapshot = term.visible_text();
assert!(
snapshot.contains("/bin/echo croft-header-probe"),
"expected the run command in the header line; got:\n{snapshot}"
);
assert!(
snapshot.starts_with('▶') || snapshot.contains("▶ "),
"expected a ▶ marker on the header line; got:\n{snapshot}"
);
}
#[test]
fn new_running_appends_exit_footer_when_child_finishes() {
let tmp = tempfile::tempdir().unwrap();
let term =
PtyTerminal::new_running("/bin/echo", &[String::from("croft-exit-probe")], tmp.path())
.unwrap();
let mut waited_ms = 0u32;
let footer_needle = "[Process exited]";
loop {
if term.visible_text().contains(footer_needle) {
break;
}
if waited_ms >= 4000 {
let snap = term.visible_text();
panic!(
"expected '{footer_needle}' to appear within 4s of the child exiting; got:\n{snap}"
);
}
std::thread::sleep(std::time::Duration::from_millis(20));
waited_ms += 20;
}
}
#[test]
fn new_for_interactive_shell_does_not_render_running_header() {
let tmp = tempfile::tempdir().unwrap();
let term = PtyTerminal::new(tmp.path()).unwrap();
std::thread::sleep(std::time::Duration::from_millis(50));
let snapshot = term.visible_text();
assert!(
!snapshot.contains("▶ "),
"interactive shell must not render a one-shot script header; got:\n{snapshot}"
);
assert!(
!snapshot.contains("[Process exited]"),
"interactive shell must not render an exit footer; got:\n{snapshot}"
);
}
#[test]
fn selection_normalised_handles_anchor_after_head() {
let s = Selection {
anchor: (5, 4),
head: (2, 1),
block: false,
};
assert_eq!(s.normalised(), (2, 1, 5, 4));
}
#[test]
fn selection_normalised_handles_same_row() {
let s = Selection {
anchor: (3, 9),
head: (3, 2),
block: false,
};
assert_eq!(s.normalised(), (3, 2, 3, 9));
}
#[test]
fn selection_has_area_only_when_endpoints_differ() {
let s = Selection::new(2, 5);
assert!(!s.has_area());
let s2 = Selection {
anchor: (2, 5),
head: (2, 6),
block: false,
};
assert!(s2.has_area());
}
#[test]
fn cell_in_selection_within_single_row() {
assert!(cell_in_selection(2, 5, 2, 3, 2, 7));
assert!(!cell_in_selection(2, 2, 2, 3, 2, 7));
assert!(!cell_in_selection(2, 8, 2, 3, 2, 7));
assert!(!cell_in_selection(1, 5, 2, 3, 2, 7));
assert!(!cell_in_selection(3, 5, 2, 3, 2, 7));
}
#[test]
fn cell_in_selection_spans_multiple_rows() {
assert!(!cell_in_selection(1, 4, 1, 5, 3, 2));
assert!(cell_in_selection(1, 5, 1, 5, 3, 2));
assert!(cell_in_selection(1, 9, 1, 5, 3, 2));
assert!(cell_in_selection(2, 0, 1, 5, 3, 2));
assert!(cell_in_selection(2, 9, 1, 5, 3, 2));
assert!(cell_in_selection(3, 2, 1, 5, 3, 2));
assert!(!cell_in_selection(3, 3, 1, 5, 3, 2));
assert!(!cell_in_selection(4, 0, 1, 5, 3, 2));
}
#[test]
fn osc52_copy_seq_wraps_with_correct_envelope() {
let bytes = osc52_copy_seq("hello");
assert_eq!(bytes, b"\x1b]52;c;aGVsbG8=\x07");
}
#[test]
fn osc52_copy_seq_handles_empty() {
assert_eq!(osc52_copy_seq(""), b"\x1b]52;c;\x07");
}
#[test]
fn osc52_copy_seq_handles_unicode() {
let bytes = osc52_copy_seq("héllo");
assert!(bytes.starts_with(b"\x1b]52;c;"));
assert_eq!(*bytes.last().unwrap(), 0x07);
let body = &bytes[7..bytes.len() - 1];
use base64::Engine;
let decoded = base64::engine::general_purpose::STANDARD
.decode(body)
.unwrap();
assert_eq!(decoded, "héllo".as_bytes());
}
#[test]
fn select_word_at_in_term_brackets_the_alphanumeric_run_around_the_pivot() {
let mut t = fresh_term(40, 5);
feed(&mut t, b"hello world from croft");
let got = select_word_at_in_term(&t, 0, 0, 8);
assert_eq!(
got,
Some(((0, 6), (0, 10))),
"pivot inside 'world' must select cols 6..=10"
);
}
#[test]
fn select_word_at_in_term_returns_none_when_pivot_is_on_whitespace() {
let mut t = fresh_term(40, 5);
feed(&mut t, b"hello world");
assert_eq!(
select_word_at_in_term(&t, 0, 0, 5),
None,
"pivot on the space between 'hello' and 'world' must yield no selection"
);
}
#[test]
fn select_word_at_in_term_treats_underscores_as_word_chars_and_dots_as_boundaries() {
let mut t = fresh_term(40, 5);
feed(&mut t, b"foo_bar.baz");
assert_eq!(
select_word_at_in_term(&t, 0, 0, 2),
Some(((0, 0), (0, 6))),
"'foo_bar' is one word (underscore is a word char), '.baz' is separate"
);
assert_eq!(
select_word_at_in_term(&t, 0, 0, 9),
Some(((0, 8), (0, 10))),
"pivot inside 'baz' must select cols 8..=10"
);
}
#[test]
fn select_word_at_in_term_word_selects_in_scrollback_when_display_offset_is_nonzero() {
let mut t = fresh_term(20, 3);
feed(
&mut t,
b"scroll-A row\r\nscroll-B row\r\nscroll-C row\r\nlive-D row\r\nlive-E row\r\nlive-F row",
);
t.scroll_display(alacritty_terminal::grid::Scroll::Delta(2));
let display_offset = t.grid().display_offset();
assert_eq!(
display_offset, 2,
"precondition: Scroll::Delta(2) must move the viewport into scrollback"
);
let got = select_word_at_in_term(&t, display_offset, 0, 2);
assert!(
got.is_some(),
"double-click on a scrolled-back row must return a real anchor/head, not None - if this is None the user sees the double-click 'do nothing'"
);
let (anchor, head) = got.unwrap();
assert_eq!(
anchor,
(0, 0),
"anchor must mark the start of the word run on viewport row 0"
);
assert_eq!(
head,
(0, 5),
"head must mark the last char of 'scroll' before the hyphen breaks the word run"
);
}
#[test]
fn extract_selection_text_single_line() {
let mut t = fresh_term(20, 5);
feed(&mut t, b"hello world");
let txt = extract_selection_text(&t, 0, 6, 0, 10);
assert_eq!(txt, "world");
}
#[test]
fn extract_selection_text_multi_line_trims_trailing_spaces() {
let mut t = fresh_term(20, 5);
feed(&mut t, b"first line\r\nsecond line");
let txt = extract_selection_text(&t, 0, 6, 1, 5);
assert_eq!(txt, "line\nsecond");
}
#[test]
fn extract_selection_text_addresses_absolute_grid_lines() {
let mut t = fresh_term(20, 3);
feed(
&mut t,
b"scroll-A row\r\nscroll-B row\r\nscroll-C row\r\nlive-D row\r\nlive-E row\r\nlive-F row",
);
assert_eq!(
extract_selection_text(&t, 0, 0, 0, 19),
"live-D row",
"Line(0) is the first live row"
);
assert_eq!(
extract_selection_text(&t, -2, 0, -2, 19),
"scroll-B row",
"Line(-2) reads the scrollback row directly, no display_offset needed"
);
t.scroll_display(alacritty_terminal::grid::Scroll::Delta(2));
assert_eq!(t.grid().display_offset(), 2);
assert_eq!(
extract_selection_text(&t, -2, 0, -2, 19),
"scroll-B row",
"Line(-2) still reads 'scroll-B row' after scrolling - absolute lines are scroll-invariant"
);
}
#[test]
fn selection_stays_glued_to_its_content_while_output_streams() {
let tmp = tempfile::tempdir().unwrap();
let go = tmp.path().join("go");
let script = format!(
"t=TAR; echo \"${{t}}GET-line\"; until [ -e {} ]; do sleep 0.05; done; seq 1 60; sleep 30",
go.display()
);
let mut term =
PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script], tmp.path()).unwrap();
let mut waited = 0u32;
let line = loop {
let (lines, top) = term.grid_lines();
if let Some(idx) = lines.iter().position(|l| l.starts_with("TARGET-line")) {
break top + idx as i32;
}
assert!(waited < 8000, "sentinel never arrived");
std::thread::sleep(std::time::Duration::from_millis(20));
waited += 20;
};
term.set_selection(Some(Selection {
anchor: (line, 0),
head: (line, 30),
block: false,
}));
assert_eq!(term.selection_text(), "TARGET-line");
std::fs::File::create(&go).unwrap();
let mut waited = 0u32;
while !term.grid_lines().0.iter().any(|l| l == "60") {
assert!(waited < 8000, "streamed output never arrived");
std::thread::sleep(std::time::Duration::from_millis(20));
waited += 20;
}
assert_eq!(
term.selection_text(),
"TARGET-line",
"the selection must follow its content as output streams past it"
);
let sel = term.selection().expect("selection survives streaming");
assert!(
sel.anchor.0 < line,
"reported endpoints re-anchor upward as lines scroll into history"
);
}
#[test]
fn selection_survives_streaming_past_a_saturated_scrollback() {
let tmp = tempfile::tempdir().unwrap();
let go = tmp.path().join("go");
let script = format!(
"seq 1 5200; t=TAR; echo \"${{t}}GET-line\"; until [ -e {} ]; do sleep 0.05; done; seq 1 60; sleep 30",
go.display()
);
let mut term =
PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script], tmp.path()).unwrap();
let mut waited = 0u32;
let line = loop {
let (lines, top) = term.grid_lines();
if let Some(idx) = lines.iter().position(|l| l.starts_with("TARGET-line")) {
break top + idx as i32;
}
assert!(waited < 8000, "sentinel never arrived");
std::thread::sleep(std::time::Duration::from_millis(20));
waited += 20;
};
let hist_at_select = term.term.lock().grid().history_size();
term.set_selection(Some(Selection {
anchor: (line, 0),
head: (line, 30),
block: false,
}));
assert_eq!(term.selection_text(), "TARGET-line");
std::fs::File::create(&go).unwrap();
let mut waited = 0u32;
while !term.grid_lines().0.iter().any(|l| l == "60") {
assert!(waited < 8000, "streamed output never arrived");
std::thread::sleep(std::time::Duration::from_millis(20));
waited += 20;
}
assert_eq!(
term.term.lock().grid().history_size(),
hist_at_select,
"test setup must saturate the scrollback before streaming"
);
assert_eq!(
term.selection_text(),
"TARGET-line",
"the selection must follow its content even with history_size saturated"
);
}
#[test]
fn alt_screen_selection_stays_partially_visible_when_app_chrome_covers_its_edge() {
let (_tmp, mut t) = quiet_pty();
feed_pty(
&t,
b"\x1b[?1049h\x1b[H\x1b[2Jalpha one\r\nbravo two\r\ncharlie three\r\ndelta four\r\necho five",
);
t.set_selection(Some(Selection {
anchor: (1, 0),
head: (3, 9),
block: false,
}));
assert_eq!(t.selection_text(), "bravo two\ncharlie three\ndelta four");
feed_pty(
&t,
b"\x1b[H\x1b[2Jbravo two\r\ncharlie three\r\n> INPUT BOX\r\n> more chrome\r\n> even more",
);
t.rebase_selection();
let anchor = t.alt_sel.as_ref().expect("anchor survives");
assert!(
!anchor.dormant,
"two of three selected rows are still on screen: not dormant"
);
assert_eq!(
anchor.visible,
Some(vec![(0, 0, u16::MAX), (1, 0, u16::MAX)]),
"only the surviving rows keep their highlight"
);
assert_eq!(
t.selection_text(),
"bravo two\ncharlie three\ndelta four",
"copy yields the whole remembered selection while partially covered"
);
feed_pty(
&t,
b"\x1b[H\x1b[2Jalpha one\r\nbravo two\r\ncharlie three\r\ndelta four\r\necho five",
);
t.rebase_selection();
let anchor = t.alt_sel.as_ref().expect("anchor survives");
assert!(!anchor.dormant);
assert_eq!(anchor.visible, None, "fully visible again: no clip");
assert_eq!(t.selection_text(), "bravo two\ncharlie three\ndelta four");
}
#[test]
fn a_single_row_selection_on_a_repeated_row_reanchors_to_its_own_copy() {
let (_tmp, mut t) = quiet_pty();
feed_pty(
&t,
b"\x1b[?1049h\x1b[H\x1b[2Jalpha\r\n-----\r\nbravo\r\n-----\r\ncharlie",
);
t.set_selection(Some(Selection {
anchor: (3, 0),
head: (3, 4),
block: false,
}));
assert_eq!(t.selection_text(), "-----");
feed_pty(
&t,
b"\x1b[H\x1b[2Jbravo\r\n-----\r\ncharlie\r\ndelta\r\n-----",
);
t.rebase_selection();
let anchor = t.alt_sel.as_ref().expect("anchor survives");
assert_eq!(
anchor.top, 1,
"the highlight must follow its own copy (neighbours bravo/charlie), not the nearest lookalike"
);
assert_eq!(
t.selection.map(|s| (s.anchor, s.head)),
Some(((1, 0), (1, 4))),
"the selection coordinates must move with the content"
);
assert_eq!(t.selection_text(), "-----");
}
fn feed_pty(t: &PtyTerminal, bytes: &[u8]) {
let mut p = Processor::<StdSyncHandler>::new();
let mut term = t.term.lock();
p.advance(&mut *term, bytes);
}
fn quiet_pty() -> (tempfile::TempDir, PtyTerminal) {
let tmp = tempfile::tempdir().unwrap();
let t = PtyTerminal::new_running("/bin/sleep", &[String::from("30")], tmp.path()).unwrap();
(tmp, t)
}
#[test]
fn timestamps_survive_an_alt_screen_round_trip() {
let (_tmp, t) = quiet_pty();
let mut prev = 0i64;
feed_pty(&t, b"one\r\ntwo\r\nthree\r\n");
t.stamp_chunk_for_test(&mut prev, 1000);
let before = t.line_time_entries_for_test();
assert!(!before.is_empty(), "rows got stamped");
let (first_id, first_ms) = before[0];
assert_eq!(first_ms, 1000);
feed_pty(&t, b"\x1b[?1049h\x1b[Hpager-screen");
t.stamp_chunk_for_test(&mut prev, 2000);
feed_pty(&t, b"\x1b[?1049l");
t.stamp_chunk_for_test(&mut prev, 3000);
let after = t.line_time_entries_for_test();
assert_eq!(
before.iter().map(|&(k, _)| k).collect::<Vec<_>>(),
after.iter().map(|&(k, _)| k).collect::<Vec<_>>(),
"an alt-screen trip must not wipe or invent stamped rows"
);
let kept = after.iter().find(|&&(k, _)| k == first_id).unwrap().1;
assert_eq!(
kept, 1000,
"an old row must keep its true arrival time, not the pager's exit time"
);
}
#[test]
fn timestamps_keep_advancing_past_a_saturated_scrollback() {
let (_tmp, t) = quiet_pty();
let mut prev = 0i64;
let mut chunk = String::new();
for i in 0..5300 {
chunk.push_str(&format!("s-{i}\r\n"));
}
feed_pty(&t, chunk.as_bytes());
t.stamp_chunk_for_test(&mut prev, 1000);
let max1 = t
.line_time_entries_for_test()
.last()
.map(|&(k, _)| k)
.unwrap();
let mut more = String::new();
for i in 0..100 {
more.push_str(&format!("t-{i}\r\n"));
}
feed_pty(&t, more.as_bytes());
t.stamp_chunk_for_test(&mut prev, 2000);
let max2 = t
.line_time_entries_for_test()
.last()
.map(|&(k, _)| k)
.unwrap();
assert!(
max2 >= max1 + 100,
"row ids must keep advancing after saturation (got {max1} then {max2})"
);
}
#[test]
fn an_inline_image_rides_scrollback_past_saturation() {
let (_tmp, t) = quiet_pty();
let mut chunk = String::new();
for i in 0..5200 {
chunk.push_str(&format!("pre-{i}\r\n"));
}
feed_pty(&t, chunk.as_bytes());
feed_pty(&t, b"image-anchor-row");
t.push_image_for_test(vec![9, 9, 9]);
feed_pty(&t, b"\r\n");
let find_anchor = |t: &PtyTerminal| {
let (lines, top) = t.grid_lines();
top + lines
.iter()
.position(|l| l.starts_with("image-anchor-row"))
.unwrap() as i32
};
assert_eq!(
t.pane_images().pop().unwrap().line,
find_anchor(&t),
"the anchor starts on its row"
);
let mut more = String::new();
for i in 0..60 {
more.push_str(&format!("post-{i}\r\n"));
}
feed_pty(&t, more.as_bytes());
assert_eq!(
t.pane_images().pop().unwrap().line,
find_anchor(&t),
"the anchor must follow its content through ring rotation"
);
}
#[test]
fn a_program_emitted_scrollback_wipe_drops_captured_images() {
use base64::Engine;
let mut png_buf = Vec::new();
image::RgbaImage::from_pixel(1, 1, image::Rgba([0, 255, 0, 255]))
.write_to(
&mut std::io::Cursor::new(&mut png_buf),
image::ImageFormat::Png,
)
.expect("encode test png");
let b64 = base64::engine::general_purpose::STANDARD.encode(&png_buf);
let tmp = tempfile::tempdir().unwrap();
let script = format!(
"i=0; while [ $i -lt 60 ]; do echo fill-$i; i=$((i+1)); done; printf '\\033]1337;File=inline=1:{b64}\\007\\n'; read x; printf '\\033[3J\\033[2J'; printf 'wiped\\n'; sleep 30"
);
let mut term =
PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script], tmp.path()).unwrap();
let mut waited = 0u32;
while term.pane_images().is_empty() {
assert!(waited < 8000, "inline image never captured");
std::thread::sleep(std::time::Duration::from_millis(40));
waited += 40;
}
term.write_input(b"\n");
wait_for_grid(&term, |ls| ls.iter().any(|l| l.starts_with("wiped")));
assert!(
term.pane_images().is_empty(),
"an ED 3 scrollback wipe from the program must drop the pane's images"
);
}
#[test]
fn a_zero_history_screen_wipe_drops_captured_images() {
use base64::Engine;
let mut png_buf = Vec::new();
image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255]))
.write_to(
&mut std::io::Cursor::new(&mut png_buf),
image::ImageFormat::Png,
)
.expect("encode test png");
let b64 = base64::engine::general_purpose::STANDARD.encode(&png_buf);
let tmp = tempfile::tempdir().unwrap();
let script = format!(
"printf '\\033]1337;File=inline=1:{b64}\\007\\n'; read x; printf '\\033[2J\\033[3J\\033[H'; printf 'wiped\\n'; sleep 30"
);
let mut term =
PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script], tmp.path()).unwrap();
let mut waited = 0u32;
while term.pane_images().is_empty() {
assert!(waited < 8000, "inline image never captured");
std::thread::sleep(std::time::Duration::from_millis(40));
waited += 40;
}
term.write_input(b"\n");
wait_for_grid(&term, |ls| ls.iter().any(|l| l.starts_with("wiped")));
assert!(
term.pane_images().is_empty(),
"a screen wipe with empty history must still drop the pane's images"
);
}
#[test]
fn a_cancelled_csi_does_not_hide_a_wipe_from_the_sniffer() {
let mut w = WipeSniffer::default();
let (_s, h) = w.scan(b"\x1b[12\x1b[3J", false);
assert!(h, "ESC-in-CSI swallowed the scrollback wipe");
let mut w = WipeSniffer::default();
let (s, _h) = w.scan(b"\x1b[\x18\x1b[?1049h\x1b[2J", false);
assert!(!s, "CAN-cancelled CSI hid the alt entry from the sniffer");
}
#[test]
fn a_wipe_followed_by_alt_entry_in_one_chunk_still_drops_images() {
use base64::Engine;
let mut png_buf = Vec::new();
image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 255, 0, 255]))
.write_to(
&mut std::io::Cursor::new(&mut png_buf),
image::ImageFormat::Png,
)
.expect("encode test png");
let b64 = base64::engine::general_purpose::STANDARD.encode(&png_buf);
let tmp = tempfile::tempdir().unwrap();
let script = format!(
"printf '\\033]1337;File=inline=1:{b64}\\007\\n'; read x; printf '\\033[2J\\033[3J\\033[?1049halt-owns-this'; sleep 1; printf '\\033[?1049l'; printf 'back\\n'; sleep 30"
);
let mut term =
PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script], tmp.path()).unwrap();
let mut waited = 0u32;
while term.pane_images().is_empty() {
assert!(waited < 8000, "inline image never captured");
std::thread::sleep(std::time::Duration::from_millis(40));
waited += 40;
}
term.write_input(b"\n");
wait_for_grid(&term, |ls| ls.iter().any(|l| l.starts_with("back")));
assert!(
term.pane_images().is_empty(),
"the wipe preceded the alt entry, so the primary images are gone"
);
}
#[test]
fn clearing_the_terminal_drops_its_marks() {
use crate::shell_integration::OscEvent;
let (_tmp, mut t) = quiet_pty();
feed_pty(&t, b"\r\n$ ");
t.push_mark_for_test(OscEvent::PromptStart, 0);
t.push_mark_for_test(OscEvent::PromptEnd, 2);
feed_pty(&t, b"cmd\r\nout\r\n");
t.push_mark_for_test(OscEvent::CommandStart, 0);
t.push_mark_for_test(OscEvent::CommandEnd(Some(0)), 0);
assert_eq!(
pair_decorations(&t.marks_snapshot()).len(),
1,
"staging: one finished command"
);
t.clear_screen_and_scrollback();
assert!(
pair_decorations(&t.marks_snapshot()).is_empty(),
"cleared content keeps no command decorations"
);
}
#[test]
fn a_prompt_mark_rides_scrollback_past_saturation() {
use crate::shell_integration::OscEvent;
let (_tmp, mut t) = quiet_pty();
let mut chunk = String::new();
for i in 0..5200 {
chunk.push_str(&format!("pre-{i}\r\n"));
}
feed_pty(&t, chunk.as_bytes());
feed_pty(&t, b"$ marker-prompt");
t.push_mark_for_test(OscEvent::PromptStart, 0);
feed_pty(&t, b"\r\n");
let find = |t: &mut PtyTerminal| {
let (lines, top) = t.grid_lines();
top + lines
.iter()
.position(|l| l.starts_with("$ marker-prompt"))
.unwrap() as i32
};
assert_eq!(
t.marks_snapshot()[0].1,
find(&mut t),
"the mark starts on its prompt row"
);
let mut more = String::new();
for i in 0..60 {
more.push_str(&format!("post-{i}\r\n"));
}
feed_pty(&t, more.as_bytes());
assert_eq!(
t.marks_snapshot()[0].1,
find(&mut t),
"the mark must follow its prompt through ring rotation"
);
}
#[test]
fn clearing_the_terminal_drops_its_captured_images() {
let (_tmp, mut t) = quiet_pty();
feed_pty(&t, b"\r\nsome output");
t.push_image_for_test(vec![1, 2, 3]);
feed_pty(&t, b"\r\n");
assert_eq!(t.pane_images().len(), 1);
t.clear_screen_and_scrollback();
assert!(
t.pane_images().is_empty(),
"a cleared pane keeps no image anchored to erased content"
);
}
#[test]
fn capture_jump_matches_wrapped_lines_without_false_prefixes() {
let (_tmp, mut t) = quiet_pty();
let area = Rect::new(0, 0, 40, 12);
let mut buf = Buffer::empty(area);
(&mut t).render(area, &mut buf);
let needle: String = format!("error[E0308]: {}", "x".repeat(60))
.chars()
.take(60)
.collect();
feed_pty(&t, b"\r\nerror[E0308]: unrelated short\r\n");
assert_eq!(
t.find_captured_line(&needle),
None,
"a short non-wrapped lookalike must not match"
);
let full = format!("error[E0308]: {}", "x".repeat(60));
feed_pty(&t, full.as_bytes());
let start = {
let term = t.term.lock();
term.grid().cursor.point.line.0 - 1
};
assert_eq!(
t.find_captured_line(&needle),
Some(start),
"the wrapped line's FIRST row is the jump target, not its continuation"
);
}
#[test]
fn selection_over_a_soft_wrapped_line_copies_one_logical_line() {
let (_tmp, mut t) = quiet_pty();
let area = Rect::new(0, 0, 40, 10);
let mut buf = Buffer::empty(area);
(&mut t).render(area, &mut buf);
let cols = t.term.lock().columns();
feed_pty(&t, b"\r\n");
let start = t.term.lock().grid().cursor.point.line.0;
let long: String = "abcdefghij".repeat(6); feed_pty(&t, long.as_bytes());
t.set_selection(Some(Selection {
anchor: (start, 0),
head: (start + 1, cols.saturating_sub(1) as u16),
block: false,
}));
assert_eq!(
t.selection_text(),
long,
"the wrapped rows must rejoin without a newline"
);
feed_pty(&t, b"\r\nsecond");
t.set_selection(Some(Selection {
anchor: (start + 1, 0),
head: (start + 2, 6),
block: false,
}));
assert!(
t.selection_text().contains('\n'),
"a real row break still copies as two lines: {:?}",
t.selection_text()
);
}
#[test]
fn annotation_lookup_translates_at_the_callers_clock() {
let (_tmp, mut t) = quiet_pty();
feed_pty(&t, b"existing span\r\n");
let clock = t.scroll_clock();
t.add_annotation(0, clock, 0, 13, String::from("existing note"));
let (_, snap_clock) = t.selection_and_clock();
let mut fill = String::new();
for i in 0..30 {
fill.push_str(&format!("late-{i}\r\n"));
}
feed_pty(&t, fill.as_bytes());
let cur = t.annotations_at_clock(snap_clock);
assert_eq!(
cur[0].0, 0,
"translated at the captured clock, the note still names the captured line"
);
}
#[test]
fn annotations_hide_while_an_alt_screen_app_owns_the_viewport() {
let (_tmp, mut t) = quiet_pty();
t.last_inner = Rect {
x: 0,
y: 0,
width: 80,
height: 24,
};
feed_pty(&t, b"annotated content row\r\n");
let clock = t.scroll_clock();
t.add_annotation(0, clock, 0, 15, String::from("note"));
assert!(
t.annotation_at(3, 0).is_some(),
"the note resolves on the primary screen"
);
feed_pty(&t, b"\x1b[?1049h\x1b[Hvim-owns-this-screen");
assert!(
t.annotation_at(3, 0).is_none(),
"no hit while the alternate screen is up"
);
feed_pty(&t, b"\x1b[?1049l");
assert!(
t.annotation_at(3, 0).is_some(),
"back on the primary screen the note resolves again"
);
}
#[test]
fn an_annotation_committed_after_output_streamed_pins_where_it_was_captured() {
let (_tmp, mut t) = quiet_pty();
feed_pty(&t, b"target-line alpha\r\n");
let (lines, top) = t.grid_lines();
let line = top
+ lines
.iter()
.position(|l| l.starts_with("target-line"))
.unwrap() as i32;
let clock = t.scroll_clock();
let mut more = String::new();
for i in 0..40 {
more.push_str(&format!("while-typing-{i}\r\n"));
}
feed_pty(&t, more.as_bytes());
t.add_annotation(line, clock, 0, 11, String::from("note"));
let cur = t.annotations_current();
assert_eq!(cur.len(), 1, "the annotation survives");
let term = t.term.lock();
let text = extract_selection_text(&term, cur[0].0, 0, cur[0].0, 20);
assert!(
text.starts_with("target-line alpha"),
"the note must pin to the text selected at open, got row: {text:?}"
);
}
#[test]
fn an_annotation_survives_streaming_past_a_saturated_scrollback() {
let (_tmp, mut t) = quiet_pty();
let mut chunk = String::new();
for i in 0..5200 {
chunk.push_str(&format!("pre-{i}\r\n"));
}
feed_pty(&t, chunk.as_bytes());
feed_pty(&t, b"note-worthy-marker here\r\n");
let (lines, top) = t.grid_lines();
let line = top
+ lines
.iter()
.position(|l| l.starts_with("note-worthy-marker"))
.unwrap() as i32;
let clock = t.scroll_clock();
t.add_annotation(line, clock, 0, 18, String::from("pinned"));
let mut more = String::new();
for i in 0..60 {
more.push_str(&format!("post-{i}\r\n"));
}
feed_pty(&t, more.as_bytes());
let cur = t.annotations_current();
assert_eq!(cur.len(), 1, "the annotation survives the rotation");
let term = t.term.lock();
let text = extract_selection_text(&term, cur[0].0, 0, cur[0].0, 25);
assert!(
text.starts_with("note-worthy-marker"),
"the note must follow its content through ring rotation, got row: {text:?}"
);
}
#[test]
fn sticky_header_never_paints_a_control_char_for_a_multi_row_command() {
use crate::shell_integration::OscEvent;
let (_tmp, mut t) = quiet_pty();
let area = Rect::new(0, 0, 80, 20);
let mut buf = Buffer::empty(area);
(&mut t).render(area, &mut buf);
feed_pty(&t, b"$ ");
t.push_mark_for_test(OscEvent::PromptEnd, 2);
feed_pty(&t, b"echo \"build-it-99\r\nsecond-line\"");
feed_pty(&t, b"\r\n");
t.push_mark_for_test(OscEvent::CommandStart, 0);
for i in 0..40 {
feed_pty(&t, format!("out-{i}\r\n").as_bytes());
}
t.push_mark_for_test(OscEvent::CommandEnd(Some(0)), 0);
assert!(
!t.command_decorations().is_empty(),
"the marks must pair into a decoration"
);
t.scroll_to_top();
for _ in 0..5 {
t.scroll_down(1);
}
let mut buf = Buffer::empty(area);
(&mut t).render(area, &mut buf);
let inner = t.last_inner;
let top: String = (inner.x..inner.x + inner.width)
.map(|x| buf[(x, inner.y)].symbol().chars().next().unwrap_or(' '))
.collect();
assert!(
top.contains("build-it-99"),
"the wrapped command must still pin: {top:?}"
);
for y in 0..area.height {
for x in 0..area.width {
let sym = buf[(x, y)].symbol();
assert!(
!sym.chars().any(|c| c.is_control()),
"cell ({x},{y}) holds a control char: {sym:?}"
);
}
}
}
#[test]
fn a_prompt_click_after_the_row_was_rewritten_shorter_does_not_panic() {
let (_tmp, mut t) = quiet_pty();
t.last_inner = Rect {
x: 0,
y: 0,
width: 80,
height: 24,
};
feed_pty(&t, b"user@host ~/Documents/croft % ");
t.push_mark_for_test(crate::shell_integration::OscEvent::PromptEnd, 30);
feed_pty(&t, b"\r\x1b[Kworking");
let row = t.term.lock().grid().cursor.point.line.0 as u16;
assert_eq!(
t.prompt_click_arrows(5, row),
None,
"a click on a shortened prompt row must degrade, not panic"
);
}
#[test]
fn alt_screen_selection_follows_content_across_repaints() {
let (_tmp, mut t) = quiet_pty();
feed_pty(
&t,
b"\x1b[?1049h\x1b[H\x1b[2Jalpha one\r\nbravo two\r\ncharlie three\r\ndelta four",
);
t.set_selection(Some(Selection {
anchor: (1, 0),
head: (1, 8),
block: false,
}));
assert_eq!(t.selection_text(), "bravo two");
feed_pty(
&t,
b"\x1b[H\x1b[2Jbravo two\r\ncharlie three\r\ndelta four\r\necho five",
);
t.rebase_selection();
assert_eq!(t.selection_text(), "bravo two");
assert_eq!(
t.selection().unwrap().anchor.0,
0,
"the highlight must move to where the app repainted its text"
);
feed_pty(
&t,
b"\x1b[H\x1b[2Jfoxtrot six\r\ngolf seven\r\nhotel eight\r\nindia nine",
);
t.rebase_selection();
assert!(
t.alt_sel.as_ref().is_some_and(|a| a.dormant),
"no matching content anywhere in the grid: dormant"
);
assert_eq!(t.selection_text(), "bravo two");
feed_pty(
&t,
b"\x1b[H\x1b[2Jalpha one\r\nbravo two\r\ncharlie three\r\ndelta four",
);
t.rebase_selection();
assert!(t.alt_sel.as_ref().is_some_and(|a| !a.dormant));
assert_eq!(t.selection().unwrap().anchor.0, 1);
assert_eq!(t.selection_text(), "bravo two");
}
#[test]
fn alt_screen_row_half_covered_by_a_floating_pill_keeps_its_surviving_prefix() {
let (_tmp, mut t) = quiet_pty();
feed_pty(
&t,
b"\x1b[?1049h\x1b[H\x1b[2Jalpha one\r\nbravo two words here\r\ncharlie three words here\r\ndelta four words here\r\necho five",
);
t.set_selection(Some(Selection {
anchor: (1, 0),
head: (3, 20),
block: false,
}));
feed_pty(
&t,
b"\x1b[H\x1b[2Jalpha one\r\nbravo two words here\r\ncharlie three[ PILL ]here\r\ndelta four words here\r\necho five",
);
t.rebase_selection();
let anchor = t.alt_sel.as_ref().expect("anchor survives");
assert!(!anchor.dormant);
let clips = anchor.visible.as_ref().expect("partially covered");
assert!(
clips.contains(&(1, 0, u16::MAX)) && clips.contains(&(3, 0, u16::MAX)),
"intact rows keep their full highlight: {clips:?}"
);
assert!(
clips
.iter()
.any(|&(l, lo, hi)| l == 2 && lo == 0 && (12..14).contains(&hi)),
"the covered row keeps its surviving prefix ('charlie three'): {clips:?}"
);
assert!(
clips
.iter()
.any(|&(l, lo, hi)| l == 2 && lo == 21 && hi == 24),
"the surviving suffix ('here') stays lit too, even under half the row: {clips:?}"
);
}
#[test]
fn alt_screen_bottom_up_drag_from_a_blank_row_selects_and_survives_release() {
let (_tmp, mut t) = quiet_pty();
feed_pty(
&t,
b"\x1b[?1049h\x1b[H\x1b[2Jalpha one\r\nbravo two\r\ncharlie three\r\n\r\ntokens 42",
);
t.last_inner = Rect::new(0, 0, 40, 10);
t.start_selection_at(5, 3);
feed_pty(&t, b"\x1b[5;1Htokens 43\x1b[K");
t.extend_selection_to(0, 1);
let anchor = t.alt_sel.as_ref().expect("anchor present");
assert!(
!anchor.dormant,
"a held drag never hides itself, whatever the anchor matched"
);
assert_eq!(t.selection_text(), "bravo two\ncharlie three\n");
t.end_drag();
feed_pty(
&t,
b"\x1b[H\x1b[2Jnew line\r\nalpha one\r\nbravo two\r\ncharlie three\r\n\r\ntokens 44",
);
t.rebase_selection();
assert_eq!(t.selection().expect("survives").normalised().0, 2);
assert_eq!(t.selection_text(), "bravo two\ncharlie three\n");
}
#[test]
fn alt_screen_edge_autoscroll_forwards_wheel_to_the_tracking_app() {
let tmp = tempfile::tempdir().unwrap();
let mut t =
PtyTerminal::new_running("/bin/cat", &[String::from("-v")], tmp.path()).unwrap();
feed_pty(&t, b"\x1b[?1049h\x1b[?1002h\x1b[?1006h\x1b[H\x1b[2J");
t.last_inner = Rect::new(0, 0, 40, 10);
t.set_selection(Some(Selection {
anchor: (2, 0),
head: (2, 5),
block: false,
}));
t.autoscroll_select(1, 5);
assert_eq!(
t.selection().unwrap().head.0,
9,
"the head re-pins to the bottom edge row"
);
let mut waited = 0u32;
while !t.grid_lines().0.iter().any(|l| l.contains("[<65;6;10M")) {
assert!(waited < 8000, "the app never received the wheel report");
std::thread::sleep(std::time::Duration::from_millis(20));
waited += 20;
}
}
#[test]
fn primary_selection_survives_alt_round_trip_but_alt_selection_dies_on_exit() {
let (_tmp, mut t) = quiet_pty();
feed_pty(&t, b"hello world\r\n");
let (lines, top) = t.grid_lines();
let line = top
+ lines
.iter()
.position(|l| l.starts_with("hello"))
.expect("fed line present") as i32;
t.set_selection(Some(Selection {
anchor: (line, 0),
head: (line, 4),
block: false,
}));
assert_eq!(t.selection_text(), "hello");
feed_pty(&t, b"\x1b[?1049h\x1b[H\x1b[2Jvim vim vim");
t.rebase_selection();
feed_pty(&t, b"\x1b[?1049l");
t.rebase_selection();
assert_eq!(
t.selection_text(),
"hello",
"a primary-screen selection is frozen across an alt-screen trip"
);
feed_pty(&t, b"\x1b[?1049h\x1b[H\x1b[2Jquick brown fox");
t.set_selection(Some(Selection {
anchor: (0, 0),
head: (0, 4),
block: false,
}));
assert_eq!(t.selection_text(), "quick");
feed_pty(&t, b"\x1b[?1049l");
t.rebase_selection();
assert!(
t.selection().is_none(),
"an alt-screen selection dies with the alternate grid"
);
}
#[test]
fn selection_spanning_scrollback_into_live_extracts_every_line() {
let mut t = fresh_term(20, 3);
feed(&mut t, b"AAAA\r\nBBBB\r\nCCCC\r\nDDDD\r\nEEEE\r\nFFFF");
let all = extract_selection_text(&t, -3, 0, 2, 19);
assert_eq!(all, "AAAA\nBBBB\nCCCC\nDDDD\nEEEE\nFFFF");
}
#[test]
fn process_name_resolves_a_live_pid() {
let me = std::process::id() as i32;
let name = process_name(me);
assert!(
name.as_deref().is_some_and(|n| !n.is_empty()),
"the test process resolves to a non-empty name: {name:?}"
);
}
#[test]
fn pick_pane_label_prefers_a_manual_name() {
assert_eq!(pick_pane_label(Some("server"), "zsh"), "server");
assert_eq!(pick_pane_label(None, "vim"), "vim");
assert_eq!(pick_pane_label(None, ""), "");
}
#[test]
fn parse_shells_skips_comments_and_dedupes_by_basename() {
let s = "# /etc/shells\n/bin/zsh\n/bin/bash\n/usr/local/bin/bash\n\nnot-a-path\n/usr/bin/fish\n";
let p = parse_shells(s);
let bases: Vec<&str> = p.iter().map(|(_, b)| b.as_str()).collect();
assert_eq!(
bases,
vec!["zsh", "bash", "fish"],
"comments/blanks/non-paths skipped, basenames deduped"
);
assert_eq!(p[0].0, "/bin/zsh", "full path retained");
}
#[test]
fn finished_command_carries_its_output_block() {
let tmp = tempfile::tempdir().unwrap();
let script = "printf '\\033]133;A\\007$ \\033]133;B\\007make\\n\\033]133;C\\007'; printf 'main.c:7:3: error: boom\\nsecond line\\n'; printf '\\033]133;D;1\\007'";
let term =
PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
.unwrap();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
let mut finished = Vec::new();
while std::time::Instant::now() < deadline {
finished.extend(term.drain_finished_commands());
if !finished.is_empty() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(40));
}
let f = finished
.first()
.expect("the 133;D must yield a FinishedCommand");
assert!(
f.output.contains("main.c:7:3: error: boom") && f.output.contains("second line"),
"the output block must ride the completion; got {:?}",
f.output
);
}
#[test]
fn finished_output_keeps_a_final_line_without_trailing_newline() {
let tmp = tempfile::tempdir().unwrap();
let script = "printf '\\033]133;A\\007$ \\033]133;B\\007cc\\n\\033]133;C\\007'; printf 'lib.c:2:1: error: no newline here'; printf '\\033]133;D;1\\007'";
let term =
PtyTerminal::new_running("/bin/sh", &[String::from("-c"), script.into()], tmp.path())
.unwrap();
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
let mut finished = Vec::new();
while std::time::Instant::now() < deadline {
finished.extend(term.drain_finished_commands());
if !finished.is_empty() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(40));
}
let f = finished.first().expect("completion expected");
assert!(
f.output.contains("lib.c:2:1: error: no newline here"),
"the unterminated final row must be captured; got {:?}",
f.output
);
}
}