use super::*;
pub type ScreenAnsi = (Vec<(String, String, bool)>, Option<(u16, u16)>);
impl PtyTerminal {
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 (lines, _, top) = self.grid_lines_wrapped();
(lines, top)
}
pub fn grid_lines_wrapped(&self) -> (Vec<String>, Vec<bool>, i32) {
grid_rows_wrapped(&self.term.lock())
}
pub fn find_lines(&self) -> Vec<FindLine> {
let (lines, wraps, top) = self.grid_lines_wrapped();
join_wrapped_rows(lines, &wraps, top)
}
pub fn find_lines_and_clock(&self) -> (Vec<FindLine>, i64) {
let term = self.term.lock();
let (lines, wraps, top) = grid_rows_wrapped(&term);
(join_wrapped_rows(lines, &wraps, top), self.clock_now(&term))
}
pub fn grid_lines_ansi(&self) -> Vec<(String, String)> {
self.grid_lines_ansi_wrapped()
.into_iter()
.map(|(plain, ansi, _)| (plain, ansi))
.collect()
}
pub fn grid_lines_ansi_wrapped(&self) -> Vec<(String, String, bool)> {
let term = self.term.lock();
if term.columns() == 0 {
return Vec::new();
}
let top = term.grid().topmost_line().0;
ansi_rows(&term, top)
}
pub fn screen_ansi_wrapped(&self) -> ScreenAnsi {
let term = self.term.lock();
if term.columns() == 0 {
return (Vec::new(), None);
}
let rows = ansi_rows(&term, 0);
let p = term.grid().cursor.point;
let cursor = (term.mode().contains(TermMode::SHOW_CURSOR)
&& p.line.0 >= 0
&& (p.line.0 as usize) < rows.len())
.then_some((p.line.0 as u16, p.column.0 as u16));
(rows, cursor)
}
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 tail_rows(&self, n: usize) -> Vec<String> {
let text = self.visible_text();
let mut rows: Vec<String> = text
.lines()
.rev()
.filter(|l| !l.trim().is_empty())
.take(n)
.map(|l| l.trim_end().to_string())
.collect();
rows.reverse();
rows
}
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 (row_text, cols_map) = row_text_and_cols(&term, line);
let idx = cols_map.iter().rposition(|&gc| gc <= c as usize)?;
let top = -(term.grid().history_size() as i32);
let bottom = term.screen_lines() as i32 - 1;
let mut first = line;
while first > top && row_wraps(&term, first - 1) {
first -= 1;
}
let mut last = line;
while last < bottom && row_wraps(&term, last) {
last += 1;
}
if first == line && last == line {
return Some((row_text, idx));
}
let mut text = String::new();
let mut offset = 0;
for l in first..=last {
let part = if l == line {
offset = text.chars().count();
row_text.clone()
} else {
row_text_and_cols(&term, l).0
};
text.push_str(&part);
}
Some((text, offset + idx))
}
pub fn row_text(&self, line: i32) -> (String, Vec<usize>) {
let term = self.term.lock();
row_text_and_cols(&term, line)
}
}
pub fn logical_row_text(term: &Term<VoidListener>, line_idx: i32) -> (String, usize) {
let (joined, offset, _start) = logical_row_span(term, line_idx);
(joined, offset)
}
pub fn logical_row_span(term: &Term<VoidListener>, line_idx: i32) -> (String, usize, i32) {
const REACH: i32 = 64;
let top = term.grid().topmost_line().0;
let bottom = term.screen_lines() as i32 - 1;
let mut start = line_idx;
while start > top && line_idx - start < REACH && row_wraps(term, start - 1) {
start -= 1;
}
let mut end = line_idx;
while end < bottom && end - line_idx < REACH && row_wraps(term, end) {
end += 1;
}
let mut joined = String::new();
let mut offset = 0;
for l in start..=end {
let (s, _) = row_text_and_cols(term, l);
if l == line_idx {
offset = joined.chars().count();
}
joined.push_str(&s);
}
(joined, offset, start)
}
pub(super) fn grid_rows_wrapped(term: &Term<VoidListener>) -> (Vec<String>, Vec<bool>, i32) {
if term.columns() == 0 {
return (Vec::new(), 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 wraps = Vec::new();
let mut l = top;
while l <= bottom {
let (s, _cols) = row_text_and_cols(term, l);
let wraps_on = l < bottom && row_wraps(term, l);
lines.push(if wraps_on {
s
} else {
s.trim_end().to_string()
});
wraps.push(wraps_on);
l += 1;
}
(lines, wraps, top)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FindLine {
pub text: String,
pub start: i32,
pub row_lens: Vec<usize>,
}
impl FindLine {
pub fn line_of(&self, col: usize) -> i32 {
let mut seen = 0;
for (i, len) in self.row_lens.iter().enumerate() {
seen += len;
if col < seen {
return self.start + i as i32;
}
}
self.start + self.row_lens.len().saturating_sub(1) as i32
}
}
pub fn join_wrapped_rows(lines: Vec<String>, wraps: &[bool], top: i32) -> Vec<FindLine> {
let mut out: Vec<FindLine> = Vec::new();
let mut continues = false;
for (i, row) in lines.into_iter().enumerate() {
let len = row.chars().count();
match out.last_mut() {
Some(line) if continues => {
line.text.push_str(&row);
line.row_lens.push(len);
}
_ => out.push(FindLine {
text: row,
start: top + i as i32,
row_lens: vec![len],
}),
}
continues = wraps.get(i).copied().unwrap_or(false);
}
out
}
pub(super) fn ansi_rows(term: &Term<VoidListener>, top: i32) -> Vec<(String, String, bool)> {
let bottom = term.screen_lines() as i32 - 1;
let ncols = term.columns();
let mut lines = Vec::new();
let mut l = top;
while l <= bottom {
let mut cells: Vec<(char, (AnsiColor, AnsiColor, Flags))> = Vec::with_capacity(ncols);
for c in 0..ncols {
let cell = &term.grid()[Point::new(Line(l), Column(c))];
if cell
.flags
.intersects(Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER)
{
continue;
}
let ch = cell_glyph(cell.c);
cells.push((ch, (cell.fg, cell.bg, cell.flags & SGR_FLAGS)));
}
let wraps_on = l < bottom && row_wraps(term, l);
let plain: String = cells.iter().map(|(ch, _)| *ch).collect::<String>();
let plain = if wraps_on {
plain
} else {
plain.trim_end().to_string()
};
while cells
.last()
.is_some_and(|(ch, (fg, bg, flags))| *ch == ' ' && style_is_default(*fg, *bg, *flags))
{
cells.pop();
}
let mut out = String::new();
let mut current: Option<(AnsiColor, AnsiColor, Flags)> = None;
let mut styled = false;
for (ch, key) in cells {
if current != Some(key) {
if styled {
out.push_str("\x1b[0m");
}
let sgr = cell_sgr(key.0, key.1, key.2);
styled = !sgr.is_empty();
out.push_str(&sgr);
current = Some(key);
}
out.push(ch);
}
if styled {
out.push_str("\x1b[0m");
}
lines.push((plain, out, wraps_on));
l += 1;
}
lines
}
pub(crate) fn ansi_rows_from(term: &Term<VoidListener>, top: i32) -> Vec<(String, String, bool)> {
ansi_rows(term, top)
}
pub fn row_wraps(term: &Term<VoidListener>, line_idx: i32) -> bool {
let cols = term.columns();
cols > 0
&& term.grid()[Point::new(Line(line_idx), Column(cols - 1))]
.flags
.contains(Flags::WRAPLINE)
}
pub(super) fn cell_glyph(c: char) -> char {
if c == '\0' || c.is_control() { ' ' } else { c }
}
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(cell_glyph(cell.c));
cols.push(c);
}
(s, cols)
}
pub(super) const SGR_FLAGS: Flags = Flags::BOLD
.union(Flags::DIM)
.union(Flags::ITALIC)
.union(Flags::UNDERLINE)
.union(Flags::DOUBLE_UNDERLINE)
.union(Flags::UNDERCURL)
.union(Flags::DOTTED_UNDERLINE)
.union(Flags::DASHED_UNDERLINE)
.union(Flags::INVERSE)
.union(Flags::HIDDEN)
.union(Flags::STRIKEOUT);
pub(super) fn cell_sgr(fg: AnsiColor, bg: AnsiColor, flags: Flags) -> String {
let mut codes: Vec<String> = Vec::new();
if flags.contains(Flags::BOLD) {
codes.push("1".into());
}
if flags.contains(Flags::DIM) {
codes.push("2".into());
}
if flags.contains(Flags::ITALIC) {
codes.push("3".into());
}
if flags.intersects(
Flags::UNDERLINE
| Flags::DOUBLE_UNDERLINE
| Flags::UNDERCURL
| Flags::DOTTED_UNDERLINE
| Flags::DASHED_UNDERLINE,
) {
codes.push("4".into());
}
if flags.contains(Flags::INVERSE) {
codes.push("7".into());
}
if flags.contains(Flags::HIDDEN) {
codes.push("8".into());
}
if flags.contains(Flags::STRIKEOUT) {
codes.push("9".into());
}
if let Some(code) = color_sgr(fg, false) {
codes.push(code);
}
if let Some(code) = color_sgr(bg, true) {
codes.push(code);
}
if codes.is_empty() {
String::new()
} else {
format!("\x1b[{}m", codes.join(";"))
}
}
pub(super) fn style_is_default(fg: AnsiColor, bg: AnsiColor, flags: Flags) -> bool {
let plain = |c: AnsiColor| matches!(c, AnsiColor::Named(n) if named_slot(n).is_none());
plain(fg)
&& plain(bg)
&& !flags.intersects(
Flags::BOLD
| Flags::DIM
| Flags::ITALIC
| Flags::UNDERLINE
| Flags::DOUBLE_UNDERLINE
| Flags::UNDERCURL
| Flags::DOTTED_UNDERLINE
| Flags::DASHED_UNDERLINE
| Flags::INVERSE
| Flags::HIDDEN
| Flags::STRIKEOUT,
)
}
pub(super) fn color_sgr(c: AnsiColor, background: bool) -> Option<String> {
let base = if background { 40 } else { 30 };
let bright = if background { 100 } else { 90 };
let extended = if background { 48 } else { 38 };
let slot = |i: u8| {
if i < 8 {
(base + i as u16).to_string()
} else {
(bright + (i - 8) as u16).to_string()
}
};
match c {
AnsiColor::Spec(rgb) => Some(format!("{extended};2;{};{};{}", rgb.r, rgb.g, rgb.b)),
AnsiColor::Indexed(i) if i < 16 => Some(slot(i)),
AnsiColor::Indexed(i) => Some(format!("{extended};5;{i}")),
AnsiColor::Named(named) => named_slot(named).map(slot),
}
}
pub(super) fn named_slot(n: NamedColor) -> Option<u8> {
use NamedColor::*;
Some(match n {
Foreground | Background | Cursor | DimForeground | BrightForeground => return None,
Black | DimBlack => 0,
Red | DimRed => 1,
Green | DimGreen => 2,
Yellow | DimYellow => 3,
Blue | DimBlue => 4,
Magenta | DimMagenta => 5,
Cyan | DimCyan => 6,
White | DimWhite => 7,
BrightBlack => 8,
BrightRed => 9,
BrightGreen => 10,
BrightYellow => 11,
BrightBlue => 12,
BrightMagenta => 13,
BrightCyan => 14,
BrightWhite => 15,
})
}