Skip to main content

egui_pop_model/
clipboard.rs

1//! The clipboard's pure parts (ADR 0015): formats, items, slots, the
2//! boundaries content crosses, and the negotiation between what a copy
3//! offers and what a paste target accepts. No egui: the contract, its
4//! default owner and the commands are `egui_pop_api::clipboard`'s.
5//!
6//! <div class="warning">Experimental: may change in any release
7//! (docs/stability.md).</div>
8//!
9//! - A **format** ([`FormatId`]) is a MIME-like id: an application's
10//!   private types are `application/x-<app>.<type>+json` (egui-pop's
11//!   own `application/x-egui-pop.<type>+json`), the standard ones
12//!   `text/plain`, `text/html`, `image/png`, `text/uri-list`.
13//! - An **item** ([`ClipItem`]) is what one copy made: its private type,
14//!   its version, a structured payload, a title ("3 nodes"), readable
15//!   **fallbacks** for the system clipboard, where it came from and what
16//!   sanitisers left out.
17//! - A **target** declares the formats it accepts, richest first;
18//!   [`negotiate`] takes the first the item offers, or one a declared
19//!   transform makes from what it offers (one transform, never a chain).
20//!   Nothing fits: a [`Refusal`] saying why (ADR 0003).
21//!
22//! ```
23//! use egui_pop_model::clipboard::{self, ClipItem, FormatId, TransformSpec, TEXT};
24//!
25//! const COLOR: FormatId = FormatId::from_static("application/x-demo.color+json");
26//! const GRAY: FormatId = FormatId::from_static("application/x-demo.gray+json");
27//!
28//! let item = ClipItem::new(COLOR, 1, serde_json::json!({ "hex": "#d9a441" }), "a colour")
29//!     .fallback(TEXT, serde_json::json!("#d9a441"));
30//! assert_eq!(item.offers(), [COLOR, TEXT]);
31//!
32//! let to_gray = TransformSpec::new("demo.color-to-gray", COLOR, GRAY).lossy();
33//! // A target taking colours takes the item as it is.
34//! let plan = clipboard::negotiate(&item.offers(), &[COLOR, TEXT], &[to_gray.clone()]).unwrap();
35//! assert_eq!((plan.format, plan.transform), (COLOR, None));
36//! // A target taking greys only gets it through the transform.
37//! let plan = clipboard::negotiate(&item.offers(), &[GRAY], &[to_gray]).unwrap();
38//! assert_eq!(plan.transform.as_deref(), Some("demo.color-to-gray"));
39//! assert!(plan.lossy);
40//! // A target taking images refuses it, saying why.
41//! assert!(clipboard::negotiate(&item.offers(), &[clipboard::PNG], &[]).is_err());
42//! ```
43
44use std::borrow::Cow;
45use std::fmt;
46
47use serde::{Deserialize, Deserializer, Serialize, Serializer};
48use serde_json::Value as Json;
49
50use crate::commands::Origin;
51
52/// A format: a MIME-like type, `type/subtype` with optional parameters.
53#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
54pub struct FormatId(Cow<'static, str>);
55
56/// Plain text: every item renders one, and external text arrives as it.
57pub const TEXT: FormatId = FormatId::from_static("text/plain");
58/// HTML, with a text alternative.
59pub const HTML: FormatId = FormatId::from_static("text/html");
60/// An image.
61pub const PNG: FormatId = FormatId::from_static("image/png");
62/// A list of files or links.
63pub const URI_LIST: FormatId = FormatId::from_static("text/uri-list");
64
65const fn valid(text: &str) -> Result<(), &'static str> {
66    let b = text.as_bytes();
67    if b.is_empty() {
68        return Err("it is empty");
69    }
70    let mut slash = 0;
71    let mut i = 0;
72    while i < b.len() {
73        let c = b[i];
74        if c == b'/' {
75            slash += 1;
76        } else if !(c.is_ascii_alphanumeric()
77            || matches!(c, b'.' | b'_' | b'-' | b'+' | b';' | b'=' | b' '))
78        {
79            return Err("only ASCII letters, digits and `/ . _ - + ; =` are allowed");
80        }
81        i += 1;
82    }
83    if slash != 1 || b[0] == b'/' || b[b.len() - 1] == b'/' {
84        return Err("it is not `type/subtype`");
85    }
86    Ok(())
87}
88
89impl FormatId {
90    /// A format from a literal; an invalid one panics (a compile error in
91    /// a constant).
92    pub const fn from_static(text: &'static str) -> Self {
93        match valid(text) {
94            Ok(()) => Self(Cow::Borrowed(text)),
95            Err(_) => panic!("not a format: expected `type/subtype`"),
96        }
97    }
98
99    /// A format from a text, or why it is not one.
100    pub fn new(text: &str) -> Result<Self, String> {
101        valid(text)
102            .map(|()| Self(Cow::Owned(text.to_string())))
103            .map_err(|e| format!("`{text}` is not a format: {e}"))
104    }
105
106    /// An application's private type: `application/x-<app>.<type>+json`.
107    pub fn private(app: &str, kind: &str) -> Result<Self, String> {
108        Self::new(&format!("application/x-{app}.{kind}+json"))
109    }
110
111    pub fn as_str(&self) -> &str {
112        &self.0
113    }
114
115    /// Whether it is a private type (`application/x-…+json`).
116    pub fn is_private(&self) -> bool {
117        self.0.starts_with("application/x-") && self.0.ends_with("+json")
118    }
119
120    /// Whether its data is text (`text/…`): a JSON string.
121    pub fn is_text(&self) -> bool {
122        self.0.starts_with("text/")
123    }
124}
125
126impl fmt::Display for FormatId {
127    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128        f.write_str(&self.0)
129    }
130}
131
132impl fmt::Debug for FormatId {
133    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134        write!(f, "{:?}", self.0)
135    }
136}
137
138impl Serialize for FormatId {
139    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
140        s.serialize_str(&self.0)
141    }
142}
143
144impl<'de> Deserialize<'de> for FormatId {
145    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
146        let text = String::deserialize(d)?;
147        FormatId::new(&text).map_err(serde::de::Error::custom)
148    }
149}
150
151/// Where an item is kept in the owner: the user's slot, or a session's
152/// own (an agent's, a script's), so that an agent neither reads nor
153/// overwrites what the user copied unless the owner allows it.
154#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
155pub enum Slot {
156    User,
157    /// A session, by its journal name (`agent:<name>`, `script:<name>`).
158    Session(String),
159}
160
161impl Slot {
162    /// The slot a run by `origin` uses unless it names another.
163    pub fn of(origin: &Origin) -> Slot {
164        match origin {
165            Origin::User => Slot::User,
166            Origin::Agent(n) => Slot::Session(format!("agent:{n}")),
167            Origin::Script(n) => Slot::Session(format!("script:{n}")),
168            Origin::Device(n) => Slot::Session(format!("device:{n}")),
169            Origin::Remote(n) => Slot::Session(format!("remote:{n}")),
170        }
171    }
172
173    /// `user`, or the session's name.
174    pub fn name(&self) -> &str {
175        match self {
176            Slot::User => "user",
177            Slot::Session(s) => s,
178        }
179    }
180
181    /// The slot named `user`, or a session's.
182    pub fn parse(text: &str) -> Slot {
183        if text == "user" {
184            Slot::User
185        } else {
186            Slot::Session(text.to_string())
187        }
188    }
189}
190
191impl fmt::Display for Slot {
192    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
193        f.write_str(self.name())
194    }
195}
196
197impl Serialize for Slot {
198    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
199        s.serialize_str(self.name())
200    }
201}
202
203impl<'de> Deserialize<'de> for Slot {
204    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
205        Ok(Slot::parse(&String::deserialize(d)?))
206    }
207}
208
209/// The boundary a representation crosses, which sanitisers run on.
210#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
211#[serde(rename_all = "lowercase")]
212pub enum Boundary {
213    /// Kept inside the owner: nothing is removed by default.
214    Owner,
215    /// Written to the system clipboard, where other applications read
216    /// it: local paths, secrets and owner-local ids go.
217    System,
218    /// Coming in from outside (another application's content): reduced
219    /// before a target sees it.
220    External,
221}
222
223/// One representation of an item: a format and its data (a JSON string
224/// for a text format).
225#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
226pub struct Repr {
227    pub format: FormatId,
228    pub data: Json,
229}
230
231impl Repr {
232    pub fn new(format: FormatId, data: Json) -> Self {
233        Self { format, data }
234    }
235
236    /// Its data as text, when it is a string.
237    pub fn text(&self) -> Option<&str> {
238        self.data.as_str()
239    }
240}
241
242/// Where an item came from.
243#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
244pub struct ClipOrigin {
245    /// Who copied it, as the journal names them (`user`, `agent:<name>`).
246    #[serde(default)]
247    pub by: String,
248    /// The source it was copied from (its registered name).
249    #[serde(default)]
250    pub source: String,
251    /// The window it was copied in, when there are several.
252    #[serde(default, skip_serializing_if = "Option::is_none")]
253    pub window: Option<String>,
254    /// The place of the context stack it was copied in (ADR 0012).
255    #[serde(default, skip_serializing_if = "Option::is_none")]
256    pub place: Option<String>,
257    /// The owner (kernel) that keeps it, when it names itself.
258    #[serde(default, skip_serializing_if = "Option::is_none")]
259    pub owner: Option<String>,
260}
261
262/// What a sanitiser removed, and why.
263#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
264pub struct Stripped {
265    /// The sanitiser.
266    pub by: String,
267    /// What went ("a local path", "3 control characters").
268    pub what: String,
269    pub boundary: Boundary,
270    /// The representation it went from.
271    pub format: FormatId,
272}
273
274/// A title as a catalogue message: its key and its arguments.
275#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
276pub struct TitleKey {
277    pub key: String,
278    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
279    pub args: std::collections::BTreeMap<String, String>,
280}
281
282/// What one copy made: a typed item with its readable fallbacks.
283#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
284pub struct ClipItem {
285    /// Its type: a private type, or a standard format for content that
286    /// came from outside.
287    pub kind: FormatId,
288    /// The version of its type it was made at.
289    pub version: u32,
290    pub payload: Json,
291    /// What it is, for menus and toasts ("a colour", "3 nodes"), in
292    /// English.
293    pub title: String,
294    /// Its title as a catalogue message, shown in the interface's
295    /// language (`title` is its English).
296    #[serde(default, skip_serializing_if = "Option::is_none")]
297    pub title_key: Option<TitleKey>,
298    /// Its other representations, richest first (text last).
299    #[serde(default)]
300    pub fallbacks: Vec<Repr>,
301    #[serde(default)]
302    pub origin: ClipOrigin,
303    /// What sanitisers removed on the boundaries it crossed.
304    #[serde(default)]
305    pub stripped: Vec<Stripped>,
306    /// Whether it came from outside the owner (the system clipboard).
307    #[serde(default)]
308    pub external: bool,
309}
310
311impl ClipItem {
312    pub fn new(kind: FormatId, version: u32, payload: Json, title: &str) -> Self {
313        Self {
314            kind,
315            version,
316            payload,
317            title: title.into(),
318            title_key: None,
319            fallbacks: Vec::new(),
320            origin: ClipOrigin::default(),
321            stripped: Vec::new(),
322            external: false,
323        }
324    }
325
326    /// Text from outside the owner (another application's).
327    pub fn external_text(text: &str) -> Self {
328        let mut item = Self::new(TEXT, 0, Json::String(text.into()), "text");
329        item.external = true;
330        item
331    }
332
333    /// Its title as a catalogue message with its arguments (`{ $count }`
334    /// nodes): the interface shows it in its language, the English
335    /// `title` where the catalogue has no translation. The arguments are
336    /// text, shown as they are written: a count is written by the caller.
337    pub fn title_key(mut self, key: &str, args: &[(&str, &str)]) -> Self {
338        self.title_key = Some(TitleKey {
339            key: key.into(),
340            args: args
341                .iter()
342                .map(|(k, v)| (k.to_string(), v.to_string()))
343                .collect(),
344        });
345        self
346    }
347
348    /// Content from outside the owner in several representations,
349    /// richest first (what the system clipboard held: files, an image,
350    /// HTML, text); `None` when there is none. Its type is the first
351    /// representation's format, its title the plain text's name.
352    pub fn external(reprs: Vec<Repr>) -> Option<Self> {
353        let mut reprs = reprs.into_iter();
354        let first = reprs.next()?;
355        let mut item = Self::new(first.format, 0, first.data, "");
356        item.fallbacks = reprs.collect();
357        item.title = if item.kind == TEXT {
358            "text".into()
359        } else {
360            item.kind.to_string()
361        };
362        item.external = true;
363        Some(item)
364    }
365
366    /// Adds a fallback representation.
367    pub fn fallback(mut self, format: FormatId, data: Json) -> Self {
368        self.fallbacks.push(Repr::new(format, data));
369        self
370    }
371
372    /// The formats it offers: its type, then its fallbacks, each once.
373    pub fn offers(&self) -> Vec<FormatId> {
374        let mut out = vec![self.kind.clone()];
375        for r in &self.fallbacks {
376            if !out.contains(&r.format) {
377                out.push(r.format.clone());
378            }
379        }
380        out
381    }
382
383    /// Its representation in a format, when it offers it.
384    pub fn repr(&self, format: &FormatId) -> Option<Repr> {
385        if *format == self.kind {
386            return Some(Repr::new(self.kind.clone(), self.payload.clone()));
387        }
388        self.fallbacks.iter().find(|r| r.format == *format).cloned()
389    }
390
391    /// Its plain text fallback (or its payload, when it is text).
392    pub fn text(&self) -> Option<&str> {
393        if self.kind == TEXT {
394            return self.payload.as_str();
395        }
396        self.fallbacks
397            .iter()
398            .find(|r| r.format == TEXT)
399            .and_then(Repr::text)
400    }
401}
402
403/// A transform a plugin declares: it makes `to` from `from`.
404#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
405pub struct TransformSpec {
406    pub id: String,
407    pub from: FormatId,
408    pub to: FormatId,
409    /// Whether it loses information (a colour out of gamut, a dropped
410    /// parameter): applied with a toast naming the loss.
411    #[serde(default)]
412    pub lossy: bool,
413}
414
415impl TransformSpec {
416    pub fn new(id: &str, from: FormatId, to: FormatId) -> Self {
417        Self {
418            id: id.into(),
419            from,
420            to,
421            lossy: false,
422        }
423    }
424
425    pub fn lossy(mut self) -> Self {
426        self.lossy = true;
427        self
428    }
429}
430
431/// How a paste goes: the representation taken from the offer, what the
432/// target receives, and the transform between them, if any.
433#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
434pub struct Plan {
435    /// The representation taken from the offer.
436    pub format: FormatId,
437    /// The format the target receives.
438    pub to: FormatId,
439    /// The transform from `format` to `to`.
440    #[serde(default, skip_serializing_if = "Option::is_none")]
441    pub transform: Option<String>,
442    #[serde(default)]
443    pub lossy: bool,
444}
445
446/// Why nothing on the clipboard fits a target.
447#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
448pub struct Refusal {
449    pub reason: String,
450    pub offered: Vec<FormatId>,
451    pub accepted: Vec<FormatId>,
452}
453
454impl fmt::Display for Refusal {
455    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
456        f.write_str(&self.reason)
457    }
458}
459
460/// Every way an offer fits a target, the best first: per accepted format
461/// (richest first), the offer's own representation, or else each
462/// transform making it from what is offered (from the richest offered).
463pub fn candidates(
464    offer: &[FormatId],
465    accepts: &[FormatId],
466    transforms: &[TransformSpec],
467) -> Vec<Plan> {
468    let mut out = Vec::new();
469    for to in accepts {
470        if offer.contains(to) {
471            out.push(Plan {
472                format: to.clone(),
473                to: to.clone(),
474                transform: None,
475                lossy: false,
476            });
477        }
478        if offer.contains(to) {
479            // Offered as it is: no transform needed.
480            continue;
481        }
482        for from in offer {
483            for t in transforms.iter().filter(|t| t.to == *to && t.from == *from) {
484                out.push(Plan {
485                    format: from.clone(),
486                    to: to.clone(),
487                    transform: Some(t.id.clone()),
488                    lossy: t.lossy,
489                });
490            }
491        }
492    }
493    out
494}
495
496/// The plan of a paste: the first accepted format the offer has, or one
497/// a transform makes from it; nothing: why not.
498pub fn negotiate(
499    offer: &[FormatId],
500    accepts: &[FormatId],
501    transforms: &[TransformSpec],
502) -> Result<Plan, Refusal> {
503    choose(offer, accepts, transforms, None, None)
504}
505
506/// [`negotiate`], held to the format the target should receive
507/// (`format`) and the transform to use (`transform`), when given: what
508/// paste special and an agent's paste ask for.
509pub fn choose(
510    offer: &[FormatId],
511    accepts: &[FormatId],
512    transforms: &[TransformSpec],
513    format: Option<&FormatId>,
514    transform: Option<&str>,
515) -> Result<Plan, Refusal> {
516    candidates(offer, accepts, transforms)
517        .into_iter()
518        .find(|p| {
519            format.is_none_or(|f| p.to == *f)
520                && transform.is_none_or(|t| p.transform.as_deref() == Some(t))
521        })
522        .ok_or_else(|| {
523            let reason = if offer.is_empty() {
524                "the clipboard is empty".to_string()
525            } else if let Some(t) = transform {
526                format!("the transform `{t}` does not apply here")
527            } else if let Some(f) = format {
528                format!("`{f}` cannot be made from what the clipboard holds")
529            } else {
530                format!(
531                    "nothing on the clipboard fits here: it holds {}, this takes {}",
532                    list(offer),
533                    list(accepts)
534                )
535            };
536            Refusal {
537                reason,
538                offered: offer.to_vec(),
539                accepted: accepts.to_vec(),
540            }
541        })
542}
543
544fn list(formats: &[FormatId]) -> String {
545    if formats.is_empty() {
546        return "nothing".into();
547    }
548    formats
549        .iter()
550        .map(|f| format!("`{f}`"))
551        .collect::<Vec<_>>()
552        .join(", ")
553}
554
555/// The marker of a text written to the system clipboard: 64-bit FNV-1a.
556/// A paste whose text has the marker of the owner's last write is the
557/// owner's own item, not external content.
558pub fn marker(text: &str) -> u64 {
559    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
560    for b in text.bytes() {
561        h ^= u64::from(b);
562        h = h.wrapping_mul(0x0100_0000_01b3);
563    }
564    h
565}
566
567/// Text without control characters: escape sequences (`ESC [ … final`,
568/// `ESC ] … BEL`) and every C0 and C1 control but tab, line feed and
569/// carriage return. The text and how many characters went.
570pub fn strip_controls(text: &str) -> (String, usize) {
571    let mut out = String::with_capacity(text.len());
572    let mut removed = 0;
573    let mut chars = text.chars().peekable();
574    while let Some(c) = chars.next() {
575        if c == '\u{1b}' {
576            removed += 1;
577            match chars.peek() {
578                Some('[') => {
579                    // CSI: parameters, then one final byte in @..~.
580                    chars.next();
581                    removed += 1;
582                    for n in chars.by_ref() {
583                        removed += 1;
584                        if ('@'..='~').contains(&n) {
585                            break;
586                        }
587                    }
588                }
589                Some(']') => {
590                    // OSC: up to BEL or ESC \.
591                    chars.next();
592                    removed += 1;
593                    while let Some(n) = chars.next() {
594                        removed += 1;
595                        if n == '\u{7}' {
596                            break;
597                        }
598                        if n == '\u{1b}' && chars.peek() == Some(&'\\') {
599                            chars.next();
600                            removed += 1;
601                            break;
602                        }
603                    }
604                }
605                Some(_) => {
606                    chars.next();
607                    removed += 1;
608                }
609                None => {}
610            }
611            continue;
612        }
613        if c.is_control() && !matches!(c, '\t' | '\n' | '\r') {
614            removed += 1;
615            continue;
616        }
617        out.push(c);
618    }
619    (out, removed)
620}
621
622/// HTML reduced to its text: tags removed (with the content of `script`
623/// and `style`), block ends as line breaks, the common entities decoded.
624pub fn html_to_text(html: &str) -> String {
625    let mut out = String::with_capacity(html.len());
626    let lower = html.to_ascii_lowercase();
627    let mut i = 0;
628    let b = html.as_bytes();
629    while i < b.len() {
630        if b[i] == b'<' {
631            let end = html[i..].find('>').map_or(b.len(), |e| i + e + 1);
632            let tag = &lower[i..end];
633            let name: String = tag
634                .trim_start_matches(['<', '/'])
635                .chars()
636                .take_while(|c| c.is_ascii_alphanumeric())
637                .collect();
638            if !tag.starts_with("</") && (name == "script" || name == "style") {
639                let close = format!("</{name}");
640                i = lower[end..].find(&close).map_or(b.len(), |c| {
641                    let at = end + c;
642                    lower[at..].find('>').map_or(b.len(), |e| at + e + 1)
643                });
644                continue;
645            }
646            if matches!(
647                name.as_str(),
648                "br" | "p" | "div" | "li" | "tr" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6"
649            ) && (tag.starts_with("</") || name == "br")
650                && !out.ends_with('\n')
651            {
652                out.push('\n');
653            }
654            i = end;
655            continue;
656        }
657        let next = html[i..].find('<').map_or(b.len(), |n| i + n);
658        out.push_str(&decode_entities(&html[i..next]));
659        i = next;
660    }
661    out.trim_end_matches('\n').to_string()
662}
663
664fn decode_entities(text: &str) -> String {
665    text.replace("&lt;", "<")
666        .replace("&gt;", ">")
667        .replace("&quot;", "\"")
668        .replace("&#39;", "'")
669        .replace("&nbsp;", " ")
670        .replace("&amp;", "&")
671}
672
673#[cfg(test)]
674mod tests {
675    use super::*;
676    use serde_json::json;
677
678    const COLOR: FormatId = FormatId::from_static("application/x-demo.color+json");
679    const GRAY: FormatId = FormatId::from_static("application/x-demo.gray+json");
680
681    #[test]
682    fn formats_are_mime_like_and_private_types_are_recognised() {
683        assert!(COLOR.is_private());
684        assert!(!TEXT.is_private());
685        assert!(TEXT.is_text());
686        assert_eq!(
687            FormatId::private("egui-pop", "color").unwrap().as_str(),
688            "application/x-egui-pop.color+json"
689        );
690        assert!(FormatId::new("no-slash").is_err());
691        assert!(FormatId::new("text/plain;charset=utf-8").is_ok());
692        assert_eq!(serde_json::to_value(&TEXT).unwrap(), json!("text/plain"));
693        let back: FormatId = serde_json::from_value(json!("text/html")).unwrap();
694        assert_eq!(back, HTML);
695    }
696
697    #[test]
698    fn slots_follow_the_origin() {
699        assert_eq!(Slot::of(&Origin::User), Slot::User);
700        let agent = Slot::of(&Origin::Agent("a".into()));
701        assert_eq!(agent.name(), "agent:a");
702        assert_eq!(Slot::parse("agent:a"), agent);
703        assert_eq!(serde_json::to_value(&Slot::User).unwrap(), json!("user"));
704    }
705
706    #[test]
707    fn an_item_offers_its_type_then_its_fallbacks() {
708        let item = ClipItem::new(COLOR, 2, json!({ "hex": "#102030" }), "a colour")
709            .fallback(HTML, json!("<b>#102030</b>"))
710            .fallback(TEXT, json!("#102030"));
711        assert_eq!(item.offers(), [COLOR, HTML, TEXT]);
712        assert_eq!(item.text(), Some("#102030"));
713        assert_eq!(item.repr(&COLOR).unwrap().data["hex"], "#102030");
714        assert_eq!(item.repr(&PNG), None);
715        let ext = ClipItem::external_text("hello");
716        assert!(ext.external);
717        assert_eq!(ext.offers(), [TEXT]);
718        assert_eq!(ext.text(), Some("hello"));
719    }
720
721    #[test]
722    fn negotiation_takes_the_richest_accepted_then_a_transform() {
723        let offer = [COLOR, TEXT];
724        let to_gray = TransformSpec::new("gray", COLOR, GRAY).lossy();
725        let parse = TransformSpec::new("parse", TEXT, COLOR);
726        // Direct beats a transform for the same accepted format.
727        let p = negotiate(&offer, &[COLOR], std::slice::from_ref(&parse)).unwrap();
728        assert_eq!(p.transform, None);
729        // The target's order wins over the offer's.
730        let p = negotiate(&offer, &[TEXT, COLOR], &[]).unwrap();
731        assert_eq!(p.to, TEXT);
732        // Only through a transform; one, never a chain.
733        let p = negotiate(&offer, &[GRAY], std::slice::from_ref(&to_gray)).unwrap();
734        assert_eq!((p.format, p.to, p.lossy), (COLOR, GRAY, true));
735        let chain = negotiate(&[TEXT], &[GRAY], &[parse.clone(), to_gray.clone()]);
736        assert!(chain.is_err());
737        // Text from outside parsed into a colour.
738        let p = negotiate(&[TEXT], &[COLOR], std::slice::from_ref(&parse)).unwrap();
739        assert_eq!(p.transform.as_deref(), Some("parse"));
740    }
741
742    #[test]
743    fn a_refusal_says_what_was_offered_and_accepted() {
744        let r = negotiate(&[COLOR], &[PNG], &[]).unwrap_err();
745        assert!(r.reason.contains("application/x-demo.color+json"), "{r}");
746        assert!(r.reason.contains("image/png"), "{r}");
747        assert_eq!(r.offered, [COLOR]);
748        let empty = negotiate(&[], &[TEXT], &[]).unwrap_err();
749        assert_eq!(empty.reason, "the clipboard is empty");
750    }
751
752    #[test]
753    fn paste_special_lists_every_way_and_can_be_held_to_one() {
754        let offer = [COLOR, TEXT];
755        let to_gray = TransformSpec::new("gray", COLOR, GRAY).lossy();
756        let all = candidates(&offer, &[COLOR, GRAY, TEXT], std::slice::from_ref(&to_gray));
757        assert_eq!(all.len(), 3);
758        let p = choose(
759            &offer,
760            &[COLOR, GRAY, TEXT],
761            std::slice::from_ref(&to_gray),
762            Some(&TEXT),
763            None,
764        )
765        .unwrap();
766        assert_eq!(p.to, TEXT);
767        let p = choose(
768            &offer,
769            &[COLOR, GRAY],
770            std::slice::from_ref(&to_gray),
771            None,
772            Some("gray"),
773        )
774        .unwrap();
775        assert_eq!(p.to, GRAY);
776        assert!(choose(&offer, &[COLOR], &[to_gray], None, Some("gray")).is_err());
777    }
778
779    #[test]
780    fn control_characters_and_escapes_are_stripped() {
781        let (t, n) = strip_controls("ls\u{1b}[201~; rm -rf /\u{7}\n\tok\u{1b}]0;title\u{7}!");
782        assert_eq!(t, "ls; rm -rf /\n\tok!");
783        assert!(n > 0);
784        assert_eq!(strip_controls("plain\r\n"), ("plain\r\n".to_string(), 0));
785    }
786
787    #[test]
788    fn html_is_reduced_to_its_text() {
789        let t = html_to_text(
790            "<p>A &amp; B</p><script>alert(1)</script><style>p{}</style><div>C<br>D</div>",
791        );
792        assert_eq!(t, "A & B\nC\nD");
793    }
794
795    #[test]
796    fn the_marker_is_stable() {
797        assert_eq!(marker(""), 0xcbf2_9ce4_8422_2325);
798        assert_ne!(marker("a"), marker("b"));
799    }
800}