use arboard::Clipboard;
pub struct ClipboardManager {
clipboard: Option<Clipboard>,
last_copied: Option<String>,
}
impl ClipboardManager {
pub fn new() -> Self {
let clipboard = Clipboard::new().ok();
if clipboard.is_none() {
eprintln!("Warning: Could not initialize system clipboard");
}
Self {
clipboard,
last_copied: None,
}
}
pub fn copy(&mut self, text: String) -> Result<(), String> {
if text.is_empty() {
return Err("Cannot copy empty text".to_string());
}
self.last_copied = Some(text.clone());
if let Some(clipboard) = &mut self.clipboard {
clipboard
.set_text(text)
.map_err(|e| format!("Failed to copy to system clipboard: {}", e))?;
}
Ok(())
}
pub fn paste(&mut self) -> Result<String, String> {
if let Some(clipboard) = &mut self.clipboard {
if let Ok(text) = clipboard.get_text() {
return Ok(text);
}
}
self.last_copied
.clone()
.ok_or_else(|| "Clipboard is empty".to_string())
}
pub fn has_content(&self) -> bool {
self.last_copied.is_some()
}
pub fn clear(&mut self) {
self.last_copied = None;
if let Some(clipboard) = &mut self.clipboard {
let _ = clipboard.clear();
}
}
#[allow(dead_code)]
pub fn last_copied(&self) -> Option<&str> {
self.last_copied.as_deref()
}
}
impl Default for ClipboardManager {
fn default() -> Self {
Self::new()
}
}