Skip to main content

slt/
terminal.rs

1use std::collections::HashMap;
2use std::io::{self, Read, Stdout, Write};
3use std::time::{Duration, Instant};
4
5use crossterm::event::{
6    DisableBracketedPaste, DisableFocusChange, DisableMouseCapture, EnableBracketedPaste,
7    EnableFocusChange, EnableMouseCapture,
8};
9use crossterm::style::{
10    Attribute, Color as CtColor, Print, ResetColor, SetAttribute, SetBackgroundColor,
11    SetForegroundColor,
12};
13use crossterm::terminal::{BeginSynchronizedUpdate, EndSynchronizedUpdate};
14use crossterm::{cursor, execute, queue, terminal};
15
16use unicode_width::UnicodeWidthStr;
17
18use crate::buffer::{Buffer, KittyPlacement};
19use crate::rect::Rect;
20use crate::style::{Color, ColorDepth, Modifiers, Style};
21
22// ---------------------------------------------------------------------------
23// Kitty graphics protocol image manager
24// ---------------------------------------------------------------------------
25
26/// Manages Kitty graphics protocol image IDs, uploads, and placements.
27///
28/// Images are deduplicated by content hash — identical RGBA data is uploaded
29/// only once. Each frame, placements are diffed against the previous frame
30/// to minimize terminal I/O.
31pub(crate) struct KittyImageManager {
32    next_id: u32,
33    /// content_hash → kitty image ID for uploaded images.
34    uploaded: HashMap<u64, u32>,
35    /// Previous frame's placements (for diff).
36    prev_placements: Vec<KittyPlacement>,
37}
38
39impl KittyImageManager {
40    pub fn new() -> Self {
41        Self {
42            next_id: 1,
43            uploaded: HashMap::new(),
44            prev_placements: Vec::new(),
45        }
46    }
47
48    /// Flush Kitty image placements: upload new images, manage placements.
49    pub fn flush(&mut self, stdout: &mut impl Write, current: &[KittyPlacement]) -> io::Result<()> {
50        // Fast path: nothing changed
51        if current == self.prev_placements.as_slice() {
52            return Ok(());
53        }
54
55        // Delete all previous placements (keep uploaded image data for reuse)
56        if !self.prev_placements.is_empty() {
57            // Delete all visible placements by ID
58            let mut deleted_ids = std::collections::HashSet::new();
59            for p in &self.prev_placements {
60                if let Some(&img_id) = self.uploaded.get(&p.content_hash) {
61                    if deleted_ids.insert(img_id) {
62                        // Delete all placements of this image (but keep image data)
63                        queue!(
64                            stdout,
65                            Print(format!("\x1b_Ga=d,d=i,i={},q=2\x1b\\", img_id))
66                        )?;
67                    }
68                }
69            }
70        }
71
72        // Upload new images and create placements
73        for (idx, p) in current.iter().enumerate() {
74            let img_id = if let Some(&existing_id) = self.uploaded.get(&p.content_hash) {
75                existing_id
76            } else {
77                // Upload new image with zlib compression if available
78                let id = self.next_id;
79                self.next_id += 1;
80                self.upload_image(stdout, id, p)?;
81                self.uploaded.insert(p.content_hash, id);
82                id
83            };
84
85            // Place the image
86            let pid = idx as u32 + 1;
87            self.place_image(stdout, img_id, pid, p)?;
88        }
89
90        // Clean up images no longer used by any placement
91        let used_hashes: std::collections::HashSet<u64> =
92            current.iter().map(|p| p.content_hash).collect();
93        let stale: Vec<u64> = self
94            .uploaded
95            .keys()
96            .filter(|h| !used_hashes.contains(h))
97            .copied()
98            .collect();
99        for hash in stale {
100            if let Some(id) = self.uploaded.remove(&hash) {
101                // Delete image data from terminal memory
102                queue!(stdout, Print(format!("\x1b_Ga=d,d=I,i={},q=2\x1b\\", id)))?;
103            }
104        }
105
106        self.prev_placements = current.to_vec();
107        Ok(())
108    }
109
110    /// Upload image data to the terminal with `a=t` (transmit only, no display).
111    fn upload_image(&self, stdout: &mut impl Write, id: u32, p: &KittyPlacement) -> io::Result<()> {
112        let (payload, compression) = compress_rgba(&p.rgba);
113        let encoded = base64_encode(&payload);
114        let chunks = split_base64(&encoded, 4096);
115
116        for (i, chunk) in chunks.iter().enumerate() {
117            let more = if i < chunks.len() - 1 { 1 } else { 0 };
118            if i == 0 {
119                queue!(
120                    stdout,
121                    Print(format!(
122                        "\x1b_Ga=t,i={},f=32,{}s={},v={},q=2,m={};{}\x1b\\",
123                        id, compression, p.src_width, p.src_height, more, chunk
124                    ))
125                )?;
126            } else {
127                queue!(stdout, Print(format!("\x1b_Gm={};{}\x1b\\", more, chunk)))?;
128            }
129        }
130        Ok(())
131    }
132
133    /// Place an already-uploaded image at a screen position with optional crop.
134    fn place_image(
135        &self,
136        stdout: &mut impl Write,
137        img_id: u32,
138        placement_id: u32,
139        p: &KittyPlacement,
140    ) -> io::Result<()> {
141        queue!(stdout, cursor::MoveTo(p.x as u16, p.y as u16))?;
142
143        let mut cmd = format!(
144            "\x1b_Ga=p,i={},p={},c={},r={},C=1,q=2",
145            img_id, placement_id, p.cols, p.rows
146        );
147
148        // Add crop parameters for scroll clipping
149        if p.crop_y > 0 || p.crop_h > 0 {
150            cmd.push_str(&format!(",y={}", p.crop_y));
151            if p.crop_h > 0 {
152                cmd.push_str(&format!(",h={}", p.crop_h));
153            }
154        }
155
156        cmd.push_str("\x1b\\");
157        queue!(stdout, Print(cmd))?;
158        Ok(())
159    }
160
161    /// Delete all images from the terminal (used on drop/cleanup).
162    pub fn delete_all(&self, stdout: &mut impl Write) -> io::Result<()> {
163        queue!(stdout, Print("\x1b_Ga=d,d=A,q=2\x1b\\"))
164    }
165}
166
167/// Compress RGBA data with zlib if available, returning (payload, format_string).
168fn compress_rgba(data: &[u8]) -> (Vec<u8>, &'static str) {
169    #[cfg(feature = "kitty-compress")]
170    {
171        use flate2::write::ZlibEncoder;
172        use flate2::Compression;
173        let mut encoder = ZlibEncoder::new(Vec::new(), Compression::fast());
174        if encoder.write_all(data).is_ok() {
175            if let Ok(compressed) = encoder.finish() {
176                // Only use compression if it actually saves space
177                if compressed.len() < data.len() {
178                    return (compressed, "o=z,");
179                }
180            }
181        }
182    }
183    (data.to_vec(), "")
184}
185
186/// Query the terminal for the actual cell pixel dimensions via CSI 16 t.
187///
188/// Returns `(cell_width, cell_height)` in pixels. Falls back to `(8, 16)` if
189/// detection fails. Used by `kitty_image_fit` for accurate aspect ratio.
190///
191/// Cached after first successful detection.
192pub fn cell_pixel_size() -> (u32, u32) {
193    use std::sync::OnceLock;
194    static CACHED: OnceLock<(u32, u32)> = OnceLock::new();
195    *CACHED.get_or_init(|| detect_cell_pixel_size().unwrap_or((8, 16)))
196}
197
198fn detect_cell_pixel_size() -> Option<(u32, u32)> {
199    // CSI 16 t → reports cell size as CSI 6 ; height ; width t
200    let mut stdout = io::stdout();
201    write!(stdout, "\x1b[16t").ok()?;
202    stdout.flush().ok()?;
203
204    let response = read_osc_response(Duration::from_millis(100))?;
205
206    // Parse: ESC [ 6 ; <height> ; <width> t
207    let body = response.strip_prefix("\x1b[6;").or_else(|| {
208        // CSI can also start with 0x9B (single-byte CSI)
209        let bytes = response.as_bytes();
210        if bytes.len() > 3 && bytes[0] == 0x9b && bytes[1] == b'6' && bytes[2] == b';' {
211            Some(&response[3..])
212        } else {
213            None
214        }
215    })?;
216    let body = body
217        .strip_suffix('t')
218        .or_else(|| body.strip_suffix("t\x1b"))?;
219    let mut parts = body.split(';');
220    let ch: u32 = parts.next()?.parse().ok()?;
221    let cw: u32 = parts.next()?.parse().ok()?;
222    if cw > 0 && ch > 0 {
223        Some((cw, ch))
224    } else {
225        None
226    }
227}
228
229fn split_base64(encoded: &str, chunk_size: usize) -> Vec<&str> {
230    let mut chunks = Vec::new();
231    let bytes = encoded.as_bytes();
232    let mut offset = 0;
233    while offset < bytes.len() {
234        let end = (offset + chunk_size).min(bytes.len());
235        chunks.push(&encoded[offset..end]);
236        offset = end;
237    }
238    if chunks.is_empty() {
239        chunks.push("");
240    }
241    chunks
242}
243
244pub(crate) struct Terminal {
245    stdout: Stdout,
246    current: Buffer,
247    previous: Buffer,
248    mouse_enabled: bool,
249    cursor_visible: bool,
250    kitty_keyboard: bool,
251    color_depth: ColorDepth,
252    pub(crate) theme_bg: Option<Color>,
253    kitty_mgr: KittyImageManager,
254}
255
256pub(crate) struct InlineTerminal {
257    stdout: Stdout,
258    current: Buffer,
259    previous: Buffer,
260    mouse_enabled: bool,
261    cursor_visible: bool,
262    height: u32,
263    start_row: u16,
264    reserved: bool,
265    color_depth: ColorDepth,
266    pub(crate) theme_bg: Option<Color>,
267    kitty_mgr: KittyImageManager,
268}
269
270impl Terminal {
271    pub fn new(mouse: bool, kitty_keyboard: bool, color_depth: ColorDepth) -> io::Result<Self> {
272        let (cols, rows) = terminal::size()?;
273        let area = Rect::new(0, 0, cols as u32, rows as u32);
274
275        let mut stdout = io::stdout();
276        terminal::enable_raw_mode()?;
277        execute!(
278            stdout,
279            terminal::EnterAlternateScreen,
280            cursor::Hide,
281            EnableBracketedPaste
282        )?;
283        if mouse {
284            execute!(stdout, EnableMouseCapture, EnableFocusChange)?;
285        }
286        if kitty_keyboard {
287            use crossterm::event::{KeyboardEnhancementFlags, PushKeyboardEnhancementFlags};
288            let _ = execute!(
289                stdout,
290                PushKeyboardEnhancementFlags(
291                    KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES
292                        | KeyboardEnhancementFlags::REPORT_EVENT_TYPES
293                )
294            );
295        }
296
297        Ok(Self {
298            stdout,
299            current: Buffer::empty(area),
300            previous: Buffer::empty(area),
301            mouse_enabled: mouse,
302            cursor_visible: false,
303            kitty_keyboard,
304            color_depth,
305            theme_bg: None,
306            kitty_mgr: KittyImageManager::new(),
307        })
308    }
309
310    pub fn size(&self) -> (u32, u32) {
311        (self.current.area.width, self.current.area.height)
312    }
313
314    pub fn buffer_mut(&mut self) -> &mut Buffer {
315        &mut self.current
316    }
317
318    pub fn flush(&mut self) -> io::Result<()> {
319        if self.current.area.width < self.previous.area.width {
320            execute!(self.stdout, terminal::Clear(terminal::ClearType::All))?;
321        }
322
323        queue!(self.stdout, BeginSynchronizedUpdate)?;
324
325        let mut last_style = Style::new();
326        let mut first_style = true;
327        let mut last_pos: Option<(u32, u32)> = None;
328        let mut active_link: Option<&str> = None;
329        let mut has_updates = false;
330
331        for y in self.current.area.y..self.current.area.bottom() {
332            for x in self.current.area.x..self.current.area.right() {
333                let cur = self.current.get(x, y);
334                let prev = self.previous.get(x, y);
335                if cur == prev {
336                    continue;
337                }
338                if cur.symbol.is_empty() {
339                    continue;
340                }
341                has_updates = true;
342
343                let need_move = last_pos.map_or(true, |(lx, ly)| ly != y || lx != x);
344                if need_move {
345                    queue!(self.stdout, cursor::MoveTo(x as u16, y as u16))?;
346                }
347
348                if cur.style != last_style {
349                    if first_style {
350                        queue!(self.stdout, ResetColor, SetAttribute(Attribute::Reset))?;
351                        apply_style(&mut self.stdout, &cur.style, self.color_depth)?;
352                        first_style = false;
353                    } else {
354                        apply_style_delta(
355                            &mut self.stdout,
356                            &last_style,
357                            &cur.style,
358                            self.color_depth,
359                        )?;
360                    }
361                    last_style = cur.style;
362                }
363
364                let cell_link = cur.hyperlink.as_deref();
365                if cell_link != active_link {
366                    if let Some(url) = cell_link {
367                        queue!(self.stdout, Print(format!("\x1b]8;;{url}\x07")))?;
368                    } else {
369                        queue!(self.stdout, Print("\x1b]8;;\x07"))?;
370                    }
371                    active_link = cell_link;
372                }
373
374                queue!(self.stdout, Print(&*cur.symbol))?;
375                let char_width = UnicodeWidthStr::width(cur.symbol.as_str()).max(1) as u32;
376                if char_width > 1 && cur.symbol.chars().any(|c| c == '\u{FE0F}') {
377                    queue!(self.stdout, Print(" "))?;
378                }
379                last_pos = Some((x + char_width, y));
380            }
381        }
382
383        if has_updates {
384            if active_link.is_some() {
385                queue!(self.stdout, Print("\x1b]8;;\x07"))?;
386            }
387            queue!(self.stdout, ResetColor, SetAttribute(Attribute::Reset))?;
388        }
389
390        // Kitty graphics: structured image management with IDs and compression
391        self.kitty_mgr
392            .flush(&mut self.stdout, &self.current.kitty_placements)?;
393
394        // Raw sequences (sixel, other passthrough) — simple diff
395        if self.current.raw_sequences != self.previous.raw_sequences {
396            for (x, y, seq) in &self.current.raw_sequences {
397                queue!(self.stdout, cursor::MoveTo(*x as u16, *y as u16))?;
398                queue!(self.stdout, Print(seq))?;
399            }
400        }
401
402        queue!(self.stdout, EndSynchronizedUpdate)?;
403
404        let cursor_pos = self.current.cursor_pos();
405        match cursor_pos {
406            Some((cx, cy)) => {
407                if !self.cursor_visible {
408                    queue!(self.stdout, cursor::Show)?;
409                    self.cursor_visible = true;
410                }
411                queue!(self.stdout, cursor::MoveTo(cx as u16, cy as u16))?;
412            }
413            None => {
414                if self.cursor_visible {
415                    queue!(self.stdout, cursor::Hide)?;
416                    self.cursor_visible = false;
417                }
418            }
419        }
420
421        self.stdout.flush()?;
422
423        std::mem::swap(&mut self.current, &mut self.previous);
424        if let Some(bg) = self.theme_bg {
425            self.current.reset_with_bg(bg);
426        } else {
427            self.current.reset();
428        }
429        Ok(())
430    }
431
432    pub fn handle_resize(&mut self) -> io::Result<()> {
433        let (cols, rows) = terminal::size()?;
434        let area = Rect::new(0, 0, cols as u32, rows as u32);
435        self.current.resize(area);
436        self.previous.resize(area);
437        execute!(
438            self.stdout,
439            terminal::Clear(terminal::ClearType::All),
440            cursor::MoveTo(0, 0)
441        )?;
442        Ok(())
443    }
444}
445
446impl crate::Backend for Terminal {
447    fn size(&self) -> (u32, u32) {
448        Terminal::size(self)
449    }
450
451    fn buffer_mut(&mut self) -> &mut Buffer {
452        Terminal::buffer_mut(self)
453    }
454
455    fn flush(&mut self) -> io::Result<()> {
456        Terminal::flush(self)
457    }
458}
459
460impl InlineTerminal {
461    pub fn new(height: u32, mouse: bool, color_depth: ColorDepth) -> io::Result<Self> {
462        let (cols, _) = terminal::size()?;
463        let area = Rect::new(0, 0, cols as u32, height);
464
465        let mut stdout = io::stdout();
466        terminal::enable_raw_mode()?;
467        execute!(stdout, cursor::Hide, EnableBracketedPaste)?;
468        if mouse {
469            execute!(stdout, EnableMouseCapture, EnableFocusChange)?;
470        }
471
472        let (_, cursor_row) = cursor::position()?;
473        Ok(Self {
474            stdout,
475            current: Buffer::empty(area),
476            previous: Buffer::empty(area),
477            mouse_enabled: mouse,
478            cursor_visible: false,
479            height,
480            start_row: cursor_row,
481            reserved: false,
482            color_depth,
483            theme_bg: None,
484            kitty_mgr: KittyImageManager::new(),
485        })
486    }
487
488    pub fn size(&self) -> (u32, u32) {
489        (self.current.area.width, self.current.area.height)
490    }
491
492    pub fn buffer_mut(&mut self) -> &mut Buffer {
493        &mut self.current
494    }
495
496    pub fn flush(&mut self) -> io::Result<()> {
497        if self.current.area.width < self.previous.area.width {
498            execute!(self.stdout, terminal::Clear(terminal::ClearType::All))?;
499        }
500
501        queue!(self.stdout, BeginSynchronizedUpdate)?;
502
503        if !self.reserved {
504            queue!(self.stdout, cursor::MoveToColumn(0))?;
505            for _ in 0..self.height {
506                queue!(self.stdout, Print("\n"))?;
507            }
508            self.reserved = true;
509
510            let (_, rows) = terminal::size()?;
511            let bottom = self.start_row + self.height as u16;
512            if bottom > rows {
513                self.start_row = rows.saturating_sub(self.height as u16);
514            }
515        }
516
517        let mut last_style = Style::new();
518        let mut first_style = true;
519        let mut last_pos: Option<(u32, u32)> = None;
520        let mut active_link: Option<&str> = None;
521        let mut has_updates = false;
522
523        for y in self.current.area.y..self.current.area.bottom() {
524            for x in self.current.area.x..self.current.area.right() {
525                let cell = self.current.get(x, y);
526                let prev = self.previous.get(x, y);
527                if cell == prev || cell.symbol.is_empty() {
528                    continue;
529                }
530                has_updates = true;
531
532                let abs_y = self.start_row as u32 + y;
533                let need_move = last_pos.map_or(true, |(lx, ly)| ly != abs_y || lx != x);
534                if need_move {
535                    queue!(self.stdout, cursor::MoveTo(x as u16, abs_y as u16))?;
536                }
537
538                if cell.style != last_style {
539                    if first_style {
540                        queue!(self.stdout, ResetColor, SetAttribute(Attribute::Reset))?;
541                        apply_style(&mut self.stdout, &cell.style, self.color_depth)?;
542                        first_style = false;
543                    } else {
544                        apply_style_delta(
545                            &mut self.stdout,
546                            &last_style,
547                            &cell.style,
548                            self.color_depth,
549                        )?;
550                    }
551                    last_style = cell.style;
552                }
553
554                let cell_link = cell.hyperlink.as_deref();
555                if cell_link != active_link {
556                    if let Some(url) = cell_link {
557                        queue!(self.stdout, Print(format!("\x1b]8;;{url}\x07")))?;
558                    } else {
559                        queue!(self.stdout, Print("\x1b]8;;\x07"))?;
560                    }
561                    active_link = cell_link;
562                }
563
564                queue!(self.stdout, Print(&cell.symbol))?;
565                let char_width = UnicodeWidthStr::width(cell.symbol.as_str()).max(1) as u32;
566                if char_width > 1 && cell.symbol.chars().any(|c| c == '\u{FE0F}') {
567                    queue!(self.stdout, Print(" "))?;
568                }
569                last_pos = Some((x + char_width, abs_y));
570            }
571        }
572
573        if has_updates {
574            if active_link.is_some() {
575                queue!(self.stdout, Print("\x1b]8;;\x07"))?;
576            }
577            queue!(self.stdout, ResetColor, SetAttribute(Attribute::Reset))?;
578        }
579
580        // Kitty graphics: structured image management with IDs and compression
581        // Adjust Y positions for inline terminal offset
582        let adjusted: Vec<KittyPlacement> = self
583            .current
584            .kitty_placements
585            .iter()
586            .map(|p| {
587                let mut ap = p.clone();
588                ap.y += self.start_row as u32;
589                ap
590            })
591            .collect();
592        self.kitty_mgr.flush(&mut self.stdout, &adjusted)?;
593
594        // Raw sequences (sixel, other passthrough) — simple diff
595        if self.current.raw_sequences != self.previous.raw_sequences {
596            for (x, y, seq) in &self.current.raw_sequences {
597                let abs_y = self.start_row as u32 + *y;
598                queue!(self.stdout, cursor::MoveTo(*x as u16, abs_y as u16))?;
599                queue!(self.stdout, Print(seq))?;
600            }
601        }
602
603        queue!(self.stdout, EndSynchronizedUpdate)?;
604
605        let cursor_pos = self.current.cursor_pos();
606        match cursor_pos {
607            Some((cx, cy)) => {
608                let abs_cy = self.start_row as u32 + cy;
609                if !self.cursor_visible {
610                    queue!(self.stdout, cursor::Show)?;
611                    self.cursor_visible = true;
612                }
613                queue!(self.stdout, cursor::MoveTo(cx as u16, abs_cy as u16))?;
614            }
615            None => {
616                if self.cursor_visible {
617                    queue!(self.stdout, cursor::Hide)?;
618                    self.cursor_visible = false;
619                }
620                let end_row = self.start_row + self.height.saturating_sub(1) as u16;
621                queue!(self.stdout, cursor::MoveTo(0, end_row))?;
622            }
623        }
624
625        self.stdout.flush()?;
626
627        std::mem::swap(&mut self.current, &mut self.previous);
628        reset_current_buffer(&mut self.current, self.theme_bg);
629        Ok(())
630    }
631
632    pub fn handle_resize(&mut self) -> io::Result<()> {
633        let (cols, _) = terminal::size()?;
634        let area = Rect::new(0, 0, cols as u32, self.height);
635        self.current.resize(area);
636        self.previous.resize(area);
637        execute!(
638            self.stdout,
639            terminal::Clear(terminal::ClearType::All),
640            cursor::MoveTo(0, 0)
641        )?;
642        Ok(())
643    }
644}
645
646impl crate::Backend for InlineTerminal {
647    fn size(&self) -> (u32, u32) {
648        InlineTerminal::size(self)
649    }
650
651    fn buffer_mut(&mut self) -> &mut Buffer {
652        InlineTerminal::buffer_mut(self)
653    }
654
655    fn flush(&mut self) -> io::Result<()> {
656        InlineTerminal::flush(self)
657    }
658}
659
660impl Drop for Terminal {
661    fn drop(&mut self) {
662        // Clean up Kitty images before leaving alternate screen
663        let _ = self.kitty_mgr.delete_all(&mut self.stdout);
664        let _ = self.stdout.flush();
665        if self.kitty_keyboard {
666            use crossterm::event::PopKeyboardEnhancementFlags;
667            let _ = execute!(self.stdout, PopKeyboardEnhancementFlags);
668        }
669        if self.mouse_enabled {
670            let _ = execute!(self.stdout, DisableMouseCapture, DisableFocusChange);
671        }
672        let _ = execute!(
673            self.stdout,
674            ResetColor,
675            SetAttribute(Attribute::Reset),
676            cursor::Show,
677            DisableBracketedPaste,
678            terminal::LeaveAlternateScreen
679        );
680        let _ = terminal::disable_raw_mode();
681    }
682}
683
684impl Drop for InlineTerminal {
685    fn drop(&mut self) {
686        if self.mouse_enabled {
687            let _ = execute!(self.stdout, DisableMouseCapture, DisableFocusChange);
688        }
689        let _ = execute!(
690            self.stdout,
691            ResetColor,
692            SetAttribute(Attribute::Reset),
693            cursor::Show,
694            DisableBracketedPaste
695        );
696        if self.reserved {
697            let _ = execute!(
698                self.stdout,
699                cursor::MoveToColumn(0),
700                cursor::MoveDown(1),
701                cursor::MoveToColumn(0),
702                Print("\n")
703            );
704        } else {
705            let _ = execute!(self.stdout, Print("\n"));
706        }
707        let _ = terminal::disable_raw_mode();
708    }
709}
710
711mod selection;
712pub(crate) use selection::{apply_selection_overlay, extract_selection_text, SelectionState};
713#[cfg(test)]
714pub(crate) use selection::{find_innermost_rect, normalize_selection};
715
716/// Detected terminal color scheme from OSC 11.
717#[non_exhaustive]
718#[cfg(feature = "crossterm")]
719#[derive(Debug, Clone, Copy, PartialEq, Eq)]
720pub enum ColorScheme {
721    /// Dark background detected.
722    Dark,
723    /// Light background detected.
724    Light,
725    /// Could not determine the scheme.
726    Unknown,
727}
728
729#[cfg(feature = "crossterm")]
730fn read_osc_response(timeout: Duration) -> Option<String> {
731    let deadline = Instant::now() + timeout;
732    let mut stdin = io::stdin();
733    let mut bytes = Vec::new();
734    let mut buf = [0u8; 1];
735
736    while Instant::now() < deadline {
737        if !crossterm::event::poll(Duration::from_millis(10)).ok()? {
738            continue;
739        }
740
741        let read = stdin.read(&mut buf).ok()?;
742        if read == 0 {
743            continue;
744        }
745
746        bytes.push(buf[0]);
747
748        if buf[0] == b'\x07' {
749            break;
750        }
751        let len = bytes.len();
752        if len >= 2 && bytes[len - 2] == 0x1B && bytes[len - 1] == b'\\' {
753            break;
754        }
755
756        if bytes.len() >= 4096 {
757            break;
758        }
759    }
760
761    if bytes.is_empty() {
762        return None;
763    }
764
765    String::from_utf8(bytes).ok()
766}
767
768/// Query the terminal's background color via OSC 11 and return the detected scheme.
769#[cfg(feature = "crossterm")]
770pub fn detect_color_scheme() -> ColorScheme {
771    let mut stdout = io::stdout();
772    if write!(stdout, "\x1b]11;?\x07").is_err() {
773        return ColorScheme::Unknown;
774    }
775    if stdout.flush().is_err() {
776        return ColorScheme::Unknown;
777    }
778
779    let Some(response) = read_osc_response(Duration::from_millis(100)) else {
780        return ColorScheme::Unknown;
781    };
782
783    parse_osc11_response(&response)
784}
785
786#[cfg(feature = "crossterm")]
787pub(crate) fn parse_osc11_response(response: &str) -> ColorScheme {
788    let Some(rgb_pos) = response.find("rgb:") else {
789        return ColorScheme::Unknown;
790    };
791
792    let payload = &response[rgb_pos + 4..];
793    let end = payload
794        .find(['\x07', '\x1b', '\r', '\n', ' ', '\t'])
795        .unwrap_or(payload.len());
796    let rgb = &payload[..end];
797
798    let mut channels = rgb.split('/');
799    let (Some(r), Some(g), Some(b), None) = (
800        channels.next(),
801        channels.next(),
802        channels.next(),
803        channels.next(),
804    ) else {
805        return ColorScheme::Unknown;
806    };
807
808    fn parse_channel(channel: &str) -> Option<f64> {
809        if channel.is_empty() || channel.len() > 4 {
810            return None;
811        }
812        let value = u16::from_str_radix(channel, 16).ok()? as f64;
813        let max = ((1u32 << (channel.len() * 4)) - 1) as f64;
814        if max <= 0.0 {
815            return None;
816        }
817        Some((value / max).clamp(0.0, 1.0))
818    }
819
820    let (Some(r), Some(g), Some(b)) = (parse_channel(r), parse_channel(g), parse_channel(b)) else {
821        return ColorScheme::Unknown;
822    };
823
824    let luminance = 0.299 * r + 0.587 * g + 0.114 * b;
825    if luminance < 0.5 {
826        ColorScheme::Dark
827    } else {
828        ColorScheme::Light
829    }
830}
831
832fn base64_encode(input: &[u8]) -> String {
833    const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
834    let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
835    for chunk in input.chunks(3) {
836        let b0 = chunk[0] as u32;
837        let b1 = chunk.get(1).copied().unwrap_or(0) as u32;
838        let b2 = chunk.get(2).copied().unwrap_or(0) as u32;
839        let triple = (b0 << 16) | (b1 << 8) | b2;
840        out.push(CHARS[((triple >> 18) & 0x3F) as usize] as char);
841        out.push(CHARS[((triple >> 12) & 0x3F) as usize] as char);
842        out.push(if chunk.len() > 1 {
843            CHARS[((triple >> 6) & 0x3F) as usize] as char
844        } else {
845            '='
846        });
847        out.push(if chunk.len() > 2 {
848            CHARS[(triple & 0x3F) as usize] as char
849        } else {
850            '='
851        });
852    }
853    out
854}
855
856pub(crate) fn copy_to_clipboard(w: &mut impl Write, text: &str) -> io::Result<()> {
857    let encoded = base64_encode(text.as_bytes());
858    write!(w, "\x1b]52;c;{encoded}\x1b\\")?;
859    w.flush()
860}
861
862#[cfg(feature = "crossterm")]
863fn parse_osc52_response(response: &str) -> Option<String> {
864    let osc_pos = response.find("]52;")?;
865    let body = &response[osc_pos + 4..];
866    let semicolon = body.find(';')?;
867    let payload = &body[semicolon + 1..];
868
869    let end = payload
870        .find("\x1b\\")
871        .or_else(|| payload.find('\x07'))
872        .unwrap_or(payload.len());
873    let encoded = payload[..end].trim();
874    if encoded.is_empty() || encoded == "?" {
875        return None;
876    }
877
878    base64_decode(encoded)
879}
880
881/// Read clipboard contents via OSC 52 terminal query.
882#[cfg(feature = "crossterm")]
883pub fn read_clipboard() -> Option<String> {
884    let mut stdout = io::stdout();
885    write!(stdout, "\x1b]52;c;?\x07").ok()?;
886    stdout.flush().ok()?;
887
888    let response = read_osc_response(Duration::from_millis(200))?;
889    parse_osc52_response(&response)
890}
891
892#[cfg(feature = "crossterm")]
893fn base64_decode(input: &str) -> Option<String> {
894    let mut filtered: Vec<u8> = input
895        .bytes()
896        .filter(|b| !matches!(b, b' ' | b'\n' | b'\r' | b'\t'))
897        .collect();
898
899    match filtered.len() % 4 {
900        0 => {}
901        2 => filtered.extend_from_slice(b"=="),
902        3 => filtered.push(b'='),
903        _ => return None,
904    }
905
906    fn decode_val(b: u8) -> Option<u8> {
907        match b {
908            b'A'..=b'Z' => Some(b - b'A'),
909            b'a'..=b'z' => Some(b - b'a' + 26),
910            b'0'..=b'9' => Some(b - b'0' + 52),
911            b'+' => Some(62),
912            b'/' => Some(63),
913            _ => None,
914        }
915    }
916
917    let mut out = Vec::with_capacity((filtered.len() / 4) * 3);
918    for chunk in filtered.chunks_exact(4) {
919        let p2 = chunk[2] == b'=';
920        let p3 = chunk[3] == b'=';
921        if p2 && !p3 {
922            return None;
923        }
924
925        let v0 = decode_val(chunk[0])? as u32;
926        let v1 = decode_val(chunk[1])? as u32;
927        let v2 = if p2 { 0 } else { decode_val(chunk[2])? as u32 };
928        let v3 = if p3 { 0 } else { decode_val(chunk[3])? as u32 };
929
930        let triple = (v0 << 18) | (v1 << 12) | (v2 << 6) | v3;
931        out.push(((triple >> 16) & 0xFF) as u8);
932        if !p2 {
933            out.push(((triple >> 8) & 0xFF) as u8);
934        }
935        if !p3 {
936            out.push((triple & 0xFF) as u8);
937        }
938    }
939
940    String::from_utf8(out).ok()
941}
942
943fn apply_style_delta(
944    w: &mut impl Write,
945    old: &Style,
946    new: &Style,
947    depth: ColorDepth,
948) -> io::Result<()> {
949    if old.fg != new.fg {
950        match new.fg {
951            Some(fg) => queue!(w, SetForegroundColor(to_crossterm_color(fg, depth)))?,
952            None => queue!(w, SetForegroundColor(CtColor::Reset))?,
953        }
954    }
955    if old.bg != new.bg {
956        match new.bg {
957            Some(bg) => queue!(w, SetBackgroundColor(to_crossterm_color(bg, depth)))?,
958            None => queue!(w, SetBackgroundColor(CtColor::Reset))?,
959        }
960    }
961    let removed = Modifiers(old.modifiers.0 & !new.modifiers.0);
962    let added = Modifiers(new.modifiers.0 & !old.modifiers.0);
963    if removed.contains(Modifiers::BOLD) || removed.contains(Modifiers::DIM) {
964        queue!(w, SetAttribute(Attribute::NormalIntensity))?;
965        if new.modifiers.contains(Modifiers::BOLD) {
966            queue!(w, SetAttribute(Attribute::Bold))?;
967        }
968        if new.modifiers.contains(Modifiers::DIM) {
969            queue!(w, SetAttribute(Attribute::Dim))?;
970        }
971    } else {
972        if added.contains(Modifiers::BOLD) {
973            queue!(w, SetAttribute(Attribute::Bold))?;
974        }
975        if added.contains(Modifiers::DIM) {
976            queue!(w, SetAttribute(Attribute::Dim))?;
977        }
978    }
979    if removed.contains(Modifiers::ITALIC) {
980        queue!(w, SetAttribute(Attribute::NoItalic))?;
981    }
982    if added.contains(Modifiers::ITALIC) {
983        queue!(w, SetAttribute(Attribute::Italic))?;
984    }
985    if removed.contains(Modifiers::UNDERLINE) {
986        queue!(w, SetAttribute(Attribute::NoUnderline))?;
987    }
988    if added.contains(Modifiers::UNDERLINE) {
989        queue!(w, SetAttribute(Attribute::Underlined))?;
990    }
991    if removed.contains(Modifiers::REVERSED) {
992        queue!(w, SetAttribute(Attribute::NoReverse))?;
993    }
994    if added.contains(Modifiers::REVERSED) {
995        queue!(w, SetAttribute(Attribute::Reverse))?;
996    }
997    if removed.contains(Modifiers::STRIKETHROUGH) {
998        queue!(w, SetAttribute(Attribute::NotCrossedOut))?;
999    }
1000    if added.contains(Modifiers::STRIKETHROUGH) {
1001        queue!(w, SetAttribute(Attribute::CrossedOut))?;
1002    }
1003    Ok(())
1004}
1005
1006fn apply_style(w: &mut impl Write, style: &Style, depth: ColorDepth) -> io::Result<()> {
1007    if let Some(fg) = style.fg {
1008        queue!(w, SetForegroundColor(to_crossterm_color(fg, depth)))?;
1009    }
1010    if let Some(bg) = style.bg {
1011        queue!(w, SetBackgroundColor(to_crossterm_color(bg, depth)))?;
1012    }
1013    let m = style.modifiers;
1014    if m.contains(Modifiers::BOLD) {
1015        queue!(w, SetAttribute(Attribute::Bold))?;
1016    }
1017    if m.contains(Modifiers::DIM) {
1018        queue!(w, SetAttribute(Attribute::Dim))?;
1019    }
1020    if m.contains(Modifiers::ITALIC) {
1021        queue!(w, SetAttribute(Attribute::Italic))?;
1022    }
1023    if m.contains(Modifiers::UNDERLINE) {
1024        queue!(w, SetAttribute(Attribute::Underlined))?;
1025    }
1026    if m.contains(Modifiers::REVERSED) {
1027        queue!(w, SetAttribute(Attribute::Reverse))?;
1028    }
1029    if m.contains(Modifiers::STRIKETHROUGH) {
1030        queue!(w, SetAttribute(Attribute::CrossedOut))?;
1031    }
1032    Ok(())
1033}
1034
1035fn to_crossterm_color(color: Color, depth: ColorDepth) -> CtColor {
1036    let color = color.downsampled(depth);
1037    match color {
1038        Color::Reset => CtColor::Reset,
1039        Color::Black => CtColor::Black,
1040        Color::Red => CtColor::DarkRed,
1041        Color::Green => CtColor::DarkGreen,
1042        Color::Yellow => CtColor::DarkYellow,
1043        Color::Blue => CtColor::DarkBlue,
1044        Color::Magenta => CtColor::DarkMagenta,
1045        Color::Cyan => CtColor::DarkCyan,
1046        Color::White => CtColor::White,
1047        Color::DarkGray => CtColor::DarkGrey,
1048        Color::LightRed => CtColor::Red,
1049        Color::LightGreen => CtColor::Green,
1050        Color::LightYellow => CtColor::Yellow,
1051        Color::LightBlue => CtColor::Blue,
1052        Color::LightMagenta => CtColor::Magenta,
1053        Color::LightCyan => CtColor::Cyan,
1054        Color::LightWhite => CtColor::White,
1055        Color::Rgb(r, g, b) => CtColor::Rgb { r, g, b },
1056        Color::Indexed(i) => CtColor::AnsiValue(i),
1057    }
1058}
1059
1060fn reset_current_buffer(buffer: &mut Buffer, theme_bg: Option<Color>) {
1061    if let Some(bg) = theme_bg {
1062        buffer.reset_with_bg(bg);
1063    } else {
1064        buffer.reset();
1065    }
1066}
1067
1068#[cfg(test)]
1069mod tests {
1070    use super::*;
1071
1072    #[test]
1073    fn reset_current_buffer_applies_theme_background() {
1074        let mut buffer = Buffer::empty(Rect::new(0, 0, 2, 1));
1075
1076        reset_current_buffer(&mut buffer, Some(Color::Rgb(10, 20, 30)));
1077        assert_eq!(buffer.get(0, 0).style.bg, Some(Color::Rgb(10, 20, 30)));
1078
1079        reset_current_buffer(&mut buffer, None);
1080        assert_eq!(buffer.get(0, 0).style.bg, None);
1081    }
1082
1083    #[test]
1084    fn base64_encode_empty() {
1085        assert_eq!(base64_encode(b""), "");
1086    }
1087
1088    #[test]
1089    fn base64_encode_hello() {
1090        assert_eq!(base64_encode(b"Hello"), "SGVsbG8=");
1091    }
1092
1093    #[test]
1094    fn base64_encode_padding() {
1095        assert_eq!(base64_encode(b"a"), "YQ==");
1096        assert_eq!(base64_encode(b"ab"), "YWI=");
1097        assert_eq!(base64_encode(b"abc"), "YWJj");
1098    }
1099
1100    #[test]
1101    fn base64_encode_unicode() {
1102        assert_eq!(base64_encode("한글".as_bytes()), "7ZWc6riA");
1103    }
1104
1105    #[cfg(feature = "crossterm")]
1106    #[test]
1107    fn parse_osc11_response_dark_and_light() {
1108        assert_eq!(
1109            parse_osc11_response("\x1b]11;rgb:0000/0000/0000\x1b\\"),
1110            ColorScheme::Dark
1111        );
1112        assert_eq!(
1113            parse_osc11_response("\x1b]11;rgb:ffff/ffff/ffff\x07"),
1114            ColorScheme::Light
1115        );
1116    }
1117
1118    #[cfg(feature = "crossterm")]
1119    #[test]
1120    fn base64_decode_round_trip_hello() {
1121        let encoded = base64_encode("hello".as_bytes());
1122        assert_eq!(base64_decode(&encoded), Some("hello".to_string()));
1123    }
1124
1125    #[cfg(feature = "crossterm")]
1126    #[test]
1127    fn color_scheme_equality() {
1128        assert_eq!(ColorScheme::Dark, ColorScheme::Dark);
1129        assert_ne!(ColorScheme::Dark, ColorScheme::Light);
1130        assert_eq!(ColorScheme::Unknown, ColorScheme::Unknown);
1131    }
1132
1133    fn pair(r: Rect) -> (Rect, Rect) {
1134        (r, r)
1135    }
1136
1137    #[test]
1138    fn find_innermost_rect_picks_smallest() {
1139        let rects = vec![
1140            pair(Rect::new(0, 0, 80, 24)),
1141            pair(Rect::new(5, 2, 30, 10)),
1142            pair(Rect::new(10, 4, 10, 5)),
1143        ];
1144        let result = find_innermost_rect(&rects, 12, 5);
1145        assert_eq!(result, Some(Rect::new(10, 4, 10, 5)));
1146    }
1147
1148    #[test]
1149    fn find_innermost_rect_no_match() {
1150        let rects = vec![pair(Rect::new(10, 10, 5, 5))];
1151        assert_eq!(find_innermost_rect(&rects, 0, 0), None);
1152    }
1153
1154    #[test]
1155    fn find_innermost_rect_empty() {
1156        assert_eq!(find_innermost_rect(&[], 5, 5), None);
1157    }
1158
1159    #[test]
1160    fn find_innermost_rect_returns_content_rect() {
1161        let rects = vec![
1162            (Rect::new(0, 0, 80, 24), Rect::new(1, 1, 78, 22)),
1163            (Rect::new(5, 2, 30, 10), Rect::new(6, 3, 28, 8)),
1164        ];
1165        let result = find_innermost_rect(&rects, 10, 5);
1166        assert_eq!(result, Some(Rect::new(6, 3, 28, 8)));
1167    }
1168
1169    #[test]
1170    fn normalize_selection_already_ordered() {
1171        let (s, e) = normalize_selection((2, 1), (5, 3));
1172        assert_eq!(s, (2, 1));
1173        assert_eq!(e, (5, 3));
1174    }
1175
1176    #[test]
1177    fn normalize_selection_reversed() {
1178        let (s, e) = normalize_selection((5, 3), (2, 1));
1179        assert_eq!(s, (2, 1));
1180        assert_eq!(e, (5, 3));
1181    }
1182
1183    #[test]
1184    fn normalize_selection_same_row() {
1185        let (s, e) = normalize_selection((10, 5), (3, 5));
1186        assert_eq!(s, (3, 5));
1187        assert_eq!(e, (10, 5));
1188    }
1189
1190    #[test]
1191    fn selection_state_mouse_down_finds_rect() {
1192        let hit_map = vec![pair(Rect::new(0, 0, 80, 24)), pair(Rect::new(5, 2, 20, 10))];
1193        let mut sel = SelectionState::default();
1194        sel.mouse_down(10, 5, &hit_map);
1195        assert_eq!(sel.anchor, Some((10, 5)));
1196        assert_eq!(sel.current, Some((10, 5)));
1197        assert_eq!(sel.widget_rect, Some(Rect::new(5, 2, 20, 10)));
1198        assert!(!sel.active);
1199    }
1200
1201    #[test]
1202    fn selection_state_drag_activates() {
1203        let hit_map = vec![pair(Rect::new(0, 0, 80, 24))];
1204        let mut sel = SelectionState {
1205            anchor: Some((10, 5)),
1206            current: Some((10, 5)),
1207            widget_rect: Some(Rect::new(0, 0, 80, 24)),
1208            ..Default::default()
1209        };
1210        sel.mouse_drag(10, 5, &hit_map);
1211        assert!(!sel.active, "no movement = not active");
1212        sel.mouse_drag(11, 5, &hit_map);
1213        assert!(!sel.active, "1 cell horizontal = not active yet");
1214        sel.mouse_drag(13, 5, &hit_map);
1215        assert!(sel.active, ">1 cell horizontal = active");
1216    }
1217
1218    #[test]
1219    fn selection_state_drag_vertical_activates() {
1220        let hit_map = vec![pair(Rect::new(0, 0, 80, 24))];
1221        let mut sel = SelectionState {
1222            anchor: Some((10, 5)),
1223            current: Some((10, 5)),
1224            widget_rect: Some(Rect::new(0, 0, 80, 24)),
1225            ..Default::default()
1226        };
1227        sel.mouse_drag(10, 6, &hit_map);
1228        assert!(sel.active, "any vertical movement = active");
1229    }
1230
1231    #[test]
1232    fn selection_state_drag_expands_widget_rect() {
1233        let hit_map = vec![
1234            pair(Rect::new(0, 0, 80, 24)),
1235            pair(Rect::new(5, 2, 30, 10)),
1236            pair(Rect::new(5, 2, 30, 3)),
1237        ];
1238        let mut sel = SelectionState {
1239            anchor: Some((10, 3)),
1240            current: Some((10, 3)),
1241            widget_rect: Some(Rect::new(5, 2, 30, 3)),
1242            ..Default::default()
1243        };
1244        sel.mouse_drag(10, 6, &hit_map);
1245        assert_eq!(sel.widget_rect, Some(Rect::new(5, 2, 30, 10)));
1246    }
1247
1248    #[test]
1249    fn selection_state_clear_resets() {
1250        let mut sel = SelectionState {
1251            anchor: Some((1, 2)),
1252            current: Some((3, 4)),
1253            widget_rect: Some(Rect::new(0, 0, 10, 10)),
1254            active: true,
1255        };
1256        sel.clear();
1257        assert_eq!(sel.anchor, None);
1258        assert_eq!(sel.current, None);
1259        assert_eq!(sel.widget_rect, None);
1260        assert!(!sel.active);
1261    }
1262
1263    #[test]
1264    fn extract_selection_text_single_line() {
1265        let area = Rect::new(0, 0, 20, 5);
1266        let mut buf = Buffer::empty(area);
1267        buf.set_string(0, 0, "Hello World", Style::default());
1268        let sel = SelectionState {
1269            anchor: Some((0, 0)),
1270            current: Some((4, 0)),
1271            widget_rect: Some(area),
1272            active: true,
1273        };
1274        let text = extract_selection_text(&buf, &sel, &[]);
1275        assert_eq!(text, "Hello");
1276    }
1277
1278    #[test]
1279    fn extract_selection_text_multi_line() {
1280        let area = Rect::new(0, 0, 20, 5);
1281        let mut buf = Buffer::empty(area);
1282        buf.set_string(0, 0, "Line one", Style::default());
1283        buf.set_string(0, 1, "Line two", Style::default());
1284        buf.set_string(0, 2, "Line three", Style::default());
1285        let sel = SelectionState {
1286            anchor: Some((5, 0)),
1287            current: Some((3, 2)),
1288            widget_rect: Some(area),
1289            active: true,
1290        };
1291        let text = extract_selection_text(&buf, &sel, &[]);
1292        assert_eq!(text, "one\nLine two\nLine");
1293    }
1294
1295    #[test]
1296    fn extract_selection_text_clamped_to_widget() {
1297        let area = Rect::new(0, 0, 40, 10);
1298        let widget = Rect::new(5, 2, 10, 3);
1299        let mut buf = Buffer::empty(area);
1300        buf.set_string(5, 2, "ABCDEFGHIJ", Style::default());
1301        buf.set_string(5, 3, "KLMNOPQRST", Style::default());
1302        let sel = SelectionState {
1303            anchor: Some((3, 1)),
1304            current: Some((20, 5)),
1305            widget_rect: Some(widget),
1306            active: true,
1307        };
1308        let text = extract_selection_text(&buf, &sel, &[]);
1309        assert_eq!(text, "ABCDEFGHIJ\nKLMNOPQRST");
1310    }
1311
1312    #[test]
1313    fn extract_selection_text_inactive_returns_empty() {
1314        let area = Rect::new(0, 0, 10, 5);
1315        let buf = Buffer::empty(area);
1316        let sel = SelectionState {
1317            anchor: Some((0, 0)),
1318            current: Some((5, 2)),
1319            widget_rect: Some(area),
1320            active: false,
1321        };
1322        assert_eq!(extract_selection_text(&buf, &sel, &[]), "");
1323    }
1324
1325    #[test]
1326    fn apply_selection_overlay_reverses_cells() {
1327        let area = Rect::new(0, 0, 10, 3);
1328        let mut buf = Buffer::empty(area);
1329        buf.set_string(0, 0, "ABCDE", Style::default());
1330        let sel = SelectionState {
1331            anchor: Some((1, 0)),
1332            current: Some((3, 0)),
1333            widget_rect: Some(area),
1334            active: true,
1335        };
1336        apply_selection_overlay(&mut buf, &sel, &[]);
1337        assert!(!buf.get(0, 0).style.modifiers.contains(Modifiers::REVERSED));
1338        assert!(buf.get(1, 0).style.modifiers.contains(Modifiers::REVERSED));
1339        assert!(buf.get(2, 0).style.modifiers.contains(Modifiers::REVERSED));
1340        assert!(buf.get(3, 0).style.modifiers.contains(Modifiers::REVERSED));
1341        assert!(!buf.get(4, 0).style.modifiers.contains(Modifiers::REVERSED));
1342    }
1343
1344    #[test]
1345    fn extract_selection_text_skips_border_cells() {
1346        // Simulate two bordered columns side by side:
1347        // Col1: full=(0,0,20,5) content=(1,1,18,3)
1348        // Col2: full=(20,0,20,5) content=(21,1,18,3)
1349        // Parent widget_rect covers both: (0,0,40,5)
1350        let area = Rect::new(0, 0, 40, 5);
1351        let mut buf = Buffer::empty(area);
1352        // Col1 border characters
1353        buf.set_string(0, 0, "╭", Style::default());
1354        buf.set_string(0, 1, "│", Style::default());
1355        buf.set_string(0, 2, "│", Style::default());
1356        buf.set_string(0, 3, "│", Style::default());
1357        buf.set_string(0, 4, "╰", Style::default());
1358        buf.set_string(19, 0, "╮", Style::default());
1359        buf.set_string(19, 1, "│", Style::default());
1360        buf.set_string(19, 2, "│", Style::default());
1361        buf.set_string(19, 3, "│", Style::default());
1362        buf.set_string(19, 4, "╯", Style::default());
1363        // Col2 border characters
1364        buf.set_string(20, 0, "╭", Style::default());
1365        buf.set_string(20, 1, "│", Style::default());
1366        buf.set_string(20, 2, "│", Style::default());
1367        buf.set_string(20, 3, "│", Style::default());
1368        buf.set_string(20, 4, "╰", Style::default());
1369        buf.set_string(39, 0, "╮", Style::default());
1370        buf.set_string(39, 1, "│", Style::default());
1371        buf.set_string(39, 2, "│", Style::default());
1372        buf.set_string(39, 3, "│", Style::default());
1373        buf.set_string(39, 4, "╯", Style::default());
1374        // Content inside Col1
1375        buf.set_string(1, 1, "Hello Col1", Style::default());
1376        buf.set_string(1, 2, "Line2 Col1", Style::default());
1377        // Content inside Col2
1378        buf.set_string(21, 1, "Hello Col2", Style::default());
1379        buf.set_string(21, 2, "Line2 Col2", Style::default());
1380
1381        let content_map = vec![
1382            (Rect::new(0, 0, 20, 5), Rect::new(1, 1, 18, 3)),
1383            (Rect::new(20, 0, 20, 5), Rect::new(21, 1, 18, 3)),
1384        ];
1385
1386        // Select across both columns, rows 1-2
1387        let sel = SelectionState {
1388            anchor: Some((0, 1)),
1389            current: Some((39, 2)),
1390            widget_rect: Some(area),
1391            active: true,
1392        };
1393        let text = extract_selection_text(&buf, &sel, &content_map);
1394        // Should NOT contain border characters (│, ╭, ╮, etc.)
1395        assert!(!text.contains('│'), "Border char │ found in: {text}");
1396        assert!(!text.contains('╭'), "Border char ╭ found in: {text}");
1397        assert!(!text.contains('╮'), "Border char ╮ found in: {text}");
1398        // Should contain actual content
1399        assert!(
1400            text.contains("Hello Col1"),
1401            "Missing Col1 content in: {text}"
1402        );
1403        assert!(
1404            text.contains("Hello Col2"),
1405            "Missing Col2 content in: {text}"
1406        );
1407        assert!(text.contains("Line2 Col1"), "Missing Col1 line2 in: {text}");
1408        assert!(text.contains("Line2 Col2"), "Missing Col2 line2 in: {text}");
1409    }
1410
1411    #[test]
1412    fn apply_selection_overlay_skips_border_cells() {
1413        let area = Rect::new(0, 0, 20, 3);
1414        let mut buf = Buffer::empty(area);
1415        buf.set_string(0, 0, "│", Style::default());
1416        buf.set_string(1, 0, "ABC", Style::default());
1417        buf.set_string(19, 0, "│", Style::default());
1418
1419        let content_map = vec![(Rect::new(0, 0, 20, 3), Rect::new(1, 0, 18, 3))];
1420        let sel = SelectionState {
1421            anchor: Some((0, 0)),
1422            current: Some((19, 0)),
1423            widget_rect: Some(area),
1424            active: true,
1425        };
1426        apply_selection_overlay(&mut buf, &sel, &content_map);
1427        // Border cells at x=0 and x=19 should NOT be reversed
1428        assert!(
1429            !buf.get(0, 0).style.modifiers.contains(Modifiers::REVERSED),
1430            "Left border cell should not be reversed"
1431        );
1432        assert!(
1433            !buf.get(19, 0).style.modifiers.contains(Modifiers::REVERSED),
1434            "Right border cell should not be reversed"
1435        );
1436        // Content cells should be reversed
1437        assert!(buf.get(1, 0).style.modifiers.contains(Modifiers::REVERSED));
1438        assert!(buf.get(2, 0).style.modifiers.contains(Modifiers::REVERSED));
1439        assert!(buf.get(3, 0).style.modifiers.contains(Modifiers::REVERSED));
1440    }
1441
1442    #[test]
1443    fn copy_to_clipboard_writes_osc52() {
1444        let mut output: Vec<u8> = Vec::new();
1445        copy_to_clipboard(&mut output, "test").unwrap();
1446        let s = String::from_utf8(output).unwrap();
1447        assert!(s.starts_with("\x1b]52;c;"));
1448        assert!(s.ends_with("\x1b\\"));
1449        assert!(s.contains(&base64_encode(b"test")));
1450    }
1451}