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
15const LIST_SELECTION_CURSOR: &str = ui::MODAL_LIST_HIGHLIGHT_SYMBOL;
21
22const DOUBLE_CLICK_INTERVAL: Duration = Duration::from_millis(450);
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub(crate) enum DragAutoScrollDirection {
27 Up,
28 Down,
29}
30
31#[derive(Debug, Clone, Copy)]
33pub(crate) struct DragAutoScroll {
34 pub(crate) direction: DragAutoScrollDirection,
35 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#[derive(Debug, Default)]
51pub struct MouseSelectionState {
52 pub(crate) is_selecting: bool,
54 surface: SelectionSurface,
56 start: (u16, u16),
58 end: (u16, u16),
60 pub(crate) has_selection: bool,
62 copied: bool,
64 copy_requested: bool,
66 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 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 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 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 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 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 self.has_selection = self.start != self.end;
127 }
128 }
129
130 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 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 (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 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 pub(crate) fn clear_click_history(&mut self) {
184 self.last_click = None;
185 }
186
187 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 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 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 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 let strip_gutter = self.surface == SelectionSurface::Overlay;
228
229 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 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 if index < rows.len() - 1 {
290 let trimmed = result.trim_end().len();
292 result.truncate(trimmed);
293 result.push('\n');
294 }
295 }
296
297 let trimmed = result.trim_end();
299 trimmed.to_string()
300 }
301
302 pub(crate) fn apply_highlight(&self, buf: &mut Buffer, area: Rect) {
304 if !self.has_selection && !self.is_selecting {
305 return;
306 }
307
308 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 let fg = cell.fg;
338 let bg = cell.bg;
339 cell.set_fg(bg);
340 cell.set_bg(fg);
341 }
342 }
343 }
344
345 pub(crate) fn needs_copy(&self) -> bool {
347 self.has_selection && !self.is_selecting && !self.copied
348 }
349
350 pub(crate) fn has_copy_request(&self) -> bool {
352 self.copy_requested
353 }
354
355 pub(crate) fn request_copy(&mut self) {
357 if self.has_selection {
358 self.copy_requested = true;
359 }
360 }
361
362 pub(crate) fn mark_copied(&mut self) {
364 self.copied = true;
365 }
366
367 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 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
436fn trace_clipboard(message: &str) {
438 tracing::debug!(target: "vtcode_ui::clipboard", "{message}");
439}
440
441fn 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 const WAIT_BUDGET: Duration = Duration::from_millis(300);
458 const POLL_INTERVAL: Duration = Duration::from_millis(10);
459 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 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 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 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 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 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
549fn inside_tmux() -> bool {
552 std::env::var_os("TMUX").is_some_and(|value| !value.is_empty())
553}
554
555fn wrap_tmux_passthrough(sequence: &str) -> String {
558 format!("\x1bPtmux;\x1b{}\x1b\\", sequence.replace('\x1b', "\x1b\x1b"))
559}
560
561fn 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
574fn 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
629pub(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 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 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 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 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 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 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 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 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 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}