1use 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
69pub const PLUGIN: PluginId = clipboard::SYSTEM_PLUGIN;
73
74const FORMATS: [FormatId; 4] = [URI_LIST, PNG, HTML, TEXT];
76
77#[derive(Default)]
79pub struct Arboard {
80 clipboard: Option<arboard::Clipboard>,
81 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 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 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
259pub 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 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
286pub 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 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
332fn 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
348fn 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#[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}