tilo-clipboard 0.5.1

The clipboard on Linux, macOS and the web: text, images and the primary selection, behind the connection an app's session or launcher serves it on.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
#![cfg_attr(
    test,
    allow(
        clippy::disallowed_methods,
        reason = "in a test these are the assertion, not a hazard"
    )
)]

//! The clipboard: one API on Linux, macOS and the web.
//!
//! [`ClipboardBackend`] is the boundary a host fills; [`system`] is this process's clipboard:
//!
//! | Target | Backend |
//! |---|---|
//! | Linux, macOS | the connection the app's session or launcher opened for it ([`service::Connected`]) |
//! | Web | the trusted clipboard event being dispatched ([`events`]), else a synchronous copy inside the user's click |
//!
//! An app runs in a process of its own, so it holds no selection to offer or read: the process
//! that holds the person's selection serves it, and an app's copies and pastes cross to it over the
//! one service ([`service`]) whether the app is written in Rust or in tilolang. Where a Tilo
//! session serves no clipboard — a person's own macOS, Windows or Linux desktop, or `tilolang run`
//! outside a session — the launcher serves the same wire from the operating system's clipboard
//! ([`os`]). A process handed no connection (the launch runs without services) copies nothing and
//! pastes nothing, rather than keeping a copy that reaches no one.

use std::sync::{Mutex, OnceLock};

mod caps;
pub use caps::{Availability, Feature, Unsupported, availability, available};

pub mod conformance;
pub mod events;
/// The clipboard over a connection an app's session or launcher opened for it: `serve` answers on
/// the serving end, [`service::Connected`] and [`service::ServiceClipboard`] are the app's.
#[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;

/// Largest plain-text fallback captured with a rich clipboard offer.
pub const MAX_CLIPBOARD_PLAIN_FALLBACK_BYTES: usize = 1024 * 1024;

/// HTML and its optional plain fallback captured from the same clipboard offer.
/// Adapters must bound payloads before copying them into this value. Decoders
/// may use this fallback after rejecting HTML, without rereading the clipboard.
#[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()
    }
}

/// Marks a Tilo copy as a secret: the compositor keeps it out of clipboard
/// history and never syncs it to the person's other devices. Its bytes are
/// [`SECRET_MARKER`].
pub const SECRET_MIME: &str = "application/x-tilo-secret";

/// The password-manager convention other Linux clipboard managers honour
/// (KDE Klipper, `cliphist`, `CopyQ`): an offer carrying it is kept out of
/// their histories. Its bytes are [`SECRET_MARKER`].
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,
    /// The image file's bytes, as the copying app offered them.
    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,
    /// The select-then-middle-click-paste primary selection. Distinct storage
    /// from [`ClipboardTarget::Clipboard`] — a terminal writes it on every
    /// drag-select without disturbing what the user last copied. Only Linux
    /// has one ([`Feature::PrimarySelection`]).
    Primary,
}

/// A source of clipboard content for this process.
///
/// Implementors must be cheap to call and must never block on the compositor's
/// event loop from a widget's event handler — a host backend reads a mirror
/// in memory, and the Wayland backend does its protocol work on its own
/// thread.
pub trait ClipboardBackend: Send + Sync {
    fn set_text(&self, target: ClipboardTarget, text: &str) -> bool;

    /// Read `target` as UTF-8. `None` when it is empty, unavailable, or holds
    /// something that is not text.
    fn text(&self, target: ClipboardTarget) -> Option<String>;

    /// Request text for an explicit paste. A native transfer may finish after
    /// this call returns; the backend must wake its owner when it answers.
    /// No answer may substitute text from an older selection or focus owner.
    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
    }

    /// Read HTML and its plain fallback from one Ctrl+V clipboard offer.
    /// Optional: unsupported backends return `None` without reading plain text.
    /// A successful read consumes event-scoped offers; use the captured plain
    /// fallback if decoding refuses the HTML. Never reread to recover a stale
    /// selection, a permission refusal, or an active composition.
    fn rich_text(&self) -> Option<RichTextOffer> {
        None
    }

    /// Take the Ctrl+C clipboard and offer formatted text on it: `html` as
    /// `text/html` and `plain` as its plain-text fallback, both from one
    /// copy, so an app that reads formatting pastes the formatting and every
    /// other app the words. Returns `false` if the backend could not.
    ///
    /// The default offers only `plain`, for a backend that carries no
    /// formatting; every system clipboard overrides it.
    fn set_rich_text(&self, html: &str, plain: &str) -> bool {
        let _ = html;
        self.set_text(ClipboardTarget::Clipboard, plain)
    }

    /// Offer an RGBA8 image on the clipboard. Optional: the default refuses,
    /// which is appropriate for backends that only carry text.
    fn set_image(&self, width: usize, height: usize, rgba: &[u8]) -> bool {
        let _ = (width, height, rgba);
        false
    }

    /// The image on the Ctrl+V clipboard, when it holds one: a screenshot,
    /// an image copied in a viewer or a browser. Optional: the default reads
    /// none, which is right for backends that only carry text.
    fn image(&self) -> Option<ClipboardImage> {
        None
    }

    /// Offer `text` only where other processes can read it. Returns `false`
    /// rather than keeping it in a buffer private to this process, so a
    /// secret is never reported as copied when it was not. The default is
    /// [`set_text`](Self::set_text), right for a backend that only reaches a
    /// shared clipboard.
    fn set_shared_text(&self, target: ClipboardTarget, text: &str) -> bool {
        self.set_text(target, text)
    }

    /// Offer `text` on the Ctrl+V clipboard marked as a secret: a password,
    /// a one-time code, an enrolment token. Other apps can still paste it as
    /// plain text, but clipboard managers and Tilo's own history and device
    /// sync are told not to keep it ([`SECRET_MIME`],
    /// [`PASSWORD_MANAGER_HINT_MIME`]).
    ///
    /// Returns `false` rather than keeping the secret in a buffer private to
    /// this process, so it is never reported as copied when it was not. The
    /// default refuses: a backend must opt in to carrying secrets.
    fn set_secret_text(&self, text: &str) -> bool {
        let _ = text;
        false
    }

    /// Start a Ctrl+C copy without waiting for it, and answer its outcome
    /// through the returned [`ClipboardCopy`]. A copy through an app's own
    /// Wayland connection waits on compositor roundtrips; this lets the UI
    /// thread go on while it does, and wakes the app when it settles.
    ///
    /// The default copies now through the methods above, so its outcome is
    /// settled before this returns.
    fn copy(&self, content: CopyContent<'_>) -> ClipboardCopy {
        copy_now(self, content)
    }

    /// Hold a Ctrl+C copy for text that is not known yet: a link the
    /// person's click asks a host for. A browser copies only inside the
    /// click, so a backend with that rule claims the clipboard now and
    /// fills it once [`ReservedCopy::fill`] hands the text over. `None`
    /// when this backend copies just as well later, or has no way to claim
    /// the clipboard now; the text is then copied when it arrives.
    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),
    })
}

/// What a [`ClipboardBackend::copy`] puts on the Ctrl+C clipboard; each
/// matches the blocking method of the same meaning.
#[derive(Clone, Copy)]
pub enum CopyContent<'a> {
    Text(&'a str),
    /// [`ClipboardBackend::set_shared_text`] — only where other processes
    /// can read it.
    SharedText(&'a str),
    SecretText(&'a str),
    /// [`ClipboardBackend::set_rich_text`] — formatted text as HTML with its
    /// plain-text fallback.
    Rich {
        html: &'a str,
        plain: &'a str,
    },
    /// [`ClipboardBackend::set_image`] — RGBA8, `width * height * 4` bytes.
    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 {
        // Never the bytes: a secret must not reach a log.
        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(),
        }
    }
}

/// The outcome of a [`ClipboardBackend::copy`]: copied, failed, or not
/// known yet. It settles exactly once, and settling wakes the app that
/// started the copy, so the app reads it on its next pass through its event
/// loop.
#[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)),
        }
    }

    /// Wait for the outcome. Only off the UI thread, which must never wait
    /// on the compositor: a worker finishing an effect, say. Every copy
    /// settles, if only as failed when whatever answers it goes away.
    #[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()
    }
}

/// Reports a pending [`ClipboardCopy`]'s outcome. Dropping it unsettled
/// reports a failure, so a copy whose worker went away never stays pending.
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")
    }
}

/// This process's clipboard: over the connection its session or launcher opened for it on Linux
/// and macOS ([`service::ServiceClipboard`]), the Windows clipboard on Windows, which has no
/// socket to carry the service, and the browser's clipboard on the web.
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()
}

/// A clipboard that holds nothing and takes nothing: a process its session handed no clipboard
/// connection, which must refuse rather than keep a copy that reaches no one.
pub fn unavailable() -> std::sync::Arc<dyn ClipboardBackend> {
    std::sync::Arc::new(Nowhere)
}

/// Whether `backend` is [`unavailable`]: a copy made to it can only be refused, so an app offers no
/// Copy there.
pub fn is_unavailable(backend: &dyn ClipboardBackend) -> bool {
    backend.name() == Nowhere.name()
}

/// The operating system's clipboard of this process: the selection a person's own desktop holds.
///
/// This is for the process that serves an app's clipboard where no Tilo session does — the
/// launcher, or `tilolang run` — not for an app, which talks only to [`service::Connected`]. It is
/// `arboard`, the protocol for a client without focus: Wayland's data-control protocol, X11
/// (including `XWayland`) where a compositor lacks data-control, `NSPasteboard` and the Windows
/// clipboard; where none of those answers, a buffer private to the process.
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()
    }
}

/// Emit the "this clipboard does not leave the process" warning exactly once.
///
/// Once per process, not once per call: a text editor pastes often, and a log
/// line per keystroke would bury the fact instead of reporting it.
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"
    }
}

/// A clipboard private to this process, for a host that performs nothing outside it: the inert
/// services a test runs an app with, the session shell's primary selection, and Android's
/// select-to-copy.
///
/// Keeps copy → paste round-tripping inside the process. It refuses
/// [`ClipboardBackend::set_shared_text`], secrets and images.
#[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::*;

    /// Serialises tests that drive the process's one OS clipboard.
    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())
            ));
        }
    }
}