Skip to main content

tilo_clipboard/
service.rs

1//! The clipboard as a service: an app's copies and pastes over the connection its session
2//! opened for it, answered by the process that holds the person's selection.
3//!
4//! An app runs in a process of its own, so the selection is not there to offer or read: the
5//! session holds it, and this is the wire between the two. That wire is the one an app reaches
6//! the clipboard through in either language — [`Connected`] for tilolang's runtime and
7//! [`ServiceClipboard`] for a Rust `ui` app — so a copy an app makes is the person's copy
8//! wherever it was made. Every message is one length-prefixed text header and, for each format
9//! whose bytes it carries, one length-prefixed body after it — the framing every socket in the
10//! tree uses ([`wire_frame`]).
11//!
12//! A side is whatever answers on the session's end ([`ClipboardSide`]): the session's own
13//! clipboard, so what an app copies is the person's copy (it lands in their history and on every
14//! app's clipboard) and what it pastes is what they copied anywhere.
15
16use std::io::Write as _;
17use std::sync::{Arc, Mutex, MutexGuard};
18use std::time::Duration;
19use tilo_socket::Stream;
20
21use wire_frame::Framing;
22
23use crate::{
24    ClipboardBackend, ClipboardImage, ClipboardTarget, CopyContent,
25    MAX_CLIPBOARD_IMAGE_INPUT_BYTES, MAX_CLIPBOARD_PLAIN_FALLBACK_BYTES, MAX_PASTED_IMAGE_BYTES,
26    RichTextOffer,
27};
28
29/// The descriptor the launcher hands an app it starts (`TILO_SVC_CLIPBOARD_FD`): the app's end of
30/// the connection served here.
31pub const FD_ENV: &str = "TILO_SVC_CLIPBOARD_FD";
32
33/// A request's header: `copy <target> <plain|secret> <n> <mime>…`,
34/// `paste <target> <n> <type>…`, or `quit`.
35const HEADER: Framing = Framing::little_endian(4096);
36/// The bytes one copy offers or one paste answers: an image as copied anywhere, held to the bound
37/// the clipboard itself sets for one taken in.
38const BODY: Framing = Framing::little_endian(MAX_CLIPBOARD_IMAGE_INPUT_BYTES);
39/// The longest text one copy or paste carries.
40const TEXT: usize = MAX_CLIPBOARD_PLAIN_FALLBACK_BYTES;
41
42/// Which selection a copy or paste is about.
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44pub enum Target {
45    /// Ctrl+C and Ctrl+V.
46    Clipboard,
47    /// Select, then middle-click.
48    Primary,
49}
50
51impl Target {
52    fn name(self) -> &'static str {
53        match self {
54            Self::Clipboard => "clipboard",
55            Self::Primary => "primary",
56        }
57    }
58
59    fn parse(word: &str) -> Option<Self> {
60        match word {
61            "clipboard" => Some(Self::Clipboard),
62            "primary" => Some(Self::Primary),
63            _ => None,
64        }
65    }
66}
67
68/// One copy's media types and their bytes.
69type Formats = Vec<(String, Vec<u8>)>;
70
71/// What answers on the session's end of an app's clipboard connection: the selection the
72/// person's device holds.
73pub trait ClipboardSide: Send + Sync {
74    /// Offer `formats` — one copy's media types and their bytes — as the person's copy on
75    /// `target`. `secret` marks a copy that histories and device sync must not keep. False when
76    /// the selection could not take it.
77    fn copy(&self, target: Target, secret: bool, formats: &[(String, Vec<u8>)]) -> bool;
78
79    /// What the selection holds of the `types` it offers on `target`, each requested type it
80    /// holds with its bytes. Empty when it holds none of them.
81    fn paste(&self, target: Target, types: &[&str]) -> Formats;
82}
83
84/// Serve an app's clipboard requests on `stream` until it closes the connection.
85pub fn serve(stream: Stream, side: &dyn ClipboardSide) {
86    let Ok(mut writer) = stream.try_clone() else {
87        return;
88    };
89    let mut reader = stream;
90    loop {
91        let Ok(Some(header)) = HEADER.read(&mut reader) else {
92            return;
93        };
94        let Ok(text) = String::from_utf8(header) else {
95            return;
96        };
97        let mut words = text.split_whitespace();
98        match words.next() {
99            Some("copy") => {
100                let Some((target, secret, formats)) = copy_request(&mut words, &mut reader) else {
101                    return;
102                };
103                let answer: &[u8] = if side.copy(target, secret, &formats) {
104                    b"ok"
105                } else {
106                    b"no"
107                };
108                if HEADER.write(&mut writer, answer).is_err() || writer.flush().is_err() {
109                    return;
110                }
111            }
112            Some("paste") => {
113                let Some((target, types)) = paste_request(&mut words) else {
114                    return;
115                };
116                let types: Vec<&str> = types.iter().map(String::as_str).collect();
117                let held = side.paste(target, &types);
118                let mut header = format!("pasted {}", held.len());
119                for (mime, bytes) in &held {
120                    header.push(' ');
121                    header.push_str(mime);
122                    header.push(' ');
123                    header.push_str(&bytes.len().to_string());
124                }
125                let wrote = HEADER.write(&mut writer, header.as_bytes()).and_then(|()| {
126                    held.iter()
127                        .try_for_each(|(_, bytes)| BODY.write(&mut writer, bytes))
128                });
129                if wrote.is_err() || writer.flush().is_err() {
130                    return;
131                }
132            }
133            _ => return,
134        }
135    }
136}
137
138/// The most formats one copy or paste may name: a rich copy offers two, and a paste asks for the
139/// types it reads, so a request naming far more is not one an app makes.
140const MAX_FORMATS: usize = 8;
141
142/// The target, secrecy and formats of a copy request, its bodies read from `reader`.
143fn copy_request(
144    words: &mut std::str::SplitWhitespace<'_>,
145    reader: &mut Stream,
146) -> Option<(Target, bool, Formats)> {
147    let target = Target::parse(words.next()?)?;
148    let secret = match words.next()? {
149        "secret" => true,
150        "plain" => false,
151        _ => return None,
152    };
153    let count: usize = words.next()?.parse().ok()?;
154    if count > MAX_FORMATS {
155        return None;
156    }
157    let mut formats = Vec::with_capacity(count);
158    for _ in 0..count {
159        let mime = words.next()?.to_owned();
160        let body = BODY.read(reader).ok()??;
161        if body.len() > most_of(&mime) {
162            return None;
163        }
164        formats.push((mime, body));
165    }
166    Some((target, secret, formats))
167}
168
169/// The target and wanted types of a paste request.
170fn paste_request(words: &mut std::str::SplitWhitespace<'_>) -> Option<(Target, Vec<String>)> {
171    let target = Target::parse(words.next()?)?;
172    let count: usize = words.next()?.parse().ok()?;
173    if count > MAX_FORMATS {
174        return None;
175    }
176    let types = words.take(count).map(str::to_owned).collect();
177    Some((target, types))
178}
179
180/// The most a copy may offer of `mime`: a text is held to what text is, an image to what an image
181/// taken in may be.
182#[must_use]
183pub fn most_of(mime: &str) -> usize {
184    if mime.starts_with("text/") {
185        TEXT
186    } else {
187        MAX_CLIPBOARD_IMAGE_INPUT_BYTES
188    }
189}
190
191/// The media types a paste of an image asks for, in the order the device's clipboard is asked:
192/// the types an image copied anywhere (a screenshot, a browser, a viewer) is offered as.
193const IMAGE_TYPES: [&str; 3] = ["image/png", "image/jpeg", "image/webp"];
194
195/// How long an app waits for the session's answer: a paste waits on the app that owns the
196/// selection, which answers when it gets round to it, and never for good.
197const WAIT: Duration = Duration::from_secs(30);
198
199/// An app's end of the clipboard connection: what its runtime copies and pastes through.
200pub struct Connected {
201    writer: Mutex<Stream>,
202    reader: Mutex<Stream>,
203}
204
205fn held<T>(lock: Result<T, std::sync::PoisonError<T>>) -> T {
206    lock.unwrap_or_else(std::sync::PoisonError::into_inner)
207}
208
209impl Connected {
210    /// The clipboard over `stream`, the connection the session opened for the app; none when the
211    /// connection cannot be read or written.
212    #[must_use]
213    pub fn connect(stream: Stream) -> Option<Self> {
214        let reader = stream.try_clone().ok()?;
215        let _ = reader.set_read_timeout(Some(WAIT));
216        let _ = reader.set_write_timeout(Some(WAIT));
217        Some(Self {
218            reader: Mutex::new(reader),
219            writer: Mutex::new(stream),
220        })
221    }
222
223    /// Offer `bytes` of `mime` as the person's copy: false when the session did not take it.
224    #[must_use]
225    pub fn copy(&self, mime: &str, bytes: &[u8]) -> bool {
226        self.copy_formats(Target::Clipboard, false, &[(mime, bytes)])
227    }
228
229    /// Offer `text` as a secret copy (a password, a token, a key) that histories and device sync
230    /// must not keep, and take it off the clipboard after `clear_after` unless the person copied
231    /// something else meanwhile, so a later copy is never destroyed: what a Rust app's
232    /// `ui::try_clipboard_copy_secret` does, for tilolang's runtime. False when the session did
233    /// not take it.
234    #[must_use]
235    pub fn copy_secret(self: &Arc<Self>, text: &str, clear_after: Duration) -> bool {
236        if !self.copy_formats(Target::Clipboard, true, &[("text/plain", text.as_bytes())]) {
237            return false;
238        }
239        let clipboard = Arc::clone(self);
240        let secret = text.to_owned();
241        let cleared = std::thread::Builder::new()
242            .name("clipboard-secret-clear".to_owned())
243            .spawn(move || {
244                std::thread::sleep(clear_after);
245                let held = clipboard.paste(&["text/plain"]);
246                if held.is_some_and(|(_, bytes)| bytes == secret.as_bytes()) {
247                    let _ = clipboard.copy_formats(Target::Clipboard, true, &[("text/plain", b"")]);
248                }
249            });
250        // A clear that cannot be scheduled must not leave the secret behind: take it back now.
251        if cleared.is_err() {
252            let _ = self.copy_formats(Target::Clipboard, true, &[("text/plain", b"")]);
253            return false;
254        }
255        true
256    }
257
258    /// Offer `formats` as the person's copy on `target`, marked secret for a copy histories and
259    /// device sync must not keep: false when the session did not take it, or a format is larger
260    /// than the clipboard holds.
261    #[must_use]
262    pub fn copy_formats(&self, target: Target, secret: bool, formats: &[(&str, &[u8])]) -> bool {
263        if formats
264            .iter()
265            .any(|(mime, bytes)| bytes.len() > most_of(mime))
266        {
267            return false;
268        }
269        let mimes: Vec<&str> = formats.iter().map(|(mime, _)| *mime).collect();
270        let header = format!(
271            "copy {} {} {} {}",
272            target.name(),
273            if secret { "secret" } else { "plain" },
274            formats.len(),
275            mimes.join(" ")
276        );
277        let mut writer: MutexGuard<'_, Stream> = held(self.writer.lock());
278        let sent = HEADER
279            .write(&mut *writer, header.as_bytes())
280            .and_then(|()| {
281                formats
282                    .iter()
283                    .try_for_each(|(_, bytes)| BODY.write(&mut *writer, bytes))
284            });
285        if sent.is_err() || writer.flush().is_err() {
286            return false;
287        }
288        drop(writer);
289        let mut reader = held(self.reader.lock());
290        matches!(HEADER.read(&mut *reader), Ok(Some(answer)) if answer.as_slice() == b"ok")
291    }
292
293    /// What the selection holds of the first of `types` it offers, as its media type and bytes.
294    #[must_use]
295    pub fn paste(&self, types: &[&str]) -> Option<(String, Vec<u8>)> {
296        self.paste_formats(Target::Clipboard, types)
297            .into_iter()
298            .next()
299    }
300
301    /// What the selection holds of each of `types` it offers on `target`, each with its bytes.
302    #[must_use]
303    pub fn paste_formats(&self, target: Target, types: &[&str]) -> Formats {
304        let header = format!(
305            "paste {} {} {}",
306            target.name(),
307            types.len(),
308            types.join(" ")
309        );
310        let mut writer = held(self.writer.lock());
311        if HEADER.write(&mut *writer, header.as_bytes()).is_err() || writer.flush().is_err() {
312            return Vec::new();
313        }
314        drop(writer);
315        let mut reader = held(self.reader.lock());
316        let Ok(Some(reply)) = HEADER.read(&mut *reader) else {
317            return Vec::new();
318        };
319        let Ok(reply) = String::from_utf8(reply) else {
320            return Vec::new();
321        };
322        let mut words = reply.split_whitespace();
323        if words.next() != Some("pasted") {
324            return Vec::new();
325        }
326        let Some(count) = words.next().and_then(|count| count.parse().ok()) else {
327            return Vec::new();
328        };
329        if count > MAX_FORMATS {
330            return Vec::new();
331        }
332        let mut pasted = Vec::with_capacity(count);
333        for _ in 0..count {
334            let (Some(mime), Some(limit)) = (
335                words.next().map(str::to_owned),
336                words.next().and_then(|limit| limit.parse::<usize>().ok()),
337            ) else {
338                return Vec::new();
339            };
340            let Ok(Some(bytes)) = BODY.read(&mut *reader) else {
341                return Vec::new();
342            };
343            // The header bounds what is read: a body of another length is not the paste it named.
344            if bytes.len() != limit {
345                return Vec::new();
346            }
347            pasted.push((mime, bytes));
348        }
349        drop(reader);
350        pasted
351    }
352}
353
354/// An app's clipboard as its `ClipboardBackend`: a Rust `ui` app's copies and pastes over the
355/// session's connection, the same service [`Connected`] reaches in tilolang.
356pub struct ServiceClipboard(Connected);
357
358impl ServiceClipboard {
359    /// The clipboard over the connection the session opened for this app, named by [`FD_ENV`];
360    /// none when this process was handed none.
361    #[cfg(unix)]
362    #[must_use]
363    pub fn from_env() -> Option<Self> {
364        let fd = std::env::var(FD_ENV).ok()?.parse::<i32>().ok()?;
365        if fd < 0 {
366            return None;
367        }
368        // SAFETY: the launcher passes this descriptor to this process, and it is this process's
369        // from here: nothing else in the app holds the number.
370        let stream = Stream::from(unsafe {
371            <std::os::fd::OwnedFd as std::os::fd::FromRawFd>::from_raw_fd(fd)
372        });
373        Some(Self(Connected::connect(stream)?))
374    }
375}
376
377impl ClipboardBackend for ServiceClipboard {
378    fn set_text(&self, target: ClipboardTarget, text: &str) -> bool {
379        self.0.copy_formats(
380            service_target(target),
381            false,
382            &[("text/plain", text.as_bytes())],
383        )
384    }
385
386    fn text(&self, target: ClipboardTarget) -> Option<String> {
387        let (_, bytes) = self
388            .0
389            .paste_formats(service_target(target), &["text/plain"])
390            .into_iter()
391            .next()?;
392        String::from_utf8(bytes).ok()
393    }
394
395    fn request_text(&self, target: ClipboardTarget) -> std::sync::mpsc::Receiver<Option<String>> {
396        let (reply, result) = std::sync::mpsc::channel();
397        let _ = reply.send(self.text(target));
398        result
399    }
400
401    fn set_shared_text(&self, target: ClipboardTarget, text: &str) -> bool {
402        // Every copy through the service is one other processes read.
403        self.set_text(target, text)
404    }
405
406    fn set_secret_text(&self, text: &str) -> bool {
407        self.0
408            .copy_formats(Target::Clipboard, true, &[("text/plain", text.as_bytes())])
409    }
410
411    fn set_rich_text(&self, html: &str, plain: &str) -> bool {
412        self.0.copy_formats(
413            Target::Clipboard,
414            false,
415            &[
416                ("text/html", html.as_bytes()),
417                ("text/plain", plain.as_bytes()),
418            ],
419        )
420    }
421
422    fn rich_text(&self) -> Option<RichTextOffer> {
423        let held = self
424            .0
425            .paste_formats(Target::Clipboard, &["text/html", "text/plain"]);
426        let html = held
427            .iter()
428            .find(|(mime, _)| mime == "text/html")
429            .map(|(_, bytes)| String::from_utf8_lossy(bytes).into_owned())?;
430        let plain = held
431            .iter()
432            .find(|(mime, _)| mime == "text/plain")
433            .map(|(_, bytes)| String::from_utf8_lossy(bytes).into_owned());
434        Some(RichTextOffer { html, plain }).filter(RichTextOffer::is_valid)
435    }
436
437    fn set_image(&self, width: usize, height: usize, rgba: &[u8]) -> bool {
438        let Some(png) = crate::images::encode_png(width, height, rgba) else {
439            return false;
440        };
441        self.0
442            .copy_formats(Target::Clipboard, false, &[("image/png", &png)])
443    }
444
445    fn image(&self) -> Option<ClipboardImage> {
446        let (mime, bytes) = self
447            .0
448            .paste_formats(Target::Clipboard, &IMAGE_TYPES)
449            .into_iter()
450            .next()?;
451        if bytes.len() > MAX_PASTED_IMAGE_BYTES {
452            return None;
453        }
454        Some(ClipboardImage {
455            mime: IMAGE_TYPES
456                .into_iter()
457                .find(|known| *known == mime)
458                .unwrap_or(IMAGE_TYPES[0]),
459            bytes,
460        })
461    }
462
463    fn copy(&self, content: CopyContent<'_>) -> crate::ClipboardCopy {
464        crate::copy_now(self, content)
465    }
466
467    fn name(&self) -> &'static str {
468        "session"
469    }
470}
471
472fn service_target(target: ClipboardTarget) -> Target {
473    match target {
474        ClipboardTarget::Clipboard => Target::Clipboard,
475        ClipboardTarget::Primary => Target::Primary,
476    }
477}
478
479fn clipboard_target(target: Target) -> ClipboardTarget {
480    match target {
481        Target::Clipboard => ClipboardTarget::Clipboard,
482        Target::Primary => ClipboardTarget::Primary,
483    }
484}
485
486/// The service's answer where no Tilo session serves the clipboard: an app's copies and pastes
487/// over the operating system's own clipboard, served by the process that started the app (the
488/// launcher, or `tilolang run`). An app still talks only to [`Connected`] either way.
489pub struct BackendSide {
490    backend: Arc<dyn ClipboardBackend>,
491}
492
493impl BackendSide {
494    /// The service side of `backend`: the operating system's clipboard, or a test's.
495    #[must_use]
496    pub fn new(backend: Arc<dyn ClipboardBackend>) -> Self {
497        Self { backend }
498    }
499
500    fn text_of<'a>(formats: &'a [(String, Vec<u8>)], mime: &str) -> Option<&'a str> {
501        formats
502            .iter()
503            .find(|(held, _)| held == mime)
504            .and_then(|(_, bytes)| std::str::from_utf8(bytes).ok())
505    }
506}
507
508impl ClipboardSide for BackendSide {
509    fn copy(&self, target: Target, secret: bool, formats: &[(String, Vec<u8>)]) -> bool {
510        if secret {
511            // Histories and device sync are told not to keep a secret by the marker the OS
512            // backend offers beside the words; outside a Tilo session the OS clipboard's own
513            // conventions apply.
514            return Self::text_of(formats, "text/plain")
515                .is_some_and(|text| self.backend.set_secret_text(text));
516        }
517        if let (Some(html), Some(plain)) = (
518            Self::text_of(formats, "text/html"),
519            Self::text_of(formats, "text/plain"),
520        ) {
521            return self.backend.set_rich_text(html, plain);
522        }
523        let Some((mime, bytes)) = formats.first() else {
524            return false;
525        };
526        if mime.starts_with("image/") {
527            if target != Target::Clipboard {
528                return false;
529            }
530            let Some((width, height, rgba)) = crate::images::decode_image(bytes) else {
531                return false;
532            };
533            return self.backend.set_image(width, height, &rgba);
534        }
535        if mime == "text/plain" {
536            let Ok(text) = std::str::from_utf8(bytes) else {
537                return false;
538            };
539            return self.backend.set_text(clipboard_target(target), text);
540        }
541        false
542    }
543
544    fn paste(&self, target: Target, types: &[&str]) -> Formats {
545        let target = clipboard_target(target);
546        let mut held = Vec::new();
547        for want in types {
548            match *want {
549                "text/plain" => {
550                    if let Some(text) = self.backend.text(target)
551                        && !text.is_empty()
552                        && text.len() <= most_of("text/plain")
553                    {
554                        held.push(((*want).to_owned(), text.into_bytes()));
555                    }
556                }
557                "text/html" => {
558                    if let Some(offer) = self.backend.rich_text()
559                        && offer.html.len() <= most_of("text/html")
560                    {
561                        held.push(((*want).to_owned(), offer.html.into_bytes()));
562                    }
563                }
564                mime if mime.starts_with("image/") => {
565                    let Some(image) = self.backend.image() else {
566                        continue;
567                    };
568                    if image.mime == mime
569                        && image.bytes.len() <= most_of(mime)
570                        && image.bytes.len() <= MAX_PASTED_IMAGE_BYTES
571                    {
572                        held.push(((*want).to_owned(), image.bytes));
573                    }
574                }
575                _ => {}
576            }
577        }
578        held
579    }
580}
581
582/// The clipboard connection an app is handed, the one service a Rust app and a tilolang instance
583/// both reach their copy and paste through: the session's, connected at `session_socket`, where a
584/// session serves one, so a copy is the person's copy on their other devices too. Where none does
585/// (the person's own desktop, or a dev run outside a session), this process serves the same wire
586/// from the operating system's clipboard ([`crate::os`]) on a thread that lives as long as the
587/// app. `None` when neither can be had, and the app's copies and pastes are then refused.
588#[cfg(any(unix, windows))]
589#[must_use]
590pub fn for_app(session_socket: &std::path::Path) -> Option<Stream> {
591    if session_socket.exists() {
592        return connect_session(session_socket);
593    }
594    serve_os()
595}
596
597/// The session's clipboard at `path`; `None` where nothing answers there.
598#[cfg(any(unix, windows))]
599#[must_use]
600pub fn connect_session(path: &std::path::Path) -> Option<Stream> {
601    if !path.exists() {
602        return None;
603    }
604    match tilo_socket::connect(path) {
605        Ok(stream) => Some(stream),
606        Err(error) => {
607            tracing::warn!(%error, path = %path.display(), "clipboard service refused connection");
608            None
609        }
610    }
611}
612
613/// The app's end of a connection this process answers from the operating system's clipboard.
614#[cfg(any(unix, windows))]
615#[must_use]
616pub fn serve_os() -> Option<Stream> {
617    let (app, serving) = tilo_socket::pair().ok()?;
618    std::thread::Builder::new()
619        .name("tilo-clipboard-os".into())
620        .spawn(move || {
621            let side = BackendSide::new(crate::os());
622            serve(serving, &side);
623        })
624        .ok()?;
625    Some(app)
626}
627
628#[cfg(test)]
629mod tests {
630    use std::sync::Arc;
631
632    use super::*;
633
634    /// What the person's selection holds on each of the two selections, as the session would
635    /// answer it, and the last copy's secrecy.
636    #[derive(Default)]
637    struct Selection {
638        held: Mutex<[Formats; 2]>,
639        secret: Mutex<bool>,
640    }
641
642    impl Selection {
643        fn slot(target: Target) -> usize {
644            match target {
645                Target::Clipboard => 0,
646                Target::Primary => 1,
647            }
648        }
649    }
650
651    impl ClipboardSide for Selection {
652        fn copy(&self, target: Target, secret: bool, formats: &[(String, Vec<u8>)]) -> bool {
653            if formats.is_empty() {
654                return false;
655            }
656            held(self.held.lock())[Self::slot(target)] = formats.to_vec();
657            *held(self.secret.lock()) = secret;
658            true
659        }
660
661        fn paste(&self, target: Target, types: &[&str]) -> Vec<(String, Vec<u8>)> {
662            let slot = Self::slot(target);
663            let held = held(self.held.lock());
664            types
665                .iter()
666                .filter_map(|wanted| held[slot].iter().find(|(mime, _)| mime == wanted).cloned())
667                .collect()
668        }
669    }
670
671    /// A session's end and both apps' ends of one service: a Rust app's
672    /// ([`ServiceClipboard`]) and a tilolang instance's ([`Connected`]).
673    fn served() -> (Arc<Selection>, ServiceClipboard, Connected) {
674        let selection = Arc::new(Selection::default());
675        let (rust_app, rust_session) = tilo_socket::pair().expect("a socket pair");
676        let (lang_app, lang_session) = tilo_socket::pair().expect("a socket pair");
677        for session in [rust_session, lang_session] {
678            let side = Arc::clone(&selection);
679            std::thread::spawn(move || serve(session, &*side));
680        }
681        (
682            selection,
683            ServiceClipboard(Connected::connect(rust_app).expect("the connection is usable")),
684            Connected::connect(lang_app).expect("the connection is usable"),
685        )
686    }
687
688    /// What the selection holds as text now.
689    fn text_held(selection: &Selection) -> Option<Vec<u8>> {
690        selection
691            .paste(Target::Clipboard, &["text/plain"])
692            .into_iter()
693            .next()
694            .map(|(_, bytes)| bytes)
695    }
696
697    #[test]
698    fn a_tilolang_secret_copy_leaves_the_clipboard_unless_something_else_was_copied() {
699        let (selection, rust, lang) = served();
700        let lang = Arc::new(lang);
701        assert!(lang.copy_secret("sk-live-1234", Duration::from_millis(50)));
702        assert!(
703            *held(selection.secret.lock()),
704            "histories are told it is a secret"
705        );
706        assert_eq!(text_held(&selection).as_deref(), Some(&b"sk-live-1234"[..]));
707        let gone = std::time::Instant::now() + Duration::from_secs(10);
708        while text_held(&selection).as_deref() != Some(&b""[..]) {
709            assert!(
710                std::time::Instant::now() < gone,
711                "the secret is taken off the clipboard"
712            );
713            std::thread::yield_now();
714        }
715
716        // A copy the person makes after the secret is theirs: the clear leaves it alone.
717        assert!(lang.copy_secret("hunter2", Duration::from_millis(50)));
718        assert!(rust.set_text(ClipboardTarget::Clipboard, "the next thing"));
719        std::thread::park_timeout(Duration::from_millis(300));
720        assert_eq!(
721            text_held(&selection).as_deref(),
722            Some(&b"the next thing"[..]),
723            "a later copy is never destroyed"
724        );
725    }
726
727    #[test]
728    fn a_rust_apps_copy_pastes_in_a_tilolang_app_and_the_reverse() {
729        let (_selection, rust, lang) = served();
730        assert!(rust.set_text(ClipboardTarget::Clipboard, "Lisbon in May"));
731        assert_eq!(
732            lang.paste(&["text/plain"]),
733            Some(("text/plain".to_owned(), b"Lisbon in May".to_vec())),
734            "what a Rust app copies is what a tilolang app pastes"
735        );
736        assert!(lang.copy("text/plain", b"from the language"));
737        assert_eq!(
738            rust.text(ClipboardTarget::Clipboard).as_deref(),
739            Some("from the language"),
740            "what a tilolang app copies is what a Rust app pastes"
741        );
742    }
743
744    #[test]
745    fn every_format_an_app_copies_crosses_the_one_service() {
746        let (selection, rust, lang) = served();
747        // An image a Rust app copies as RGBA8 pastes in tilolang as its file's type.
748        let rgba = [0x89, b'P', b'N', b'G'];
749        assert!(rust.set_image(1, 1, &rgba));
750        let (mime, png) = lang.paste(&IMAGE_TYPES).expect("the image pastes");
751        assert_eq!(mime, "image/png");
752        assert_eq!(&png[..4], b"\x89PNG", "the image pastes as encoded PNG");
753        assert!(lang.copy("image/png", &png));
754        assert_eq!(
755            rust.image().map(|image| (image.mime, image.bytes)),
756            Some(("image/png", png)),
757            "an image a tilolang app copies pastes in a Rust app"
758        );
759        // Formatted text keeps its formatting for an app that reads it and is its words
760        // elsewhere.
761        assert!(rust.set_rich_text("<b>bold</b>", "bold"));
762        let offer = rust.rich_text().expect("the formatting pastes back");
763        assert_eq!(offer.html, "<b>bold</b>");
764        assert_eq!(offer.plain.as_deref(), Some("bold"));
765        assert_eq!(
766            lang.paste(&["text/plain"]),
767            Some(("text/plain".to_owned(), b"bold".to_vec()))
768        );
769        // The primary selection is its own: a copy there is not the Ctrl+C clipboard.
770        assert!(rust.set_text(ClipboardTarget::Primary, "picked"));
771        assert_eq!(
772            rust.text(ClipboardTarget::Primary).as_deref(),
773            Some("picked")
774        );
775        assert_ne!(
776            rust.text(ClipboardTarget::Clipboard).as_deref(),
777            Some("picked")
778        );
779        // A secret copy is marked as one, and still pastes as plain text.
780        assert!(rust.set_secret_text("hunter2"));
781        assert!(*held(selection.secret.lock()));
782        assert_eq!(
783            lang.paste(&["text/plain"]),
784            Some(("text/plain".to_owned(), b"hunter2".to_vec()))
785        );
786        // Clearing a secret is a copy of nothing over the same service.
787        assert!(rust.set_secret_text(""));
788        assert_eq!(rust.text(ClipboardTarget::Clipboard).as_deref(), Some(""));
789    }
790
791    #[test]
792    fn a_copy_the_selection_refuses_answers_no_and_nothing_pastes() {
793        struct Refusing;
794        impl ClipboardSide for Refusing {
795            fn copy(&self, _: Target, _: bool, _: &[(String, Vec<u8>)]) -> bool {
796                false
797            }
798
799            fn paste(&self, _: Target, _: &[&str]) -> Vec<(String, Vec<u8>)> {
800                Vec::new()
801            }
802        }
803        let (app, session) = tilo_socket::pair().expect("a socket pair");
804        let refusing: Arc<dyn ClipboardSide> = Arc::new(Refusing);
805        std::thread::spawn(move || serve(session, &*refusing));
806        let app = ServiceClipboard(Connected::connect(app).expect("the connection is usable"));
807        assert!(!app.set_text(ClipboardTarget::Clipboard, "words"));
808        assert_eq!(app.text(ClipboardTarget::Clipboard), None);
809        assert_eq!(app.image(), None);
810    }
811
812    /// An app is handed its session connection as an inherited descriptor, which only Unix does.
813    #[cfg(unix)]
814    #[test]
815    fn an_app_with_no_session_connection_refuses_rather_than_keeping_a_private_copy() {
816        assert!(
817            ServiceClipboard::from_env().is_none(),
818            "no connection is handed to this process"
819        );
820        // A connection whose session went away refuses what it tries to copy and reads nothing.
821        let (app, session) = tilo_socket::pair().expect("a socket pair");
822        drop(session);
823        let app = ServiceClipboard(Connected::connect(app).expect("the connection is usable"));
824        assert!(!app.set_text(ClipboardTarget::Clipboard, "gone"));
825        assert_eq!(app.text(ClipboardTarget::Clipboard), None);
826        assert_eq!(app.rich_text(), None);
827    }
828
829    #[test]
830    fn a_copy_larger_than_the_clipboard_holds_is_refused_before_it_is_sent() {
831        let (app, session) = tilo_socket::pair().expect("a socket pair");
832        // Nothing answers on the other end: the bound is the client's, checked before anything is
833        // written, and nothing here waits for a reply.
834        drop(session);
835        let app = ServiceClipboard(Connected::connect(app).expect("the connection is usable"));
836        assert!(!app.set_text(ClipboardTarget::Clipboard, &"a".repeat(TEXT + 1)));
837        assert!(!app.set_rich_text(&"a".repeat(TEXT + 1), "plain"));
838        assert!(
839            !app.set_image(0, 0, &[]),
840            "an image with no pixels copies nothing"
841        );
842        assert!(
843            !app.set_image(2, 1, &[0; 4]),
844            "an image whose bytes do not match copies nothing"
845        );
846    }
847
848    #[test]
849    fn the_wire_bounds_text_to_what_text_is_and_images_to_what_an_image_taken_in_is() {
850        assert_eq!(most_of("text/plain"), TEXT);
851        assert_eq!(most_of("text/html"), TEXT);
852        assert_eq!(most_of("image/png"), MAX_CLIPBOARD_IMAGE_INPUT_BYTES);
853        assert_eq!(most_of("image/jpeg"), MAX_CLIPBOARD_IMAGE_INPUT_BYTES);
854    }
855
856    /// An in-memory OS clipboard: what the launcher's side reads and writes on a person's own
857    /// desktop, with no Tilo session and no display.
858    #[derive(Default)]
859    struct TestOs {
860        text: Mutex<[Option<String>; 2]>,
861        rich: Mutex<Option<(String, String)>>,
862        image: Mutex<Option<(&'static str, Vec<u8>)>>,
863        secret: Mutex<bool>,
864    }
865
866    impl TestOs {
867        fn slot(target: ClipboardTarget) -> usize {
868            match target {
869                ClipboardTarget::Clipboard => 0,
870                ClipboardTarget::Primary => 1,
871            }
872        }
873    }
874
875    impl ClipboardBackend for TestOs {
876        fn set_text(&self, target: ClipboardTarget, text: &str) -> bool {
877            held(self.text.lock())[Self::slot(target)] = Some(text.to_owned());
878            if target == ClipboardTarget::Clipboard {
879                *held(self.rich.lock()) = None;
880            }
881            true
882        }
883
884        fn text(&self, target: ClipboardTarget) -> Option<String> {
885            held(self.text.lock())[Self::slot(target)].clone()
886        }
887
888        fn set_rich_text(&self, html: &str, plain: &str) -> bool {
889            self.set_text(ClipboardTarget::Clipboard, plain);
890            *held(self.rich.lock()) = Some((html.to_owned(), plain.to_owned()));
891            true
892        }
893
894        fn rich_text(&self) -> Option<RichTextOffer> {
895            let (html, plain) = held(self.rich.lock()).clone()?;
896            Some(RichTextOffer {
897                html,
898                plain: Some(plain),
899            })
900        }
901
902        fn set_secret_text(&self, text: &str) -> bool {
903            *held(self.secret.lock()) = true;
904            self.set_text(ClipboardTarget::Clipboard, text)
905        }
906
907        fn set_image(&self, width: usize, height: usize, rgba: &[u8]) -> bool {
908            let Some(png) = crate::images::encode_png(width, height, rgba) else {
909                return false;
910            };
911            *held(self.image.lock()) = Some(("image/png", png));
912            true
913        }
914
915        fn image(&self) -> Option<ClipboardImage> {
916            held(self.image.lock())
917                .clone()
918                .map(|(mime, bytes)| ClipboardImage { mime, bytes })
919        }
920
921        fn name(&self) -> &'static str {
922            "test-os"
923        }
924    }
925
926    /// The launcher's service over one OS clipboard, for a Rust app and a tilolang instance that
927    /// have no Tilo session: each gets its own connection to the same served clipboard.
928    fn served_by_os() -> (Arc<TestOs>, ServiceClipboard, Connected) {
929        let os = Arc::new(TestOs::default());
930        let (rust_app, rust_session) = tilo_socket::pair().expect("a socket pair");
931        let (lang_app, lang_session) = tilo_socket::pair().expect("a socket pair");
932        for session in [rust_session, lang_session] {
933            let backend = os.clone() as Arc<dyn ClipboardBackend>;
934            std::thread::spawn(move || serve(session, &BackendSide::new(backend)));
935        }
936        (
937            os,
938            ServiceClipboard(Connected::connect(rust_app).expect("the connection is usable")),
939            Connected::connect(lang_app).expect("the connection is usable"),
940        )
941    }
942
943    #[test]
944    fn with_no_session_both_languages_copy_and_paste_through_the_launchers_os_clipboard() {
945        let (os, rust, lang) = served_by_os();
946        assert!(rust.set_text(ClipboardTarget::Clipboard, "from the Rust app"));
947        assert_eq!(
948            os.text(ClipboardTarget::Clipboard).as_deref(),
949            Some("from the Rust app")
950        );
951        assert_eq!(
952            lang.paste(&["text/plain"]),
953            Some(("text/plain".to_owned(), b"from the Rust app".to_vec())),
954            "what a Rust app copies with no session is what a tilolang app pastes"
955        );
956        assert!(lang.copy("text/plain", b"from the language"));
957        assert_eq!(
958            rust.text(ClipboardTarget::Clipboard).as_deref(),
959            Some("from the language"),
960            "what a tilolang app copies with no session is what a Rust app pastes"
961        );
962
963        assert!(rust.set_rich_text("<b>bold</b>", "bold"));
964        assert_eq!(
965            lang.paste(&["text/plain"]),
966            Some(("text/plain".to_owned(), b"bold".to_vec()))
967        );
968        assert_eq!(
969            rust.rich_text().and_then(|offer| offer.plain),
970            Some("bold".to_owned())
971        );
972
973        assert!(rust.set_image(1, 1, &[0x89, b'P', b'N', b'G']));
974        let (mime, png) = lang.paste(&IMAGE_TYPES).expect("the image pastes");
975        assert_eq!(mime, "image/png");
976        assert!(png.starts_with(b"\x89PNG"));
977        assert!(lang.copy("image/png", &png));
978        assert_eq!(
979            rust.image().map(|image| (image.mime, image.bytes)),
980            Some(("image/png", png))
981        );
982
983        assert!(rust.set_text(ClipboardTarget::Primary, "picked"));
984        assert_eq!(
985            rust.text(ClipboardTarget::Primary).as_deref(),
986            Some("picked")
987        );
988        assert_ne!(
989            rust.text(ClipboardTarget::Clipboard).as_deref(),
990            Some("picked")
991        );
992
993        assert!(rust.set_secret_text("hunter2"));
994        assert!(
995            *held(os.secret.lock()),
996            "the OS side is told it is a secret"
997        );
998        assert_eq!(
999            lang.paste(&["text/plain"]),
1000            Some(("text/plain".to_owned(), b"hunter2".to_vec()))
1001        );
1002    }
1003}