#![cfg_attr(
test,
allow(
clippy::disallowed_methods,
reason = "in a test these are the assertion, not a hazard"
)
)]
use std::sync::{Mutex, OnceLock};
mod caps;
pub use caps::{Availability, Feature, Unsupported, availability, available};
pub mod conformance;
pub mod events;
#[cfg(any(unix, windows))]
pub mod service;
#[cfg(any(unix, windows))]
mod images;
#[cfg(any(target_os = "linux", target_os = "macos", windows))]
mod native;
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
mod web;
pub const MAX_CLIPBOARD_HTML_BYTES: usize = 1024 * 1024;
pub const MAX_CLIPBOARD_PLAIN_FALLBACK_BYTES: usize = 1024 * 1024;
#[derive(Clone, PartialEq, Eq)]
pub struct RichTextOffer {
pub html: String,
pub plain: Option<String>,
}
impl RichTextOffer {
#[must_use]
pub fn is_valid(&self) -> bool {
!self.html.is_empty()
&& self.html.len() <= MAX_CLIPBOARD_HTML_BYTES
&& self
.plain
.as_ref()
.is_none_or(|plain| plain.len() <= MAX_CLIPBOARD_PLAIN_FALLBACK_BYTES)
}
}
impl std::fmt::Debug for RichTextOffer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RichTextOffer")
.field("html_bytes", &self.html.len())
.field("plain_bytes", &self.plain.as_ref().map(String::len))
.finish()
}
}
pub const SECRET_MIME: &str = "application/x-tilo-secret";
pub const PASSWORD_MANAGER_HINT_MIME: &str = "x-kde-passwordManagerHint";
pub const SECRET_MARKER: &[u8] = b"secret";
pub const MAX_CLIPBOARD_IMAGE_BYTES: usize = 8 * 1024 * 1024;
pub const MAX_CLIPBOARD_IMAGE_INPUT_BYTES: usize = 64 * 1024 * 1024;
pub const MAX_PASTED_IMAGE_BYTES: usize = 32 * 1024 * 1024;
pub const PASTED_IMAGE_TYPES: [&str; 3] = ["image/png", "image/jpeg", "image/webp"];
#[derive(Clone, PartialEq, Eq)]
pub struct ClipboardImage {
pub mime: &'static str,
pub bytes: Vec<u8>,
}
impl std::fmt::Debug for ClipboardImage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ClipboardImage")
.field("mime", &self.mime)
.field("len", &self.bytes.len())
.finish()
}
}
pub fn preferred_image_type<'a>(
offered: impl IntoIterator<Item = &'a str>,
) -> Option<&'static str> {
let offered: Vec<&str> = offered.into_iter().collect();
PASTED_IMAGE_TYPES
.into_iter()
.find(|mime| offered.contains(mime))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ClipboardTarget {
Clipboard,
Primary,
}
pub trait ClipboardBackend: Send + Sync {
fn set_text(&self, target: ClipboardTarget, text: &str) -> bool;
fn text(&self, target: ClipboardTarget) -> Option<String>;
fn request_text(&self, target: ClipboardTarget) -> std::sync::mpsc::Receiver<Option<String>> {
let (reply, result) = std::sync::mpsc::channel();
let _ = reply.send(self.text(target));
result
}
fn rich_text(&self) -> Option<RichTextOffer> {
None
}
fn set_rich_text(&self, html: &str, plain: &str) -> bool {
let _ = html;
self.set_text(ClipboardTarget::Clipboard, plain)
}
fn set_image(&self, width: usize, height: usize, rgba: &[u8]) -> bool {
let _ = (width, height, rgba);
false
}
fn image(&self) -> Option<ClipboardImage> {
None
}
fn set_shared_text(&self, target: ClipboardTarget, text: &str) -> bool {
self.set_text(target, text)
}
fn set_secret_text(&self, text: &str) -> bool {
let _ = text;
false
}
fn copy(&self, content: CopyContent<'_>) -> ClipboardCopy {
copy_now(self, content)
}
fn reserve_text(&self) -> Option<ReservedCopy> {
None
}
fn name(&self) -> &'static str;
}
fn copy_now<B: ClipboardBackend + ?Sized>(backend: &B, content: CopyContent<'_>) -> ClipboardCopy {
ClipboardCopy::settled(match content {
CopyContent::Text(text) => backend.set_text(ClipboardTarget::Clipboard, text),
CopyContent::SharedText(text) => backend.set_shared_text(ClipboardTarget::Clipboard, text),
CopyContent::SecretText(text) => backend.set_secret_text(text),
CopyContent::Rich { html, plain } => backend.set_rich_text(html, plain),
CopyContent::Image {
width,
height,
rgba,
} => backend.set_image(width, height, rgba),
})
}
#[derive(Clone, Copy)]
pub enum CopyContent<'a> {
Text(&'a str),
SharedText(&'a str),
SecretText(&'a str),
Rich {
html: &'a str,
plain: &'a str,
},
Image {
width: usize,
height: usize,
rgba: &'a [u8],
},
}
impl std::fmt::Debug for CopyContent<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Text(text) => f.debug_tuple("Text").field(&text.len()).finish(),
Self::SharedText(text) => f.debug_tuple("SharedText").field(&text.len()).finish(),
Self::SecretText(_) => f.write_str("SecretText"),
Self::Rich { html, plain } => f
.debug_struct("Rich")
.field("html", &html.len())
.field("plain", &plain.len())
.finish(),
Self::Image { width, height, .. } => f
.debug_struct("Image")
.field("width", width)
.field("height", height)
.finish(),
}
}
}
#[derive(Clone)]
#[must_use = "a copy can fail after it returns; read its outcome"]
pub struct ClipboardCopy {
state: std::sync::Arc<CopyState>,
}
struct CopyState {
progress: Mutex<CopyProgress>,
settled: std::sync::Condvar,
wake: tilo_rt::wake::WakeHandle,
}
#[derive(Default)]
struct CopyProgress {
outcome: Option<bool>,
then: Vec<Box<dyn FnOnce(bool) + Send>>,
}
impl CopyState {
fn progress(&self) -> std::sync::MutexGuard<'_, CopyProgress> {
self.progress
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
}
impl ClipboardCopy {
pub fn settled(copied: bool) -> Self {
let (copy, settle) = Self::pending();
settle.settle(copied);
copy
}
pub fn pending() -> (Self, CopySettler) {
let state = std::sync::Arc::new(CopyState {
progress: Mutex::default(),
settled: std::sync::Condvar::new(),
wake: tilo_rt::wake::WakeHandle::new(),
});
(
Self {
state: std::sync::Arc::clone(&state),
},
CopySettler { state: Some(state) },
)
}
#[must_use]
pub fn outcome(&self) -> Option<bool> {
self.state.progress().outcome
}
pub fn on_settled(&self, then: impl FnOnce(bool) + Send + 'static) {
let mut progress = self.state.progress();
match progress.outcome {
Some(copied) => {
drop(progress);
then(copied);
}
None => progress.then.push(Box::new(then)),
}
}
#[must_use]
pub fn wait(&self) -> bool {
let mut progress = self.state.progress();
loop {
if let Some(copied) = progress.outcome {
return copied;
}
progress = self
.state
.settled
.wait(progress)
.unwrap_or_else(std::sync::PoisonError::into_inner);
}
}
}
impl std::fmt::Debug for ClipboardCopy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("ClipboardCopy")
.field(&self.outcome())
.finish()
}
}
pub struct CopySettler {
state: Option<std::sync::Arc<CopyState>>,
}
impl CopySettler {
pub fn settle(mut self, copied: bool) {
self.finish(copied);
}
fn finish(&mut self, copied: bool) {
if let Some(state) = self.state.take() {
let then = {
let mut progress = state.progress();
progress.outcome = Some(copied);
std::mem::take(&mut progress.then)
};
state.settled.notify_all();
for then in then {
then(copied);
}
state.wake.wake();
}
}
}
impl Drop for CopySettler {
fn drop(&mut self) {
self.finish(false);
}
}
#[must_use = "dropping a reserved copy gives it up"]
pub struct ReservedCopy {
fill: Option<Fill>,
}
type Fill = Box<dyn FnOnce(Option<&str>) -> ClipboardCopy + Send>;
impl ReservedCopy {
pub fn new(fill: impl FnOnce(Option<&str>) -> ClipboardCopy + Send + 'static) -> Self {
Self {
fill: Some(Box::new(fill)),
}
}
pub fn fill(mut self, text: &str) -> ClipboardCopy {
self.fill
.take()
.map_or_else(|| ClipboardCopy::settled(false), |fill| fill(Some(text)))
}
}
impl Drop for ReservedCopy {
fn drop(&mut self) {
if let Some(fill) = self.fill.take() {
let _ = fill(None);
}
}
}
impl std::fmt::Debug for ReservedCopy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("ReservedCopy")
}
}
pub fn system() -> std::sync::Arc<dyn ClipboardBackend> {
static SYSTEM: OnceLock<std::sync::Arc<dyn ClipboardBackend>> = OnceLock::new();
SYSTEM.get_or_init(backend).clone()
}
#[cfg(all(unix, not(all(target_arch = "wasm32", target_os = "unknown"))))]
fn backend() -> std::sync::Arc<dyn ClipboardBackend> {
service::ServiceClipboard::from_env().map_or_else(unavailable, |clipboard| {
std::sync::Arc::new(clipboard) as std::sync::Arc<dyn ClipboardBackend>
})
}
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
fn backend() -> std::sync::Arc<dyn ClipboardBackend> {
std::sync::Arc::new(web::BrowserClipboard)
}
#[cfg(windows)]
fn backend() -> std::sync::Arc<dyn ClipboardBackend> {
os()
}
#[cfg(not(any(unix, windows, all(target_arch = "wasm32", target_os = "unknown"))))]
fn backend() -> std::sync::Arc<dyn ClipboardBackend> {
unavailable()
}
static RESOLVER: OnceLock<fn() -> std::sync::Arc<dyn ClipboardBackend>> = OnceLock::new();
pub fn install_resolver(resolve: fn() -> std::sync::Arc<dyn ClipboardBackend>) {
let _ = RESOLVER.set(resolve);
}
#[must_use]
pub fn current() -> std::sync::Arc<dyn ClipboardBackend> {
static IN_PROCESS: OnceLock<std::sync::Arc<dyn ClipboardBackend>> = OnceLock::new();
if let Some(resolve) = RESOLVER.get() {
return resolve();
}
IN_PROCESS
.get_or_init(|| std::sync::Arc::new(InProcessClipboard::default()))
.clone()
}
pub fn unavailable() -> std::sync::Arc<dyn ClipboardBackend> {
std::sync::Arc::new(Nowhere)
}
pub fn is_unavailable(backend: &dyn ClipboardBackend) -> bool {
backend.name() == Nowhere.name()
}
pub fn os() -> std::sync::Arc<dyn ClipboardBackend> {
#[cfg(any(target_os = "linux", target_os = "macos", windows))]
{
static OS: OnceLock<std::sync::Arc<dyn ClipboardBackend>> = OnceLock::new();
OS.get_or_init(|| std::sync::Arc::new(native::NativeClipboard::default()))
.clone()
}
#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
{
unavailable()
}
}
pub fn warn_fallback_once(op: &str) {
static WARNED: OnceLock<()> = OnceLock::new();
WARNED.get_or_init(|| {
tracing::warn!(
target: "tilo_ui::clipboard",
operation = op,
"no system clipboard: falling back to an in-process buffer. Copy and paste \
will work inside this process and silently do nothing between processes. \
On Wayland this means the compositor offers neither \
zwlr_data_control_manager_v1 nor ext_data_control_v1 and no X11 (XWayland) \
clipboard is reachable either."
);
});
}
struct Nowhere;
impl ClipboardBackend for Nowhere {
fn set_text(&self, _target: ClipboardTarget, _text: &str) -> bool {
false
}
fn text(&self, _target: ClipboardTarget) -> Option<String> {
None
}
fn name(&self) -> &'static str {
"unavailable"
}
}
#[derive(Debug, Default)]
pub struct InProcessClipboard {
clipboard: Mutex<Option<String>>,
primary: Mutex<Option<String>>,
rich: Mutex<Option<String>>,
}
impl InProcessClipboard {
fn slot(&self, target: ClipboardTarget) -> &Mutex<Option<String>> {
match target {
ClipboardTarget::Clipboard => &self.clipboard,
ClipboardTarget::Primary => &self.primary,
}
}
}
impl ClipboardBackend for InProcessClipboard {
fn set_text(&self, target: ClipboardTarget, text: &str) -> bool {
let Ok(mut slot) = self.slot(target).lock() else {
return false;
};
*slot = Some(text.to_string());
if target == ClipboardTarget::Clipboard
&& let Ok(mut rich) = self.rich.lock()
{
*rich = None;
}
true
}
fn text(&self, target: ClipboardTarget) -> Option<String> {
self.slot(target).lock().ok()?.clone()
}
fn set_rich_text(&self, html: &str, plain: &str) -> bool {
if !self.set_text(ClipboardTarget::Clipboard, plain) {
return false;
}
let Ok(mut rich) = self.rich.lock() else {
return false;
};
*rich = Some(html.to_owned());
true
}
fn rich_text(&self) -> Option<RichTextOffer> {
let html = self.rich.lock().ok()?.clone()?;
let plain = self.text(ClipboardTarget::Clipboard);
Some(RichTextOffer { html, plain }).filter(RichTextOffer::is_valid)
}
fn set_shared_text(&self, _target: ClipboardTarget, _text: &str) -> bool {
false
}
fn name(&self) -> &'static str {
"in-process"
}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
pub(crate) static SYSTEM: Mutex<()> = Mutex::new(());
#[test]
fn a_copy_settles_once_and_runs_what_waits_on_it() {
let (copy, settler) = ClipboardCopy::pending();
let (ran, outcomes) = std::sync::mpsc::channel();
let early = ran.clone();
copy.on_settled(move |copied| early.send(("before", copied)).unwrap());
assert_eq!(copy.outcome(), None);
assert!(
outcomes.try_recv().is_err(),
"nothing runs before it settles"
);
settler.settle(true);
assert_eq!(copy.outcome(), Some(true));
assert!(copy.wait());
copy.on_settled(move |copied| ran.send(("after", copied)).unwrap());
assert_eq!(
outcomes.try_iter().collect::<Vec<_>>(),
[("before", true), ("after", true)]
);
let (copy, settler) = ClipboardCopy::pending();
drop(settler);
assert_eq!(copy.outcome(), Some(false), "an abandoned copy failed");
}
#[test]
fn the_in_process_clipboard_keeps_text_inside_the_process() {
let clipboard = InProcessClipboard::default();
assert!(clipboard.set_text(ClipboardTarget::Clipboard, "local"));
assert_eq!(
clipboard.text(ClipboardTarget::Clipboard).as_deref(),
Some("local")
);
assert!(clipboard.set_rich_text("<b>bold</b>", "bold"));
assert_eq!(
clipboard.rich_text().map(|offer| offer.plain),
Some(Some("bold".to_owned()))
);
assert!(
!clipboard.set_shared_text(ClipboardTarget::Clipboard, "shared"),
"an in-process buffer does not claim a shared copy"
);
assert!(
!clipboard.set_secret_text("secret"),
"an in-process buffer does not claim a secret copy"
);
assert!(!clipboard.set_image(1, 1, &[0, 0, 0, 0]));
assert!(clipboard.image().is_none());
}
#[test]
fn a_process_handed_no_connection_holds_and_takes_nothing() {
let nowhere = unavailable();
assert!(!nowhere.set_text(ClipboardTarget::Clipboard, "lost"));
assert_eq!(nowhere.text(ClipboardTarget::Clipboard), None);
assert!(!nowhere.set_shared_text(ClipboardTarget::Clipboard, "lost"));
assert!(!nowhere.set_secret_text("lost"));
assert!(!nowhere.set_image(1, 1, &[0, 0, 0, 0]));
assert!(nowhere.image().is_none());
assert_eq!(nowhere.name(), "unavailable");
}
tilo_test_env::scenario! {
fn the_in_process_and_system_clipboards_conform;
phase the_in_process_clipboard_conforms;
{
conformance::check_local(&InProcessClipboard::default());
}
phase the_system_clipboard_conforms_with_or_without_a_system_clipboard;
{
let _system = SYSTEM.lock();
let system = os();
conformance::check_system(&*system);
assert!(std::ptr::addr_eq(
std::sync::Arc::as_ptr(&system),
std::sync::Arc::as_ptr(&self::os())
));
}
}
}