diff --git a/Cargo.lock b/Cargo.lock index 7013cc9..a2177c1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1057,6 +1057,7 @@ name = "hx-tui" version = "0.1.0" dependencies = [ "async-trait", + "base64 0.23.1", "crossterm", "futures", "hx-ai", diff --git a/crates/hx-core/src/command.rs b/crates/hx-core/src/command.rs index b8b1d68..0be66cf 100644 --- a/crates/hx-core/src/command.rs +++ b/crates/hx-core/src/command.rs @@ -66,6 +66,7 @@ pub fn builtins(models: &[&str]) -> Vec { b("clear", "alias of /new", None), b("sessions", "browse, resume, delete sessions", None), b("lsp", "language server status", None), + b("copy", "copy the last answer to the clipboard", None), b("usage", "subscription limits, resets, credits", None), b( "keys", @@ -312,7 +313,7 @@ mod tests { assert_eq!(c("/").items.len(), MAX_ITEMS); assert_eq!(labels(&c("/mo")), ["/model"]); - assert_eq!(labels(&c("/co")), ["/compact"]); + assert_eq!(labels(&c("/co")), ["/copy", "/compact"]); let r = c("/rev"); assert_eq!(labels(&r), ["/review"]); assert_eq!(r.items[0].detail, "skill · code review"); diff --git a/crates/hx-tui/Cargo.toml b/crates/hx-tui/Cargo.toml index 3f84606..9a3fffb 100644 --- a/crates/hx-tui/Cargo.toml +++ b/crates/hx-tui/Cargo.toml @@ -6,6 +6,7 @@ license.workspace = true [dependencies] async-trait = "0.1.92" +base64 = "0.23.1" crossterm = { version = "0.29.0", features = ["event-stream"] } futures = "0.3.34" hx-ai = { version = "0.1.0", path = "../hx-ai" } diff --git a/crates/hx-tui/src/lib.rs b/crates/hx-tui/src/lib.rs index 681b1c3..9351924 100644 --- a/crates/hx-tui/src/lib.rs +++ b/crates/hx-tui/src/lib.rs @@ -8,6 +8,7 @@ pub mod picker; pub mod popup; pub mod review; pub mod scroll; +pub mod select; pub mod sessions; pub mod stats_view; pub mod status; @@ -15,7 +16,7 @@ pub mod theme; pub mod transcript; use crossterm::event::{ - Event as TEvent, EventStream, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, + Event as TEvent, EventStream, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, }; use editor::{Action, Editor}; use futures::StreamExt; @@ -25,11 +26,12 @@ use hx_core::agent::{AbortHandle, Agent}; use hx_core::command::{self as cmd, CmdSpec, Completion, Source}; use hx_core::hook::{Event, Hook, HookAction}; use hx_core::switch::Switcher; +use ratatui::buffer::Buffer; use ratatui::layout::{Constraint, Layout, Rect}; use ratatui::style::Modifier; use ratatui::text::Line; use ratatui::text::Span; -use ratatui::widgets::{Block, Borders, Clear, Paragraph, Wrap}; +use ratatui::widgets::{Block, Borders, Clear, Paragraph, Widget, Wrap}; use std::collections::VecDeque; use std::sync::Arc; use std::time::Instant; @@ -51,7 +53,7 @@ pub struct Setup { pub specs: Vec, /// Open the session picker at startup (`hx -r`). pub open_sessions: bool, - /// Capture the mouse (wheel scrolling); terminal text selection then needs shift-drag. + /// Capture the mouse (wheel scrolling, drag-select + copy in the chat via OSC 52). pub mouse: bool, /// No permission prompts (`--yolo`). pub yolo: bool, @@ -123,6 +125,11 @@ struct App { panel_scroll: scroll::Scroll, /// where the chat / side panel / agent detail were last drawn (mouse wheel targets) areas: Areas, + /// chat text selection (content coordinates) and whether the button is still down + sel: Option, + drag: bool, + /// last left press for double/triple click: (when, content pos, count) + click: Option<(Instant, (u16, u16), u8)>, expanded: bool, busy: bool, queue: VecDeque, @@ -296,6 +303,9 @@ pub async fn run(setup: Setup) -> std::io::Result<()> { scroll: Default::default(), panel_scroll: Default::default(), areas: Default::default(), + sel: None, + drag: false, + click: None, expanded: false, busy: false, queue: VecDeque::new(), @@ -445,6 +455,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> { } TEvent::Mouse(m) => on_mouse(&mut app, m), TEvent::Paste(s) => app.ed.insert(&s), + TEvent::Resize(..) => app.sel = None, _ => {} } } @@ -710,12 +721,120 @@ fn inside(r: Rect, x: u16, y: u16) -> bool { /// Mouse wheel scrolls the region under the pointer: agent detail, side panel, or chat. fn on_mouse(app: &mut App, m: crossterm::event::MouseEvent) { - use crossterm::event::MouseEventKind::{ScrollDown, ScrollUp}; - let up = match m.kind { - ScrollUp => true, - ScrollDown => false, - _ => return, - }; + use crossterm::event::MouseEventKind::{Down, Drag, ScrollDown, ScrollUp, Up}; + match m.kind { + ScrollUp => wheel(app, m, true), + ScrollDown => wheel(app, m, false), + Down(MouseButton::Left) | Drag(MouseButton::Left) | Up(MouseButton::Left) => { + select_mouse(app, m) + } + _ => {} + } +} + +/// The chat text as drawn, full height (for extracting a selection). +fn chat_buf(app: &App) -> Buffer { + let w = app.areas.chat.width; + let para = Paragraph::new(app.t.lines(app.expanded, w)).wrap(Wrap { trim: false }); + let r = Rect::new(0, 0, w, para.line_count(w) as u16); + let mut b = Buffer::empty(r); + Widget::render(para, r, &mut b); + b +} + +/// Put `t` on the clipboard (OSC 52) and say so in the footer. +fn copy(app: &mut App, t: &str) { + let t = select::clamp(t); + if t.is_empty() { + return; + } + if !cfg!(test) { + use std::io::Write; + let mut o = std::io::stdout(); + let _ = o.write_all(select::osc52(t).as_bytes()); + let _ = o.flush(); + } + app.hint = format!("copied {} chars", t.chars().count()); +} + +/// Left button in the chat: drag selects, release copies; double click = word, triple = line. +fn select_mouse(app: &mut App, m: crossterm::event::MouseEvent) { + use crossterm::event::MouseEventKind::{Down, Drag}; + if app.agents.is_some() + || app.picker.is_some() + || app.sessions.is_some() + || app.choose.is_some() + || app.review.is_some() + || app.perm.is_some() + { + return; + } + let c = app.areas.chat; + if c.width == 0 || c.height == 0 { + return; + } + if matches!(m.kind, Down(_)) { + app.sel = None; + app.drag = false; + if !inside(c, m.column, m.row) { + return; + } + } else if !app.drag { + return; + } else if matches!(m.kind, Drag(_)) { + // dragging past the top/bottom edge scrolls + if m.row <= c.y { + app.scroll.up(1); + } else if m.row + 1 >= c.y + c.height { + app.scroll.down(1); + } + } + let x = m.column.clamp(c.x, c.x + c.width - 1) - c.x; + let y = m.row.clamp(c.y, c.y + c.height - 1) - c.y; + let p = (app.scroll.top().saturating_add(y), x); + match m.kind { + Down(_) => { + let now = Instant::now(); + let n = match app.click { + Some((t, q, n)) if q == p && now.duration_since(t).as_millis() < 400 => n % 3 + 1, + _ => 1, + }; + app.click = Some((now, p, n)); + if n == 1 { + app.sel = Some(select::Sel { anchor: p, head: p }); + app.drag = true; + } else { + let b = chat_buf(app); + let s = if n == 2 { + select::word(&b, p.0, p.1) + } else { + select::line(&b, p.0) + }; + let t = select::text(&b, &s); + app.sel = Some(s); + copy(app, &t); + } + } + Drag(_) => { + if let Some(s) = &mut app.sel { + s.head = p; + } + } + _ => { + app.drag = false; + match app.sel { + Some(s) if s.anchor != p => { + let t = select::text(&chat_buf(app), &s); + copy(app, &t); + } + _ => app.sel = None, + } + } + } +} + +/// Mouse wheel scrolls the region under the pointer: agent detail, side panel, or chat. +fn wheel(app: &mut App, m: crossterm::event::MouseEvent, up: bool) { let s = if let Some(agents::View::Detail { scroll, .. }) = &mut app.agents { scroll } else if app.picker.is_some() || app.sessions.is_some() || app.choose.is_some() { @@ -771,6 +890,8 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option { let alt = k.modifiers.contains(KeyModifiers::ALT); let shift = k.modifiers.contains(KeyModifiers::SHIFT); app.hint.clear(); + app.sel = None; + app.drag = false; if app.probe { if k.code == KeyCode::Esc { app.probe = false; @@ -1027,6 +1148,16 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) { None => app.t.push(Item::Info("no edits to review".into())), } } + "copy" => { + let last = app.t.items.iter().rev().find_map(|i| match i { + Item::Assistant(t) => Some(t.clone()), + _ => None, + }); + match last { + Some(t) => copy(app, &t), + None => app.hint = "nothing to copy".into(), + } + } "usage" => { let r = status::report(&app.st, status::now_secs()); show(app, "usage", r); @@ -1264,6 +1395,9 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) { let total = para.line_count(main.width) as u16; let top = app.scroll.resolve(total, main.height); f.render_widget(para.scroll((top, 0)), main); + if let Some(s) = &app.sel { + select::paint(f.buffer_mut(), main, top, s); + } if !sub_rows.is_empty() { let w = subs_area.width.min(56); @@ -1755,6 +1889,34 @@ mod tests { assert_eq!((app.ed.cur, app.scroll.behind()), (0, 0)); } + #[test] + fn mouse_drag_selects_and_click_clears() { + use crossterm::event::{MouseEvent, MouseEventKind::*}; + let ev = |kind, column, row| MouseEvent { + kind, + column, + row, + modifiers: KeyModifiers::NONE, + }; + let mut app = test_app(); + long_chat(&mut app, 30); + draw_at(&mut app, 80, 20); + let c = app.areas.chat; + let l = MouseButton::Left; + on_mouse(&mut app, ev(Down(l), c.x + 1, c.y)); + on_mouse(&mut app, ev(Drag(l), c.x + 5, c.y + 2)); + assert!(app.drag && app.sel.is_some()); + on_mouse(&mut app, ev(Up(l), c.x + 5, c.y + 2)); + assert!(!app.drag && app.sel.is_some() && app.hint.starts_with("copied")); + // a plain click (no drag) clears; a key press clears too + on_mouse(&mut app, ev(Down(l), c.x + 9, c.y + 4)); + on_mouse(&mut app, ev(Up(l), c.x + 9, c.y + 4)); + assert!(app.sel.is_none()); + // presses outside the chat start nothing + on_mouse(&mut app, ev(Down(l), 5, 19)); + assert!(!app.drag); + } + #[test] fn mouse_wheel_goes_to_region_under_pointer() { use crossterm::event::{MouseEvent, MouseEventKind}; @@ -1814,6 +1976,9 @@ mod tests { scroll: Default::default(), panel_scroll: Default::default(), areas: Default::default(), + sel: None, + drag: false, + click: None, expanded: false, busy: false, queue: VecDeque::new(), @@ -1894,7 +2059,7 @@ mod tests { }; assert_eq!( labels(&app), - Some((vec!["/clear".into(), "/compact".into()], 0)) + Some((vec!["/copy".into(), "/clear".into(), "/compact".into()], 0)) ); let mut term = ratatui::Terminal::new(TestBackend::new(40, 10)).unwrap(); term.draw(|f| draw(f, &mut app)).unwrap(); @@ -1903,10 +2068,10 @@ mod tests { .map(|y| (0..40).map(|x| buf[(x, y)].symbol().to_string()).collect()) .collect(); assert_eq!( - rows[3], " │ /clear alias of /new │ ", + rows[3], "│ /clear alias of /new │", "{rows:#?}" ); - assert!(rows[4].starts_with(" │ /compact summarize"), "{rows:#?}"); + assert!(rows[4].starts_with("│ /compact summarize"), "{rows:#?}"); assert!(rows[9].ends_with("Claude · m1"), "{rows:#?}"); // footer at 100 cols, and a hint replacing only the right side @@ -1944,7 +2109,7 @@ mod tests { key(&mut app, KeyCode::Down); key(&mut app, KeyCode::Up); key(&mut app, KeyCode::Up); - assert_eq!(labels(&app).unwrap().1, 1, "wraps"); + assert_eq!(labels(&app).unwrap().1, 2, "wraps"); assert_eq!( key(&mut app, KeyCode::Enter), None, diff --git a/crates/hx-tui/src/scroll.rs b/crates/hx-tui/src/scroll.rs index a1ef465..4e219bc 100644 --- a/crates/hx-tui/src/scroll.rs +++ b/crates/hx-tui/src/scroll.rs @@ -37,6 +37,10 @@ impl Scroll { self.top = None; } } + /// First visible line as of the last draw. + pub fn top(&self) -> u16 { + self.cur() + } pub fn half_page(&self) -> u16 { (self.height / 2).max(1) } diff --git a/crates/hx-tui/src/select.rs b/crates/hx-tui/src/select.rs new file mode 100644 index 0000000..440beb2 --- /dev/null +++ b/crates/hx-tui/src/select.rs @@ -0,0 +1,204 @@ +//! 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. +pub fn text(buf: &Buffer, s: &Sel) -> 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 rows = vec![]; + 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 + } + rows.push(line.trim_end().to_string()); + } + rows.join("\n") +} + +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 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))); + } +}