Skip to main content

tilo_clipboard/
lib.rs

1#![cfg_attr(
2    test,
3    allow(
4        clippy::disallowed_methods,
5        reason = "in a test these are the assertion, not a hazard"
6    )
7)]
8
9//! The clipboard: one API on Linux, macOS and the web.
10//!
11//! [`ClipboardBackend`] is the boundary a host fills; [`system`] is this process's clipboard:
12//!
13//! | Target | Backend |
14//! |---|---|
15//! | Linux, macOS | the connection the app's session or launcher opened for it ([`service::Connected`]) |
16//! | Web | the trusted clipboard event being dispatched ([`events`]), else a synchronous copy inside the user's click |
17//!
18//! An app runs in a process of its own, so it holds no selection to offer or read: the process
19//! that holds the person's selection serves it, and an app's copies and pastes cross to it over the
20//! one service ([`service`]) whether the app is written in Rust or in tilolang. Where a Tilo
21//! session serves no clipboard — a person's own macOS, Windows or Linux desktop, or `tilolang run`
22//! outside a session — the launcher serves the same wire from the operating system's clipboard
23//! ([`os`]). A process handed no connection (the launch runs without services) copies nothing and
24//! pastes nothing, rather than keeping a copy that reaches no one.
25
26use std::sync::{Mutex, OnceLock};
27
28mod caps;
29pub use caps::{Availability, Feature, Unsupported, availability, available};
30
31pub mod conformance;
32pub mod events;
33/// The clipboard over a connection an app's session or launcher opened for it: `serve` answers on
34/// the serving end, [`service::Connected`] and [`service::ServiceClipboard`] are the app's.
35#[cfg(any(unix, windows))]
36pub mod service;
37
38#[cfg(any(unix, windows))]
39mod images;
40#[cfg(any(target_os = "linux", target_os = "macos", windows))]
41mod native;
42#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
43mod web;
44
45pub const MAX_CLIPBOARD_HTML_BYTES: usize = 1024 * 1024;
46
47/// Largest plain-text fallback captured with a rich clipboard offer.
48pub const MAX_CLIPBOARD_PLAIN_FALLBACK_BYTES: usize = 1024 * 1024;
49
50/// HTML and its optional plain fallback captured from the same clipboard offer.
51/// Adapters must bound payloads before copying them into this value. Decoders
52/// may use this fallback after rejecting HTML, without rereading the clipboard.
53#[derive(Clone, PartialEq, Eq)]
54pub struct RichTextOffer {
55    pub html: String,
56    pub plain: Option<String>,
57}
58
59impl RichTextOffer {
60    #[must_use]
61    pub fn is_valid(&self) -> bool {
62        !self.html.is_empty()
63            && self.html.len() <= MAX_CLIPBOARD_HTML_BYTES
64            && self
65                .plain
66                .as_ref()
67                .is_none_or(|plain| plain.len() <= MAX_CLIPBOARD_PLAIN_FALLBACK_BYTES)
68    }
69}
70
71impl std::fmt::Debug for RichTextOffer {
72    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        f.debug_struct("RichTextOffer")
74            .field("html_bytes", &self.html.len())
75            .field("plain_bytes", &self.plain.as_ref().map(String::len))
76            .finish()
77    }
78}
79
80/// Marks a Tilo copy as a secret: the compositor keeps it out of clipboard
81/// history and never syncs it to the person's other devices. Its bytes are
82/// [`SECRET_MARKER`].
83pub const SECRET_MIME: &str = "application/x-tilo-secret";
84
85/// The password-manager convention other Linux clipboard managers honour
86/// (KDE Klipper, `cliphist`, `CopyQ`): an offer carrying it is kept out of
87/// their histories. Its bytes are [`SECRET_MARKER`].
88pub const PASSWORD_MANAGER_HINT_MIME: &str = "x-kde-passwordManagerHint";
89
90pub const SECRET_MARKER: &[u8] = b"secret";
91
92pub const MAX_CLIPBOARD_IMAGE_BYTES: usize = 8 * 1024 * 1024;
93
94pub const MAX_CLIPBOARD_IMAGE_INPUT_BYTES: usize = 64 * 1024 * 1024;
95
96pub const MAX_PASTED_IMAGE_BYTES: usize = 32 * 1024 * 1024;
97
98pub const PASTED_IMAGE_TYPES: [&str; 3] = ["image/png", "image/jpeg", "image/webp"];
99
100#[derive(Clone, PartialEq, Eq)]
101pub struct ClipboardImage {
102    pub mime: &'static str,
103    /// The image file's bytes, as the copying app offered them.
104    pub bytes: Vec<u8>,
105}
106
107impl std::fmt::Debug for ClipboardImage {
108    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109        f.debug_struct("ClipboardImage")
110            .field("mime", &self.mime)
111            .field("len", &self.bytes.len())
112            .finish()
113    }
114}
115
116pub fn preferred_image_type<'a>(
117    offered: impl IntoIterator<Item = &'a str>,
118) -> Option<&'static str> {
119    let offered: Vec<&str> = offered.into_iter().collect();
120    PASTED_IMAGE_TYPES
121        .into_iter()
122        .find(|mime| offered.contains(mime))
123}
124
125#[derive(Debug, Clone, Copy, PartialEq, Eq)]
126pub enum ClipboardTarget {
127    Clipboard,
128    /// The select-then-middle-click-paste primary selection. Distinct storage
129    /// from [`ClipboardTarget::Clipboard`] — a terminal writes it on every
130    /// drag-select without disturbing what the user last copied. Only Linux
131    /// has one ([`Feature::PrimarySelection`]).
132    Primary,
133}
134
135/// A source of clipboard content for this process.
136///
137/// Implementors must be cheap to call and must never block on the compositor's
138/// event loop from a widget's event handler — a host backend reads a mirror
139/// in memory, and the Wayland backend does its protocol work on its own
140/// thread.
141pub trait ClipboardBackend: Send + Sync {
142    fn set_text(&self, target: ClipboardTarget, text: &str) -> bool;
143
144    /// Read `target` as UTF-8. `None` when it is empty, unavailable, or holds
145    /// something that is not text.
146    fn text(&self, target: ClipboardTarget) -> Option<String>;
147
148    /// Request text for an explicit paste. A native transfer may finish after
149    /// this call returns; the backend must wake its owner when it answers.
150    /// No answer may substitute text from an older selection or focus owner.
151    fn request_text(&self, target: ClipboardTarget) -> std::sync::mpsc::Receiver<Option<String>> {
152        let (reply, result) = std::sync::mpsc::channel();
153        let _ = reply.send(self.text(target));
154        result
155    }
156
157    /// Read HTML and its plain fallback from one Ctrl+V clipboard offer.
158    /// Optional: unsupported backends return `None` without reading plain text.
159    /// A successful read consumes event-scoped offers; use the captured plain
160    /// fallback if decoding refuses the HTML. Never reread to recover a stale
161    /// selection, a permission refusal, or an active composition.
162    fn rich_text(&self) -> Option<RichTextOffer> {
163        None
164    }
165
166    /// Take the Ctrl+C clipboard and offer formatted text on it: `html` as
167    /// `text/html` and `plain` as its plain-text fallback, both from one
168    /// copy, so an app that reads formatting pastes the formatting and every
169    /// other app the words. Returns `false` if the backend could not.
170    ///
171    /// The default offers only `plain`, for a backend that carries no
172    /// formatting; every system clipboard overrides it.
173    fn set_rich_text(&self, html: &str, plain: &str) -> bool {
174        let _ = html;
175        self.set_text(ClipboardTarget::Clipboard, plain)
176    }
177
178    /// Offer an RGBA8 image on the clipboard. Optional: the default refuses,
179    /// which is appropriate for backends that only carry text.
180    fn set_image(&self, width: usize, height: usize, rgba: &[u8]) -> bool {
181        let _ = (width, height, rgba);
182        false
183    }
184
185    /// The image on the Ctrl+V clipboard, when it holds one: a screenshot,
186    /// an image copied in a viewer or a browser. Optional: the default reads
187    /// none, which is right for backends that only carry text.
188    fn image(&self) -> Option<ClipboardImage> {
189        None
190    }
191
192    /// Offer `text` only where other processes can read it. Returns `false`
193    /// rather than keeping it in a buffer private to this process, so a
194    /// secret is never reported as copied when it was not. The default is
195    /// [`set_text`](Self::set_text), right for a backend that only reaches a
196    /// shared clipboard.
197    fn set_shared_text(&self, target: ClipboardTarget, text: &str) -> bool {
198        self.set_text(target, text)
199    }
200
201    /// Offer `text` on the Ctrl+V clipboard marked as a secret: a password,
202    /// a one-time code, an enrolment token. Other apps can still paste it as
203    /// plain text, but clipboard managers and Tilo's own history and device
204    /// sync are told not to keep it ([`SECRET_MIME`],
205    /// [`PASSWORD_MANAGER_HINT_MIME`]).
206    ///
207    /// Returns `false` rather than keeping the secret in a buffer private to
208    /// this process, so it is never reported as copied when it was not. The
209    /// default refuses: a backend must opt in to carrying secrets.
210    fn set_secret_text(&self, text: &str) -> bool {
211        let _ = text;
212        false
213    }
214
215    /// Start a Ctrl+C copy without waiting for it, and answer its outcome
216    /// through the returned [`ClipboardCopy`]. A copy through an app's own
217    /// Wayland connection waits on compositor roundtrips; this lets the UI
218    /// thread go on while it does, and wakes the app when it settles.
219    ///
220    /// The default copies now through the methods above, so its outcome is
221    /// settled before this returns.
222    fn copy(&self, content: CopyContent<'_>) -> ClipboardCopy {
223        copy_now(self, content)
224    }
225
226    /// Hold a Ctrl+C copy for text that is not known yet: a link the
227    /// person's click asks a host for. A browser copies only inside the
228    /// click, so a backend with that rule claims the clipboard now and
229    /// fills it once [`ReservedCopy::fill`] hands the text over. `None`
230    /// when this backend copies just as well later, or has no way to claim
231    /// the clipboard now; the text is then copied when it arrives.
232    fn reserve_text(&self) -> Option<ReservedCopy> {
233        None
234    }
235
236    fn name(&self) -> &'static str;
237}
238
239fn copy_now<B: ClipboardBackend + ?Sized>(backend: &B, content: CopyContent<'_>) -> ClipboardCopy {
240    ClipboardCopy::settled(match content {
241        CopyContent::Text(text) => backend.set_text(ClipboardTarget::Clipboard, text),
242        CopyContent::SharedText(text) => backend.set_shared_text(ClipboardTarget::Clipboard, text),
243        CopyContent::SecretText(text) => backend.set_secret_text(text),
244        CopyContent::Rich { html, plain } => backend.set_rich_text(html, plain),
245        CopyContent::Image {
246            width,
247            height,
248            rgba,
249        } => backend.set_image(width, height, rgba),
250    })
251}
252
253/// What a [`ClipboardBackend::copy`] puts on the Ctrl+C clipboard; each
254/// matches the blocking method of the same meaning.
255#[derive(Clone, Copy)]
256pub enum CopyContent<'a> {
257    Text(&'a str),
258    /// [`ClipboardBackend::set_shared_text`] — only where other processes
259    /// can read it.
260    SharedText(&'a str),
261    SecretText(&'a str),
262    /// [`ClipboardBackend::set_rich_text`] — formatted text as HTML with its
263    /// plain-text fallback.
264    Rich {
265        html: &'a str,
266        plain: &'a str,
267    },
268    /// [`ClipboardBackend::set_image`] — RGBA8, `width * height * 4` bytes.
269    Image {
270        width: usize,
271        height: usize,
272        rgba: &'a [u8],
273    },
274}
275
276impl std::fmt::Debug for CopyContent<'_> {
277    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
278        // Never the bytes: a secret must not reach a log.
279        match self {
280            Self::Text(text) => f.debug_tuple("Text").field(&text.len()).finish(),
281            Self::SharedText(text) => f.debug_tuple("SharedText").field(&text.len()).finish(),
282            Self::SecretText(_) => f.write_str("SecretText"),
283            Self::Rich { html, plain } => f
284                .debug_struct("Rich")
285                .field("html", &html.len())
286                .field("plain", &plain.len())
287                .finish(),
288            Self::Image { width, height, .. } => f
289                .debug_struct("Image")
290                .field("width", width)
291                .field("height", height)
292                .finish(),
293        }
294    }
295}
296
297/// The outcome of a [`ClipboardBackend::copy`]: copied, failed, or not
298/// known yet. It settles exactly once, and settling wakes the app that
299/// started the copy, so the app reads it on its next pass through its event
300/// loop.
301#[derive(Clone)]
302#[must_use = "a copy can fail after it returns; read its outcome"]
303pub struct ClipboardCopy {
304    state: std::sync::Arc<CopyState>,
305}
306
307struct CopyState {
308    progress: Mutex<CopyProgress>,
309    settled: std::sync::Condvar,
310    wake: tilo_rt::wake::WakeHandle,
311}
312
313#[derive(Default)]
314struct CopyProgress {
315    outcome: Option<bool>,
316    then: Vec<Box<dyn FnOnce(bool) + Send>>,
317}
318
319impl CopyState {
320    fn progress(&self) -> std::sync::MutexGuard<'_, CopyProgress> {
321        self.progress
322            .lock()
323            .unwrap_or_else(std::sync::PoisonError::into_inner)
324    }
325}
326
327impl ClipboardCopy {
328    pub fn settled(copied: bool) -> Self {
329        let (copy, settle) = Self::pending();
330        settle.settle(copied);
331        copy
332    }
333
334    pub fn pending() -> (Self, CopySettler) {
335        let state = std::sync::Arc::new(CopyState {
336            progress: Mutex::default(),
337            settled: std::sync::Condvar::new(),
338            wake: tilo_rt::wake::WakeHandle::new(),
339        });
340        (
341            Self {
342                state: std::sync::Arc::clone(&state),
343            },
344            CopySettler { state: Some(state) },
345        )
346    }
347
348    #[must_use]
349    pub fn outcome(&self) -> Option<bool> {
350        self.state.progress().outcome
351    }
352
353    pub fn on_settled(&self, then: impl FnOnce(bool) + Send + 'static) {
354        let mut progress = self.state.progress();
355        match progress.outcome {
356            Some(copied) => {
357                drop(progress);
358                then(copied);
359            }
360            None => progress.then.push(Box::new(then)),
361        }
362    }
363
364    /// Wait for the outcome. Only off the UI thread, which must never wait
365    /// on the compositor: a worker finishing an effect, say. Every copy
366    /// settles, if only as failed when whatever answers it goes away.
367    #[must_use]
368    pub fn wait(&self) -> bool {
369        let mut progress = self.state.progress();
370        loop {
371            if let Some(copied) = progress.outcome {
372                return copied;
373            }
374            progress = self
375                .state
376                .settled
377                .wait(progress)
378                .unwrap_or_else(std::sync::PoisonError::into_inner);
379        }
380    }
381}
382
383impl std::fmt::Debug for ClipboardCopy {
384    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
385        f.debug_tuple("ClipboardCopy")
386            .field(&self.outcome())
387            .finish()
388    }
389}
390
391/// Reports a pending [`ClipboardCopy`]'s outcome. Dropping it unsettled
392/// reports a failure, so a copy whose worker went away never stays pending.
393pub struct CopySettler {
394    state: Option<std::sync::Arc<CopyState>>,
395}
396
397impl CopySettler {
398    pub fn settle(mut self, copied: bool) {
399        self.finish(copied);
400    }
401
402    fn finish(&mut self, copied: bool) {
403        if let Some(state) = self.state.take() {
404            let then = {
405                let mut progress = state.progress();
406                progress.outcome = Some(copied);
407                std::mem::take(&mut progress.then)
408            };
409            state.settled.notify_all();
410            for then in then {
411                then(copied);
412            }
413            state.wake.wake();
414        }
415    }
416}
417
418impl Drop for CopySettler {
419    fn drop(&mut self) {
420        self.finish(false);
421    }
422}
423
424#[must_use = "dropping a reserved copy gives it up"]
425pub struct ReservedCopy {
426    fill: Option<Fill>,
427}
428
429type Fill = Box<dyn FnOnce(Option<&str>) -> ClipboardCopy + Send>;
430
431impl ReservedCopy {
432    pub fn new(fill: impl FnOnce(Option<&str>) -> ClipboardCopy + Send + 'static) -> Self {
433        Self {
434            fill: Some(Box::new(fill)),
435        }
436    }
437
438    pub fn fill(mut self, text: &str) -> ClipboardCopy {
439        self.fill
440            .take()
441            .map_or_else(|| ClipboardCopy::settled(false), |fill| fill(Some(text)))
442    }
443}
444
445impl Drop for ReservedCopy {
446    fn drop(&mut self) {
447        if let Some(fill) = self.fill.take() {
448            let _ = fill(None);
449        }
450    }
451}
452
453impl std::fmt::Debug for ReservedCopy {
454    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
455        f.write_str("ReservedCopy")
456    }
457}
458
459/// This process's clipboard: over the connection its session or launcher opened for it on Linux
460/// and macOS ([`service::ServiceClipboard`]), the Windows clipboard on Windows, which has no
461/// socket to carry the service, and the browser's clipboard on the web.
462pub fn system() -> std::sync::Arc<dyn ClipboardBackend> {
463    static SYSTEM: OnceLock<std::sync::Arc<dyn ClipboardBackend>> = OnceLock::new();
464    SYSTEM.get_or_init(backend).clone()
465}
466
467#[cfg(all(unix, not(all(target_arch = "wasm32", target_os = "unknown"))))]
468fn backend() -> std::sync::Arc<dyn ClipboardBackend> {
469    service::ServiceClipboard::from_env().map_or_else(unavailable, |clipboard| {
470        std::sync::Arc::new(clipboard) as std::sync::Arc<dyn ClipboardBackend>
471    })
472}
473
474#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
475fn backend() -> std::sync::Arc<dyn ClipboardBackend> {
476    std::sync::Arc::new(web::BrowserClipboard)
477}
478
479#[cfg(windows)]
480fn backend() -> std::sync::Arc<dyn ClipboardBackend> {
481    os()
482}
483
484#[cfg(not(any(unix, windows, all(target_arch = "wasm32", target_os = "unknown"))))]
485fn backend() -> std::sync::Arc<dyn ClipboardBackend> {
486    unavailable()
487}
488
489/// A clipboard that holds nothing and takes nothing: a process its session handed no clipboard
490/// connection, which must refuse rather than keep a copy that reaches no one.
491pub fn unavailable() -> std::sync::Arc<dyn ClipboardBackend> {
492    std::sync::Arc::new(Nowhere)
493}
494
495/// Whether `backend` is [`unavailable`]: a copy made to it can only be refused, so an app offers no
496/// Copy there.
497pub fn is_unavailable(backend: &dyn ClipboardBackend) -> bool {
498    backend.name() == Nowhere.name()
499}
500
501/// The operating system's clipboard of this process: the selection a person's own desktop holds.
502///
503/// This is for the process that serves an app's clipboard where no Tilo session does — the
504/// launcher, or `tilolang run` — not for an app, which talks only to [`service::Connected`]. It is
505/// `arboard`, the protocol for a client without focus: Wayland's data-control protocol, X11
506/// (including `XWayland`) where a compositor lacks data-control, `NSPasteboard` and the Windows
507/// clipboard; where none of those answers, a buffer private to the process.
508pub fn os() -> std::sync::Arc<dyn ClipboardBackend> {
509    #[cfg(any(target_os = "linux", target_os = "macos", windows))]
510    {
511        static OS: OnceLock<std::sync::Arc<dyn ClipboardBackend>> = OnceLock::new();
512        OS.get_or_init(|| std::sync::Arc::new(native::NativeClipboard::default()))
513            .clone()
514    }
515    #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
516    {
517        unavailable()
518    }
519}
520
521/// Emit the "this clipboard does not leave the process" warning exactly once.
522///
523/// Once per process, not once per call: a text editor pastes often, and a log
524/// line per keystroke would bury the fact instead of reporting it.
525pub fn warn_fallback_once(op: &str) {
526    static WARNED: OnceLock<()> = OnceLock::new();
527    WARNED.get_or_init(|| {
528        tracing::warn!(
529            target: "tilo_ui::clipboard",
530            operation = op,
531            "no system clipboard: falling back to an in-process buffer. Copy and paste \
532             will work inside this process and silently do nothing between processes. \
533             On Wayland this means the compositor offers neither \
534             zwlr_data_control_manager_v1 nor ext_data_control_v1 and no X11 (XWayland) \
535             clipboard is reachable either."
536        );
537    });
538}
539
540struct Nowhere;
541
542impl ClipboardBackend for Nowhere {
543    fn set_text(&self, _target: ClipboardTarget, _text: &str) -> bool {
544        false
545    }
546
547    fn text(&self, _target: ClipboardTarget) -> Option<String> {
548        None
549    }
550
551    fn name(&self) -> &'static str {
552        "unavailable"
553    }
554}
555
556/// A clipboard private to this process, for a host that performs nothing outside it: the inert
557/// services a test runs an app with, the session shell's primary selection, and Android's
558/// select-to-copy.
559///
560/// Keeps copy → paste round-tripping inside the process. It refuses
561/// [`ClipboardBackend::set_shared_text`], secrets and images.
562#[derive(Debug, Default)]
563pub struct InProcessClipboard {
564    clipboard: Mutex<Option<String>>,
565    primary: Mutex<Option<String>>,
566    rich: Mutex<Option<String>>,
567}
568
569impl InProcessClipboard {
570    fn slot(&self, target: ClipboardTarget) -> &Mutex<Option<String>> {
571        match target {
572            ClipboardTarget::Clipboard => &self.clipboard,
573            ClipboardTarget::Primary => &self.primary,
574        }
575    }
576}
577
578impl ClipboardBackend for InProcessClipboard {
579    fn set_text(&self, target: ClipboardTarget, text: &str) -> bool {
580        let Ok(mut slot) = self.slot(target).lock() else {
581            return false;
582        };
583        *slot = Some(text.to_string());
584        if target == ClipboardTarget::Clipboard
585            && let Ok(mut rich) = self.rich.lock()
586        {
587            *rich = None;
588        }
589        true
590    }
591
592    fn text(&self, target: ClipboardTarget) -> Option<String> {
593        self.slot(target).lock().ok()?.clone()
594    }
595
596    fn set_rich_text(&self, html: &str, plain: &str) -> bool {
597        if !self.set_text(ClipboardTarget::Clipboard, plain) {
598            return false;
599        }
600        let Ok(mut rich) = self.rich.lock() else {
601            return false;
602        };
603        *rich = Some(html.to_owned());
604        true
605    }
606
607    fn rich_text(&self) -> Option<RichTextOffer> {
608        let html = self.rich.lock().ok()?.clone()?;
609        let plain = self.text(ClipboardTarget::Clipboard);
610        Some(RichTextOffer { html, plain }).filter(RichTextOffer::is_valid)
611    }
612
613    fn set_shared_text(&self, _target: ClipboardTarget, _text: &str) -> bool {
614        false
615    }
616
617    fn name(&self) -> &'static str {
618        "in-process"
619    }
620}
621
622#[cfg(test)]
623pub(crate) mod tests {
624    use super::*;
625
626    /// Serialises tests that drive the process's one OS clipboard.
627    pub(crate) static SYSTEM: Mutex<()> = Mutex::new(());
628
629    #[test]
630    fn a_copy_settles_once_and_runs_what_waits_on_it() {
631        let (copy, settler) = ClipboardCopy::pending();
632        let (ran, outcomes) = std::sync::mpsc::channel();
633        let early = ran.clone();
634        copy.on_settled(move |copied| early.send(("before", copied)).unwrap());
635        assert_eq!(copy.outcome(), None);
636        assert!(
637            outcomes.try_recv().is_err(),
638            "nothing runs before it settles"
639        );
640        settler.settle(true);
641        assert_eq!(copy.outcome(), Some(true));
642        assert!(copy.wait());
643        copy.on_settled(move |copied| ran.send(("after", copied)).unwrap());
644        assert_eq!(
645            outcomes.try_iter().collect::<Vec<_>>(),
646            [("before", true), ("after", true)]
647        );
648
649        let (copy, settler) = ClipboardCopy::pending();
650        drop(settler);
651        assert_eq!(copy.outcome(), Some(false), "an abandoned copy failed");
652    }
653
654    #[test]
655    fn the_in_process_clipboard_keeps_text_inside_the_process() {
656        let clipboard = InProcessClipboard::default();
657        assert!(clipboard.set_text(ClipboardTarget::Clipboard, "local"));
658        assert_eq!(
659            clipboard.text(ClipboardTarget::Clipboard).as_deref(),
660            Some("local")
661        );
662        assert!(clipboard.set_rich_text("<b>bold</b>", "bold"));
663        assert_eq!(
664            clipboard.rich_text().map(|offer| offer.plain),
665            Some(Some("bold".to_owned()))
666        );
667        assert!(
668            !clipboard.set_shared_text(ClipboardTarget::Clipboard, "shared"),
669            "an in-process buffer does not claim a shared copy"
670        );
671        assert!(
672            !clipboard.set_secret_text("secret"),
673            "an in-process buffer does not claim a secret copy"
674        );
675        assert!(!clipboard.set_image(1, 1, &[0, 0, 0, 0]));
676        assert!(clipboard.image().is_none());
677    }
678
679    #[test]
680    fn a_process_handed_no_connection_holds_and_takes_nothing() {
681        let nowhere = unavailable();
682        assert!(!nowhere.set_text(ClipboardTarget::Clipboard, "lost"));
683        assert_eq!(nowhere.text(ClipboardTarget::Clipboard), None);
684        assert!(!nowhere.set_shared_text(ClipboardTarget::Clipboard, "lost"));
685        assert!(!nowhere.set_secret_text("lost"));
686        assert!(!nowhere.set_image(1, 1, &[0, 0, 0, 0]));
687        assert!(nowhere.image().is_none());
688        assert_eq!(nowhere.name(), "unavailable");
689    }
690
691    tilo_test_env::scenario! {
692        fn the_in_process_and_system_clipboards_conform;
693
694        phase the_in_process_clipboard_conforms;
695        {
696            conformance::check_local(&InProcessClipboard::default());
697        }
698
699        phase the_system_clipboard_conforms_with_or_without_a_system_clipboard;
700        {
701            let _system = SYSTEM.lock();
702            let system = os();
703            conformance::check_system(&*system);
704            assert!(std::ptr::addr_eq(
705                std::sync::Arc::as_ptr(&system),
706                std::sync::Arc::as_ptr(&self::os())
707            ));
708        }
709    }
710}