use anyhow::{Context, Result};
#[cfg(not(target_os = "linux"))]
pub fn copy_text_to_clipboard(text: &str) -> Result<()> {
use arboard::Clipboard;
match Clipboard::new() {
Ok(mut clipboard) => {
clipboard
.set_text(text.to_string())
.context("Failed to copy to clipboard")?;
Ok(())
}
Err(e) => Err(anyhow::anyhow!("Failed to initialize clipboard: {}", e)),
}
}
#[cfg(target_os = "linux")]
pub fn serve_clipboard_daemon() -> Result<()> {
use arboard::{Clipboard, LinuxClipboardKind, SetExtLinux};
use std::io::Read;
let mut content_from_stdin = String::new();
std::io::stdin()
.read_to_string(&mut content_from_stdin)
.context("Failed to read from stdin")?;
let mut clipboard = Clipboard::new().context("Failed to initialize clipboard")?;
clipboard
.set()
.clipboard(LinuxClipboardKind::Clipboard)
.wait()
.text(content_from_stdin)
.context("Failed to set clipboard content")?;
Ok(())
}
#[cfg(target_os = "linux")]
pub fn spawn_clipboard_daemon(content: &str) -> Result<()> {
use std::process::{Command, Stdio};
use log::info;
let current_exe: std::path::PathBuf =
std::env::current_exe().context("Failed to get current executable path")?;
let mut args: Vec<String> = std::env::args().collect();
args.push("--clipboard-daemon".to_string());
let mut child = Command::new(current_exe)
.args(&args[1..])
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.context("Failed to launch clipboard daemon process")?;
use std::io::Write;
let mut stdin = child
.stdin
.take()
.context("Failed to acquire stdin pipe for clipboard daemon process")?;
stdin
.write_all(content.as_bytes())
.context("Failed to write content to clipboard daemon process")?;
info!("Clipboard daemon launched successfully");
Ok(())
}
pub fn copy_to_clipboard(text: &str) -> Result<()> {
#[cfg(target_os = "linux")]
{
spawn_clipboard_daemon(text)
}
#[cfg(not(target_os = "linux"))]
{
copy_text_to_clipboard(text)
}
}