Skip to main content

vtcode_ui/tui/core_tui/session/
mouse_selection.rs

1use ratatui::buffer::Buffer;
2use ratatui::crossterm::{Command, clipboard::CopyToClipboard};
3use ratatui::layout::Rect;
4use std::io::Write;
5#[cfg(test)]
6use std::path::PathBuf;
7#[cfg(test)]
8use std::sync::{Mutex, OnceLock};
9use std::time::{Duration, Instant};
10use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
11
12use crate::tui::config::constants::ui;
13use crate::tui::core_tui::session::inline_list;
14
15/// The modal list's selection cursor.
16///
17/// `┃` is the only glyph VT Code paints as a selection indicator, which makes
18/// it unambiguous chrome: the transcript marks hierarchy with `│`, so a copied
19/// `│` could be content while a copied `┃` never is.
20const LIST_SELECTION_CURSOR: &str = ui::MODAL_LIST_HIGHLIGHT_SYMBOL;
21
22const DOUBLE_CLICK_INTERVAL: Duration = Duration::from_millis(450);
23
24/// Edge direction for auto-scroll while dragging a transcript selection.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub(crate) enum DragAutoScrollDirection {
27    Up,
28    Down,
29}
30
31/// Pending edge auto-scroll for an in-progress transcript drag.
32#[derive(Debug, Clone, Copy)]
33pub(crate) struct DragAutoScroll {
34    pub(crate) direction: DragAutoScrollDirection,
35    /// Pointer position clamped into the transcript area so the selection end
36    /// keeps extending onto newly revealed rows.
37    pub(crate) column: u16,
38    pub(crate) row: u16,
39    pub(crate) last_step: Instant,
40}
41
42#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
43enum SelectionSurface {
44    #[default]
45    Transcript,
46    Overlay,
47}
48
49/// Tracks shared mouse-driven text selection for the transcript and overlays.
50#[derive(Debug, Default)]
51pub struct MouseSelectionState {
52    /// Whether the user is currently dragging to select text.
53    pub(crate) is_selecting: bool,
54    /// Retained after mouse-up, unlike the active drag target.
55    surface: SelectionSurface,
56    /// Screen coordinates where the selection started (column, row).
57    start: (u16, u16),
58    /// Screen coordinates where the selection currently ends (column, row).
59    end: (u16, u16),
60    /// Whether a completed selection exists (ready for highlight rendering).
61    pub(crate) has_selection: bool,
62    /// Whether the current selection has already been copied to clipboard.
63    copied: bool,
64    /// Whether Ctrl+C was pressed to explicitly copy the current selection.
65    copy_requested: bool,
66    /// Tracks the previous mouse click so double-clicks can be detected.
67    last_click: Option<ClickRecord>,
68}
69
70#[derive(Clone, Copy, Debug)]
71struct ClickRecord {
72    column: u16,
73    row: u16,
74    at: Instant,
75}
76
77impl MouseSelectionState {
78    pub(crate) fn new() -> Self {
79        Self::default()
80    }
81
82    /// Begin a new selection at the given screen position.
83    pub(crate) fn start_selection(&mut self, col: u16, row: u16) {
84        self.surface = SelectionSurface::Transcript;
85        self.is_selecting = true;
86        self.has_selection = false;
87        self.copied = false;
88        self.start = (col, row);
89        self.end = (col, row);
90    }
91
92    /// Begin an overlay selection that must not move with transcript geometry.
93    pub(crate) fn start_overlay_selection(&mut self, col: u16, row: u16) {
94        self.start_selection(col, row);
95        self.surface = SelectionSurface::Overlay;
96    }
97
98    pub(crate) fn is_transcript_selection(&self) -> bool {
99        self.surface == SelectionSurface::Transcript
100    }
101
102    /// Set a transcript selection directly, bypassing drag state.
103    pub(crate) fn set_selection(&mut self, start: (u16, u16), end: (u16, u16)) {
104        self.surface = SelectionSurface::Transcript;
105        self.is_selecting = false;
106        self.has_selection = start != end;
107        self.copied = false;
108        self.start = start;
109        self.end = end;
110    }
111
112    /// Update the end position while dragging.
113    pub(crate) fn update_selection(&mut self, col: u16, row: u16) {
114        if self.is_selecting {
115            self.end = (col, row);
116            self.has_selection = true;
117        }
118    }
119
120    /// Finalize the selection on mouse-up.
121    pub(crate) fn finish_selection(&mut self, col: u16, row: u16) {
122        if self.is_selecting {
123            self.end = (col, row);
124            self.is_selecting = false;
125            // Only mark as having a selection if start != end
126            self.has_selection = self.start != self.end;
127        }
128    }
129
130    /// Adjust transcript selection coordinates when the underlying content moves.
131    /// Overlay text retains its screen position during background scrolling.
132    ///
133    /// `row_delta` is positive when content moves down on screen (scroll up / showing
134    /// older content) and negative when content moves up (scroll down / showing newer
135    /// content).  If the adjustment pushes the selection completely off-screen the
136    /// selection is cleared.
137    pub(crate) fn adjust_for_scroll(&mut self, row_delta: i32) {
138        if !self.is_transcript_selection() || (!self.has_selection && !self.is_selecting) {
139            return;
140        }
141        if row_delta == 0 {
142            return;
143        }
144
145        let new_start_row = self.start.1 as i32 + row_delta;
146        let new_end_row = self.end.1 as i32 + row_delta;
147
148        // If both ends are completely off-screen in the same direction, clear.
149        // Clamp to screen bounds (0..=viewport_height, roughly 0..=u16::MAX).
150        // If after clamping both are the same and off-screen, or both are off-screen
151        // in a way that suggests selection is gone, clear.
152
153        let clamped_start = new_start_row.clamp(0, i32::from(u16::MAX));
154        let clamped_end = new_end_row.clamp(0, i32::from(u16::MAX));
155
156        // If the selection is now completely off-screen in a way that means
157        // the original selection range was entirely off-screen, clear.
158        if (new_start_row < 0 && new_end_row < 0)
159            || (new_start_row > i32::from(u16::MAX) && new_end_row > i32::from(u16::MAX))
160        {
161            self.is_selecting = false;
162            self.has_selection = false;
163            self.copied = false;
164            self.copy_requested = false;
165            return;
166        }
167
168        self.start.1 = clamped_start as u16;
169        self.end.1 = clamped_end as u16;
170    }
171
172    /// Clear any active selection.
173    pub(crate) fn clear(&mut self) {
174        self.surface = SelectionSurface::Transcript;
175        self.is_selecting = false;
176        self.has_selection = false;
177        self.copied = false;
178        self.copy_requested = false;
179        self.last_click = None;
180    }
181
182    /// Clears only the mouse click history used for double-click detection.
183    pub(crate) fn clear_click_history(&mut self) {
184        self.last_click = None;
185    }
186
187    /// Records a click and returns `true` when it matches the previous click closely enough
188    /// to be treated as a double click.
189    pub(crate) fn register_click(&mut self, col: u16, row: u16, at: Instant) -> bool {
190        let is_double_click = self.last_click.is_some_and(|last| {
191            last.column == col && last.row == row && at.saturating_duration_since(last.at) <= DOUBLE_CLICK_INTERVAL
192        });
193
194        self.last_click = Some(ClickRecord { column: col, row, at });
195        is_double_click
196    }
197
198    /// Returns the selection range normalized so that `from` is before `to`.
199    fn normalized(&self) -> ((u16, u16), (u16, u16)) {
200        let (s, e) = (self.start, self.end);
201        if s.1 < e.1 || (s.1 == e.1 && s.0 <= e.0) {
202            (s, e)
203        } else {
204            (e, s)
205        }
206    }
207
208    /// Extract selected text from a ratatui `Buffer`.
209    pub(crate) fn extract_text(&self, buf: &Buffer, area: Rect) -> String {
210        if !self.has_selection && !self.is_selecting {
211            return String::new();
212        }
213
214        // Clamp to the actual buffer area to avoid out-of-range buffer indexing panics.
215        let area = area.intersection(buf.area);
216        if area.width == 0 || area.height == 0 {
217            return String::new();
218        }
219
220        let ((start_col, start_row), (end_col, end_row)) = self.normalized();
221
222        // The selection cursor is chrome, not content: the gutter it sits in
223        // marks the focused list row, and a copy that carried the marker
224        // would paste something that means nothing outside the TUI. Only the
225        // overlay surface draws that gutter; a transcript row may hold the
226        // glyph as ordinary content.
227        let strip_gutter = self.surface == SelectionSurface::Overlay;
228
229        // Collect the rows as (screen column, symbol) pairs.
230        let mut rows: Vec<Vec<(u16, &str)>> = Vec::new();
231        let mut cursor_columns: Vec<u16> = Vec::new();
232
233        for row in start_row..=end_row {
234            if row < area.y || row >= area.bottom() {
235                continue;
236            }
237            let line_start = if row == start_row {
238                start_col.max(area.x)
239            } else {
240                area.x
241            };
242            let line_end = if row == end_row {
243                end_col.min(area.right())
244            } else {
245                area.right()
246            };
247
248            let mut cells: Vec<(u16, &str)> = Vec::new();
249            for col in line_start..line_end {
250                if col < area.x || col >= area.right() {
251                    continue;
252                }
253                let symbol = buf[(col, row)].symbol();
254                if symbol.is_empty() {
255                    continue;
256                }
257                if strip_gutter && symbol == LIST_SELECTION_CURSOR && !cursor_columns.contains(&col) {
258                    cursor_columns.push(col);
259                }
260                cells.push((col, symbol));
261            }
262            rows.push(cells);
263        }
264
265        // The list gutter is the marker plus its trailing padding
266        // (`MODAL_LIST_HIGHLIGHT_FULL`). Drop that whole span wherever it
267        // falls inside the selection, so the copy neither carries the marker
268        // nor keeps its orphaned indentation. A cell holding real content
269        // stays: the gutter is only ever blank or the marker itself.
270        let gutter_width = u16::try_from(inline_list::selection_padding_width()).unwrap_or(1);
271        let is_gutter_cell = |col: u16, symbol: &str| {
272            strip_gutter
273                && cursor_columns
274                    .iter()
275                    .any(|start| col >= *start && col < start.saturating_add(gutter_width))
276                && (symbol.trim().is_empty() || symbol == LIST_SELECTION_CURSOR)
277        };
278
279        let mut result = String::new();
280        for (index, cells) in rows.iter().enumerate() {
281            for (col, symbol) in cells {
282                if is_gutter_cell(*col, symbol) {
283                    continue;
284                }
285                result.push_str(symbol);
286            }
287
288            // Add newline between rows (but not after the last)
289            if index < rows.len() - 1 {
290                // Trim trailing whitespace from each line
291                let trimmed = result.trim_end().len();
292                result.truncate(trimmed);
293                result.push('\n');
294            }
295        }
296
297        // Trim trailing whitespace from the final line
298        let trimmed = result.trim_end();
299        trimmed.to_string()
300    }
301
302    /// Apply selection highlight (inverted colors) to the frame buffer.
303    pub(crate) fn apply_highlight(&self, buf: &mut Buffer, area: Rect) {
304        if !self.has_selection && !self.is_selecting {
305            return;
306        }
307
308        // Clamp to the actual buffer area to avoid out-of-range buffer indexing panics.
309        let area = area.intersection(buf.area);
310        if area.width == 0 || area.height == 0 {
311            return;
312        }
313
314        let ((start_col, start_row), (end_col, end_row)) = self.normalized();
315
316        for row in start_row..=end_row {
317            if row < area.y || row >= area.bottom() {
318                continue;
319            }
320            let line_start = if row == start_row {
321                start_col.max(area.x)
322            } else {
323                area.x
324            };
325            let line_end = if row == end_row {
326                end_col.min(area.right())
327            } else {
328                area.right()
329            };
330
331            for col in line_start..line_end {
332                if col < area.x || col >= area.right() {
333                    continue;
334                }
335                let cell = &mut buf[(col, row)];
336                // Swap foreground and background to show selection
337                let fg = cell.fg;
338                let bg = cell.bg;
339                cell.set_fg(bg);
340                cell.set_bg(fg);
341            }
342        }
343    }
344
345    /// Returns `true` if the selection needs to be copied (finalized and not yet copied).
346    pub(crate) fn needs_copy(&self) -> bool {
347        self.has_selection && !self.is_selecting && !self.copied
348    }
349
350    /// Returns `true` if an explicit copy was requested via Ctrl+C.
351    pub(crate) fn has_copy_request(&self) -> bool {
352        self.copy_requested
353    }
354
355    /// Request an explicit copy of the current selection (triggered by Ctrl+C).
356    pub(crate) fn request_copy(&mut self) {
357        if self.has_selection {
358            self.copy_requested = true;
359        }
360    }
361
362    /// Mark the selection as already copied.
363    pub(crate) fn mark_copied(&mut self) {
364        self.copied = true;
365    }
366
367    /// Copy the selected text to the system clipboard.
368    ///
369    /// Tries native OS clipboard utilities first (`pbcopy` on macOS, `xclip`/`xsel`/`wl-copy`
370    /// on Linux, `clip.exe` on Windows/WSL) for maximum compatibility, then falls back to the
371    /// OSC 52 escape sequence. Returns whether any strategy reported success.
372    ///
373    /// OSC 52 delivery is best-effort: terminals never acknowledge the sequence, so a clean
374    /// stderr write counts as success even if the terminal silently drops it (unsupported,
375    /// disabled, or swallowed by a multiplexer). Every strategy attempt emits a
376    /// `tracing::debug!` event; enable `RUST_LOG=vtcode_ui=debug` when diagnosing.
377    pub fn copy_to_clipboard(text: &str) -> bool {
378        if text.is_empty() {
379            trace_clipboard("nothing to copy: empty text");
380            return false;
381        }
382
383        if Self::copy_via_native(text) {
384            return true;
385        }
386
387        let copied = copy_via_osc52(text, inside_tmux());
388        trace_clipboard(&format!(
389            "native candidates exhausted; osc52 fallback result={copied} text_bytes={}",
390            text.len()
391        ));
392        copied
393    }
394
395    /// Attempt to copy text using native OS clipboard utilities.
396    /// Returns `true` if successful.
397    fn copy_via_native(text: &str) -> bool {
398        use std::process::Command;
399
400        #[cfg(test)]
401        if let Some(program) = clipboard_command_override() {
402            return spawn_clipboard_command(Command::new(program), text);
403        }
404
405        let candidates: &[&str] = if cfg!(target_os = "macos") {
406            &["pbcopy"]
407        } else if cfg!(target_os = "linux") {
408            &["xclip", "xsel", "wl-copy"]
409        } else if cfg!(target_os = "windows") {
410            &["clip.exe"]
411        } else {
412            &[]
413        };
414
415        for program in candidates {
416            let mut cmd = Command::new(program);
417            match *program {
418                "xclip" => {
419                    cmd.arg("-selection").arg("clipboard");
420                }
421                "xsel" => {
422                    cmd.arg("--clipboard").arg("--input");
423                }
424                _ => {}
425            }
426            if spawn_clipboard_command(cmd, text) {
427                trace_clipboard(&format!("native '{program}' succeeded ({} bytes)", text.len()));
428                return true;
429            }
430        }
431        trace_clipboard("all native clipboard candidates failed or missing");
432        false
433    }
434}
435
436/// Emits clipboard strategy diagnostics for support/debugging sessions.
437fn trace_clipboard(message: &str) {
438    tracing::debug!(target: "vtcode_ui::clipboard", "{message}");
439}
440
441/// Waits on `child` from a detached thread so no zombie accumulates and the caller never blocks.
442fn reap_in_background(mut child: std::process::Child) {
443    let _ = std::thread::spawn(move || {
444        let _ = child.wait();
445    });
446}
447
448fn spawn_clipboard_command(mut cmd: std::process::Command, text: &str) -> bool {
449    use std::process::Stdio;
450
451    // Helpers such as xclip/wl-copy normally exit right away, but some builds
452    // fork-and-hold while serving the selection, and a helper that never reads
453    // stdin could block a synchronous write_all forever once the pipe buffer
454    // fills (>= 64KB). The input is therefore written on a detached writer
455    // thread and the result is read via try_recv, so the UI thread never blocks
456    // longer than this budget regardless of helper behavior.
457    const WAIT_BUDGET: Duration = Duration::from_millis(300);
458    const POLL_INTERVAL: Duration = Duration::from_millis(10);
459    // After the helper exits, its writer report is usually already delivered;
460    // this grace window only covers the rare in-flight race.
461    const WRITE_REPORT_GRACE: Duration = Duration::from_millis(100);
462
463    let program = cmd.get_program().to_string_lossy().into_owned();
464    let Ok(mut child) = cmd.stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::null()).spawn() else {
465        trace_clipboard(&format!("'{program}' unavailable: spawn failed"));
466        return false;
467    };
468    // The writer is detached and never joined so a blocked write_all cannot
469    // stall the UI thread; only the stdin pipe (plus a copy of the text) moves
470    // into it. `child` stays on this thread for try_wait polling and is handed
471    // to a detached reaper if the budget expires.
472    let mut stdin = child.stdin.take();
473    let text_owned = text.to_owned();
474    let (write_tx, write_rx) = std::sync::mpsc::channel();
475    let _ = std::thread::spawn(move || {
476        let result = match stdin.as_mut() {
477            Some(pipe) => pipe.write_all(text_owned.as_bytes()).err(),
478            None => None,
479        };
480        drop(stdin.take());
481        let _ = write_tx.send(result);
482    });
483    // Tracks the first observed write failure; None until the writer reports or
484    // a status/deadline path makes a decision.
485    let mut write_error = None;
486    let mut write_complete = false;
487    let deadline = Instant::now() + WAIT_BUDGET;
488    loop {
489        if let Ok(report) = write_rx.try_recv() {
490            write_error = report;
491            write_complete = true;
492        }
493        match child.try_wait() {
494            Ok(Some(status)) => {
495                // The helper has exited, so the writer will finish promptly;
496                // give its report a short grace window, otherwise a write
497                // failing concurrently with a clean exit would count as ok.
498                let flush_deadline = Instant::now() + WRITE_REPORT_GRACE;
499                while !write_complete {
500                    match write_rx.try_recv() {
501                        Ok(report) => {
502                            write_error = report;
503                            write_complete = true;
504                        }
505                        Err(std::sync::mpsc::TryRecvError::Empty) => {
506                            if Instant::now() >= flush_deadline {
507                                break;
508                            }
509                            std::thread::sleep(POLL_INTERVAL);
510                        }
511                        Err(std::sync::mpsc::TryRecvError::Disconnected) => break,
512                    }
513                }
514                let ok = status.success() && write_error.is_none();
515                if !ok {
516                    if let Some(err) = write_error {
517                        trace_clipboard(&format!("'{program}' stdin write failed: {err}; status={status}"));
518                    } else {
519                        trace_clipboard(&format!("'{program}' failed: status={status}"));
520                    }
521                }
522                return ok;
523            }
524            Ok(None) => {
525                if Instant::now() >= deadline {
526                    // The writer may still be blocked; do NOT join it (that
527                    // would hang the UI thread). Input was at least accepted
528                    // into the pipe unless a write failure was already reported.
529                    let ok = write_error.is_none();
530                    trace_clipboard(&format!(
531                        "'{program}' still running after {WAIT_BUDGET:?}; input {}",
532                        if ok { "accepted" } else { "failed" }
533                    ));
534                    // Fork-and-hold helpers legitimately outlive the copy call.
535                    reap_in_background(child);
536                    return ok;
537                }
538                std::thread::sleep(POLL_INTERVAL);
539            }
540            Err(err) => {
541                trace_clipboard(&format!("'{program}' wait failed: {err}"));
542                reap_in_background(child);
543                return false;
544            }
545        }
546    }
547}
548
549/// Whether the session runs inside tmux; OSC 52 must then be DCS-wrapped or tmux
550/// consumes it without ever reaching the outer terminal.
551fn inside_tmux() -> bool {
552    std::env::var_os("TMUX").is_some_and(|value| !value.is_empty())
553}
554
555/// Wrap an escape sequence in tmux's DCS passthrough so tmux forwards it verbatim to
556/// the outer terminal. Every ESC inside the payload must be doubled.
557fn wrap_tmux_passthrough(sequence: &str) -> String {
558    format!("\x1bPtmux;\x1b{}\x1b\\", sequence.replace('\x1b', "\x1b\x1b"))
559}
560
561/// Build the OSC 52 payload for `text`, wrapped for tmux when requested.
562fn build_osc52_payload(text: &str, inside_tmux: bool) -> Option<String> {
563    let mut sequence = String::new();
564    CopyToClipboard::to_clipboard_from(text.as_bytes())
565        .write_ansi(&mut sequence)
566        .ok()?;
567    Some(if inside_tmux {
568        wrap_tmux_passthrough(&sequence)
569    } else {
570        sequence
571    })
572}
573
574/// Emit the OSC 52 clipboard sequence on stderr. Delivery cannot be confirmed —
575/// terminals never acknowledge it — so success means "written without IO error".
576fn copy_via_osc52(text: &str, inside_tmux: bool) -> bool {
577    #[cfg(test)]
578    if let Some(forced) = osc52_write_override() {
579        return forced;
580    }
581
582    let Some(payload) = build_osc52_payload(text, inside_tmux) else {
583        return false;
584    };
585
586    let mut stderr = std::io::stderr();
587    let written = stderr.write_all(payload.as_bytes()).is_ok() && stderr.flush().is_ok();
588    trace_clipboard(&format!("osc52 written={written} payload_bytes={} tmux_passthrough={inside_tmux}", payload.len()));
589    written
590}
591
592#[cfg(test)]
593static CLIPBOARD_COMMAND_OVERRIDE: OnceLock<Mutex<Option<PathBuf>>> = OnceLock::new();
594
595#[cfg(test)]
596static OSC52_WRITE_OVERRIDE: OnceLock<Mutex<Option<bool>>> = OnceLock::new();
597
598#[cfg(test)]
599pub(crate) fn set_osc52_write_override(result: Option<bool>) {
600    let lock = OSC52_WRITE_OVERRIDE.get_or_init(|| Mutex::new(None));
601    if let Ok(mut guard) = lock.lock() {
602        *guard = result;
603    }
604}
605
606#[cfg(test)]
607fn osc52_write_override() -> Option<bool> {
608    let lock = OSC52_WRITE_OVERRIDE.get_or_init(|| Mutex::new(None));
609    lock.lock().ok().and_then(|guard| *guard)
610}
611
612#[cfg(test)]
613pub(crate) fn set_clipboard_command_override(path: Option<PathBuf>) {
614    let lock = CLIPBOARD_COMMAND_OVERRIDE.get_or_init(|| Mutex::new(None));
615    if let Ok(mut guard) = lock.lock() {
616        *guard = path;
617    }
618}
619
620#[cfg(test)]
621pub(crate) fn clipboard_command_override() -> Option<PathBuf> {
622    let lock = CLIPBOARD_COMMAND_OVERRIDE.get_or_init(|| Mutex::new(None));
623    match lock.lock() {
624        Ok(guard) => guard.clone(),
625        Err(_) => None,
626    }
627}
628
629/// Return the half-open display-column range for the word under `column`.
630pub(crate) fn word_selection_range(text: &str, column: u16) -> Option<(u16, u16)> {
631    if text.is_empty() {
632        return None;
633    }
634
635    let chars: Vec<char> = text.chars().collect();
636    if chars.is_empty() {
637        return None;
638    }
639
640    let line_width = UnicodeWidthStr::width(text);
641    if usize::from(column) >= line_width {
642        return None;
643    }
644
645    let mut consumed = 0usize;
646    let mut char_index = 0usize;
647    for ch in &chars {
648        let width = UnicodeWidthChar::width(*ch).unwrap_or(0);
649        if consumed.saturating_add(width) > usize::from(column) {
650            break;
651        }
652        consumed = consumed.saturating_add(width);
653        char_index += 1;
654    }
655
656    if char_index >= chars.len() || chars[char_index].is_whitespace() {
657        return None;
658    }
659
660    let mut start = char_index;
661    while start > 0 && !chars[start - 1].is_whitespace() {
662        start -= 1;
663    }
664
665    let mut end = char_index + 1;
666    while end < chars.len() && !chars[end].is_whitespace() {
667        end += 1;
668    }
669
670    Some((display_width_for_char_count(&chars, start), display_width_for_char_count(&chars, end)))
671}
672
673fn display_width_for_char_count(chars: &[char], char_count: usize) -> u16 {
674    chars
675        .iter()
676        .take(char_count)
677        .map(|ch| UnicodeWidthChar::width(*ch).unwrap_or(0) as u16)
678        .fold(0_u16, u16::saturating_add)
679}
680
681#[cfg(test)]
682mod tests {
683    use super::*;
684    use ratatui::style::Color;
685    use std::time::{Duration, Instant};
686
687    #[test]
688    fn extract_text_clamps_area_to_buffer_bounds() {
689        let mut buf = Buffer::empty(Rect::new(0, 0, 2, 2));
690        buf[(0, 0)].set_symbol("A");
691        buf[(1, 0)].set_symbol("B");
692        buf[(0, 1)].set_symbol("C");
693        buf[(1, 1)].set_symbol("D");
694
695        let mut selection = MouseSelectionState::new();
696        selection.start_selection(0, 0);
697        selection.finish_selection(5, 5);
698
699        let text = selection.extract_text(&buf, Rect::new(0, 0, 10, 10));
700        assert_eq!(text, "AB\nCD");
701    }
702
703    /// Build a buffer whose rows are the given strings, left-aligned.
704    fn buffer_with_rows(rows: &[&str], width: u16) -> Buffer {
705        let height = u16::try_from(rows.len()).expect("row count fits in u16");
706        let mut buf = Buffer::empty(Rect::new(0, 0, width, height));
707        for (row_index, row) in rows.iter().enumerate() {
708            for (col, ch) in row.chars().enumerate() {
709                let col = u16::try_from(col).expect("column fits in u16");
710                if col >= width {
711                    break;
712                }
713                buf[(col, u16::try_from(row_index).expect("row fits in u16"))].set_symbol(&ch.to_string());
714            }
715        }
716        buf
717    }
718
719    #[test]
720    fn overlay_copy_drops_the_list_selection_cursor() {
721        // A modal list renders a two-cell gutter: the cursor on the focused
722        // row, blanks on the others.
723        let buf = buffer_with_rows(&["┃ Option one", "  Option two"], 20);
724
725        let mut selection = MouseSelectionState::new();
726        selection.start_overlay_selection(0, 0);
727        selection.finish_selection(14, 1);
728
729        let text = selection.extract_text(&buf, buf.area);
730        assert_eq!(text, "Option one\nOption two", "the gutter is chrome, the item text is content");
731    }
732
733    #[test]
734    fn overlay_copy_drops_the_gutter_when_the_selection_starts_inside_it() {
735        // Dragging from the marker itself must not leave the padding behind.
736        let buf = buffer_with_rows(&["┃ Option one"], 20);
737
738        let mut selection = MouseSelectionState::new();
739        selection.start_overlay_selection(0, 0);
740        selection.finish_selection(13, 0);
741
742        let text = selection.extract_text(&buf, buf.area);
743        assert_eq!(text, "Option one");
744    }
745
746    #[test]
747    fn transcript_copy_keeps_semantic_gutters() {
748        // The transcript marks hierarchy with `│`, and that marker is content:
749        // a copy must keep it.
750        let buf = buffer_with_rows(&["  │ nested output"], 20);
751
752        let mut selection = MouseSelectionState::new();
753        selection.start_selection(0, 0);
754        selection.finish_selection(17, 0);
755
756        let text = selection.extract_text(&buf, buf.area);
757        assert_eq!(text, "  │ nested output");
758    }
759
760    #[test]
761    fn transcript_copy_keeps_a_selection_cursor_that_is_part_of_the_content() {
762        // A transcript row may legitimately contain the cursor glyph; the
763        // transcript surface never treats it as chrome.
764        let buf = buffer_with_rows(&["┃ literal text"], 20);
765
766        let mut selection = MouseSelectionState::new();
767        selection.start_selection(0, 0);
768        selection.finish_selection(14, 0);
769
770        let text = selection.extract_text(&buf, buf.area);
771        assert_eq!(text, "┃ literal text");
772    }
773
774    #[test]
775    fn apply_highlight_clamps_area_to_buffer_bounds() {
776        let mut buf = Buffer::empty(Rect::new(0, 0, 1, 1));
777        buf[(0, 0)].set_fg(Color::Red);
778        buf[(0, 0)].set_bg(Color::Blue);
779
780        let mut selection = MouseSelectionState::new();
781        selection.start_selection(0, 0);
782        selection.finish_selection(5, 5);
783
784        selection.apply_highlight(&mut buf, Rect::new(0, 0, 10, 10));
785
786        assert_eq!(buf[(0, 0)].fg, Color::Blue);
787        assert_eq!(buf[(0, 0)].bg, Color::Red);
788    }
789
790    #[test]
791    fn word_selection_range_selects_clicked_word() {
792        assert_eq!(word_selection_range("hello world", 1), Some((0, 5)));
793        assert_eq!(word_selection_range("hello world", 7), Some((6, 11)));
794    }
795
796    #[test]
797    fn word_selection_range_returns_none_for_whitespace() {
798        assert_eq!(word_selection_range("hello world", 5), None);
799    }
800
801    #[test]
802    fn adjust_for_scroll_shifts_rows() {
803        let mut sel = MouseSelectionState::new();
804        sel.set_selection((2, 5), (10, 8));
805
806        sel.adjust_for_scroll(3);
807        assert_eq!(sel.start, (2, 8));
808        assert_eq!(sel.end, (10, 11));
809        assert!(sel.has_selection);
810    }
811
812    #[test]
813    fn adjust_for_scroll_negative() {
814        let mut sel = MouseSelectionState::new();
815        sel.set_selection((0, 10), (5, 15));
816
817        sel.adjust_for_scroll(-4);
818        assert_eq!(sel.start, (0, 6));
819        assert_eq!(sel.end, (5, 11));
820    }
821
822    #[test]
823    fn adjust_for_scroll_clears_when_offscreen() {
824        let mut sel = MouseSelectionState::new();
825        sel.set_selection((0, 2), (5, 4));
826
827        sel.adjust_for_scroll(-10);
828        assert!(!sel.has_selection);
829        assert!(!sel.is_selecting);
830    }
831
832    #[test]
833    fn adjust_for_scroll_noop_without_selection() {
834        let mut sel = MouseSelectionState::new();
835        sel.adjust_for_scroll(5);
836        assert!(!sel.has_selection);
837    }
838
839    #[test]
840    fn register_click_detects_double_clicks_at_same_position() {
841        let mut selection = MouseSelectionState::new();
842        let now = Instant::now();
843
844        assert!(!selection.register_click(3, 7, now));
845        assert!(selection.register_click(3, 7, now + Duration::from_millis(250)));
846        assert!(!selection.register_click(4, 7, now + Duration::from_millis(250)));
847    }
848
849    #[test]
850    fn spawn_clipboard_command_requires_success_exit_status() {
851        let failing = {
852            let mut cmd = std::process::Command::new("sh");
853            cmd.arg("-c").arg("exit 1");
854            cmd
855        };
856        assert!(!spawn_clipboard_command(failing, "hello"));
857
858        let succeeding = {
859            let mut cmd = std::process::Command::new("sh");
860            cmd.arg("-c").arg("cat > /dev/null");
861            cmd
862        };
863        assert!(spawn_clipboard_command(succeeding, "hello"));
864    }
865
866    #[test]
867    fn spawn_clipboard_command_treats_hanging_helper_as_success() {
868        // A helper that holds stdin open and never exits must not block the
869        // UI thread forever: the bounded wait accepts the already-written
870        // input and returns without hanging.
871        let hanging = {
872            let mut cmd = std::process::Command::new("sh");
873            cmd.arg("-c").arg("cat > /dev/null & sleep 10");
874            cmd
875        };
876        let start = Instant::now();
877        assert!(spawn_clipboard_command(hanging, "hello"));
878        assert!(
879            start.elapsed() < Duration::from_secs(2),
880            "bounded wait must return promptly, took {:?}",
881            start.elapsed()
882        );
883    }
884
885    #[test]
886    fn spawn_clipboard_command_large_write_to_non_reading_helper_returns_promptly() {
887        // A helper that never reads stdin would block a synchronous write_all
888        // forever once the 64KB pipe buffer fills. The detached writer must not
889        // stall the caller: the bounded poll returns without joining it.
890        let non_reading = {
891            let mut cmd = std::process::Command::new("sh");
892            cmd.arg("-c").arg("sleep 10");
893            cmd
894        };
895        let big: String = "x".repeat(128 * 1024);
896        let start = Instant::now();
897        let result = spawn_clipboard_command(non_reading, &big);
898        assert!(start.elapsed() < Duration::from_secs(2), "must not block on the writer, took {:?}", start.elapsed());
899        // No write failure was observed within the budget, so the input is
900        // treated as accepted even though the helper never reads.
901        assert!(result);
902    }
903
904    #[test]
905    fn build_osc52_payload_emits_base64_clipboard_sequence() {
906        let payload = build_osc52_payload("hi", false).expect("osc52 payload");
907        assert!(payload.starts_with("\x1b]52;c;"), "unexpected payload: {payload:?}");
908        assert!(payload.ends_with("\x1b\\"));
909        assert!(payload.contains("aGk="));
910    }
911
912    #[test]
913    fn build_osc52_payload_wraps_in_tmux_passthrough() {
914        let plain = build_osc52_payload("hi", false).expect("plain payload");
915        let wrapped = build_osc52_payload("hi", true).expect("wrapped payload");
916
917        // DCS introducer + doubled-ESC payload + ST terminator.
918        assert_eq!(wrapped, format!("\x1bPtmux;\x1b{}\x1b\\", plain.replace('\x1b', "\x1b\x1b")));
919        assert!(wrapped.starts_with("\x1bPtmux;\x1b\x1b\x1b]52;c;"));
920        assert!(wrapped.ends_with("\x1b\x1b\\\x1b\\"));
921    }
922
923    #[test]
924    fn wrap_tmux_passthrough_doubles_every_escape() {
925        assert_eq!(wrap_tmux_passthrough("\x1ba\x1bb"), "\x1bPtmux;\x1b\x1b\x1ba\x1b\x1bb\x1b\\");
926    }
927}