use std::cell::RefCell;
thread_local! {
static CLIPBOARD: RefCell<Option<arboard::Clipboard>> = const { RefCell::new(None) };
}
fn with<T>(
f: impl FnOnce(&mut arboard::Clipboard) -> Result<T, arboard::Error>,
) -> Result<T, String> {
CLIPBOARD.with(|c| {
let mut c = c.borrow_mut();
if c.is_none() {
*c = Some(arboard::Clipboard::new().map_err(|e| format!("no clipboard: {e}"))?);
}
match c.as_mut() {
Some(cb) => f(cb).map_err(|e| format!("clipboard: {e}")),
None => Err("no clipboard".into()),
}
})
}
pub fn copy_text(text: &str) -> Result<(), String> {
with(|c| c.set_text(text.to_string()))
}
pub fn copy_image(rgba: &[u8], width: u32, height: u32) -> Result<(), String> {
if rgba.len() != (width as usize) * (height as usize) * 4 {
return Err("pixels do not match the size".into());
}
with(|c| {
c.set_image(arboard::ImageData {
width: width as usize,
height: height as usize,
bytes: std::borrow::Cow::Borrowed(rgba),
})
})
}