pub const HOLD_SECONDS: u64 = crate::policy::CLIPBOARD_SECONDS;
#[cfg(feature = "clipboard")]
pub use system::{Clipboard, Held};
#[cfg(feature = "clipboard")]
mod system {
use crate::{Error, Result};
use zeroize::Zeroizing;
pub struct Clipboard {
inner: arboard::Clipboard,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Held {
pub cleared: bool,
}
impl Clipboard {
pub fn open() -> Result<Self> {
let inner = arboard::Clipboard::new().map_err(unreachable)?;
Ok(Self { inner })
}
pub fn put(&mut self, value: &str) -> Result<()> {
marked(&mut self.inner)
.text(value.to_owned())
.map_err(unwritable)
}
pub fn check(&mut self) -> Result<()> {
match self.inner.get_text().map(Zeroizing::new) {
Ok(_) | Err(arboard::Error::ContentNotAvailable) => Ok(()),
Err(error) => Err(Error::Clipboard(format!(
"the clipboard cannot be read: {error}"
))),
}
}
pub fn holds(&mut self, value: &str) -> bool {
matches!(self.inner.get_text().map(Zeroizing::new), Ok(current) if *current == value)
}
pub fn take_back(&mut self, value: &str) -> bool {
self.holds(value) && self.inner.clear().is_ok()
}
pub fn hold(mut self, value: &str, seconds: u64) -> Result<Held> {
#[cfg(all(
unix,
not(any(target_os = "macos", target_os = "android", target_os = "emscripten"))
))]
{
use arboard::SetExtLinux;
const FOREVER_IN_PRACTICE: u64 = 8 * 60 * 60;
let lifetime = if seconds == 0 {
FOREVER_IN_PRACTICE
} else {
seconds
};
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(lifetime);
marked(&mut self.inner)
.wait_until(deadline)
.text(value.to_owned())
.map_err(unwritable)?;
Ok(Held { cleared: true })
}
#[cfg(not(all(
unix,
not(any(target_os = "macos", target_os = "android", target_os = "emscripten"))
)))]
{
self.put(value)?;
if seconds == 0 {
return Ok(Held { cleared: false });
}
std::thread::sleep(std::time::Duration::from_secs(seconds));
Ok(Held {
cleared: self.take_back(value),
})
}
}
}
fn marked(clipboard: &mut arboard::Clipboard) -> arboard::Set<'_> {
let set = clipboard.set();
#[cfg(windows)]
let set = {
use arboard::SetExtWindows;
set.exclude_from_monitoring()
.exclude_from_history()
.exclude_from_cloud()
};
#[cfg(target_os = "macos")]
let set = {
use arboard::SetExtApple;
set.exclude_from_history()
};
#[cfg(all(
unix,
not(any(target_os = "macos", target_os = "android", target_os = "emscripten"))
))]
let set = {
use arboard::SetExtLinux;
set.exclude_from_history()
};
set
}
fn unreachable(error: arboard::Error) -> Error {
Error::Clipboard(format!("cannot reach the clipboard: {error}"))
}
fn unwritable(error: arboard::Error) -> Error {
Error::Clipboard(format!("cannot write to the clipboard: {error}"))
}
}