On some Wayland compositors, Ctrl+V never reaches egui as a key-press event—only the key-release event arrives. Consuming raw key events and firing paste on key release avoids missed pastes.
The helper below keeps clipboard reads payload-first rather than decoding straight into pixels:
- Original encoded bytes (best case): When the platform exposes PNG/JPEG/WebP bytes, keep them intact with MIME type and filename so saving or exporting does not re-encode.
- Desktop fallback: Most desktop clipboard APIs only return an RGBA8 bitmap. Re-encoding that bitmap to PNG keeps the downstream interface bytes-first, with
synthesized: trueflagging that the bytes are not the original file. - UI preview: egui textures expect RGBA8. Keep pixel decoding isolated to the preview path.
Dependencies used here: arboard on desktop, web-sys (Clipboard / ClipboardItem / Blob) + wasm-bindgen-futures on WASM, and image for optional preview decoding and desktop PNG fallback.
use egui::{Context, InputState, Key, Modifiers};
#[derive(Debug, Clone)]
pub struct ClipboardImagePayload {
pub bytes: Vec<u8>,
pub mime_type: String,
pub filename: String,
/// True when bytes were re-encoded from a raw bitmap rather than read verbatim.
pub synthesized: bool,
}
pub trait ClipboardProvider {
fn get_image_payload(&mut self) -> Option<ClipboardImagePayload>;
}
#[derive(Debug, Clone)]
pub struct ClipboardImageRgba8 {
pub width: usize,
pub height: usize,
/// Tightly packed RGBA8 (`width * height * 4`).
pub bytes: Vec<u8>,
}
pub fn decode_image_for_preview(payload: &ClipboardImagePayload) -> Option<ClipboardImageRgba8> {
let rgba = image::load_from_memory(&payload.bytes).ok()?.to_rgba8();
let (w, h) = rgba.dimensions();
Some(ClipboardImageRgba8 {
width: w as usize,
height: h as usize,
bytes: rgba.into_raw(),
})
}
// -------- Native (desktop) --------
#[cfg(not(target_arch = "wasm32"))]
pub struct ArboardClipboard {
inner: arboard::Clipboard,
}
#[cfg(not(target_arch = "wasm32"))]
impl ArboardClipboard {
pub fn new() -> Result<Self, arboard::Error> {
Ok(Self {
inner: arboard::Clipboard::new()?,
})
}
}
#[cfg(not(target_arch = "wasm32"))]
impl ClipboardProvider for ArboardClipboard {
fn get_image_payload(&mut self) -> Option<ClipboardImagePayload> {
// Fallback path: arboard returns decoded RGBA8 pixels on desktop.
// Re-encode to PNG so callers only handle encoded payloads.
let img = self.inner.get_image().ok()?;
let width = img.width as u32;
let height = img.height as u32;
let rgba_bytes = img.bytes.into_owned();
let mut out = Vec::new();
{
use image::codecs::png::PngEncoder;
use image::{ColorType, ImageEncoder};
let encoder = PngEncoder::new(&mut out);
encoder
.write_image(&rgba_bytes, width, height, ColorType::Rgba8)
.ok()?;
}
Some(ClipboardImagePayload {
bytes: out,
mime_type: "image/png".to_string(),
filename: "clipboard.png".to_string(),
synthesized: true,
})
}
}
// -------- Web (WASM) --------
// Requires a secure context (https or localhost), a user gesture (Ctrl+V qualifies),
// and browser permission to read the clipboard. Call `poll()` each frame and read
// the completed payload via `take_image_payload()`.
#[cfg(target_arch = "wasm32")]
#[derive(Default)]
pub struct WebClipboard {
pending: bool,
last_payload: Option<ClipboardImagePayload>,
}
#[cfg(target_arch = "wasm32")]
impl WebClipboard {
pub fn request_paste(&mut self) {
if self.pending {
return;
}
self.pending = true;
wasm_bindgen_futures::spawn_local(async {
let maybe_payload = read_clipboard_image_payload().await;
WEB_CLIPBOARD_RESULT.with(|cell| {
*cell.borrow_mut() = Some(maybe_payload);
});
});
}
pub fn poll(&mut self) {
let done = WEB_CLIPBOARD_RESULT.with(|cell| cell.borrow_mut().take());
if let Some(result) = done {
self.pending = false;
self.last_payload = result;
}
}
pub fn take_image_payload(&mut self) -> Option<ClipboardImagePayload> {
self.last_payload.take()
}
}
#[cfg(target_arch = "wasm32")]
thread_local! {
static WEB_CLIPBOARD_RESULT: std::cell::RefCell<Option<Option<ClipboardImagePayload>>> =
std::cell::RefCell::new(None);
}
#[cfg(target_arch = "wasm32")]
async fn read_clipboard_image_payload() -> Option<ClipboardImagePayload> {
use wasm_bindgen::JsCast;
let clipboard = web_sys::window()?.navigator().clipboard()?;
let items_js = wasm_bindgen_futures::JsFuture::from(clipboard.read().ok()?)
.await
.ok()?;
let items: js_sys::Array = items_js.dyn_into().ok()?;
let candidates = [
("image/png", "clipboard.png"),
("image/jpeg", "clipboard.jpg"),
("image/webp", "clipboard.webp"),
("image/gif", "clipboard.gif"),
("image/bmp", "clipboard.bmp"),
("image/tiff", "clipboard.tiff"),
];
for item in items.iter() {
let item: web_sys::ClipboardItem = item.dyn_into().ok()?;
let types = item.types();
for (mime, filename) in candidates {
if !types.includes(&wasm_bindgen::JsValue::from_str(mime), 0) {
continue;
}
let blob_js = wasm_bindgen_futures::JsFuture::from(item.get_type(mime).ok()?)
.await
.ok()?;
let blob: web_sys::Blob = blob_js.dyn_into().ok()?;
let ab_js = wasm_bindgen_futures::JsFuture::from(blob.array_buffer().ok()?)
.await
.ok()?;
let u8 = js_sys::Uint8Array::new(&ab_js);
let mut bytes = vec![0u8; u8.length() as usize];
u8.copy_to(&mut bytes);
return Some(ClipboardImagePayload {
bytes,
mime_type: mime.to_string(),
filename: filename.to_string(),
synthesized: false,
});
}
}
None
}
// -------- Shortcut handling --------
/// Triggers on key release for Ctrl+V (Wayland workaround) and key press for Cmd+V (macOS).
pub fn paste_image_on_shortcut<C: ClipboardProvider>(
ctx: &Context,
clipboard: &mut C,
) -> Option<ClipboardImagePayload> {
let paste = ctx.input_mut(|i| {
consume_key(i, Modifiers::CTRL, Key::V, true)
|| consume_key(i, Modifiers::COMMAND, Key::V, false)
});
if paste {
clipboard.get_image_payload()
} else {
None
}
}
#[cfg(target_arch = "wasm32")]
pub fn paste_image_on_shortcut_web(ctx: &Context, clipboard: &mut WebClipboard) {
let paste = ctx.input_mut(|i| {
consume_key(i, Modifiers::CTRL, Key::V, true)
|| consume_key(i, Modifiers::COMMAND, Key::V, false)
});
if paste {
clipboard.request_paste();
}
}
fn consume_key(
input: &mut InputState,
mods: Modifiers,
key: Key,
trigger_on_release: bool,
) -> bool {
let mut found = false;
input.events.retain(|event| {
let is_match = matches!(
event,
egui::Event::Key { key: k, modifiers: m, pressed, .. }
if *k == key
&& m.matches_exact(mods)
&& (*pressed == !trigger_on_release)
);
found |= is_match;
!is_match
});
found
}