Skip to main content

cellix_term/
clipboard.rs

1//! Paste events from the Kitty clipboard protocol (OSC 5522), which is how a terminal hands
2//! over a picture: OSC 52 carries only text. With mode 5522 on, a paste doesn't arrive as
3//! bracketed text but as a list of what the clipboard holds, with a one-time password. The
4//! program asks for the kind it wants with that password, and the terminal sends it without
5//! asking the person, since they pressed paste. Kitty since 0.44.1 and Ghostty since 1.4 do this.
6//! Spec: <https://rockorager.dev/misc/bracketed-paste-mime/> and kitty's clipboard page.
7
8use base64::Engine;
9
10/// Turns paste events on and off.
11pub const PASTE_EVENTS_ON: &str = "\x1b[?5522h";
12pub const PASTE_EVENTS_OFF: &str = "\x1b[?5522l";
13/// What a terminal is asked to learn whether it has paste events, with the questions at start.
14pub const ASK_PASTE_EVENTS: &str = "\x1b[?5522$p";
15/// The name a read with a paste's password gives, which the terminal checks the password by.
16const PASTE_EVENT: &str = "Paste event";
17/// Where an OSC 5522 message's body starts, after `ESC ]`.
18pub const PREFIX: &str = "5522;";
19
20/// Whether a reply to the questions at start says paste events are on offer: set or reset.
21pub fn has_paste_events(reply: &[u8]) -> bool {
22    let has = |s: &[u8]| reply.windows(s.len()).any(|w| w == s);
23    has(b"?5522;1$y") || has(b"?5522;2$y")
24}
25
26/// What the terminal said, once a whole exchange is in.
27#[derive(Debug, PartialEq, Eq)]
28pub enum Pasted {
29    /// The person pasted: what the clipboard holds, and the password to read it with.
30    Offer {
31        types: Vec<String>,
32        password: Option<String>,
33    },
34    /// What was asked for.
35    Data { mime: String, bytes: Vec<u8> },
36    /// The terminal wouldn't, with its reason: EPERM, ENOSYS, EBUSY and so on.
37    Refused(String),
38}
39
40/// Reads OSC 5522 messages, one body at a time, into what they add up to.
41#[derive(Default)]
42pub struct Reader {
43    /// An exchange under way: its password, the types listed, and the data so far.
44    open: Option<Exchange>,
45}
46
47#[derive(Default)]
48struct Exchange {
49    password: Option<String>,
50    listed: Option<String>,
51    mime: Option<String>,
52    bytes: Vec<u8>,
53}
54
55impl Reader {
56    /// Takes one message's body, the part after `ESC ] 5522 ;` and before its end.
57    pub fn take(&mut self, body: &str) -> Option<Pasted> {
58        let (meta, payload) = body.split_once(';').unwrap_or((body, ""));
59        let keys: Vec<(&str, &str)> = meta
60            .split(':')
61            .filter_map(|pair| pair.split_once('='))
62            .collect();
63        let key = |name: &str| keys.iter().find(|(k, _)| *k == name).map(|(_, v)| *v);
64        if key("type") != Some("read") {
65            return None;
66        }
67        let password = key("pw").map(str::to_string);
68        match key("status")? {
69            "OK" => {
70                self.open = Some(Exchange {
71                    password,
72                    ..Exchange::default()
73                });
74                None
75            }
76            "DATA" => {
77                let exchange = self.open.get_or_insert_with(Exchange::default);
78                exchange.password = exchange.password.take().or(password);
79                let mime = key("mime").and_then(decode_text).unwrap_or_default();
80                // Each chunk is padded on its own, so each is decoded on its own.
81                let bytes = decode(payload).unwrap_or_default();
82                if mime == "." {
83                    let listed = exchange.listed.get_or_insert_with(String::new);
84                    listed.push_str(&String::from_utf8_lossy(&bytes));
85                } else if exchange.mime.as_deref().is_none_or(|m| m == mime) {
86                    exchange.mime = Some(mime);
87                    exchange.bytes.extend(bytes);
88                }
89                None
90            }
91            "DONE" => {
92                let exchange = self.open.take()?;
93                let password = exchange.password.or(password);
94                if let Some(listed) = exchange.listed {
95                    let types = listed.split_whitespace().map(str::to_string).collect();
96                    return Some(Pasted::Offer { types, password });
97                }
98                Some(Pasted::Data {
99                    mime: exchange.mime?,
100                    bytes: exchange.bytes,
101                })
102            }
103            error => {
104                self.open = None;
105                Some(Pasted::Refused(error.to_string()))
106            }
107        }
108    }
109}
110
111/// What to read of what's offered: text if there's any, as an ordinary paste is, and
112/// otherwise a picture, PNG first.
113pub fn choose(types: &[String]) -> Option<&str> {
114    let text = types
115        .iter()
116        .find(|t| *t == "text/plain" || t.starts_with("text/plain;"));
117    let picture = [
118        "image/png",
119        "image/jpeg",
120        "image/gif",
121        "image/webp",
122        "image/tiff",
123    ]
124    .iter()
125    .find_map(|want| types.iter().find(|t| t == want));
126    let any_picture = types.iter().find(|t| t.starts_with("image/"));
127    text.or(picture).or(any_picture).map(String::as_str)
128}
129
130/// Asks for `mime`, with a paste's password so the terminal needn't ask the person.
131pub fn read_request(mime: &str, password: Option<&str>) -> String {
132    let engine = base64::engine::general_purpose::STANDARD;
133    let proof = password.map_or_else(String::new, |pw| {
134        format!(":pw={pw}:name={}", engine.encode(PASTE_EVENT))
135    });
136    format!("\x1b]5522;type=read{proof};{}\x1b\\", engine.encode(mime))
137}
138
139fn decode(text: &str) -> Option<Vec<u8>> {
140    base64::engine::general_purpose::STANDARD.decode(text).ok()
141}
142
143fn decode_text(text: &str) -> Option<String> {
144    String::from_utf8(decode(text)?).ok()
145}
146
147#[cfg(test)]
148mod tests {
149    use super::*;
150
151    fn b64(s: &[u8]) -> String {
152        base64::engine::general_purpose::STANDARD.encode(s)
153    }
154
155    /// Feeds whole messages, as they'd arrive, and keeps what they add up to.
156    fn read(reader: &mut Reader, bodies: &[String]) -> Vec<Pasted> {
157        bodies.iter().filter_map(|b| reader.take(b)).collect()
158    }
159
160    #[test]
161    fn a_paste_event_lists_what_the_clipboard_holds_with_its_password() {
162        // As Ghostty 1.4 sends it: the password in every packet, the list ending in a newline.
163        let pw = b64(b"one-time");
164        let bodies = [
165            format!("type=read:status=OK:pw={pw}"),
166            format!(
167                "type=read:status=DATA:mime=Lg==:pw={pw};{}",
168                b64(b"text/plain image/png\n")
169            ),
170            format!("type=read:status=DONE:pw={pw}"),
171        ];
172        let got = read(&mut Reader::default(), &bodies);
173        assert_eq!(
174            got,
175            vec![Pasted::Offer {
176                types: vec!["text/plain".into(), "image/png".into()],
177                password: Some(pw),
178            }]
179        );
180    }
181
182    #[test]
183    fn data_comes_back_whole_from_its_chunks() {
184        let picture: Vec<u8> = (0..9000u32).map(|i| (i % 251) as u8).collect();
185        let mut bodies = vec!["type=read:status=OK".to_string()];
186        for chunk in picture.chunks(4096) {
187            bodies.push(format!(
188                "type=read:status=DATA:mime={};{}",
189                b64(b"image/png"),
190                b64(chunk)
191            ));
192        }
193        bodies.push("type=read:status=DONE".into());
194        let got = read(&mut Reader::default(), &bodies);
195        assert_eq!(
196            got,
197            vec![Pasted::Data {
198                mime: "image/png".into(),
199                bytes: picture
200            }]
201        );
202    }
203
204    #[test]
205    fn a_refusal_says_why() {
206        let got = read(
207            &mut Reader::default(),
208            &["type=read:status=EPERM".to_string()],
209        );
210        assert_eq!(got, vec![Pasted::Refused("EPERM".into())]);
211        // What isn't a read, such as a write's answer, is none of this.
212        assert_eq!(Reader::default().take("type=write:status=DONE"), None);
213    }
214
215    #[test]
216    fn text_is_chosen_over_a_picture_and_png_over_other_pictures() {
217        let types = |list: &[&str]| list.iter().map(|s| s.to_string()).collect::<Vec<_>>();
218        assert_eq!(
219            choose(&types(&["image/png", "text/plain"])),
220            Some("text/plain")
221        );
222        assert_eq!(
223            choose(&types(&["image/tiff", "image/png"])),
224            Some("image/png")
225        );
226        // A Mac screenshot can be only TIFF.
227        assert_eq!(choose(&types(&["image/tiff"])), Some("image/tiff"));
228        assert_eq!(choose(&types(&["text/html"])), None);
229    }
230
231    #[test]
232    fn a_read_carries_the_pastes_password_and_name() {
233        assert_eq!(
234            read_request("image/png", Some("cHc=")),
235            "\x1b]5522;type=read:pw=cHc=:name=UGFzdGUgZXZlbnQ=;aW1hZ2UvcG5n\x1b\\"
236        );
237        assert!(has_paste_events(b"\x1b[?5522;2$y"));
238        assert!(!has_paste_events(b"\x1b[?5522;0$y"));
239    }
240}