guido 0.6.0

A reactive Rust GUI library using wgpu for Wayland layer shell widgets
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
//! The two system selections: the clipboard and the primary selection.
//!
//! Both work the same way — an offer arrives, a reader thread pulls the
//! content through a pipe, and the result comes back on the calloop ingress
//! channel — so they are kept together and share one prefetch path.
//!
//! Reading a selection means blocking on a pipe until the owning application
//! answers, which is why it never happens on the UI thread. Generation
//! counters drop any result that a newer offer has already made stale.

use std::fs::File;
use std::io::{Read, Write};
use std::os::fd::OwnedFd;
use std::time::{Duration, Instant};

use smithay_client_toolkit::{
    data_device_manager::{
        DataDeviceManagerState, ReadPipe,
        data_device::{DataDevice, DataDeviceHandler},
        data_offer::DataOfferHandler,
        data_source::{CopyPasteSource, DataSourceHandler},
    },
    delegate_data_device, delegate_primary_selection,
    primary_selection::{
        PrimarySelectionManagerState,
        device::{PrimarySelectionDevice, PrimarySelectionDeviceHandler},
        selection::{PrimarySelectionSource, PrimarySelectionSourceHandler},
    },
};

use smithay_client_toolkit::reexports::client::{
    Connection, Proxy, QueueHandle,
    protocol::{
        wl_data_device::WlDataDevice, wl_data_device_manager::DndAction,
        wl_data_source::WlDataSource, wl_seat, wl_surface,
    },
};

use super::wayland::WaylandState;

/// Which system selection a prefetched content update belongs to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SelectionKind {
    /// The regular clipboard (Ctrl+C / Ctrl+V).
    Clipboard,
    /// The primary selection (select-to-copy / middle-click paste).
    Primary,
}

/// Everything the two selections own.
///
/// The managers are bound once at startup and are `None` on a compositor that
/// does not advertise the protocol — the feature then no-ops rather than
/// failing. The devices arrive later, with the seat.
pub struct Selections {
    pub(super) data_device_manager: Option<DataDeviceManagerState>,
    pub(super) data_device: Option<DataDevice>,
    pub(super) clipboard_content: Option<String>,
    pub(super) clipboard_source: Option<CopyPasteSource>,

    pub(super) primary_selection_manager: Option<PrimarySelectionManagerState>,
    pub(super) primary_selection_device: Option<PrimarySelectionDevice>,
    pub(super) primary_content: Option<String>,
    pub(super) primary_source: Option<PrimarySelectionSource>,

    /// Bumped on every new offer. A reader thread stamps its result with the
    /// generation it started from, and a result that no longer matches is
    /// dropped: the selection moved on while the pipe was still open.
    selection_generation: u64,
    primary_generation: u64,
}

impl Selections {
    pub(super) fn new(
        data_device_manager: Option<DataDeviceManagerState>,
        primary_selection_manager: Option<PrimarySelectionManagerState>,
    ) -> Self {
        Self {
            data_device_manager,
            data_device: None,
            clipboard_content: None,
            clipboard_source: None,
            primary_selection_manager,
            primary_selection_device: None,
            primary_content: None,
            primary_source: None,
            selection_generation: 0,
            primary_generation: 0,
        }
    }

    /// Apply a prefetched clipboard/primary content update. Reads made stale by
    /// a newer offer are dropped via the generation check.
    pub(super) fn apply(&self, kind: SelectionKind, generation: u64, content: Option<String>) {
        let current = match kind {
            SelectionKind::Clipboard => self.selection_generation,
            SelectionKind::Primary => self.primary_generation,
        };
        if generation != current {
            log::debug!("Dropping stale {kind:?} content (gen {generation} != {current})");
            return;
        }
        match kind {
            SelectionKind::Clipboard => match content {
                Some(text) => crate::reactive::set_system_clipboard(text),
                None => crate::reactive::clear_system_clipboard(),
            },
            SelectionKind::Primary => crate::reactive::set_system_primary(content),
        }
    }

    fn next_generation(&mut self, kind: SelectionKind) -> u64 {
        let generation = match kind {
            SelectionKind::Clipboard => &mut self.selection_generation,
            SelectionKind::Primary => &mut self.primary_generation,
        };
        *generation += 1;
        *generation
    }

    /// A selection with no content: cleared, or offered in nothing readable.
    pub(super) fn clear(&mut self, kind: SelectionKind) {
        let generation = self.next_generation(kind);
        self.apply(kind, generation, None);
    }

    /// A new offer for `kind`, read by `start_reader`, which is handed the
    /// offer's generation to stamp its result with and answers whether the read
    /// could start. One that could not is an offer with no content.
    pub(super) fn offer(
        &mut self,
        kind: SelectionKind,
        start_reader: impl FnOnce(u64) -> Result<(), String>,
    ) {
        let generation = self.next_generation(kind);
        if let Err(e) = start_reader(generation) {
            log::warn!("Selection prefetch skipped: {e}");
            self.apply(kind, generation, None);
        }
    }

    /// Bind both devices to a seat that just reported a keyboard.
    ///
    /// Selections hang off the seat, so they cannot be created at startup with
    /// the managers — they wait for the capability.
    pub(super) fn attach_devices(
        &mut self,
        qh: &QueueHandle<WaylandState>,
        seat: &wl_seat::WlSeat,
    ) {
        if self.data_device.is_none()
            && let Some(ref manager) = self.data_device_manager
        {
            log::info!("Creating data device for clipboard");
            self.data_device = Some(manager.get_data_device(qh, seat));
        }

        if self.primary_selection_device.is_none()
            && let Some(ref manager) = self.primary_selection_manager
        {
            log::info!("Creating primary selection device");
            self.primary_selection_device = Some(manager.get_selection_device(qh, seat));
        }
    }
}

impl WaylandState {
    /// Set clipboard content (copy)
    pub fn set_clipboard(&mut self, text: String) {
        let qh = &self.qh;
        if let Some(ref manager) = self.selections.data_device_manager {
            // Create a data source for the clipboard
            let source = manager.create_copy_paste_source(
                qh,
                vec!["text/plain;charset=utf-8", "UTF8_STRING", "TEXT", "STRING"],
            );

            // Store the text to write when compositor requests it
            self.selections.clipboard_content = Some(text);

            // Set selection using the keyboard serial
            if let Some(ref device) = self.selections.data_device {
                source.set_selection(device, self.input.keyboard_serial);
                self.selections.clipboard_source = Some(source);
            }
        }
    }

    /// Get clipboard content (paste)
    /// Returns the content if available, or None if clipboard is empty
    pub fn get_clipboard(&self) -> Option<String> {
        self.selections.clipboard_content.clone()
    }

    /// Set the primary selection content (select-to-copy).
    pub fn set_primary(&mut self, text: String) {
        let qh = &self.qh;
        let Some(ref manager) = self.selections.primary_selection_manager else {
            return;
        };
        let Some(ref device) = self.selections.primary_selection_device else {
            return;
        };

        let source = manager.create_selection_source(
            qh,
            vec!["text/plain;charset=utf-8", "UTF8_STRING", "TEXT", "STRING"],
        );
        self.selections.primary_content = Some(text);
        source.set_selection(device, self.input.latest_input_serial);
        self.selections.primary_source = Some(source);
    }

    /// Apply a prefetched clipboard/primary content update (from the loop's
    /// ingress channel callback).
    pub(crate) fn apply_clipboard_update(
        &mut self,
        kind: SelectionKind,
        generation: u64,
        content: Option<String>,
    ) {
        self.selections.apply(kind, generation, content);
    }

    /// Start an async prefetch of an offer's content on a reader thread.
    /// `receive` turns a chosen mime type into a read pipe. The result comes
    /// back through the calloop ingress channel — the message itself wakes
    /// the loop, no hand-rolled wakeup involved.
    fn prefetch_selection<R>(&mut self, kind: SelectionKind, mimes: Vec<String>, receive: R)
    where
        R: FnOnce(&str) -> Option<ReadPipe>,
    {
        // Preferred mime order; take the first one offered.
        const PREFERRED: [&str; 5] = [
            "text/plain;charset=utf-8",
            "UTF8_STRING",
            "text/plain",
            "TEXT",
            "STRING",
        ];
        let mime = PREFERRED
            .iter()
            .find(|m| mimes.iter().any(|t| t == *m))
            .copied();

        let Some(pipe) = mime.and_then(receive) else {
            self.selections.clear(kind);
            return;
        };
        self.selections.offer(kind, |generation| {
            // Bound to the loop that is running now, because the read below has
            // three seconds to finish and a loop that restarts in the meantime
            // starts its generation counters over: a result delivered into the
            // next session would pass the check in `Selections::apply` against a
            // matching generation that means something else.
            let sender = crate::ingress::sender_handle()
                .ok_or_else(|| "no event loop running".to_string())?;
            std::thread::Builder::new()
                .name("guido-clipboard-read".into())
                .spawn(move || {
                    let content = read_pipe_with_deadline(pipe, Duration::from_secs(3));
                    sender.send(crate::ingress::IngressMessage::ClipboardUpdate {
                        kind,
                        generation,
                        content,
                    });
                })
                .map(|_| ())
                .map_err(|e| format!("failed to spawn clipboard reader thread: {e}"))
        });
    }
}

/// Read a selection pipe to EOF with a total deadline. Runs on a reader
/// thread — never on the UI thread.
fn read_pipe_with_deadline(pipe: ReadPipe, deadline: Duration) -> Option<String> {
    use std::os::unix::io::AsRawFd;

    let fd = OwnedFd::from(pipe);
    let mut file = File::from(fd);
    let raw_fd = file.as_raw_fd();
    let mut buf = Vec::new();
    let end = Instant::now() + deadline;

    loop {
        let remaining = end.saturating_duration_since(Instant::now());
        if remaining.is_zero() {
            log::warn!("Clipboard read timed out after {:?}", deadline);
            return None;
        }

        let mut poll_fd = libc::pollfd {
            fd: raw_fd,
            events: libc::POLLIN,
            revents: 0,
        };
        let timeout_ms = remaining.as_millis().min(i32::MAX as u128) as i32;
        let ret = unsafe { libc::poll(&mut poll_fd, 1, timeout_ms) };
        if ret < 0 {
            let err = std::io::Error::last_os_error();
            if err.kind() == std::io::ErrorKind::Interrupted {
                continue;
            }
            log::warn!("Clipboard read poll failed: {err}");
            return None;
        }
        if ret == 0 {
            log::warn!("Clipboard read timed out after {:?}", deadline);
            return None;
        }

        // POLLIN or POLLHUP: data available or writer closed — read either way
        let mut chunk = [0u8; 8192];
        match file.read(&mut chunk) {
            Ok(0) => break, // EOF
            Ok(n) => buf.extend_from_slice(&chunk[..n]),
            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
            Err(e) => {
                log::warn!("Clipboard read failed: {e}");
                return None;
            }
        }
    }

    let text = String::from_utf8_lossy(&buf).into_owned();
    (!text.is_empty()).then_some(text)
}

impl DataDeviceHandler for WaylandState {
    fn enter(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _data_device: &WlDataDevice,
        _x: f64,
        _y: f64,
        _surface: &wl_surface::WlSurface,
    ) {
        // Drag and drop enter - not used for clipboard
    }

    fn leave(&mut self, _conn: &Connection, _qh: &QueueHandle<Self>, _data_device: &WlDataDevice) {
        // Drag and drop leave - not used for clipboard
    }

    fn motion(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _data_device: &WlDataDevice,
        _x: f64,
        _y: f64,
    ) {
        // Drag and drop motion - not used for clipboard
    }

    fn drop_performed(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _data_device: &WlDataDevice,
    ) {
        // Drag and drop performed - not used for clipboard
    }

    fn selection(
        &mut self,
        conn: &Connection,
        _qh: &QueueHandle<Self>,
        _data_device: &WlDataDevice,
    ) {
        log::debug!("Clipboard selection changed");
        // Prefetch the new selection's content on a reader thread so paste
        // is instant and never blocks the UI thread.
        let offer = self
            .selections
            .data_device
            .as_ref()
            .and_then(|device| device.data().selection_offer());
        match offer {
            None => {
                // Selection cleared — main thread, apply directly.
                self.selections.clear(SelectionKind::Clipboard);
            }
            Some(offer) => {
                let mimes = offer.with_mime_types(|t| t.to_vec());
                self.prefetch_selection(SelectionKind::Clipboard, mimes, |mime| {
                    offer
                        .receive(mime.to_string())
                        .map_err(|e| log::debug!("Failed to receive clipboard as {mime}: {e:?}"))
                        .ok()
                });
                // Send the receive request out now so the source app starts
                // writing before the next loop-iteration flush.
                let _ = conn.flush();
            }
        }
    }
}

impl PrimarySelectionDeviceHandler for WaylandState {
    fn selection(
        &mut self,
        conn: &Connection,
        _qh: &QueueHandle<Self>,
        device: &smithay_client_toolkit::reexports::protocols::wp::primary_selection::zv1::client::zwp_primary_selection_device_v1::ZwpPrimarySelectionDeviceV1,
    ) {
        log::debug!("Primary selection changed");
        let offer = device
            .data::<smithay_client_toolkit::primary_selection::device::PrimarySelectionDeviceData>()
            .and_then(|data| data.selection_offer());
        match offer {
            None => {
                // Primary selection cleared — main thread, apply directly.
                self.selections.clear(SelectionKind::Primary);
            }
            Some(offer) => {
                let mimes = offer.with_mime_types(|t| t.to_vec());
                self.prefetch_selection(SelectionKind::Primary, mimes, |mime| {
                    offer
                        .receive(mime.to_string())
                        .map_err(|e| log::debug!("Failed to receive primary as {mime}: {e:?}"))
                        .ok()
                });
                let _ = conn.flush();
            }
        }
    }
}

impl PrimarySelectionSourceHandler for WaylandState {
    fn send_request(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _source: &smithay_client_toolkit::reexports::protocols::wp::primary_selection::zv1::client::zwp_primary_selection_source_v1::ZwpPrimarySelectionSourceV1,
        mime: String,
        write_pipe: smithay_client_toolkit::data_device_manager::WritePipe,
    ) {
        log::debug!("Primary selection send request for mime type: {mime}");
        if let Some(ref content) = self.selections.primary_content {
            let content = content.clone();
            let owned_fd = OwnedFd::from(write_pipe);
            if let Err(e) = std::thread::Builder::new()
                .name("guido-primary-send".into())
                .spawn(move || {
                    let mut file = File::from(owned_fd);
                    if let Err(e) = file.write_all(content.as_bytes()) {
                        log::warn!("Failed to write primary selection content: {e}");
                    }
                })
            {
                log::warn!("Failed to spawn primary selection writer thread: {e}");
            }
        }
    }

    fn cancelled(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _source: &smithay_client_toolkit::reexports::protocols::wp::primary_selection::zv1::client::zwp_primary_selection_source_v1::ZwpPrimarySelectionSourceV1,
    ) {
        log::debug!("Primary selection source cancelled");
        self.selections.primary_source = None;
    }
}

impl DataOfferHandler for WaylandState {
    fn source_actions(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _offer: &mut smithay_client_toolkit::data_device_manager::data_offer::DragOffer,
        _actions: DndAction,
    ) {
        // Drag and drop actions - not used for clipboard
    }

    fn selected_action(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _offer: &mut smithay_client_toolkit::data_device_manager::data_offer::DragOffer,
        _action: DndAction,
    ) {
        // Drag and drop selected action - not used for clipboard
    }
}

impl DataSourceHandler for WaylandState {
    fn accept_mime(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _source: &WlDataSource,
        _mime: Option<String>,
    ) {
        // Mime type accepted notification
    }

    fn send_request(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _source: &WlDataSource,
        mime: String,
        fd: smithay_client_toolkit::data_device_manager::WritePipe,
    ) {
        log::debug!("Clipboard send request for mime type: {}", mime);

        // Write clipboard content on a short-lived thread: a payload larger
        // than the pipe buffer with a slow reader would otherwise block the
        // UI thread indefinitely inside write_all.
        if let Some(ref content) = self.selections.clipboard_content {
            let content = content.clone();
            let owned_fd = OwnedFd::from(fd);
            if let Err(e) = std::thread::Builder::new()
                .name("guido-clipboard-send".into())
                .spawn(move || {
                    let mut file = File::from(owned_fd);
                    if let Err(e) = file.write_all(content.as_bytes()) {
                        log::warn!("Failed to write clipboard content: {}", e);
                    }
                })
            {
                log::warn!("Failed to spawn clipboard writer thread: {e}");
            }
        }
    }

    fn cancelled(&mut self, _conn: &Connection, _qh: &QueueHandle<Self>, _source: &WlDataSource) {
        log::debug!("Clipboard source cancelled");
        self.selections.clipboard_source = None;
    }

    fn dnd_dropped(&mut self, _conn: &Connection, _qh: &QueueHandle<Self>, _source: &WlDataSource) {
        // Drag and drop completed - not used for clipboard
    }

    fn dnd_finished(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _source: &WlDataSource,
    ) {
        // Drag and drop finished - not used for clipboard
    }

    fn action(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _source: &WlDataSource,
        _action: DndAction,
    ) {
        // Action notification - not used for clipboard
    }
}

delegate_data_device!(WaylandState);
delegate_primary_selection!(WaylandState);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::reactive::{
        clipboard_paste, primary_paste, set_system_clipboard, set_system_primary,
    };

    /// An offer whose read cannot start — no event loop to deliver to, no thread
    /// to read on — has no content, as one with nothing readable does.
    #[test]
    fn an_offer_whose_read_cannot_start_leaves_nothing_to_paste() {
        let mut selections = Selections::new(None, None);

        set_system_clipboard("copied two selections ago".into());
        selections.offer(SelectionKind::Clipboard, |_| {
            Err("failed to spawn clipboard reader thread".into())
        });
        assert_eq!(clipboard_paste(), None);

        set_system_primary(Some("selected two selections ago".into()));
        selections.offer(SelectionKind::Primary, |_| {
            Err("no event loop running".into())
        });
        assert_eq!(
            primary_paste(),
            None,
            "and the middle click has the same hole"
        );
    }

    /// A reader that did start is left to deliver: the text is replaced when its
    /// result arrives, not before.
    #[test]
    fn an_offer_being_read_keeps_the_text_until_the_read_lands() {
        let mut selections = Selections::new(None, None);
        set_system_clipboard("the last owner's".into());

        let mut started = None;
        selections.offer(SelectionKind::Clipboard, |generation| {
            started = Some(generation);
            Ok(())
        });
        assert_eq!(clipboard_paste().as_deref(), Some("the last owner's"));

        selections.apply(
            SelectionKind::Clipboard,
            started.unwrap(),
            Some("this one's".into()),
        );
        assert_eq!(clipboard_paste().as_deref(), Some("this one's"));
    }

    /// A read that lands after a newer offer is dropped: the slow pipe of the
    /// last owner does not get to overwrite the one that replaced it.
    #[test]
    fn a_read_overtaken_by_a_newer_offer_is_dropped() {
        let mut selections = Selections::new(None, None);

        let mut first = None;
        selections.offer(SelectionKind::Clipboard, |generation| {
            first = Some(generation);
            Ok(())
        });
        let mut second = None;
        selections.offer(SelectionKind::Clipboard, |generation| {
            second = Some(generation);
            Ok(())
        });

        selections.apply(
            SelectionKind::Clipboard,
            second.unwrap(),
            Some("newer".into()),
        );
        selections.apply(
            SelectionKind::Clipboard,
            first.unwrap(),
            Some("older".into()),
        );
        assert_eq!(clipboard_paste().as_deref(), Some("newer"));
    }
}