1use 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#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
54pub struct FormatId(Cow<'static, str>);
55
56pub const TEXT: FormatId = FormatId::from_static("text/plain");
58pub const HTML: FormatId = FormatId::from_static("text/html");
60pub const PNG: FormatId = FormatId::from_static("image/png");
62pub 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 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 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 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 pub fn is_private(&self) -> bool {
117 self.0.starts_with("application/x-") && self.0.ends_with("+json")
118 }
119
120 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#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
155pub enum Slot {
156 User,
157 Session(String),
159}
160
161impl Slot {
162 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 pub fn name(&self) -> &str {
175 match self {
176 Slot::User => "user",
177 Slot::Session(s) => s,
178 }
179 }
180
181 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#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
211#[serde(rename_all = "lowercase")]
212pub enum Boundary {
213 Owner,
215 System,
218 External,
221}
222
223#[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 pub fn text(&self) -> Option<&str> {
238 self.data.as_str()
239 }
240}
241
242#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
244pub struct ClipOrigin {
245 #[serde(default)]
247 pub by: String,
248 #[serde(default)]
250 pub source: String,
251 #[serde(default, skip_serializing_if = "Option::is_none")]
253 pub window: Option<String>,
254 #[serde(default, skip_serializing_if = "Option::is_none")]
256 pub place: Option<String>,
257 #[serde(default, skip_serializing_if = "Option::is_none")]
259 pub owner: Option<String>,
260}
261
262#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
264pub struct Stripped {
265 pub by: String,
267 pub what: String,
269 pub boundary: Boundary,
270 pub format: FormatId,
272}
273
274#[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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
284pub struct ClipItem {
285 pub kind: FormatId,
288 pub version: u32,
290 pub payload: Json,
291 pub title: String,
294 #[serde(default, skip_serializing_if = "Option::is_none")]
297 pub title_key: Option<TitleKey>,
298 #[serde(default)]
300 pub fallbacks: Vec<Repr>,
301 #[serde(default)]
302 pub origin: ClipOrigin,
303 #[serde(default)]
305 pub stripped: Vec<Stripped>,
306 #[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 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 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 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 pub fn fallback(mut self, format: FormatId, data: Json) -> Self {
368 self.fallbacks.push(Repr::new(format, data));
369 self
370 }
371
372 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 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 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
405pub struct TransformSpec {
406 pub id: String,
407 pub from: FormatId,
408 pub to: FormatId,
409 #[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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
434pub struct Plan {
435 pub format: FormatId,
437 pub to: FormatId,
439 #[serde(default, skip_serializing_if = "Option::is_none")]
441 pub transform: Option<String>,
442 #[serde(default)]
443 pub lossy: bool,
444}
445
446#[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
460pub 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 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
496pub fn negotiate(
499 offer: &[FormatId],
500 accepts: &[FormatId],
501 transforms: &[TransformSpec],
502) -> Result<Plan, Refusal> {
503 choose(offer, accepts, transforms, None, None)
504}
505
506pub 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
555pub 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
567pub 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 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 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
622pub 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("<", "<")
666 .replace(">", ">")
667 .replace(""", "\"")
668 .replace("'", "'")
669 .replace(" ", " ")
670 .replace("&", "&")
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 let p = negotiate(&offer, &[COLOR], std::slice::from_ref(&parse)).unwrap();
728 assert_eq!(p.transform, None);
729 let p = negotiate(&offer, &[TEXT, COLOR], &[]).unwrap();
731 assert_eq!(p.to, TEXT);
732 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 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 & 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}