|
| 1 | +//! System clipboard writes via OSC 52. |
| 2 | +//! |
| 3 | +//! Like [`crate::hyperlink`] (OSC 8) and [`crate::native`] (OSC 9;4), this is an |
| 4 | +//! out-of-band terminal capability: the app writes an escape sequence and the |
| 5 | +//! terminal — not the app — puts the text on the system clipboard. It needs no |
| 6 | +//! platform clipboard library and works over SSH, which is why it's the right |
| 7 | +//! fit for copying a mouse selection (see [`crate::mouse`]). |
| 8 | +//! |
| 9 | +//! The sequence is `OSC 52 ; c ; <base64> ST`, where the payload is the text |
| 10 | +//! base64-encoded (RFC 4648) and `c` selects the system clipboard. Terminals |
| 11 | +//! that support OSC 52 (Ghostty, iTerm2 with it enabled, WezTerm, Kitty, recent |
| 12 | +//! VTE, xterm) copy it; others ignore the sequence. Under tmux it requires |
| 13 | +//! `set -g allow-passthrough on` (or tmux's own `set-clipboard`), the same |
| 14 | +//! passthrough caveat as OSC 8 hyperlinks. |
| 15 | +//! |
| 16 | +//! Terminals cap an OSC 52 sequence near 100 000 bytes; encoded, that bounds |
| 17 | +//! the copyable text at [`MAX_LEN`] bytes. Longer text is refused rather than |
| 18 | +//! sent truncated (a truncated clipboard is worse than a failed copy). |
| 19 | +
|
| 20 | +use std::io::{self, Write}; |
| 21 | + |
| 22 | +/// Maximum length, in bytes, of text a single OSC 52 write will copy. Beyond |
| 23 | +/// this the terminal would truncate the sequence, so [`osc52`] refuses it. |
| 24 | +pub const MAX_LEN: usize = 74_994; |
| 25 | + |
| 26 | +/// String terminator for the OSC sequence: `ESC \`. |
| 27 | +const ST: &str = "\x1b\\"; |
| 28 | + |
| 29 | +/// Encode `text` as an OSC 52 clipboard-set sequence, or `None` when `text` is |
| 30 | +/// empty or longer than [`MAX_LEN`]. Pure and allocation-only — no I/O. |
| 31 | +pub fn osc52(text: &str) -> Option<String> { |
| 32 | + if text.is_empty() || text.len() > MAX_LEN { |
| 33 | + return None; |
| 34 | + } |
| 35 | + Some(format!("\x1b]52;c;{}{ST}", base64_encode(text.as_bytes()))) |
| 36 | +} |
| 37 | + |
| 38 | +/// Copy `text` to the system clipboard by writing an OSC 52 sequence to `out`. |
| 39 | +/// Returns `Ok(true)` when a sequence was written, `Ok(false)` when `text` was |
| 40 | +/// empty or too large (see [`MAX_LEN`]). |
| 41 | +pub fn write_clipboard(out: &mut impl Write, text: &str) -> io::Result<bool> { |
| 42 | + match osc52(text) { |
| 43 | + Some(seq) => { |
| 44 | + out.write_all(seq.as_bytes())?; |
| 45 | + out.flush()?; |
| 46 | + Ok(true) |
| 47 | + } |
| 48 | + None => Ok(false), |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +/// Standard base64 (RFC 4648) with `=` padding. Inlined to keep `tuika` free of |
| 53 | +/// a base64 dependency. |
| 54 | +fn base64_encode(data: &[u8]) -> String { |
| 55 | + const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; |
| 56 | + let mut out = String::with_capacity(data.len().div_ceil(3) * 4); |
| 57 | + for chunk in data.chunks(3) { |
| 58 | + let b0 = chunk[0] as u32; |
| 59 | + let b1 = *chunk.get(1).unwrap_or(&0) as u32; |
| 60 | + let b2 = *chunk.get(2).unwrap_or(&0) as u32; |
| 61 | + let n = (b0 << 16) | (b1 << 8) | b2; |
| 62 | + out.push(ALPHABET[((n >> 18) & 0x3f) as usize] as char); |
| 63 | + out.push(ALPHABET[((n >> 12) & 0x3f) as usize] as char); |
| 64 | + out.push(if chunk.len() > 1 { |
| 65 | + ALPHABET[((n >> 6) & 0x3f) as usize] as char |
| 66 | + } else { |
| 67 | + '=' |
| 68 | + }); |
| 69 | + out.push(if chunk.len() > 2 { |
| 70 | + ALPHABET[(n & 0x3f) as usize] as char |
| 71 | + } else { |
| 72 | + '=' |
| 73 | + }); |
| 74 | + } |
| 75 | + out |
| 76 | +} |
| 77 | + |
| 78 | +#[cfg(test)] |
| 79 | +mod tests { |
| 80 | + use super::*; |
| 81 | + |
| 82 | + #[test] |
| 83 | + fn base64_matches_known_vectors() { |
| 84 | + // RFC 4648 test vectors. |
| 85 | + assert_eq!(base64_encode(b""), ""); |
| 86 | + assert_eq!(base64_encode(b"f"), "Zg=="); |
| 87 | + assert_eq!(base64_encode(b"fo"), "Zm8="); |
| 88 | + assert_eq!(base64_encode(b"foo"), "Zm9v"); |
| 89 | + assert_eq!(base64_encode(b"foob"), "Zm9vYg=="); |
| 90 | + assert_eq!(base64_encode(b"fooba"), "Zm9vYmE="); |
| 91 | + assert_eq!(base64_encode(b"foobar"), "Zm9vYmFy"); |
| 92 | + } |
| 93 | + |
| 94 | + #[test] |
| 95 | + fn osc52_wraps_base64_payload() { |
| 96 | + assert_eq!( |
| 97 | + osc52("foobar"), |
| 98 | + Some("\x1b]52;c;Zm9vYmFy\x1b\\".to_string()) |
| 99 | + ); |
| 100 | + } |
| 101 | + |
| 102 | + #[test] |
| 103 | + fn osc52_refuses_empty_and_oversized() { |
| 104 | + assert_eq!(osc52(""), None); |
| 105 | + let big = "x".repeat(MAX_LEN + 1); |
| 106 | + assert_eq!(osc52(&big), None); |
| 107 | + // Exactly at the cap is allowed. |
| 108 | + assert!(osc52(&"x".repeat(MAX_LEN)).is_some()); |
| 109 | + } |
| 110 | + |
| 111 | + #[test] |
| 112 | + fn write_clipboard_reports_whether_it_wrote() { |
| 113 | + let mut buf: Vec<u8> = Vec::new(); |
| 114 | + assert!(write_clipboard(&mut buf, "hi").expect("write")); |
| 115 | + assert_eq!(buf, b"\x1b]52;c;aGk=\x1b\\"); |
| 116 | + |
| 117 | + let mut empty: Vec<u8> = Vec::new(); |
| 118 | + assert!(!write_clipboard(&mut empty, "").expect("write")); |
| 119 | + assert!(empty.is_empty()); |
| 120 | + } |
| 121 | +} |
0 commit comments