use arboard::Clipboard;
use crate::types::bus::ClipboardResult;
use crate::types::ids::Ticket;
pub struct NativeClipboard {
inner: Option<Clipboard>,
}
impl NativeClipboard {
pub fn new() -> Self {
Self {
inner: Clipboard::new()
.map_err(|e| {
log::warn!("clipboard open failed: {e}");
e
})
.ok(),
}
}
pub fn write(&mut self, text: &str) {
let Some(cb) = self.inner.as_mut() else {
return;
};
if let Err(e) = cb.set_text(text.to_owned()) {
log::warn!("clipboard write failed: {e}");
}
}
pub fn write_image(&mut self, img: &crate::types::bus::ClipboardImage) {
let Some(cb) = self.inner.as_mut() else {
return;
};
let data = arboard::ImageData { width: img.width as usize, height: img.height as usize, bytes: std::borrow::Cow::Borrowed(&img.rgba) };
if let Err(e) = cb.set_image(data) {
log::warn!("clipboard image write failed: {e}");
}
}
pub fn read_image(&mut self) -> Option<crate::types::bus::ClipboardImage> {
let img = self.inner.as_mut()?.get_image().ok()?;
Some(crate::types::bus::ClipboardImage { width: img.width as u32, height: img.height as u32, rgba: img.bytes.into_owned().into() })
}
pub fn read(&mut self, ticket: Ticket) -> ClipboardResult {
let text = self.inner.as_mut().and_then(|cb| match cb.get_text() {
Ok(t) if t.is_empty() => None,
Ok(t) => Some(t),
Err(e) => {
log::warn!("clipboard read failed: {e}");
None
}
});
ClipboardResult { ticket, text }
}
}
impl Default for NativeClipboard {
fn default() -> Self {
Self::new()
}
}