use super::*;
pub(super) static NEXT_MARK_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
pub(super) fn next_mark_id() -> u64 {
NEXT_MARK_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}
#[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;
impl RunningCommand {
pub(super) fn follow_wipe(&mut self, wipe: Wipe, now: i64) {
let line = self.out_line - (now - self.out_clock) as i32;
if (line >= 0 && wipe.screen) || (line < 0 && wipe.hist) {
self.out_line = 0;
self.out_clock = now;
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CommandDecoration {
pub id: u64,
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,
}
#[derive(Clone, Debug)]
pub struct MarkView {
pub id: u64,
pub kind: crate::shell_integration::OscEvent,
pub line: i32,
pub col: usize,
pub dur: Option<std::time::Duration>,
}
pub fn pair_decorations(marks: &[MarkView]) -> 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<(u64, i32)> = None;
for m in marks {
match &m.kind {
E::PromptStart => {
prompt = Some(m.line);
input = None;
}
E::PromptEnd => input = Some((m.line, m.col)),
E::CommandStart => started = Some((m.id, m.line)),
E::CommandEnd(exit) => {
if let Some((id, output_start)) = started.take() {
out.push(CommandDecoration {
id,
line: prompt.unwrap_or(output_start),
exit: *exit,
duration: m.dur,
input,
output_start,
output_end: m.line,
});
}
}
_ => {}
}
}
out
}
pub(super) const MARKS_MAX: usize = 2000;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PromptJump {
Jumped,
NoMarks,
NoneThatWay,
}
pub(super) 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()
}
}
impl PtyTerminal {
#[cfg(test)]
pub fn command_marks(&self) -> Vec<(crate::shell_integration::OscEvent, i32)> {
self.marks_snapshot()
.into_iter()
.map(|m| (m.kind, m.line))
.collect()
}
pub(super) fn marks_snapshot(&self) -> Vec<MarkView> {
self.marks_snapshot_locked(&mut self.term.lock())
}
fn marks_snapshot_locked(&self, term: &mut Term<VoidListener>) -> Vec<MarkView> {
let now = self.clock.lock().unwrap().tick(term);
let floor = term.grid().topmost_line().0;
let mut marks = self.marks.lock().unwrap();
marks.retain(|m| m.line_rec - (now - m.clock_rec) as i32 >= floor);
marks
.iter()
.map(|m| MarkView {
id: m.id,
kind: m.kind.clone(),
line: m.line_rec - (now - m.clock_rec) as i32,
col: m.col_rec,
dur: m.dur,
})
.collect()
}
pub fn jump_to_prompt(&mut self, forward: bool) -> PromptJump {
let mut term = self.term.lock();
let prompts: Vec<i32> = self
.marks_snapshot_locked(&mut term)
.into_iter()
.filter(|m| m.kind == crate::shell_integration::OscEvent::PromptStart)
.map(|m| m.line)
.collect();
let top = -(term.grid().display_offset() as i32);
let Some(target) = pick_prompt_jump(&prompts, top, forward) else {
return if prompts.is_empty() {
PromptJump::NoMarks
} else {
PromptJump::NoneThatWay
};
};
scroll_line_to_top(&mut term, target);
drop(term);
self.pty_dirty.store(true, Ordering::Release);
PromptJump::Jumped
}
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();
without_continuation_prompts(&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)
}
#[cfg(test)]
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 prompt_tail(&self) -> Option<(String, u16, u16, u16)> {
let term = self.term.lock();
if term.mode().contains(TermMode::ALT_SCREEN) || term.grid().display_offset() != 0 {
return None;
}
let cursor = term.grid().cursor.point;
let line = cursor.line.0;
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)
|| last.line_rec - (now - last.clock_rec) as i32 != line
{
return None;
}
let (text, colmap) = row_text_and_cols(&term, line);
let cur = cursor.column.0;
let b_col = last.col_rec;
if colmap
.iter()
.zip(text.chars())
.any(|(&c, ch)| c >= cur && !ch.is_whitespace())
{
return None;
}
let typed: String = colmap
.iter()
.zip(text.chars())
.filter(|(c, _)| **c >= b_col && **c < cur)
.map(|(_, ch)| ch)
.collect();
let inner = self.last_inner;
if inner.width == 0 || line < 0 || line as u16 >= inner.height {
return None;
}
Some((
typed,
inner.x + cur as u16,
inner.y + line as u16,
inner.x + inner.width,
))
}
pub fn screen_cursor(&self) -> Option<(u16, u16)> {
let term = self.term.lock();
if !term.mode().contains(TermMode::SHOW_CURSOR) || term.grid().display_offset() != 0 {
return None;
}
let p = term.grid().cursor.point;
let inner = self.last_inner;
let (line, col) = (p.line.0, p.column.0 as u16);
if inner.width == 0 || line < 0 || line as u16 >= inner.height || col >= inner.width {
return None;
}
Some((inner.x + col, inner.y + line as u16))
}
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))
}
#[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 {
id: next_mark_id(),
kind,
line_rec,
clock_rec,
col_rec,
dur: None,
});
}
#[cfg(test)]
pub fn finish_command_for_test(&self, exit: Option<i32>, dur: std::time::Duration) {
let _ = self.finished_tx_for_test.send(FinishedCommand {
exit,
dur,
cmd: String::new(),
cwd: None,
host: None,
output: String::new(),
});
}
}
pub(super) 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();
}
without_continuation_prompts(&extract_selection_text(
term,
bl,
b.col_rec,
cl - 1,
term.columns().saturating_sub(1),
))
}
pub(super) fn without_continuation_prompts(text: &str) -> String {
let strip = |line: &str| -> String {
let is_ps2 = |head: &str| {
!head.starts_with(' ') && head.chars().all(|c| c.is_ascii_lowercase() || c == ' ')
};
if let Some(i) = line.find("> ")
&& is_ps2(&line[..i])
{
return line[i + 2..].to_string();
}
match line.strip_suffix('>') {
Some(head) if is_ps2(head) => String::new(),
_ => line.to_string(),
}
};
let mut lines = text.split('\n');
let mut out = lines.next().unwrap_or_default().to_string();
for line in lines {
out.push('\n');
out.push_str(&strip(line));
}
out
}
pub(super) fn command_output_text(term: &Term<VoidListener>, start: i32) -> String {
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()
}
}