use std::borrow::Cow;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Instant, SystemTime};
use alacritty_terminal::event::{Event as TermEvent, EventListener, WindowSize};
use alacritty_terminal::event_loop::{EventLoop, EventLoopSender, Msg};
use alacritty_terminal::grid::Dimensions;
use alacritty_terminal::index::{Column, Line, Point, Side};
use alacritty_terminal::selection::{Selection, SelectionType};
use alacritty_terminal::sync::FairMutex;
use alacritty_terminal::term::cell::Flags;
use alacritty_terminal::term::{Config as TermConfig, Term, TermMode};
use alacritty_terminal::tty::{self, Options, Shell};
use winit::event_loop::EventLoopProxy;
use crate::anim::Tween;
use crate::claude::{self, Status};
use crate::editing::{self, Move};
use crate::inject::{Injector, Outcome};
use crate::layout::{PaneId, Rect};
use crate::links::Target;
use crate::search::Search;
pub struct Done {
pub what: String,
pub secs: f32,
}
pub enum TitleSignal {
None,
Pick(PathBuf),
Done(Done),
}
pub enum UserEvent {
Term(PaneId, TermEvent),
Hotkey,
ConfigChanged,
}
#[derive(Clone)]
pub struct Listener {
id: PaneId,
proxy: EventLoopProxy<UserEvent>,
}
impl EventListener for Listener {
fn send_event(&self, event: TermEvent) {
let _ = self.proxy.send_event(UserEvent::Term(self.id, event));
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct GridSize {
pub cols: usize,
pub rows: usize,
}
impl Dimensions for GridSize {
fn total_lines(&self) -> usize {
self.rows
}
fn screen_lines(&self) -> usize {
self.rows
}
fn columns(&self) -> usize {
self.cols
}
}
pub struct Pane {
pub id: PaneId,
pub term: Arc<FairMutex<Term<Listener>>>,
sender: EventLoopSender,
pub grid: GridSize,
pending_grid: Option<(GridSize, Instant)>,
cell: (f32, f32),
pub target: Rect,
pub rect: Rect,
pub focus: f32,
pub opacity: f32,
pub bell: f32,
pub rect_anim: Tween<Rect>,
pub focus_anim: Tween<f32>,
pub opacity_anim: Tween<f32>,
pub bell_anim: Tween<f32>,
pub title: String,
pub cwd: Option<PathBuf>,
pub scroll_accum: f32,
pub claude: bool,
pub claude_title: String,
pub claude_status: Option<Status>,
status_key: String,
status_mtime: Option<SystemTime>,
pub search: Option<Search>,
pub link: Option<(i32, usize, usize)>,
cmd: Option<(Instant, String)>,
claude_busy: Option<Instant>,
integrated: bool,
injector: Option<Injector>,
pub kb_sel: Option<KbSel>,
}
#[derive(Clone, Debug)]
pub struct KbSel {
pub text: String,
pub anchor: usize,
pub head: usize,
}
impl Pane {
#[allow(clippy::too_many_arguments)]
pub fn spawn(
id: PaneId,
proxy: EventLoopProxy<UserEvent>,
shell: (String, Vec<String>),
extra_env: &[(String, String)],
cwd: Option<PathBuf>,
scrollback: usize,
grid: GridSize,
cell: (f32, f32),
rect: Rect,
) -> std::io::Result<Self> {
let integrated = extra_env.iter().any(|(k, _)| k == "PROMPT_COMMAND");
let listener = Listener { id, proxy };
let mut env: HashMap<String, String> = [
("TERM", "xterm-256color"),
("COLORTERM", "truecolor"),
("TERM_PROGRAM", "rustimal"),
("CHERE_INVOKING", "1"),
]
.into_iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
for (k, v) in crate::winenv::fresh() {
env.entry(k).or_insert(v);
}
env.extend(extra_env.iter().cloned());
let status_key = format!("{}-{id}", std::process::id());
env.insert("RUSTIMAL_PANE".into(), status_key.clone());
let opts = Options {
shell: Some(Shell::new(shell.0, shell.1)),
working_directory: cwd.clone(),
drain_on_exit: false,
env,
escape_args: true,
};
let pty = tty::new(&opts, window_size(grid, cell), id)?;
let config = TermConfig { scrolling_history: scrollback, ..Default::default() };
let term = Arc::new(FairMutex::new(Term::new(config, &grid, listener.clone())));
let event_loop = EventLoop::new(term.clone(), listener, pty, false, false)?;
let sender = event_loop.channel();
event_loop.spawn();
Ok(Self {
id,
term,
sender,
grid,
pending_grid: None,
cell,
target: rect,
rect,
focus: 0.0,
opacity: 0.0,
bell: 0.0,
rect_anim: Tween::new(rect),
focus_anim: Tween::new(0.0),
opacity_anim: Tween::new(0.0),
bell_anim: Tween::new(0.0),
title: String::new(),
cwd,
scroll_accum: 0.0,
claude: false,
claude_title: String::new(),
claude_status: None,
status_key,
status_mtime: None,
search: None,
link: None,
cmd: None,
claude_busy: None,
integrated,
injector: None,
kb_sel: None,
})
}
pub fn can_type(&self) -> bool {
const BUSY: std::time::Duration = std::time::Duration::from_secs(3);
self.integrated
&& !self.claude
&& !self.term.lock().mode().contains(TermMode::ALT_SCREEN)
&& self.cmd.as_ref().is_none_or(|(started, _)| started.elapsed() < BUSY)
}
pub fn start_typing(&mut self, cmd: String, target: Option<Target>) {
self.injector = Some(Injector::new(cmd, target, Instant::now()));
}
pub fn at_empty_prompt(&self) -> bool {
cursor_at_prompt(&self.term.lock())
}
pub fn edit_ready(&self) -> bool {
self.integrated && !self.claude && self.injector.is_none() && command_line(&self.term.lock()).is_some()
}
fn live_selection(&self, cl: &CmdLine) -> Option<KbSel> {
let sel = self.kb_sel.as_ref()?;
let shown = self.term.lock().selection.is_some();
(shown && sel.anchor != sel.head && sel.text == cl.text()).then(|| sel.clone())
}
pub fn has_selection(&mut self) -> bool {
let cl = command_line(&self.term.lock());
let live = cl.and_then(|cl| self.live_selection(&cl));
if live.is_none() {
self.kb_sel = None;
}
live.is_some()
}
pub fn clear_selection(&mut self) {
if self.kb_sel.take().is_some() {
self.term.lock().selection = None;
}
}
pub fn extend_selection(&mut self, mv: Move) -> bool {
let (cl, app) = {
let term = self.term.lock();
(command_line(&term), term.mode().contains(TermMode::APP_CURSOR))
};
let Some(cl) = cl.filter(|cl| !cl.cells.is_empty()) else { return false };
let live = self.live_selection(&cl);
let cursor = live.as_ref().map_or(cl.cursor, |s| s.head);
let anchor = live.as_ref().map_or(cursor, |s| s.anchor);
let to = editing::target(&cl.chars(), cursor, mv);
self.write(editing::move_keys(cursor, to, app));
self.kb_sel = Some(KbSel { text: cl.text(), anchor, head: to });
show_selection(&mut self.term.lock(), &cl, anchor.min(to), anchor.max(to));
true
}
pub fn select_command_line(&mut self) -> bool {
let (cl, app) = {
let term = self.term.lock();
(command_line(&term), term.mode().contains(TermMode::APP_CURSOR))
};
let Some(cl) = cl.filter(|cl| !cl.cells.is_empty()) else { return false };
let cursor = self.live_selection(&cl).map_or(cl.cursor, |s| s.head);
let n = cl.cells.len();
self.write(editing::move_keys(cursor, n, app));
self.kb_sel = Some(KbSel { text: cl.text(), anchor: 0, head: n });
show_selection(&mut self.term.lock(), &cl, 0, n);
true
}
pub fn select_everything(&mut self) {
let mut term = self.term.lock();
let last = Column(term.columns().saturating_sub(1));
let mut sel = Selection::new(SelectionType::Simple, Point::new(term.topmost_line(), Column(0)), Side::Left);
sel.update(Point::new(term.bottommost_line(), last), Side::Right);
term.selection = Some(sel);
}
pub fn collapse_selection(&mut self, to_end: bool) -> bool {
let (cl, app) = {
let term = self.term.lock();
(command_line(&term), term.mode().contains(TermMode::APP_CURSOR))
};
let Some(sel) = cl.as_ref().and_then(|cl| self.live_selection(cl)) else { return false };
let to = if to_end { sel.anchor.max(sel.head) } else { sel.anchor.min(sel.head) };
self.write(editing::move_keys(sel.head, to, app));
self.clear_selection();
true
}
pub fn delete_selection(&mut self) -> bool {
let (cl, app) = {
let term = self.term.lock();
(command_line(&term), term.mode().contains(TermMode::APP_CURSOR))
};
let Some(sel) = cl.as_ref().and_then(|cl| self.live_selection(cl)) else { return false };
let (lo, hi) = (sel.anchor.min(sel.head), sel.anchor.max(sel.head));
self.write(editing::delete_keys(lo, hi, sel.head, app));
self.clear_selection();
true
}
pub fn is_typing(&self) -> bool {
self.injector.is_some()
}
pub fn pump(&mut self) -> Option<Target> {
let mut injector = self.injector.take()?;
let (writes, outcome) = injector.tick(&self.term.lock(), Instant::now());
for bytes in writes {
self.write(bytes);
}
match outcome {
Outcome::Pending => {
self.injector = Some(injector);
None
}
Outcome::Done => None,
Outcome::GiveUp => injector.target,
}
}
pub fn write(&self, bytes: impl Into<Cow<'static, [u8]>>) {
let _ = self.sender.send(Msg::Input(bytes.into()));
}
pub fn request_grid(&mut self, grid: GridSize, cell: (f32, f32), immediate: bool) {
let cell_changed = cell != self.cell;
self.cell = cell;
if grid == self.grid && !cell_changed {
self.pending_grid = None;
return;
}
if immediate {
self.apply_grid(grid);
} else {
self.pending_grid = Some((grid, Instant::now()));
}
}
pub fn flush_grid(&mut self, debounce: std::time::Duration) -> bool {
if let Some((grid, at)) = self.pending_grid {
if at.elapsed() >= debounce {
self.apply_grid(grid);
} else {
return true;
}
}
false
}
fn apply_grid(&mut self, grid: GridSize) {
self.pending_grid = None;
self.grid = grid;
self.term.lock().resize(grid);
let _ = self.sender.send(Msg::Resize(window_size(grid, self.cell)));
}
pub fn window_size(&self) -> WindowSize {
window_size(self.grid, self.cell)
}
pub fn set_title(&mut self, title: String) -> TitleSignal {
if let Some(path) = title.strip_prefix("__rustimal_pick__:") {
return match msys_to_windows(path) {
Some(dir) => TitleSignal::Pick(dir),
None => TitleSignal::Pick(self.cwd.clone().unwrap_or_else(|| PathBuf::from("."))),
};
}
if let Some(cmd) = title.strip_prefix("__rustimal_cmd__:") {
self.cmd = Some((Instant::now(), cmd.trim().to_string()));
return TitleSignal::None;
}
if title == "__rustimal_claude__" {
self.claude = true;
self.claude_title.clear();
self.claude_status = None;
self.status_mtime = None;
if let Some(f) = self.status_file() {
let _ = std::fs::remove_file(f);
}
return TitleSignal::None;
}
if let Some((prefix, path)) = title.split_once(':')
&& prefix.chars().all(|c| c.is_ascii_alphanumeric()) && path.starts_with('/') {
if let Some(p) = msys_to_windows(path) {
self.cwd = Some(p);
}
if self.claude {
self.term.lock().scroll_display(alacritty_terminal::grid::Scroll::Bottom);
}
self.claude = false;
self.claude_busy = None;
self.title = title;
return match self.cmd.take() {
Some((started, cmd)) if cmd.split_whitespace().next() != Some("claude") => {
TitleSignal::Done(Done { what: cmd, secs: started.elapsed().as_secs_f32() })
}
_ => TitleSignal::None,
};
}
let mut signal = TitleSignal::None;
if self.claude {
self.claude_title = title.trim_start_matches(|c: char| !c.is_alphanumeric()).trim().to_string();
if title.chars().next().is_some_and(|c| ('\u{2800}'..='\u{28ff}').contains(&c)) {
self.claude_busy.get_or_insert_with(Instant::now);
} else if let Some(since) = self.claude_busy.take() {
signal = TitleSignal::Done(Done { what: "Claude".into(), secs: since.elapsed().as_secs_f32() });
}
}
self.title = title;
signal
}
fn status_file(&self) -> Option<PathBuf> {
crate::config::state_dir().map(|d| d.join(format!("claude-{}.json", self.status_key)))
}
pub fn poll_status(&mut self) -> bool {
if !self.claude {
return false;
}
let Some(file) = self.status_file() else { return false };
let Ok(mtime) = std::fs::metadata(&file).and_then(|m| m.modified()) else { return false };
if self.status_mtime == Some(mtime) {
return false;
}
self.status_mtime = Some(mtime);
let Some(status) = std::fs::read_to_string(&file).ok().and_then(|t| claude::parse_status(&t)) else {
return false;
};
let changed = self.claude_status.as_ref() != Some(&status);
self.claude_status = Some(status);
changed
}
pub fn display_name(&self) -> String {
let home = dirs::home_dir();
match &self.cwd {
Some(cwd) if Some(cwd) != home.as_ref() => cwd
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| cwd.to_string_lossy().into_owned()),
_ => "rustimal".into(),
}
}
pub fn shutdown(&self) {
let _ = self.sender.send(Msg::Shutdown);
}
}
pub fn cursor_at_prompt<T>(term: &Term<T>) -> bool {
if term.mode().contains(TermMode::ALT_SCREEN) {
return false;
}
let cursor = term.grid().cursor.point;
let row = crate::search::row_chars(term, cursor.line);
let before: String = row.iter().filter(|&&(col, ..)| col < cursor.column.0).map(|&(_, c, _)| c).collect();
let after_is_empty = row.iter().all(|&(col, c, _)| col < cursor.column.0 || c == ' ');
before.ends_with("\u{276f} ") && after_is_empty
}
pub fn awaiting_more<T>(term: &Term<T>) -> bool {
let cursor = term.grid().cursor.point;
let row = crate::search::row_chars(term, cursor.line);
let before: String = row.iter().filter(|&&(col, ..)| col < cursor.column.0).map(|&(_, c, _)| c).collect();
!term.mode().contains(TermMode::ALT_SCREEN) && before.trim_end().ends_with("--More--")
}
pub fn last_output<T>(term: &Term<T>) -> Option<String> {
if term.mode().contains(TermMode::ALT_SCREEN) {
return None;
}
let marker = "\u{276f} ";
let text = |line: i32| -> String { crate::search::row_chars(term, Line(line)).iter().map(|&(_, c, _)| c).collect() };
let top = term.topmost_line().0;
let mut end = term.grid().cursor.point.line.0 - i32::from(typed_text(term).is_some());
while end >= top && text(end).trim().is_empty() {
end -= 1;
}
let cmd = (top..=end).rev().find(|&line| text(line).contains(marker))?;
let last_col = Column(term.columns().saturating_sub(1));
let mut first = cmd;
while first < end && term.grid()[Line(first)][last_col].flags.contains(Flags::WRAPLINE) {
first += 1;
}
first += 1;
if first > end {
return None;
}
let out = term.bounds_to_string(Point::new(Line(first), Column(0)), Point::new(Line(end), last_col));
let out = out.trim_matches('\n').trim_end().to_string();
(!out.is_empty()).then_some(out)
}
pub struct CmdLine {
pub line: i32,
pub cells: Vec<(usize, char, usize)>,
pub cursor: usize,
}
impl CmdLine {
pub fn chars(&self) -> Vec<char> {
self.cells.iter().map(|c| c.1).collect()
}
pub fn text(&self) -> String {
self.cells.iter().map(|c| c.1).collect()
}
}
pub fn command_line<T>(term: &Term<T>) -> Option<CmdLine> {
if term.mode().contains(TermMode::ALT_SCREEN) {
return None;
}
let cursor = term.grid().cursor.point;
let last_col = Column(term.columns().saturating_sub(1));
if term.grid()[cursor.line][last_col].flags.contains(Flags::WRAPLINE) {
return None;
}
let row = crate::search::row_chars(term, cursor.line);
let marker = row.windows(2).rposition(|w| w[0].1 == '\u{276f}' && w[1].1 == ' ')?;
let after = &row[marker + 2..];
let cursor_idx = after.iter().filter(|&&(col, ..)| col < cursor.column.0).count();
let text_end = after.iter().rposition(|c| c.1 != ' ').map_or(0, |i| i + 1);
let end = text_end.max(cursor_idx);
Some(CmdLine { line: cursor.line.0, cells: after[..end].to_vec(), cursor: cursor_idx })
}
pub fn show_selection<T>(term: &mut Term<T>, cl: &CmdLine, lo: usize, hi: usize) {
if lo >= hi || hi > cl.cells.len() {
term.selection = None;
return;
}
let cols = term.columns();
let start = cl.cells[lo].0;
let (end, side) = if hi < cl.cells.len() {
(cl.cells[hi].0, Side::Left)
} else {
let (col, _, width) = cl.cells[hi - 1];
if col + width >= cols { (cols - 1, Side::Right) } else { (col + width, Side::Left) }
};
let mut sel = Selection::new(SelectionType::Simple, Point::new(Line(cl.line), Column(start)), Side::Left);
sel.update(Point::new(Line(cl.line), Column(end)), side);
term.selection = Some(sel);
}
pub fn typed_text<T>(term: &Term<T>) -> Option<String> {
if term.mode().contains(TermMode::ALT_SCREEN) {
return None;
}
let cursor = term.grid().cursor.point;
let row = crate::search::row_chars(term, cursor.line);
let before: String = row.iter().filter(|&&(col, ..)| col < cursor.column.0).map(|&(_, c, _)| c).collect();
let marker = "\u{276f} ";
let at = before.rfind(marker)?;
Some(before[at + marker.len()..].to_string())
}
fn window_size(grid: GridSize, cell: (f32, f32)) -> WindowSize {
WindowSize {
num_lines: grid.rows as u16,
num_cols: grid.cols as u16,
cell_width: cell.0 as u16,
cell_height: cell.1 as u16,
}
}
fn msys_to_windows(path: &str) -> Option<PathBuf> {
let mut parts = path.trim_start_matches('/').splitn(2, '/');
let drive = parts.next()?;
if drive.len() != 1 || !drive.chars().all(|c| c.is_ascii_alphabetic()) {
return None;
}
let rest = parts.next().unwrap_or("");
let p = PathBuf::from(format!("{}:\\{}", drive.to_ascii_uppercase(), rest.replace('/', "\\")));
p.is_dir().then_some(p)
}
impl Drop for Pane {
fn drop(&mut self) {
self.shutdown();
if let Some(f) = self.status_file() {
let _ = std::fs::remove_file(f);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use alacritty_terminal::event::VoidListener;
use alacritty_terminal::term::Config;
use alacritty_terminal::vte::ansi::Processor;
struct Size(usize, usize);
impl Dimensions for Size {
fn total_lines(&self) -> usize {
self.0
}
fn screen_lines(&self) -> usize {
self.0
}
fn columns(&self) -> usize {
self.1
}
}
fn screen(rows: usize, cols: usize, text: &str) -> Term<VoidListener> {
let mut term = Term::new(Config::default(), &Size(rows, cols), VoidListener);
let mut parser: Processor = Processor::new();
parser.advance(&mut term, text.as_bytes());
term
}
#[test]
fn last_output_is_what_the_last_command_printed() {
let term = screen(20, 60, "~ \u{276f} echo one\r\none\r\n\r\n~ \u{276f} ls\r\nfile a\r\nfile b\r\n\r\n~ \u{276f} ");
assert_eq!(last_output(&term).as_deref(), Some("file a\nfile b"));
let term = screen(20, 60, "~ \u{276f} ls\r\nfile a\r\nfile b\r\n\r\n~ \u{276f} cd sr");
assert_eq!(last_output(&term).as_deref(), Some("file a\nfile b"));
}
#[test]
fn last_output_while_the_command_still_runs() {
let term = screen(20, 60, "~ \u{276f} make\r\nbuilding a\r\nbuilding b");
assert_eq!(last_output(&term).as_deref(), Some("building a\nbuilding b"));
}
#[test]
fn last_output_survives_scrolling_and_wrapped_commands() {
let mut text = String::from("~ \u{276f} seq 1 40\r\n");
for i in 1..=40 {
text += &format!("{i}\r\n");
}
text += "\r\n~ \u{276f} ";
let term = screen(10, 40, &text);
let out = last_output(&term).unwrap();
assert!(out.starts_with("1\n2\n3\n") && out.ends_with("\n39\n40"), "{out:?}");
assert_eq!(out.lines().count(), 40);
let long = "x".repeat(50);
let term = screen(10, 30, &format!("~ \u{276f} echo {long}\r\n{long}\r\n\r\n~ \u{276f} "));
assert_eq!(last_output(&term).as_deref(), Some(long.as_str()));
}
#[test]
fn the_command_line_is_found_with_the_cursor_in_it() {
let term = screen(10, 40, "~ \u{276f} cd src\x1b[2D");
let cl = command_line(&term).unwrap();
assert_eq!(cl.text(), "cd src");
assert_eq!(cl.cursor, 4);
let term = screen(10, 40, "~ \u{276f} ");
let cl = command_line(&term).unwrap();
assert!(cl.cells.is_empty() && cl.cursor == 0);
let term = screen(10, 40, "~ \u{276f} ls ");
let cl = command_line(&term).unwrap();
assert_eq!((cl.text().as_str(), cl.cursor), ("ls ", 4));
assert!(command_line(&screen(10, 40, "just output")).is_none());
}
#[test]
fn the_selection_covers_the_chosen_characters() {
let mut term = screen(10, 40, "~ \u{276f} echo hello world");
let cl = command_line(&term).unwrap();
show_selection(&mut term, &cl, 5, 10);
assert_eq!(term.selection_to_string().as_deref(), Some("hello"));
show_selection(&mut term, &cl, 11, cl.cells.len());
assert_eq!(term.selection_to_string().as_deref(), Some("world"), "up to the end of the line");
show_selection(&mut term, &cl, 0, cl.cells.len());
assert_eq!(term.selection_to_string().as_deref(), Some("echo hello world"));
show_selection(&mut term, &cl, 3, 3);
assert!(term.selection.is_none(), "an empty range is no selection");
}
#[test]
fn no_output_for_a_command_that_printed_nothing() {
let term = screen(10, 40, "~ \u{276f} true\r\n\r\n~ \u{276f} ");
assert_eq!(last_output(&term), None);
assert_eq!(last_output(&screen(10, 40, "")), None);
}
}