tilo-clipboard 0.5.2

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
//! Clipboard events a host dispatches to the app.
//!
//! A browser grants clipboard access only inside a trusted `copy`, `cut` or
//! `paste` event, or inside the user's click. The web runner wraps its
//! dispatch of such an event in [`during`] (or of a click in
//! [`during_input`]), and the web backend of [`system`](crate::system) reads
//! and writes through it. Nothing survives the event: a clipboard payload is
//! never kept past the dispatch that received it.
//!
//! The scopes compile and nest on every target, so a host's dispatch code has
//! no `cfg`; the desktop backends ignore them.

use std::cell::RefCell;
use std::rc::Rc;

/// The data of one trusted clipboard event (the browser's `DataTransfer`).
pub trait EventTransfer {
    fn set_text(&self, text: &str) -> bool;
    /// Offer `html` as `text/html` with `plain` as its `text/plain`
    /// fallback. Returns whether the event took both. The default offers
    /// only `plain`.
    fn set_rich_text(&self, html: &str, plain: &str) -> bool {
        let _ = html;
        self.set_text(plain)
    }
    fn text(&self) -> Option<String>;
    fn rich_text(&self) -> Option<crate::RichTextOffer> {
        None
    }
    fn image(&self) -> Option<crate::ClipboardImage> {
        None
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CopyReport {
    Copied,
    Failed(String),
}

type Report = Rc<dyn Fn(CopyReport)>;

/// Only the web backend reads the event; the desktop backends ignore it.
struct Transfer {
    #[cfg(any(test, all(target_arch = "wasm32", target_os = "unknown")))]
    data: Rc<dyn EventTransfer>,
    #[cfg(any(test, all(target_arch = "wasm32", target_os = "unknown")))]
    taken: Taken,
    copied: bool,
}

#[cfg(any(test, all(target_arch = "wasm32", target_os = "unknown")))]
#[derive(Default)]
struct Taken {
    read: bool,
    rich_attempted: bool,
    image: bool,
}

thread_local! {
    static TRANSFER: RefCell<Option<Transfer>> = const { RefCell::new(None) };
    static INPUT: RefCell<Option<Report>> = const { RefCell::new(None) };
}

pub fn during<R>(transfer: Rc<dyn EventTransfer>, run: impl FnOnce() -> R) -> R {
    struct Clear(Option<Transfer>);
    impl Drop for Clear {
        fn drop(&mut self) {
            let previous = self.0.take();
            TRANSFER.with_borrow_mut(|slot| *slot = previous);
        }
    }
    #[cfg(not(any(test, all(target_arch = "wasm32", target_os = "unknown"))))]
    drop(transfer);
    let previous = TRANSFER.with_borrow_mut(|slot| {
        slot.replace(Transfer {
            #[cfg(any(test, all(target_arch = "wasm32", target_os = "unknown")))]
            data: transfer,
            #[cfg(any(test, all(target_arch = "wasm32", target_os = "unknown")))]
            taken: Taken::default(),
            copied: false,
        })
    });
    let _clear = Clear(previous);
    run()
}

/// Run `run` while dispatching the user's input event (a click on Copy).
/// A copy made inside may publish through the browser's own copy command;
/// `report` hears how it ended.
pub fn during_input<R>(report: Rc<dyn Fn(CopyReport)>, run: impl FnOnce() -> R) -> R {
    struct Restore(Option<Report>);
    impl Drop for Restore {
        fn drop(&mut self) {
            let previous = self.0.take();
            INPUT.with_borrow_mut(|slot| *slot = previous);
        }
    }
    let _restore = Restore(INPUT.with_borrow_mut(|slot| slot.replace(report)));
    run()
}

/// Whether the app wrote the clipboard event being dispatched. A host uses it
/// to decide whether to suppress the browser's default cut.
pub fn copied() -> bool {
    TRANSFER.with_borrow(|slot| slot.as_ref().is_some_and(|t| t.copied))
}

pub fn in_event() -> bool {
    TRANSFER.with_borrow(Option::is_some)
}

#[cfg(any(test, all(target_arch = "wasm32", target_os = "unknown")))]
pub(crate) fn write(text: &str) -> Option<bool> {
    TRANSFER.with_borrow_mut(|slot| {
        let t = slot.as_mut()?;
        if !t.copied {
            t.copied = t.data.set_text(text);
        }
        Some(t.copied)
    })
}

#[cfg(any(test, all(target_arch = "wasm32", target_os = "unknown")))]
pub(crate) fn write_rich(html: &str, plain: &str) -> Option<bool> {
    TRANSFER.with_borrow_mut(|slot| {
        let t = slot.as_mut()?;
        if !t.copied {
            t.copied = t.data.set_rich_text(html, plain);
        }
        Some(t.copied)
    })
}

#[cfg(any(test, all(target_arch = "wasm32", target_os = "unknown")))]
pub(crate) fn read() -> Option<String> {
    TRANSFER.with_borrow_mut(|slot| {
        let t = slot.as_mut()?;
        if t.taken.read {
            return None;
        }
        t.taken.read = true;
        t.data.text().filter(|text| !text.is_empty())
    })
}

/// Probe rich text once. Only an accepted offer consumes the event's read;
/// missing, empty or oversized HTML leaves the ordinary plain read available.
#[cfg(any(test, all(target_arch = "wasm32", target_os = "unknown")))]
pub(crate) fn read_rich() -> Option<crate::RichTextOffer> {
    TRANSFER.with_borrow_mut(|slot| {
        let t = slot.as_mut()?;
        if t.taken.read || t.taken.rich_attempted {
            return None;
        }
        t.taken.rich_attempted = true;
        let offer = t.data.rich_text().filter(crate::RichTextOffer::is_valid)?;
        t.taken.read = true;
        Some(offer)
    })
}

#[cfg(any(test, all(target_arch = "wasm32", target_os = "unknown")))]
pub(crate) fn read_image() -> Option<crate::ClipboardImage> {
    TRANSFER.with_borrow_mut(|slot| {
        let t = slot.as_mut()?;
        if t.taken.image {
            return None;
        }
        t.taken.image = true;
        t.data
            .image()
            .filter(|image| image.bytes.len() <= crate::MAX_PASTED_IMAGE_BYTES)
    })
}

#[cfg(any(test, all(target_arch = "wasm32", target_os = "unknown")))]
pub(crate) fn input_report() -> Option<Report> {
    INPUT.with_borrow(Clone::clone)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::Cell;

    #[derive(Default)]
    struct Fake {
        offered: RefCell<Vec<String>>,
        offered_html: RefCell<Vec<String>>,
        text: Option<String>,
        refuse: bool,
        reads: Cell<usize>,
        rich: Option<crate::RichTextOffer>,
        rich_reads: Cell<usize>,
        image: Option<crate::ClipboardImage>,
    }

    impl EventTransfer for Fake {
        fn set_text(&self, text: &str) -> bool {
            self.offered.borrow_mut().push(text.to_owned());
            !self.refuse
        }
        fn set_rich_text(&self, html: &str, plain: &str) -> bool {
            self.offered_html.borrow_mut().push(html.to_owned());
            self.set_text(plain)
        }
        fn rich_text(&self) -> Option<crate::RichTextOffer> {
            self.rich_reads.set(self.rich_reads.get().saturating_add(1));
            self.rich.clone()
        }
        fn text(&self) -> Option<String> {
            self.reads.set(self.reads.get().saturating_add(1));
            self.text.clone()
        }
        fn image(&self) -> Option<crate::ClipboardImage> {
            self.image.clone()
        }
    }

    tilo_test_env::scenario! {
        fn an_events_transfer_is_written_and_read_once_and_only_inside_it;

        phase a_pasted_picture_is_read_once_inside_its_event;
        {
            let image = crate::ClipboardImage {
                mime: "image/png",
                bytes: vec![1, 2, 3],
            };
            let fake = Rc::new(Fake {
                image: Some(image.clone()),
                ..Fake::default()
            });
            assert_eq!(read_image(), None);
            during(fake, || {
                assert_eq!(read_image(), Some(image));
                assert_eq!(read_image(), None, "a picture is pasted once");
                assert_eq!(read(), None, "and is no text");
            });
            assert_eq!(read_image(), None);
        }

        phase an_event_is_written_and_read_once_and_nothing_outlives_it;
        {
            let fake = Rc::new(Fake {
                text: Some("pasted".into()),
                ..Fake::default()
            });
            assert_eq!(write("x"), None);
            during(fake.clone(), || {
                assert!(in_event());
                assert_eq!(read().as_deref(), Some("pasted"));
                assert_eq!(read(), None, "a paste is read once");
                assert_eq!(write("first"), Some(true));
                assert_eq!(write("second"), Some(true));
                assert!(copied());
            });
            assert!(!in_event());
            assert!(!copied());
            assert_eq!(*fake.offered.borrow(), ["first"]);
            assert_eq!(fake.reads.get(), 1);
        }

        phase a_rich_copy_writes_its_html_and_its_words_to_the_event_once;
        {
            let fake = Rc::new(Fake::default());
            assert_eq!(write_rich("<b>x</b>", "x"), None);
            during(fake.clone(), || {
                assert_eq!(write_rich("<b>first</b>", "first"), Some(true));
                assert_eq!(write("second"), Some(true));
                assert!(copied());
            });
            assert_eq!(*fake.offered_html.borrow(), ["<b>first</b>"]);
            assert_eq!(*fake.offered.borrow(), ["first"]);
        }

        phase a_refused_write_is_not_copied_and_scopes_nest;
        {
            let refusing = Rc::new(Fake {
                refuse: true,
                ..Fake::default()
            });
            let outer = Rc::new(Fake::default());
            during(outer.clone(), || {
                during(refusing.clone(), || {
                    assert_eq!(write("secret"), Some(false));
                    assert!(!copied());
                });
                assert_eq!(write("outer"), Some(true));
            });
            assert_eq!(*outer.offered.borrow(), ["outer"]);
        }

        phase input_reports_are_scoped;
        {
            assert!(input_report().is_none());
            let heard = Rc::new(RefCell::new(Vec::new()));
            let sink = heard.clone();
            during_input(Rc::new(move |r| sink.borrow_mut().push(r)), || {
                input_report().unwrap()(CopyReport::Copied);
            });
            assert!(input_report().is_none());
            assert_eq!(*heard.borrow(), [CopyReport::Copied]);
        }
    }

    tilo_test_env::scenario! {
        fn a_rich_offer_is_probed_once_and_falls_back_to_plain;

        phase rich_offer_captures_fallback_and_consumes_the_event_once;
        {
            let offer = crate::RichTextOffer {
                html: "<b>Ä😀</b>".into(),
                plain: Some("paired Ä😀\n".into()),
            };
            let fake = Rc::new(Fake {
                rich: Some(offer.clone()),
                text: Some("must not reread".into()),
                ..Fake::default()
            });
            assert_eq!(read_rich(), None);
            during(fake.clone(), || {
                assert_eq!(read_rich(), Some(offer));
                assert_eq!(read(), None);
                assert_eq!(read_rich(), None);
            });
            assert_eq!(read_rich(), None);
            assert_eq!(fake.rich_reads.get(), 1);
            assert_eq!(fake.reads.get(), 0);
        }

        phase refused_rich_offers_leave_plain_available_without_repeated_probes;
        {
            for rich in [
                None,
                Some(crate::RichTextOffer {
                    html: String::new(),
                    plain: None,
                }),
                Some(crate::RichTextOffer {
                    html: "a".repeat(crate::MAX_CLIPBOARD_HTML_BYTES + 1),
                    plain: None,
                }),
                Some(crate::RichTextOffer {
                    html: "<p>small</p>".into(),
                    plain: Some("a".repeat(crate::MAX_CLIPBOARD_PLAIN_FALLBACK_BYTES + 1)),
                }),
            ] {
                let fake = Rc::new(Fake {
                    rich,
                    text: Some("ordinary text".into()),
                    ..Fake::default()
                });
                during(fake.clone(), || {
                    assert_eq!(read_rich(), None);
                    assert_eq!(read_rich(), None);
                    assert_eq!(read().as_deref(), Some("ordinary text"));
                    assert_eq!(read(), None);
                });
                assert_eq!(fake.rich_reads.get(), 1);
                assert_eq!(fake.reads.get(), 1);
            }
        }

        phase plain_first_prevents_a_later_rich_read;
        {
            let fake = Rc::new(Fake {
                rich: Some(crate::RichTextOffer {
                    html: "<b>secret</b>".into(),
                    plain: None,
                }),
                text: Some("plain".into()),
                ..Fake::default()
            });
            during(fake.clone(), || {
                assert_eq!(read().as_deref(), Some("plain"));
                assert_eq!(read_rich(), None);
            });
            assert_eq!(fake.rich_reads.get(), 0);
        }

        phase nested_rich_scopes_restore_outer_payload_and_consumption;
        {
            let outer = Rc::new(Fake {
                rich: Some(crate::RichTextOffer {
                    html: "outer".into(),
                    plain: None,
                }),
                ..Fake::default()
            });
            let inner = Rc::new(Fake {
                rich: Some(crate::RichTextOffer {
                    html: "inner".into(),
                    plain: Some("paired".into()),
                }),
                ..Fake::default()
            });
            during(outer.clone(), || {
                during(inner.clone(), || {
                    assert_eq!(read_rich(), inner.rich);
                });
                assert_eq!(read_rich(), outer.rich);
                during(inner.clone(), || {
                    assert_eq!(read_rich(), inner.rich);
                });
                assert_eq!(read_rich(), None);
                assert_eq!(read(), None);
            });
            assert_eq!(read_rich(), None);
            assert_eq!(outer.rich_reads.get(), 1);
            assert_eq!(inner.rich_reads.get(), 2);
        }

        phase rich_limits_count_utf8_bytes_and_diagnostics_omit_payloads;
        {
            let mut offer = crate::RichTextOffer {
                html: "😀".repeat(crate::MAX_CLIPBOARD_HTML_BYTES / 4),
                plain: Some("p".repeat(crate::MAX_CLIPBOARD_PLAIN_FALLBACK_BYTES)),
            };
            assert!(offer.is_valid());
            offer.html.push('x');
            assert!(!offer.is_valid());
            let diagnostic = format!("{offer:?}");
            assert!(!diagnostic.contains('😀'));
            assert!(diagnostic.contains("html_bytes"));
            assert!(diagnostic.len() < 100);
        }
    }
}