1use std::io::{self, Write as _};
2use std::process::{Command, Stdio};
3
4const MAX_CLIPBOARD_BYTES: usize = 1024 * 1024;
5
6pub trait Clipboard {
8 fn copy(&mut self, text: &str) -> io::Result<()>;
14}
15
16#[derive(Debug, Default, Clone)]
18pub struct MemoryClipboard {
19 contents: Option<String>,
20}
21
22impl MemoryClipboard {
23 #[must_use]
25 pub fn contents(&self) -> Option<&str> {
26 self.contents.as_deref()
27 }
28}
29
30impl Clipboard for MemoryClipboard {
31 fn copy(&mut self, text: &str) -> io::Result<()> {
32 validate(text)?;
33 self.contents = Some(text.to_owned());
34 Ok(())
35 }
36}
37
38#[derive(Debug, Default, Clone, Copy)]
40pub struct SystemClipboard;
41
42impl Clipboard for SystemClipboard {
43 fn copy(&mut self, text: &str) -> io::Result<()> {
44 validate(text)?;
45 #[cfg(target_os = "macos")]
46 {
47 pipe_to("pbcopy", &[], text)
48 }
49 #[cfg(target_os = "windows")]
50 {
51 pipe_to("clip", &[], text)
52 }
53 #[cfg(all(unix, not(target_os = "macos")))]
54 {
55 pipe_to("wl-copy", &[], text)
56 .or_else(|_| pipe_to("xclip", &["-selection", "clipboard"], text))
57 }
58 #[cfg(not(any(unix, target_os = "windows")))]
59 {
60 let _ = text;
61 Err(io::Error::new(
62 io::ErrorKind::Unsupported,
63 "system clipboard is unavailable",
64 ))
65 }
66 }
67}
68
69fn validate(text: &str) -> io::Result<()> {
70 if text.len() > MAX_CLIPBOARD_BYTES || text.contains('\0') {
71 return Err(io::Error::new(
72 io::ErrorKind::InvalidInput,
73 "clipboard text is invalid",
74 ));
75 }
76 Ok(())
77}
78
79fn pipe_to(program: &str, arguments: &[&str], text: &str) -> io::Result<()> {
80 let mut child = Command::new(program)
81 .args(arguments)
82 .stdin(Stdio::piped())
83 .stdout(Stdio::null())
84 .stderr(Stdio::null())
85 .spawn()?;
86 child
87 .stdin
88 .take()
89 .ok_or_else(|| io::Error::other("clipboard stdin is unavailable"))?
90 .write_all(text.as_bytes())?;
91 let status = child.wait()?;
92 if status.success() {
93 Ok(())
94 } else {
95 Err(io::Error::other("clipboard command failed"))
96 }
97}