egui-winit 0.37.0

Bindings for using egui with winit
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
use raw_window_handle::RawDisplayHandle;

/// Handles interfacing with the OS clipboard.
///
/// If the "clipboard" feature is off, or we cannot connect to the OS clipboard,
/// then a fallback clipboard that just works within the same app is used instead.
pub struct Clipboard {
    #[cfg(all(
        not(any(target_os = "android", target_os = "ios")),
        feature = "arboard",
    ))]
    arboard: Option<arboard::Clipboard>,

    #[cfg(all(
        any(
            target_os = "linux",
            target_os = "dragonfly",
            target_os = "freebsd",
            target_os = "netbsd",
            target_os = "openbsd"
        ),
        feature = "smithay-clipboard"
    ))]
    smithay: Option<smithay_clipboard::Clipboard>,

    /// Fallback manual clipboard.
    clipboard: String,
}

impl Clipboard {
    /// Construct a new instance.
    ///
    /// # Safety
    ///
    /// If `raw_display_handle` is `Some`, the display handle must remain valid for the
    /// entire lifetime of the returned `Clipboard` instance.
    #[expect(unsafe_code)]
    pub unsafe fn new(_raw_display_handle: Option<RawDisplayHandle>) -> Self {
        Self {
            #[cfg(all(
                not(any(target_os = "android", target_os = "ios")),
                feature = "arboard",
            ))]
            arboard: init_arboard(),

            #[cfg(all(
                any(
                    target_os = "linux",
                    target_os = "dragonfly",
                    target_os = "freebsd",
                    target_os = "netbsd",
                    target_os = "openbsd"
                ),
                feature = "smithay-clipboard"
            ))]
            // SAFETY: The caller guarantees that the display handle remains valid.
            smithay: unsafe { init_smithay_clipboard(_raw_display_handle) },

            clipboard: Default::default(),
        }
    }

    #[cfg_attr(
        not(feature = "clipboard"),
        expect(clippy::needless_pass_by_ref_mut, clippy::unnecessary_wraps)
    )]
    pub fn get(&mut self) -> Option<String> {
        #[cfg(all(
            any(
                target_os = "linux",
                target_os = "dragonfly",
                target_os = "freebsd",
                target_os = "netbsd",
                target_os = "openbsd"
            ),
            feature = "smithay-clipboard"
        ))]
        if let Some(clipboard) = &mut self.smithay {
            match clipboard.load() {
                Ok(text) => return Some(text),
                // Smithay uses NotFound when no supported text MIME type is offered.
                Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
                Err(err) => {
                    // Not fatal: we fall back to arboard below.
                    log::debug!("smithay paste error: {err}");
                }
            }
        }

        #[cfg(all(
            not(any(target_os = "android", target_os = "ios")),
            feature = "arboard",
        ))]
        if let Some(clipboard) = &mut self.arboard {
            return match clipboard.get_text() {
                Ok(text) => Some(text),
                Err(err) => {
                    // Expected whenever the clipboard holds something other than text (e.g.
                    // an image copied with a screenshot tool) — the caller falls back to
                    // `Self::get_image` in that case, so this is not an error worth
                    // alarming the user/log about.
                    if !is_expected_content_absence(&err) {
                        log::error!("arboard paste error: {err}");
                    }
                    None
                }
            };
        }

        Some(self.clipboard.clone())
    }

    pub fn set_text(&mut self, text: String) {
        #[cfg(all(
            any(
                target_os = "linux",
                target_os = "dragonfly",
                target_os = "freebsd",
                target_os = "netbsd",
                target_os = "openbsd"
            ),
            feature = "smithay-clipboard"
        ))]
        if let Some(clipboard) = &mut self.smithay {
            clipboard.store(text);
            return;
        }

        #[cfg(all(
            not(any(target_os = "android", target_os = "ios")),
            feature = "arboard",
        ))]
        if let Some(clipboard) = &mut self.arboard {
            if let Err(err) = clipboard.set_text(text) {
                log::error!("arboard copy/cut error: {err}");
            }
            return;
        }

        self.clipboard = text;
    }

    /// Get an image from the clipboard, if there is one and the platform backend supports it.
    ///
    /// This mirrors [`Self::set_image`] for the opposite direction, so that a Ctrl+V/Cmd+V
    /// paste can carry an image (e.g. a screenshot or a copied image) instead of text — see
    /// [`egui::Event::PasteImage`].
    #[cfg_attr(
        not(feature = "clipboard"),
        expect(clippy::needless_pass_by_ref_mut, clippy::unused_self)
    )]
    pub fn get_image(&mut self) -> Option<egui::ColorImage> {
        #[cfg(all(
            not(any(target_os = "android", target_os = "ios")),
            feature = "arboard",
        ))]
        if let Some(clipboard) = &mut self.arboard {
            return match clipboard.get_image() {
                Ok(image) => Some(color_image_from_arboard(&image)),
                Err(err) => {
                    // Expected whenever the clipboard holds neither text nor an image (e.g.
                    // it's simply empty) — `Self::get` was already tried first and came up
                    // empty too, so this is the mundane "nothing to paste" case, not an error.
                    if !is_expected_content_absence(&err) {
                        log::error!("arboard paste-image error: {err}");
                    }
                    None
                }
            };
        }

        None
    }

    #[cfg_attr(
        not(feature = "clipboard"),
        expect(clippy::needless_pass_by_ref_mut, clippy::unused_self)
    )]
    pub fn set_image(&mut self, image: &egui::ColorImage) {
        #[cfg(all(
            not(any(target_os = "android", target_os = "ios")),
            feature = "arboard",
        ))]
        if let Some(clipboard) = &mut self.arboard {
            if let Err(err) = clipboard.set_image(arboard_from_color_image(image)) {
                log::error!("arboard copy/cut error: {err}");
            }
            log::debug!("Copied image to clipboard");
            return;
        }

        log::error!(
            "Copying images is not supported. Enable the 'clipboard' feature of `egui-winit` to enable it."
        );
        _ = image;
    }
}

// The X11/Wayland PRIMARY selection: filled in by selecting text, pasted with the middle mouse button.
cfg_select! {
    any(
        target_os = "linux",
        target_os = "dragonfly",
        target_os = "freebsd",
        target_os = "netbsd",
        target_os = "openbsd"
    ) => {
        #[cfg_attr(
            not(any(feature = "arboard", feature = "smithay-clipboard")),
            expect(
                clippy::unused_self,
                clippy::needless_pass_by_ref_mut,
                clippy::needless_pass_by_value,
                reason = "no backend to use"
            )
        )]
        impl Clipboard {
            /// Read the PRIMARY selection, if there is one.
            pub fn get_primary_text(&mut self) -> Option<String> {
                #[cfg(feature = "smithay-clipboard")]
                if let Some(clipboard) = &mut self.smithay {
                    return clipboard
                        .load_primary()
                        .inspect_err(|err| log::debug!("smithay primary paste error: {err}"))
                        .ok();
                }

                #[cfg(feature = "arboard")]
                if let Some(clipboard) = &mut self.arboard {
                    use arboard::GetExtLinux as _;
                    return clipboard
                        .get()
                        .clipboard(arboard::LinuxClipboardKind::Primary)
                        .text()
                        .inspect_err(|err| log::debug!("arboard primary paste error: {err}"))
                        .ok();
                }

                None
            }

            /// Set the PRIMARY selection.
            pub fn set_primary_text(&mut self, text: String) {
                #[cfg(feature = "smithay-clipboard")]
                if let Some(clipboard) = &mut self.smithay {
                    clipboard.store_primary(text);
                    return;
                }

                #[cfg(feature = "arboard")]
                if let Some(clipboard) = &mut self.arboard {
                    use arboard::SetExtLinux as _;
                    if let Err(err) = clipboard
                        .set()
                        .clipboard(arboard::LinuxClipboardKind::Primary)
                        .text(text)
                    {
                        log::error!("arboard primary copy error: {err}");
                    }
                    return;
                }

                _ = text;
            }
        }
    }
    _ => {
        #[expect(
            clippy::unused_self,
            clippy::needless_pass_by_ref_mut,
            reason = "there is no PRIMARY selection on this platform"
        )]
        impl Clipboard {
            /// Read the PRIMARY selection. Always `None` on this platform.
            pub fn get_primary_text(&mut self) -> Option<String> {
                None
            }

            /// Set the PRIMARY selection. Does nothing on this platform.
            pub fn set_primary_text(&mut self, _text: String) {}
        }
    }
}

/// Whether an `arboard::Error` from reading the clipboard is the expected, mundane outcome
/// of the clipboard simply not holding the requested content type (e.g. text was asked for
/// but the clipboard holds an image, or vice versa, or it's just empty) — as opposed to a
/// genuine failure (permissions, a locked clipboard, a conversion error) worth an `error!` log.
///
/// Pulled out as its own pure function (rather than inlined in the two `match`es above) so it
/// can be unit-tested without touching the real OS clipboard, which CI can't rely on.
#[cfg(all(
    not(any(target_os = "android", target_os = "ios")),
    feature = "arboard",
))]
fn is_expected_content_absence(err: &arboard::Error) -> bool {
    matches!(err, arboard::Error::ContentNotAvailable)
}

#[cfg(all(
    not(any(target_os = "android", target_os = "ios")),
    feature = "arboard",
))]
fn color_image_from_arboard(image: &arboard::ImageData<'_>) -> egui::ColorImage {
    egui::ColorImage::from_rgba_unmultiplied([image.width, image.height], &image.bytes)
}

/// arboard expects unmultiplied alpha, but [`egui::Color32`] is premultiplied.
#[cfg(all(
    not(any(target_os = "android", target_os = "ios")),
    feature = "arboard",
))]
fn arboard_from_color_image(image: &egui::ColorImage) -> arboard::ImageData<'static> {
    let bytes: Vec<u8> = image
        .pixels
        .iter()
        .flat_map(|color| color.to_srgba_unmultiplied())
        .collect();
    arboard::ImageData {
        width: image.width(),
        height: image.height(),
        bytes: bytes.into(),
    }
}

#[cfg(all(
    not(any(target_os = "android", target_os = "ios")),
    feature = "arboard",
))]
fn init_arboard() -> Option<arboard::Clipboard> {
    profiling::function_scope!();

    log::trace!("Initializing arboard clipboard…");
    match arboard::Clipboard::new() {
        Ok(clipboard) => Some(clipboard),
        Err(err) => {
            log::warn!("Failed to initialize arboard clipboard: {err}");
            None
        }
    }
}

/// # Safety
///
/// The display handle in `raw_display_handle` must remain valid for the
/// lifetime of the returned `Clipboard`.
#[cfg(all(
    any(
        target_os = "linux",
        target_os = "dragonfly",
        target_os = "freebsd",
        target_os = "netbsd",
        target_os = "openbsd"
    ),
    feature = "smithay-clipboard"
))]
#[expect(unsafe_code)]
unsafe fn init_smithay_clipboard(
    raw_display_handle: Option<RawDisplayHandle>,
) -> Option<smithay_clipboard::Clipboard> {
    profiling::function_scope!();

    if let Some(RawDisplayHandle::Wayland(display)) = raw_display_handle {
        log::trace!("Initializing smithay clipboard…");
        // SAFETY: The caller guarantees that the display handle remains valid.
        Some(unsafe { smithay_clipboard::Clipboard::new(display.display.as_ptr()) })
    } else {
        #[cfg(feature = "wayland")]
        log::debug!("Cannot init smithay clipboard without a Wayland display handle");
        #[cfg(not(feature = "wayland"))]
        log::debug!(
            "Cannot init smithay clipboard: the 'wayland' feature of 'egui-winit' is not enabled"
        );
        None
    }
}

#[cfg(all(
    not(any(target_os = "android", target_os = "ios")),
    feature = "arboard",
))]
#[cfg(test)]
mod tests {
    use super::{arboard_from_color_image, color_image_from_arboard, is_expected_content_absence};

    /// Regression test for the spurious `error!`-level log a maintainer caught by manually
    /// testing an image paste (nothing had exercised this distinction before): only
    /// `ContentNotAvailable` — clipboard simply doesn't hold the requested content type — is
    /// expected and should stay silent; every other `arboard::Error` variant is a real failure
    /// and must still be logged.
    #[test]
    fn only_content_not_available_is_treated_as_expected() {
        assert!(is_expected_content_absence(
            &arboard::Error::ContentNotAvailable
        ));

        assert!(!is_expected_content_absence(
            &arboard::Error::ClipboardNotSupported
        ));
        assert!(!is_expected_content_absence(
            &arboard::Error::ClipboardOccupied
        ));
        assert!(!is_expected_content_absence(
            &arboard::Error::ConversionFailure
        ));
        assert!(!is_expected_content_absence(&arboard::Error::Unknown {
            description: "anything".to_owned(),
        }));
    }

    #[test]
    fn color_image_from_arboard_converts_straight_to_premultiplied_alpha() {
        // 2x1 image: opaque red, then half-transparent white — straight (unmultiplied) alpha,
        // as arboard/the OS clipboard would hand it to us.
        let image = arboard::ImageData {
            width: 2,
            height: 1,
            bytes: std::borrow::Cow::Borrowed(&[255, 0, 0, 255, 255, 255, 255, 128]),
        };
        let color_image = color_image_from_arboard(&image);
        assert_eq!(color_image.size, [2, 1]);
        assert_eq!(
            color_image.pixels[0],
            egui::Color32::from_rgba_unmultiplied(255, 0, 0, 255)
        );
        assert_eq!(
            color_image.pixels[1],
            egui::Color32::from_rgba_unmultiplied(255, 255, 255, 128)
        );
    }

    #[test]
    fn arboard_from_color_image_converts_premultiplied_to_straight_alpha() {
        let color_image = egui::ColorImage::new(
            [3, 1],
            vec![
                egui::Color32::from_rgba_unmultiplied(255, 0, 0, 255),
                egui::Color32::from_rgba_unmultiplied(255, 255, 255, 128),
                egui::Color32::TRANSPARENT,
            ],
        );
        let image = arboard_from_color_image(&color_image);
        assert_eq!([image.width, image.height], [3, 1]);
        assert_eq!(
            &*image.bytes,
            &[255, 0, 0, 255, 255, 255, 255, 128, 0, 0, 0, 0]
        );
    }
}