Skip to main content

egui_pop_platform/
clipboard.rs

1//! The system clipboard over arboard (feature `clipboard`): the
2//! clipboard's [`SystemBackend`] for files, images, HTML and text, and
3//! the primary selection on X11 and Wayland.
4//!
5//! <div class="warning">Experimental: may change in any release
6//! (docs/stability.md).</div>
7//!
8//! egui-pop's default backend writes text through egui and reads
9//! nothing. [`SystemClipboardPlugin`] installs [`Arboard`] instead
10//! (`egui_pop_api::clipboard::set_backend`): a copy writes its richest
11//! standard representation, a paste reads every format the clipboard
12//! holds as one external item, and the paste key works when the
13//! clipboard holds no text (a file manager's files, a browser's image).
14//!
15//! | | Writes (one per copy, the first it has) | Reads |
16//! |---|---|---|
17//! | files | `text/uri-list` (`file://` URIs) | yes |
18//! | an image | `image/png` | yes |
19//! | HTML | `text/html`, with the text as its alternative | yes |
20//! | text | `text/plain` | yes |
21//!
22//! arboard writes one format per copy (HTML takes its text along):
23//! files win over an image, an image over HTML, HTML over text. Private
24//! types stay in the owner; a kernel wanting them on the system
25//! clipboard gives its own backend (`Clipboard::system`).
26//!
27//! **The platform's path** ([`Arboard::path`], in the `clipboard`
28//! collector):
29//!
30//! - Windows (the Win32 clipboard), macOS (`NSPasteboard`) and X11
31//!   (selections, through x11rb) as arboard reaches them.
32//! - Wayland: through XWayland by default. A copy then reaches native
33//!   Wayland applications only when the compositor hands XWayland's
34//!   selection over, which some do only while an X11 window has the
35//!   focus. The `clipboard-wayland` feature adds the data-control
36//!   protocol (arboard's `wayland-data-control`, through wl-clipboard-rs):
37//!   used where the compositor offers it (wlroots compositors, KDE
38//!   Plasma), XWayland elsewhere. The core protocol, which needs the
39//!   window's input serial, is what egui-winit's own text clipboard
40//!   uses (smithay-clipboard); arboard does not.
41//! - The web: nothing (the module is not built for `wasm32`).
42//!
43//! **The primary selection** (select to copy, middle-click to paste) is
44//! read and written on X11 and Wayland (`clipboard::primary_text`,
45//! `clipboard::set_primary_text`); elsewhere there is none. egui-pop's
46//! own widgets do not use it yet (ADR 0015: opt-in, for text inputs and
47//! the code editor).
48//!
49//! The clipboard is opened on first use, not when the plugin connects,
50//! so connecting it touches nothing (tests, catalogues).
51//!
52//! ```
53//! use egui_pop_platform::clipboard::{file_uris, paths_of};
54//!
55//! let list = file_uris(&[std::path::PathBuf::from("/tmp/a b.png")]);
56//! assert_eq!(list, "file:///tmp/a%20b.png");
57//! assert_eq!(paths_of(&list), [std::path::PathBuf::from("/tmp/a b.png")]);
58//! ```
59
60use std::borrow::Cow;
61use std::path::{Path, PathBuf};
62
63use base64::Engine as _;
64use egui_pop_api::clipboard::{self, FormatId, HTML, PNG, Repr, SystemBackend, TEXT, URI_LIST};
65use egui_pop_api::{Ctx, Plugin, PluginError};
66use egui_pop_model::ids::PluginId;
67use serde_json::{Value as Json, json};
68
69/// The plugin's id: with it added, `run_native` turns eframe's clipboard
70/// shortcuts off and the keymap runs the copy, cut and paste chords, in
71/// text fields too (`egui_pop_api::clipboard::set_keymap_shortcuts`).
72pub const PLUGIN: PluginId = clipboard::SYSTEM_PLUGIN;
73
74/// The formats [`Arboard`] writes and reads, richest first.
75const FORMATS: [FormatId; 4] = [URI_LIST, PNG, HTML, TEXT];
76
77/// The system clipboard through arboard, opened on first use.
78#[derive(Default)]
79pub struct Arboard {
80    clipboard: Option<arboard::Clipboard>,
81    /// Why it could not be opened, once tried.
82    failed: Option<String>,
83}
84
85impl std::fmt::Debug for Arboard {
86    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87        f.debug_struct("Arboard")
88            .field("open", &self.clipboard.is_some())
89            .field("failed", &self.failed)
90            .finish()
91    }
92}
93
94impl Arboard {
95    pub fn new() -> Self {
96        Self::default()
97    }
98
99    /// The clipboard, opened on first use (one attempt).
100    fn open(&mut self) -> Result<&mut arboard::Clipboard, String> {
101        if self.clipboard.is_none() && self.failed.is_none() {
102            match arboard::Clipboard::new() {
103                Ok(c) => self.clipboard = Some(c),
104                Err(e) => {
105                    log::warn!("the system clipboard could not be opened: {e}");
106                    self.failed = Some(e.to_string());
107                }
108            }
109        }
110        match (&mut self.clipboard, &self.failed) {
111            (Some(c), _) => Ok(c),
112            (None, Some(e)) => Err(format!("the system clipboard could not be opened: {e}")),
113            (None, None) => Err("the system clipboard is not open".into()),
114        }
115    }
116
117    /// The way it reaches the system clipboard on this platform and
118    /// session.
119    pub fn path() -> &'static str {
120        if cfg!(target_os = "windows") {
121            "win32"
122        } else if cfg!(target_os = "macos") {
123            "nspasteboard"
124        } else if std::env::var_os("WAYLAND_DISPLAY").is_some() {
125            if cfg!(feature = "clipboard-wayland") {
126                "wayland: data-control where the compositor offers it, else xwayland"
127            } else {
128                "wayland: xwayland"
129            }
130        } else {
131            "x11"
132        }
133    }
134}
135
136impl SystemBackend for Arboard {
137    fn name(&self) -> String {
138        "arboard".into()
139    }
140
141    fn writes(&self, format: &FormatId) -> bool {
142        FORMATS.contains(format)
143    }
144
145    fn write(&mut self, _ctx: &egui::Context, reprs: &[Repr]) -> Result<(), String> {
146        let find = |f: &FormatId| reprs.iter().find(|r| r.format == *f);
147        let text = find(&TEXT).and_then(Repr::text).map(str::to_string);
148        let cb = self.open()?;
149        let files = find(&URI_LIST)
150            .and_then(Repr::text)
151            .map(paths_of)
152            .unwrap_or_default();
153        let done = if !files.is_empty() {
154            cb.set().file_list(&files)
155        } else if let Some(png) = find(&PNG).and_then(Repr::text) {
156            let (width, height, rgba) = decode_png(png)?;
157            cb.set().image(arboard::ImageData {
158                width,
159                height,
160                bytes: Cow::Owned(rgba),
161            })
162        } else if let Some(html) = find(&HTML).and_then(Repr::text) {
163            cb.set().html(html.to_string(), text)
164        } else if let Some(text) = text {
165            cb.set().text(text)
166        } else {
167            return Ok(());
168        };
169        done.map_err(|e| e.to_string())
170    }
171
172    fn read(&mut self, _ctx: &egui::Context) -> Option<Vec<Repr>> {
173        let cb = self.open().ok()?;
174        let mut out = Vec::new();
175        if let Ok(files) = cb.get().file_list()
176            && !files.is_empty()
177        {
178            out.push(Repr::new(URI_LIST, Json::String(file_uris(&files))));
179        }
180        if let Ok(image) = cb.get().image() {
181            match encode_png(&image) {
182                Ok(png) => out.push(Repr::new(PNG, Json::String(png))),
183                Err(e) => log::warn!("the clipboard's image was not read: {e}"),
184            }
185        }
186        if let Ok(html) = cb.get().html()
187            && !html.is_empty()
188        {
189            out.push(Repr::new(HTML, Json::String(html)));
190        }
191        if let Ok(text) = cb.get().text()
192            && !text.is_empty()
193        {
194            out.push(Repr::new(TEXT, Json::String(text.replace("\r\n", "\n"))));
195        }
196        Some(out)
197    }
198
199    fn readable(&self) -> Vec<FormatId> {
200        vec![URI_LIST, PNG, HTML]
201    }
202
203    fn read_primary(&mut self) -> Option<String> {
204        #[cfg(all(
205            unix,
206            not(any(target_os = "macos", target_os = "android", target_os = "emscripten"))
207        ))]
208        {
209            use arboard::{GetExtLinux as _, LinuxClipboardKind};
210            let cb = self.open().ok()?;
211            cb.get().clipboard(LinuxClipboardKind::Primary).text().ok()
212        }
213        #[cfg(not(all(
214            unix,
215            not(any(target_os = "macos", target_os = "android", target_os = "emscripten"))
216        )))]
217        {
218            None
219        }
220    }
221
222    fn write_primary(&mut self, text: &str) -> Result<(), String> {
223        #[cfg(all(
224            unix,
225            not(any(target_os = "macos", target_os = "android", target_os = "emscripten"))
226        ))]
227        {
228            use arboard::{LinuxClipboardKind, SetExtLinux as _};
229            let cb = self.open()?;
230            cb.set()
231                .clipboard(LinuxClipboardKind::Primary)
232                .text(text.to_string())
233                .map_err(|e| e.to_string())
234        }
235        #[cfg(not(all(
236            unix,
237            not(any(target_os = "macos", target_os = "android", target_os = "emscripten"))
238        )))]
239        {
240            let _ = text;
241            Err("this platform has no primary selection".into())
242        }
243    }
244
245    fn describe(&self) -> Json {
246        json!({
247            "path": Self::path(),
248            "writes": "one per copy: files, else an image, else HTML with its text, else text",
249            "reads": FORMATS,
250            "primary": cfg!(all(
251                unix,
252                not(any(target_os = "macos", target_os = "android", target_os = "emscripten"))
253            )),
254            "failed": self.failed,
255        })
256    }
257}
258
259/// Files as a URI list: one `file://` URI per line, CRLF between, each
260/// byte outside the unreserved set and `/` percent-encoded.
261pub fn file_uris(paths: &[PathBuf]) -> String {
262    paths
263        .iter()
264        .map(|p| file_uri(p))
265        .collect::<Vec<_>>()
266        .join("\r\n")
267}
268
269fn file_uri(path: &Path) -> String {
270    let text = path.to_string_lossy().replace('\\', "/");
271    let mut out = String::from("file://");
272    if !text.starts_with('/') {
273        // A Windows path: `file:///C:/dir`.
274        out.push('/');
275    }
276    for b in text.bytes() {
277        if b.is_ascii_alphanumeric() || b"-._~/:".contains(&b) {
278            out.push(char::from(b));
279        } else {
280            out.push_str(&format!("%{b:02X}"));
281        }
282    }
283    out
284}
285
286/// The local files of a URI list (`file://` URIs; comments, other
287/// schemes and other hosts left out).
288pub fn paths_of(list: &str) -> Vec<PathBuf> {
289    list.lines()
290        .map(str::trim)
291        .filter(|l| !l.is_empty() && !l.starts_with('#'))
292        .filter_map(|l| {
293            let rest = l.strip_prefix("file://")?;
294            let rest = rest.strip_prefix("localhost").unwrap_or(rest);
295            if !rest.starts_with('/') {
296                return None;
297            }
298            let bytes = percent_decode(rest);
299            let text = String::from_utf8(bytes).ok()?;
300            // `/C:/dir` is a Windows path.
301            let b = text.as_bytes();
302            let text = if b.len() > 2 && b[2] == b':' && b[1].is_ascii_alphabetic() {
303                text[1..].to_string()
304            } else {
305                text
306            };
307            Some(PathBuf::from(text))
308        })
309        .collect()
310}
311
312fn percent_decode(text: &str) -> Vec<u8> {
313    let b = text.as_bytes();
314    let mut out = Vec::with_capacity(b.len());
315    let mut i = 0;
316    while i < b.len() {
317        let hex = |c: u8| char::from(c).to_digit(16);
318        if b[i] == b'%'
319            && i + 2 < b.len()
320            && let (Some(h), Some(l)) = (hex(b[i + 1]), hex(b[i + 2]))
321        {
322            out.push((h * 16 + l) as u8);
323            i += 3;
324        } else {
325            out.push(b[i]);
326            i += 1;
327        }
328    }
329    out
330}
331
332/// An image as a PNG file in standard base64.
333fn encode_png(image: &arboard::ImageData<'_>) -> Result<String, String> {
334    let width = u32::try_from(image.width).map_err(|e| e.to_string())?;
335    let height = u32::try_from(image.height).map_err(|e| e.to_string())?;
336    let mut bytes = Vec::new();
337    let mut encoder = png::Encoder::new(&mut bytes, width, height);
338    encoder.set_color(png::ColorType::Rgba);
339    encoder.set_depth(png::BitDepth::Eight);
340    let mut writer = encoder.write_header().map_err(|e| e.to_string())?;
341    writer
342        .write_image_data(&image.bytes)
343        .map_err(|e| e.to_string())?;
344    writer.finish().map_err(|e| e.to_string())?;
345    Ok(base64::engine::general_purpose::STANDARD.encode(bytes))
346}
347
348/// A PNG file in standard base64 as RGBA pixels: width, height, bytes.
349fn decode_png(data: &str) -> Result<(usize, usize, Vec<u8>), String> {
350    let bytes = base64::engine::general_purpose::STANDARD
351        .decode(data.trim())
352        .map_err(|e| format!("an image that is not base64: {e}"))?;
353    let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes));
354    decoder.set_transformations(
355        png::Transformations::normalize_to_color8() | png::Transformations::ALPHA,
356    );
357    let mut reader = decoder.read_info().map_err(|e| e.to_string())?;
358    let size = reader
359        .output_buffer_size()
360        .ok_or("an image too large to read")?;
361    let mut buf = vec![0; size];
362    let info = reader.next_frame(&mut buf).map_err(|e| e.to_string())?;
363    buf.truncate(info.buffer_size());
364    let rgba = match info.color_type {
365        png::ColorType::Rgba => buf,
366        png::ColorType::GrayscaleAlpha => buf
367            .chunks_exact(2)
368            .flat_map(|p| [p[0], p[0], p[0], p[1]])
369            .collect(),
370        other => return Err(format!("an image in {other:?}, not RGBA")),
371    };
372    Ok((info.width as usize, info.height as usize, rgba))
373}
374
375/// Installs [`Arboard`] as the clipboard's system backend when it
376/// connects, and egui's text again when it disconnects. Needs the
377/// clipboard plugin (`egui_pop_api::clipboard::ClipboardPlugin`).
378#[derive(Debug, Default)]
379pub struct SystemClipboardPlugin;
380
381impl SystemClipboardPlugin {
382    pub fn new() -> Self {
383        Self
384    }
385}
386
387impl Plugin for SystemClipboardPlugin {
388    fn id(&self) -> PluginId {
389        PLUGIN
390    }
391
392    fn title(&self) -> String {
393        "System clipboard".into()
394    }
395
396    fn requires(&self) -> Vec<PluginId> {
397        vec![clipboard::PLUGIN]
398    }
399
400    fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
401        clipboard::set_backend(&ctx.app(), Box::new(Arboard::new()));
402        Ok(())
403    }
404
405    fn disconnect(&mut self, ctx: &mut Ctx<'_>) {
406        clipboard::set_backend(&ctx.app(), Box::new(clipboard::EguiText));
407    }
408}
409
410#[cfg(test)]
411mod tests {
412    use super::*;
413
414    #[test]
415    fn uri_lists_round_trip() {
416        let paths = vec![
417            PathBuf::from("/home/me/a b.png"),
418            PathBuf::from("/tmp/été#1.txt"),
419        ];
420        let list = file_uris(&paths);
421        assert_eq!(
422            list,
423            "file:///home/me/a%20b.png\r\nfile:///tmp/%C3%A9t%C3%A9%231.txt"
424        );
425        assert_eq!(paths_of(&list), paths);
426        assert_eq!(
427            paths_of("# a comment\nhttps://example.org/x\nfile://localhost/x\nfile://host/y\n"),
428            [PathBuf::from("/x")]
429        );
430        assert_eq!(
431            paths_of("file:///C:/dir/f.txt"),
432            [PathBuf::from("C:/dir/f.txt")]
433        );
434    }
435
436    #[test]
437    fn images_round_trip_through_png() {
438        let image = arboard::ImageData {
439            width: 2,
440            height: 1,
441            bytes: Cow::Owned(vec![255, 0, 0, 255, 0, 0, 255, 128]),
442        };
443        let png = encode_png(&image).unwrap();
444        let (w, h, rgba) = decode_png(&png).unwrap();
445        assert_eq!((w, h), (2, 1));
446        assert_eq!(rgba, image.bytes.as_ref());
447    }
448}