Files
hx/crates/hx-tui/src/select.rs
T

230 lines
6.6 KiB
Rust

//! Mouse text selection in the chat view. Coordinates are `(row, col)` in the wrapped content
//! (not the screen), so scrolling doesn't move a selection. Text comes from an off-screen render.
use base64::Engine;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::{Modifier, Style};
use ratatui::text::Span;
/// OSC 52 payloads above this many bytes are cut (some terminals drop bigger ones).
pub const MAX_COPY: usize = 100_000;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Sel {
pub anchor: (u16, u16),
pub head: (u16, u16),
}
impl Sel {
fn span(&self) -> ((u16, u16), (u16, u16)) {
if self.anchor <= self.head {
(self.anchor, self.head)
} else {
(self.head, self.anchor)
}
}
/// Inclusive column range selected on `row`.
fn cols(&self, row: u16, width: u16) -> Option<(u16, u16)> {
let (a, b) = self.span();
if row < a.0 || row > b.0 {
return None;
}
let lo = if row == a.0 { a.1 } else { 0 };
let hi = if row == b.0 {
b.1
} else {
width.saturating_sub(1)
};
Some((lo, hi))
}
}
/// Reverse-video the selected cells of the visible rows (`top` = first content row shown).
pub fn paint(buf: &mut Buffer, area: Rect, top: u16, s: &Sel) {
for y in 0..area.height {
let Some((lo, hi)) = s.cols(top.saturating_add(y), area.width) else {
continue;
};
let hi = hi.min(area.width.saturating_sub(1));
if lo <= hi {
let r = Rect::new(area.x + lo, area.y + y, hi - lo + 1, 1);
buf.set_style(r, Style::new().add_modifier(Modifier::REVERSED));
}
}
}
/// Selected text from a buffer rendered at origin (0, 0); trailing blanks per row are dropped.
/// `cont[row]` = row is a soft-wrap continuation: joined to the previous row, not newline-split.
pub fn text(buf: &Buffer, s: &Sel, cont: &[bool]) -> String {
let (w, h) = (buf.area.width, buf.area.height);
if w == 0 || h == 0 {
return String::new();
}
let (a, b) = s.span();
let mut out = String::new();
let mut prev_full = false;
for row in a.0..=b.0.min(h - 1) {
let Some((lo, hi)) = s.cols(row, w) else {
continue;
};
let (mut line, mut x) = (String::new(), lo);
while x <= hi.min(w - 1) {
let sym = buf[(x, row)].symbol();
line.push_str(sym);
x += Span::raw(sym).width().max(1) as u16; // skip the trailing cell of wide chars
}
let line = line.trim_end();
let full = Span::raw(line).width() as u16 >= w; // word broken mid-token
if row > a.0 {
if cont.get(row as usize) == Some(&true) {
// ponytail: wrap at a space leaves no trace; assume one unless the row was full
if !prev_full {
out.push(' ');
}
} else {
out.push('\n');
}
}
out.push_str(line);
prev_full = full;
}
out
}
fn is_word(sym: &str) -> bool {
sym.chars()
.any(|c| c.is_alphanumeric() || "_-./~".contains(c))
}
/// Double click: the word under `(row, col)`, or just that cell when it isn't on a word.
pub fn word(buf: &Buffer, row: u16, col: u16) -> Sel {
let one = Sel {
anchor: (row, col),
head: (row, col),
};
let w = buf.area.width;
if row >= buf.area.height || col >= w || !is_word(buf[(col, row)].symbol()) {
return one;
}
let ok = |x: u16| is_word(buf[(x, row)].symbol());
let (mut lo, mut hi) = (col, col);
while lo > 0 && ok(lo - 1) {
lo -= 1;
}
while hi + 1 < w && ok(hi + 1) {
hi += 1;
}
Sel {
anchor: (row, lo),
head: (row, hi),
}
}
/// Triple click: the whole row.
pub fn line(buf: &Buffer, row: u16) -> Sel {
let hi = buf.area.width.saturating_sub(1);
Sel {
anchor: (row, 0),
head: (row, hi),
}
}
/// Cut `t` to `MAX_COPY` bytes on a char boundary.
pub fn clamp(t: &str) -> &str {
let mut n = MAX_COPY.min(t.len());
while !t.is_char_boundary(n) {
n -= 1;
}
&t[..n]
}
/// The OSC 52 sequence that puts `t` on the system clipboard.
pub fn osc52(t: &str) -> String {
format!(
"\x1b]52;c;{}\x07",
base64::engine::general_purpose::STANDARD.encode(t)
)
}
#[cfg(test)]
mod tests {
use super::*;
use ratatui::widgets::{Paragraph, Widget};
fn buf(s: &str, w: u16) -> Buffer {
let r = Rect::new(0, 0, w, s.lines().count() as u16);
let mut b = Buffer::empty(r);
Paragraph::new(s).render(r, &mut b);
b
}
#[test]
fn text_spans_rows_either_direction_and_skips_wide_tails() {
let b = buf("hello world\nsecond 日本 x\nthird", 20);
let fwd = Sel {
anchor: (0, 6),
head: (1, 5),
};
assert_eq!(text(&b, &fwd, &[]), "world\nsecond");
let rev = Sel {
anchor: (1, 5),
head: (0, 6),
};
assert_eq!(text(&b, &rev, &[]), "world\nsecond");
let wide = Sel {
anchor: (1, 7),
head: (1, 10),
};
assert_eq!(text(&b, &wide, &[]), "日本");
let past = Sel {
anchor: (2, 0),
head: (9, 3),
};
assert_eq!(text(&b, &past, &[]), "third");
}
#[test]
fn soft_wrap_rows_join_without_newline() {
let b = buf("hello\nworld\nnext", 10);
let s = Sel {
anchor: (0, 0),
head: (2, 9),
};
assert_eq!(text(&b, &s, &[false, true, false]), "hello world\nnext");
}
#[test]
fn word_and_line_pick() {
let b = buf("see src/main.rs now", 30);
assert_eq!(text(&b, &word(&b, 0, 6), &[]), "src/main.rs");
assert_eq!(
word(&b, 0, 3),
Sel {
anchor: (0, 3),
head: (0, 3)
}
);
assert_eq!(text(&b, &line(&b, 0), &[]), "see src/main.rs now");
}
#[test]
fn paint_reverses_only_selected_cells() {
let mut b = buf("abcdef\nghijkl", 10);
let s = Sel {
anchor: (0, 4),
head: (1, 1),
};
paint(&mut b, Rect::new(0, 0, 10, 2), 0, &s);
let rev = |x, y| b[(x, y)].modifier.contains(Modifier::REVERSED);
assert!(!rev(3, 0) && rev(4, 0) && rev(9, 0) && rev(0, 1) && rev(1, 1) && !rev(2, 1));
}
#[test]
fn osc52_and_clamp() {
assert_eq!(osc52("hi"), "\x1b]52;c;aGk=\x07");
let big = "é".repeat(MAX_COPY);
assert!(clamp(&big).len() <= MAX_COPY && big.starts_with(clamp(&big)));
}
}