guic-gpui-linux 0.6.2

Linux and FreeBSD backend with Wayland, X11, and headless support.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
use std::{
    fs::File,
    io::{ErrorKind, Write},
    os::fd::{AsRawFd, BorrowedFd, OwnedFd},
};

use calloop::{LoopHandle, PostAction};
use filedescriptor::Pipe;
use strum::IntoEnumIterator;
use wayland_client::{Connection, protocol::wl_data_offer::WlDataOffer};
use wayland_protocols::wp::primary_selection::zv1::client::zwp_primary_selection_offer_v1::ZwpPrimarySelectionOfferV1;

use crate::linux::{
    WaylandClientStatePtr,
    platform::{PIPE_READ_TIMEOUT, read_fd_with_timeout},
};
use gpui::{ClipboardEntry, ClipboardItem, Image, ImageFormat, hash};

/// Text mime types that we'll offer to other programs.
pub(crate) const TEXT_MIME_TYPES: [&str; 3] =
    ["text/plain;charset=utf-8", "UTF8_STRING", "text/plain"];
pub(crate) const FILE_LIST_MIME_TYPE: &str = "text/uri-list";

/// Text mime types that we'll accept from other programs.
pub(crate) const ALLOWED_TEXT_MIME_TYPES: [&str; 2] = ["text/plain;charset=utf-8", "UTF8_STRING"];

pub(crate) struct Clipboard {
    connection: Connection,
    loop_handle: LoopHandle<'static, WaylandClientStatePtr>,
    self_mime: String,

    // Internal clipboard
    contents: Option<std::sync::Arc<ClipboardItem>>,
    file_operation: Option<gpui::FileClipboardOperation>,
    primary_contents: Option<ClipboardItem>,

    // External clipboard
    cached_read: Option<ClipboardItem>,
    current_offer: Option<DataOffer<WlDataOffer>>,
    cached_primary_read: Option<ClipboardItem>,
    current_primary_offer: Option<DataOffer<ZwpPrimarySelectionOfferV1>>,
}

pub(crate) trait ReceiveData {
    fn receive_data(&self, mime_type: String, fd: BorrowedFd<'_>);
}

impl ReceiveData for WlDataOffer {
    fn receive_data(&self, mime_type: String, fd: BorrowedFd<'_>) {
        self.receive(mime_type, fd);
    }
}

impl ReceiveData for ZwpPrimarySelectionOfferV1 {
    fn receive_data(&self, mime_type: String, fd: BorrowedFd<'_>) {
        self.receive(mime_type, fd);
    }
}

#[derive(Clone, Debug)]
/// Wrapper for `WlDataOffer` and `ZwpPrimarySelectionOfferV1`, used to help track mime types.
pub(crate) struct DataOffer<T: ReceiveData> {
    pub inner: T,
    mime_types: Vec<String>,
}

impl<T: ReceiveData> DataOffer<T> {
    pub fn new(offer: T) -> Self {
        Self {
            inner: offer,
            mime_types: Vec::new(),
        }
    }

    pub fn add_mime_type(&mut self, mime_type: String) {
        self.mime_types.push(mime_type)
    }

    fn has_mime_type(&self, mime_type: &str) -> bool {
        self.mime_types.iter().any(|t| t == mime_type)
    }

    fn receive_text(&self) -> Option<filedescriptor::FileDescriptor> {
        let mime = TEXT_MIME_TYPES
            .iter()
            .find(|mime| self.has_mime_type(mime))?;
        let pipe = Pipe::new().ok()?;
        self.inner.receive_data((*mime).to_string(), unsafe {
            BorrowedFd::borrow_raw(pipe.write.as_raw_fd())
        });
        drop(pipe.write);
        Some(pipe.read)
    }

    fn read_bytes(&self, connection: &Connection, mime_type: &str) -> Option<Vec<u8>> {
        let pipe = Pipe::new().unwrap();
        self.inner.receive_data(mime_type.to_string(), unsafe {
            BorrowedFd::borrow_raw(pipe.write.as_raw_fd())
        });
        let fd = pipe.read;
        drop(pipe.write);

        connection.flush().unwrap();

        match read_fd_with_timeout(fd, PIPE_READ_TIMEOUT) {
            Ok(bytes) => Some(bytes),
            Err(err) => {
                log::error!("error reading clipboard pipe: {err:?}");
                None
            }
        }
    }

    fn read_text(&self, connection: &Connection) -> Option<ClipboardItem> {
        let mime_type = self.mime_types.iter().find(|&mime_type| {
            ALLOWED_TEXT_MIME_TYPES
                .iter()
                .any(|&allowed| allowed == mime_type)
        })?;
        let bytes = self.read_bytes(connection, mime_type)?;
        let text_content = match String::from_utf8(bytes) {
            Ok(content) => content,
            Err(e) => {
                log::error!("Failed to convert clipboard content to UTF-8: {}", e);
                return None;
            }
        };

        // Normalize the text to unix line endings, otherwise
        // copying from eg: firefox inserts a lot of blank
        // lines, and that is super annoying.
        let result = text_content.replace("\r\n", "\n");
        Some(ClipboardItem::new_string(result))
    }

    fn read_image(&self, connection: &Connection) -> Option<ClipboardItem> {
        for format in ImageFormat::iter() {
            let mime_type = format.mime_type();
            if !self.has_mime_type(mime_type) {
                continue;
            }

            if let Some(bytes) = self.read_bytes(connection, mime_type) {
                let id = hash(&bytes);
                return Some(ClipboardItem {
                    entries: vec![ClipboardEntry::Image(Image { format, bytes, id })],
                });
            }
        }
        None
    }
}

impl Clipboard {
    pub fn new(
        connection: Connection,
        loop_handle: LoopHandle<'static, WaylandClientStatePtr>,
    ) -> Self {
        Self {
            connection,
            loop_handle,
            self_mime: format!("pid/{}", std::process::id()),

            contents: None,
            file_operation: None,
            primary_contents: None,

            cached_read: None,
            current_offer: None,
            cached_primary_read: None,
            current_primary_offer: None,
        }
    }

    pub fn set(&mut self, item: ClipboardItem) {
        self.contents = Some(std::sync::Arc::new(item));
        self.file_operation = None;
    }

    pub fn set_files(
        &mut self,
        paths: gpui::ExternalPaths,
        operation: gpui::FileClipboardOperation,
    ) {
        self.contents = Some(std::sync::Arc::new(ClipboardItem {
            entries: vec![ClipboardEntry::ExternalPaths(paths)],
        }));
        self.file_operation = Some(operation);
    }

    pub fn set_primary(&mut self, item: ClipboardItem) {
        self.primary_contents = Some(item);
    }

    pub fn set_offer(&mut self, data_offer: Option<DataOffer<WlDataOffer>>) {
        self.cached_read = None;
        self.current_offer = data_offer;
    }

    pub fn set_primary_offer(&mut self, data_offer: Option<DataOffer<ZwpPrimarySelectionOfferV1>>) {
        self.cached_primary_read = None;
        self.current_primary_offer = data_offer;
    }

    pub fn self_mime(&self) -> String {
        self.self_mime.clone()
    }

    pub fn send(&self, mime_type: String, fd: OwnedFd) {
        if let Some(operation) = self.file_operation {
            let Some(ClipboardEntry::ExternalPaths(paths)) =
                self.contents.as_ref().and_then(|item| item.entries.first())
            else {
                return;
            };
            let bytes = match mime_type.as_str() {
                FILE_LIST_MIME_TYPE => paths.clipboard_uri_list().map(String::into_bytes),
                "x-special/gnome-copied-files" => paths
                    .clipboard_gnome_files(operation)
                    .map(String::into_bytes),
                "application/x-kde-cutselection" => {
                    Ok(if operation == gpui::FileClipboardOperation::Move {
                        b"1"
                    } else {
                        b"0"
                    }
                    .to_vec())
                }
                _ => return,
            };
            if let Ok(bytes) = bytes {
                self.send_bytes(fd, bytes);
            }
            return;
        }
        if let Some(text) = self.contents.as_ref().and_then(|contents| contents.text()) {
            self.send_bytes(fd, text.as_bytes().to_owned());
        }
    }

    pub fn send_primary(&self, _mime_type: String, fd: OwnedFd) {
        if let Some(text) = self
            .primary_contents
            .as_ref()
            .and_then(|contents| contents.text())
        {
            self.send_bytes(fd, text.as_bytes().to_owned());
        }
    }

    pub fn read_text_async(
        &self,
        executor: &gpui::BackgroundExecutor,
    ) -> gpui::Task<Option<String>> {
        let Some(offer) = &self.current_offer else {
            return gpui::Task::ready(None);
        };
        if offer.has_mime_type(&self.self_mime) {
            let contents = self.contents.clone();
            return executor.spawn(async move { contents.and_then(|item| item.plain_text()) });
        }
        // Capture and request the current offer on the event-loop thread. Only
        // the pipe transfer and UTF-8 decoding move to the background executor.
        let Some(fd) = offer.receive_text() else {
            return gpui::Task::ready(None);
        };
        if let Err(error) = self.connection.flush()
            && !matches!(error, wayland_client::backend::WaylandError::Io(ref error)
                if error.kind() == ErrorKind::WouldBlock)
        {
            return gpui::Task::ready(None);
        }
        executor.spawn(async move { read_received_text(fd) })
    }

    pub fn read(&mut self) -> Option<ClipboardItem> {
        let offer = self.current_offer.as_ref()?;
        if let Some(cached) = self.cached_read.clone() {
            return Some(cached);
        }

        if offer.has_mime_type(&self.self_mime) {
            return self.contents.as_deref().cloned();
        }

        let item = offer
            .read_text(&self.connection)
            .or_else(|| offer.read_image(&self.connection))?;

        self.cached_read = Some(item.clone());
        Some(item)
    }

    pub fn read_primary(&mut self) -> Option<ClipboardItem> {
        let offer = self.current_primary_offer.as_ref()?;
        if let Some(cached) = self.cached_primary_read.clone() {
            return Some(cached);
        }

        if offer.has_mime_type(&self.self_mime) {
            return self.primary_contents.clone();
        }

        let item = offer
            .read_text(&self.connection)
            .or_else(|| offer.read_image(&self.connection))?;

        self.cached_primary_read = Some(item.clone());
        Some(item)
    }

    pub fn send_bytes(&self, fd: OwnedFd, bytes: Vec<u8>) {
        // Readiness only guarantees space for some bytes. A blocking descriptor
        // can stall the event loop when the recipient stops draining a large paste.
        let mut fd = filedescriptor::FileDescriptor::new(File::from(fd));
        if let Err(error) = fd.set_non_blocking(true) {
            log::error!("failed to prepare clipboard pipe: {error}");
            return;
        }
        let mut written = 0;
        if let Err(error) = self.loop_handle.insert_source(
            calloop::generic::Generic::new(fd, calloop::Interest::WRITE, calloop::Mode::Level),
            move |_, file, _| {
                let file = unsafe { file.get_mut() };
                loop {
                    match file.write(&bytes[written..]) {
                        Ok(0) => break Ok(PostAction::Remove),
                        Ok(n) if written + n == bytes.len() => {
                            written += n;
                            break Ok(PostAction::Remove);
                        }
                        Ok(n) => written += n,
                        Err(err) if err.kind() == ErrorKind::WouldBlock => {
                            break Ok(PostAction::Continue);
                        }
                        Err(err) if err.kind() == ErrorKind::Interrupted => continue,
                        Err(_) => break Ok(PostAction::Remove),
                    }
                }
            },
        ) {
            log::error!("failed to register clipboard pipe: {error}");
        }
    }
}

fn read_received_text(fd: filedescriptor::FileDescriptor) -> Option<String> {
    let bytes = read_fd_with_timeout(fd, PIPE_READ_TIMEOUT).ok()?;
    String::from_utf8(bytes)
        .ok()
        .filter(|text| !text.is_empty())
}

#[cfg(test)]
mod text_read_tests {
    use super::*;
    use std::cell::RefCell;

    #[derive(Default)]
    struct Receiver {
        writer: RefCell<Option<File>>,
        mime: RefCell<Option<String>>,
    }
    impl ReceiveData for Receiver {
        fn receive_data(&self, mime_type: String, fd: BorrowedFd<'_>) {
            *self.writer.borrow_mut() =
                Some(File::from(fd.try_clone_to_owned().expect("duplicate pipe")));
            *self.mime.borrow_mut() = Some(mime_type);
        }
    }

    #[test]
    fn text_offer_prepares_without_waiting_for_data_and_preserves_unicode() {
        let mut offer = DataOffer::new(Receiver::default());
        offer.add_mime_type("image/png".into());
        offer.add_mime_type("text/plain".into());
        let fd = offer.receive_text().expect("text pipe");
        // No data exists yet. Preparation must return without reading the pipe.
        assert_eq!(offer.inner.mime.borrow().as_deref(), Some("text/plain"));
        let mut writer = offer.inner.writer.borrow_mut().take().expect("writer");
        drop(offer);
        let text = "日本語🙂e\u{301}\r\n".repeat(20_000);
        let bytes = text.clone().into_bytes();
        let sender = std::thread::spawn(move || writer.write_all(&bytes).expect("send text"));
        let reader = std::thread::spawn(move || read_received_text(fd));
        sender.join().expect("sender");
        assert_eq!(reader.join().expect("reader"), Some(text));
    }

    #[test]
    fn nontext_offers_and_invalid_or_empty_utf8_return_none() {
        let mut offer = DataOffer::new(Receiver::default());
        offer.add_mime_type("image/png".into());
        assert!(offer.receive_text().is_none());
        assert!(offer.inner.writer.borrow().is_none());
        for bytes in [vec![], vec![0xff]] {
            let pipe = Pipe::new().expect("pipe");
            let mut writer = pipe.write;
            writer.write_all(&bytes).expect("write");
            drop(writer);
            assert_eq!(read_received_text(pipe.read), None);
        }
    }
}