Skip to main content

uncurses/ansi/
drag_drop.rs

1//! Kitty drag and drop messages through OSC 72.
2//!
3//! [`write_drag_drop`] frames one message. Callers supply metadata and a
4//! wire-ready payload, manage registration, and complete or cancel transfers.
5//! Unregister before a shell handoff or exit.
6//!
7//! Binary payloads use standard base64. Callers split encoded payloads to meet
8//! the protocol's 4096-byte limit. For a chunked message, use `m=1` until the
9//! last chunk (`m=0`).
10//! Only the first chunk must contain the full metadata. An empty data response
11//! with `m=0` ends a transfer; a nonempty response with `m=0` only ends a message.
12//!
13//! Replies arrive as [`Event::DragDrop`](crate::event::Event::DragDrop).
14//! See the [protocol specification](https://sw.kovidgoyal.net/kitty/dnd-protocol/).
15
16use std::io::{self, Write};
17
18/// Query OSC 72 support without a routing ID.
19///
20/// Pass this as `extra` to [`Probe::query_capabilities`](crate::program::Probe::query_capabilities)
21/// to follow it with the usual primary device attributes query.
22pub const REQUEST_DRAG_DROP: &[u8] = b"\x1b]72;t=q\x1b\\";
23
24/// Write one OSC 72 message without flushing.
25///
26/// Options are joined with `:`. The payload separator is omitted when the
27/// payload is empty. Options and payload are written verbatim: callers must
28/// supply escape-safe metadata, encode binary data as base64, and split payloads
29/// to meet the protocol's 4096-byte limit.
30///
31/// This function frames the supplied bytes and propagates output errors.
32///
33/// ```
34/// use uncurses::ansi::drag_drop::write_drag_drop;
35///
36/// let mut bytes = Vec::new();
37/// write_drag_drop(&mut bytes, &["t=m", "o=1"], b"text/plain")?;
38/// assert_eq!(bytes, b"\x1b]72;t=m:o=1;text/plain\x1b\\");
39/// # Ok::<(), std::io::Error>(())
40/// ```
41pub fn write_drag_drop<W: Write>(w: &mut W, options: &[&str], payload: &[u8]) -> io::Result<()> {
42    w.write_all(b"\x1b]72;")?;
43    for (index, option) in options.iter().enumerate() {
44        if index != 0 {
45            w.write_all(b":")?;
46        }
47        w.write_all(option.as_bytes())?;
48    }
49    if !payload.is_empty() {
50        w.write_all(b";")?;
51        w.write_all(payload)?;
52    }
53    w.write_all(b"\x1b\\")
54}
55
56#[cfg(test)]
57mod tests {
58    use super::*;
59
60    #[test]
61    fn query_and_raw_chunks() {
62        let mut bytes = Vec::new();
63        write_drag_drop(&mut bytes, &["t=q"], b"").unwrap();
64        assert_eq!(bytes, REQUEST_DRAG_DROP);
65        bytes.clear();
66        write_drag_drop(&mut bytes, &["t=r", "x=1", "m=1"], b"YW").unwrap();
67        write_drag_drop(&mut bytes, &["m=0"], b"Jj").unwrap();
68        write_drag_drop(&mut bytes, &["t=r", "x=1"], b"").unwrap();
69        assert_eq!(
70            bytes,
71            b"\x1b]72;t=r:x=1:m=1;YW\x1b\\\x1b]72;m=0;Jj\x1b\\\x1b]72;t=r:x=1\x1b\\"
72        );
73    }
74
75    #[test]
76    fn verbatim_payload_and_output_errors() {
77        let mut bytes = Vec::new();
78        let payload = [b'A'; 4097];
79        write_drag_drop(&mut bytes, &["t=p", "x=0"], &payload).unwrap();
80        assert_eq!(
81            bytes,
82            [b"\x1b]72;t=p:x=0;".as_slice(), &payload, b"\x1b\\"].concat()
83        );
84        assert_eq!(
85            write_drag_drop(&mut [].as_mut_slice(), &["t=q"], b"")
86                .unwrap_err()
87                .kind(),
88            io::ErrorKind::WriteZero
89        );
90    }
91}