Debian Codegraph @

helix-view/src/clipboard.rs

raw symbols SCIP
1 // Implementation reference: https://github.com/neovim/neovim/blob/f2906a4669a2eef6d7bf86a29648793d63c98949/runtime/autoload/provider/clipboard.vim#L68-L152
2
3 use serde::{Deserialize, Serialize};
4 use std::borrow::Cow;
5 use thiserror::Error;
6
7 #[derive(Clone, Copy)]
8 pub enum ClipboardType {
9 Clipboard,
10 Selection,
11 }
12
13 #[derive(Debug, Error)]
14 pub enum ClipboardError {
15 #[error(transparent)]
16 IoError(#[from] std::io::Error),
17 #[error("could not convert terminal output to UTF-8: {0}")]
18 FromUtf8Error(#[from] std::string::FromUtf8Error),
19 #[cfg(windows)]
20 #[error("Windows API error: {0}")]
21 WinAPI(#[from] clipboard_win::ErrorCode),
22 #[error("clipboard provider command failed")]
23 CommandFailed,
24 #[error("failed to write to clipboard provider's stdin")]
25 StdinWriteFailed,
26 #[error("clipboard provider did not return any contents")]
27 MissingStdout,
28 #[error("This clipboard provider does not support reading")]
29 ReadingNotSupported,
30 }
31
32 type Result<T> = std::result::Result<T, ClipboardError>;
33
34 #[cfg(not(target_arch = "wasm32"))]
35 pub use external::ClipboardProvider;
36 #[cfg(target_arch = "wasm32")]
37 pub use noop::ClipboardProvider;
38
39 // Clipboard not supported for wasm
40 #[cfg(target_arch = "wasm32")]
41 mod noop {
42 use super::*;
43
44 #[derive(Debug, Clone)]
45 pub enum ClipboardProvider {}
46
47 impl ClipboardProvider {
48 pub fn detect() -> Self {
49 Self
50 }
51
52 pub fn name(&self) -> Cow<str> {
53 "none".into()
54 }
55
56 pub fn get_contents(&self, _clipboard_type: ClipboardType) -> Result<String> {
57 Err(ClipboardError::ReadingNotSupported)
58 }
59
60 pub fn set_contents(&self, _content: &str, _clipboard_type: ClipboardType) -> Result<()> {
61 Ok(())
62 }
63 }
64 }
65
66 #[cfg(not(target_arch = "wasm32"))]
67 mod external {
68 use super::*;
69
70 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
71 pub struct Command {
72 command: Cow<'static, str>,
73 #[serde(default)]
74 args: Cow<'static, [Cow<'static, str>]>,
75 }
76
77 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
78 #[serde(rename_all = "kebab-case")]
79 pub struct CommandProvider {
80 yank: Command,
81 paste: Command,
82 yank_primary: Option<Command>,
83 paste_primary: Option<Command>,
84 }
85
86 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
87 #[serde(rename_all = "kebab-case")]
88 #[allow(clippy::large_enum_variant)]
89 pub enum ClipboardProvider {
90 Pasteboard,
91 Wayland,
92 XClip,
93 XSel,
94 Win32Yank,
95 Tmux,
96 #[cfg(windows)]
97 Windows,
98 Termux,
99 #[cfg(feature = "term")]
100 Termcode,
101 Custom(CommandProvider),
102 None,
103 }
104
105 impl Default for ClipboardProvider {
106 #[cfg(windows)]
107 fn default() -> Self {
108 use helix_stdx::env::binary_exists;
109
110 if binary_exists("win32yank.exe") {
111 Self::Win32Yank
112 } else {
113 Self::Windows
114 }
115 }
116
117 #[cfg(target_os = "macos")]
118 fn default() -> Self {
119 use helix_stdx::env::{binary_exists, env_var_is_set};
120
121 if env_var_is_set("TMUX") && binary_exists("tmux") {
122 Self::Tmux
123 } else if binary_exists("pbcopy") && binary_exists("pbpaste") {
124 Self::Pasteboard
125 } else {
126 #[cfg(feature = "term")]
127 return Self::Termcode;
128 #[cfg(not(feature = "term"))]
129 return Self::None;
130 }
131 }
132
133 #[cfg(not(any(windows, target_os = "macos")))]
134 fn default() -> Self {
135 use helix_stdx::env::{binary_exists, env_var_is_set};
136
137 fn is_exit_success(program: &str, args: &[&str]) -> bool {
138 std::process::Command::new(program)
139 .args(args)
140 .output()
141 .ok()
142 .and_then(|out| out.status.success().then_some(()))
143 .is_some()
144 }
145
146 if binary_exists("termux-clipboard-set") && binary_exists("termux-clipboard-get") {
147 Self::Termux
148 } else if env_var_is_set("TMUX") && binary_exists("tmux") {
149 Self::Tmux
150 } else if env_var_is_set("WEZTERM_UNIX_SOCKET") && binary_exists("wezterm") {
151 Self::Termcode
152 } else if env_var_is_set("WAYLAND_DISPLAY")
153 && binary_exists("wl-copy")
154 && binary_exists("wl-paste")
155 {
156 Self::Wayland
157 } else if env_var_is_set("DISPLAY") && binary_exists("xclip") {
158 Self::XClip
159 } else if env_var_is_set("DISPLAY")
160 && binary_exists("xsel")
161 // FIXME: check performance of is_exit_success
162 && is_exit_success("xsel", &["-o", "-b"])
163 {
164 Self::XSel
165 } else if binary_exists("win32yank.exe") {
166 Self::Win32Yank
167 } else if cfg!(feature = "term") {
168 Self::Termcode
169 } else {
170 Self::None
171 }
172 }
173 }
174
175 impl ClipboardProvider {
176 pub fn name(&self) -> Cow<'_, str> {
177 fn builtin_name<'a>(
178 name: &'static str,
179 provider: &'static CommandProvider,
180 ) -> Cow<'a, str> {
181 if provider.yank.command != provider.paste.command {
182 Cow::Owned(format!(
183 "{} ({}+{})",
184 name, provider.yank.command, provider.paste.command
185 ))
186 } else {
187 Cow::Owned(format!("{} ({})", name, provider.yank.command))
188 }
189 }
190
191 match self {
192 // These names should match the config option names from Serde
193 Self::Pasteboard => builtin_name("pasteboard", &PASTEBOARD),
194 Self::Wayland => builtin_name("wayland", &WL_CLIPBOARD),
195 Self::XClip => builtin_name("x-clip", &XCLIP),
196 Self::XSel => builtin_name("x-sel", &XSEL),
197 Self::Win32Yank => builtin_name("win32-yank", &WIN32),
198 Self::Tmux => builtin_name("tmux", &TMUX),
199 Self::Termux => builtin_name("termux", &TERMUX),
200 #[cfg(windows)]
201 Self::Windows => "windows".into(),
202 #[cfg(feature = "term")]
203 Self::Termcode => "termcode".into(),
204 Self::Custom(command_provider) => Cow::Owned(format!(
205 "custom ({}+{})",
206 command_provider.yank.command, command_provider.paste.command
207 )),
208 Self::None => "none".into(),
209 }
210 }
211
212 pub fn get_contents(&self, clipboard_type: &ClipboardType) -> Result<String> {
213 fn yank_from_builtin(
214 provider: CommandProvider,
215 clipboard_type: &ClipboardType,
216 ) -> Result<String> {
217 match clipboard_type {
218 ClipboardType::Clipboard => execute_command(&provider.yank, None, true)?
219 .ok_or(ClipboardError::MissingStdout),
220 ClipboardType::Selection => {
221 if let Some(cmd) = provider.yank_primary.as_ref() {
222 return execute_command(cmd, None, true)?
223 .ok_or(ClipboardError::MissingStdout);
224 }
225
226 Ok(String::new())
227 }
228 }
229 }
230
231 match self {
232 Self::Pasteboard => yank_from_builtin(PASTEBOARD, clipboard_type),
233 Self::Wayland => yank_from_builtin(WL_CLIPBOARD, clipboard_type),
234 Self::XClip => yank_from_builtin(XCLIP, clipboard_type),
235 Self::XSel => yank_from_builtin(XSEL, clipboard_type),
236 Self::Win32Yank => yank_from_builtin(WIN32, clipboard_type),
237 Self::Tmux => yank_from_builtin(TMUX, clipboard_type),
238 Self::Termux => yank_from_builtin(TERMUX, clipboard_type),
239 #[cfg(target_os = "windows")]
240 Self::Windows => match clipboard_type {
241 ClipboardType::Clipboard => {
242 let contents =
243 clipboard_win::get_clipboard(clipboard_win::formats::Unicode)?;
244 Ok(contents)
245 }
246 ClipboardType::Selection => Ok(String::new()),
247 },
248 #[cfg(feature = "term")]
249 Self::Termcode => Err(ClipboardError::ReadingNotSupported),
250 Self::Custom(command_provider) => {
251 execute_command(&command_provider.yank, None, true)?
252 .ok_or(ClipboardError::MissingStdout)
253 }
254 Self::None => Err(ClipboardError::ReadingNotSupported),
255 }
256 }
257
258 pub fn set_contents(&self, content: &str, clipboard_type: ClipboardType) -> Result<()> {
259 fn paste_to_builtin(
260 provider: CommandProvider,
261 content: &str,
262 clipboard_type: ClipboardType,
263 ) -> Result<()> {
264 let cmd = match clipboard_type {
265 ClipboardType::Clipboard => &provider.paste,
266 ClipboardType::Selection => {
267 if let Some(cmd) = provider.paste_primary.as_ref() {
268 cmd
269 } else {
270 return Ok(());
271 }
272 }
273 };
274
275 execute_command(cmd, Some(content), false).map(|_| ())
276 }
277
278 match self {
279 Self::Pasteboard => paste_to_builtin(PASTEBOARD, content, clipboard_type),
280 Self::Wayland => paste_to_builtin(WL_CLIPBOARD, content, clipboard_type),
281 Self::XClip => paste_to_builtin(XCLIP, content, clipboard_type),
282 Self::XSel => paste_to_builtin(XSEL, content, clipboard_type),
283 Self::Win32Yank => paste_to_builtin(WIN32, content, clipboard_type),
284 Self::Tmux => paste_to_builtin(TMUX, content, clipboard_type),
285 Self::Termux => paste_to_builtin(TERMUX, content, clipboard_type),
286 #[cfg(target_os = "windows")]
287 Self::Windows => match clipboard_type {
288 ClipboardType::Clipboard => {
289 clipboard_win::set_clipboard(clipboard_win::formats::Unicode, content)?;
290 Ok(())
291 }
292 ClipboardType::Selection => Ok(()),
293 },
294 #[cfg(feature = "term")]
295 Self::Termcode => {
296 use std::io::Write;
297 use termina::escape::osc::{self, Osc};
298 let selection = match clipboard_type {
299 ClipboardType::Clipboard => osc::Selection::CLIPBOARD,
300 ClipboardType::Selection => osc::Selection::PRIMARY,
301 };
302 // NOTE: it would be ideal to have the terminal execute this but it _should_
303 // work to send this over stdout instead.
304 let mut stdout = std::io::stdout().lock();
305 write!(stdout, "{}", Osc::SetSelection(selection, content))?;
306 stdout.flush()?;
307 Ok(())
308 }
309 Self::Custom(command_provider) => match clipboard_type {
310 ClipboardType::Clipboard => {
311 execute_command(&command_provider.paste, Some(content), false).map(|_| ())
312 }
313 ClipboardType::Selection => {
314 if let Some(cmd) = &command_provider.paste_primary {
315 execute_command(cmd, Some(content), false).map(|_| ())
316 } else {
317 Ok(())
318 }
319 }
320 },
321 Self::None => Ok(()),
322 }
323 }
324 }
325
326 macro_rules! command_provider {
327 ($name:ident,
328 yank => $yank_cmd:literal $( , $yank_arg:literal )* ;
329 paste => $paste_cmd:literal $( , $paste_arg:literal )* ; ) => {
330 const $name: CommandProvider = CommandProvider {
331 yank: Command {
332 command: Cow::Borrowed($yank_cmd),
333 args: Cow::Borrowed(&[ $( Cow::Borrowed($yank_arg) ),* ])
334 },
335 paste: Command {
336 command: Cow::Borrowed($paste_cmd),
337 args: Cow::Borrowed(&[ $( Cow::Borrowed($paste_arg) ),* ])
338 },
339 yank_primary: None,
340 paste_primary: None,
341 };
342 };
343 ($name:ident,
344 yank => $yank_cmd:literal $( , $yank_arg:literal )* ;
345 paste => $paste_cmd:literal $( , $paste_arg:literal )* ;
346 yank_primary => $yank_primary_cmd:literal $( , $yank_primary_arg:literal )* ;
347 paste_primary => $paste_primary_cmd:literal $( , $paste_primary_arg:literal )* ; ) => {
348 const $name: CommandProvider = CommandProvider {
349 yank: Command {
350 command: Cow::Borrowed($yank_cmd),
351 args: Cow::Borrowed(&[ $( Cow::Borrowed($yank_arg) ),* ])
352 },
353 paste: Command {
354 command: Cow::Borrowed($paste_cmd),
355 args: Cow::Borrowed(&[ $( Cow::Borrowed($paste_arg) ),* ])
356 },
357 yank_primary: Some(Command {
358 command: Cow::Borrowed($yank_primary_cmd),
359 args: Cow::Borrowed(&[ $( Cow::Borrowed($yank_primary_arg) ),* ])
360 }),
361 paste_primary: Some(Command {
362 command: Cow::Borrowed($paste_primary_cmd),
363 args: Cow::Borrowed(&[ $( Cow::Borrowed($paste_primary_arg) ),* ])
364 }),
365 };
366 };
367 }
368
369 command_provider! {
370 TMUX,
371 yank => "tmux", "save-buffer", "-";
372 paste => "tmux", "load-buffer", "-w", "-";
373 }
374 command_provider! {
375 PASTEBOARD,
376 yank => "pbpaste";
377 paste => "pbcopy";
378 }
379 command_provider! {
380 WL_CLIPBOARD,
381 yank => "wl-paste", "--no-newline";
382 paste => "wl-copy", "--type", "text/plain";
383 yank_primary => "wl-paste", "-p", "--no-newline";
384 paste_primary => "wl-copy", "-p", "--type", "text/plain";
385 }
386 command_provider! {
387 XCLIP,
388 yank => "xclip", "-o", "-selection", "clipboard";
389 paste => "xclip", "-i", "-selection", "clipboard";
390 yank_primary => "xclip", "-o";
391 paste_primary => "xclip", "-i";
392 }
393 command_provider! {
394 XSEL,
395 yank => "xsel", "-o", "-b";
396 paste => "xsel", "-i", "-b";
397 yank_primary => "xsel", "-o";
398 paste_primary => "xsel", "-i";
399 }
400 command_provider! {
401 WIN32,
402 yank => "win32yank.exe", "-o", "--lf";
403 paste => "win32yank.exe", "-i", "--crlf";
404 }
405 command_provider! {
406 TERMUX,
407 yank => "termux-clipboard-get";
408 paste => "termux-clipboard-set";
409 }
410
411 fn execute_command(
412 cmd: &Command,
413 input: Option<&str>,
414 pipe_output: bool,
415 ) -> Result<Option<String>> {
416 use std::io::Write;
417 use std::process::{Command, Stdio};
418
419 let stdin = input.map(|_| Stdio::piped()).unwrap_or_else(Stdio::null);
420 let stdout = pipe_output.then(Stdio::piped).unwrap_or_else(Stdio::null);
421
422 let mut command: Command = Command::new(cmd.command.as_ref());
423
424 #[allow(unused_mut)]
425 let mut command_mut: &mut Command = command
426 .args(cmd.args.iter().map(AsRef::as_ref))
427 .stdin(stdin)
428 .stdout(stdout)
429 .stderr(Stdio::null());
430
431 // Fix for https://github.com/helix-editor/helix/issues/5424
432 #[cfg(unix)]
433 {
434 use std::os::unix::process::CommandExt;
435
436 unsafe {
437 command_mut = command_mut.pre_exec(|| match libc::setsid() {
438 -1 => Err(std::io::Error::last_os_error()),
439 _ => Ok(()),
440 });
441 }
442 }
443
444 let mut child = command_mut.spawn()?;
445
446 if let Some(input) = input {
447 let mut stdin = child.stdin.take().ok_or(ClipboardError::StdinWriteFailed)?;
448 stdin
449 .write_all(input.as_bytes())
450 .map_err(|_| ClipboardError::StdinWriteFailed)?;
451 }
452
453 // TODO: add timer?
454 let output = child.wait_with_output()?;
455
456 if !output.status.success() {
457 log::error!(
458 "clipboard provider {} failed with stderr: \"{}\"",
459 cmd.command,
460 String::from_utf8_lossy(&output.stderr)
461 );
462 return Err(ClipboardError::CommandFailed);
463 }
464
465 if pipe_output {
466 Ok(Some(String::from_utf8(output.stdout)?))
467 } else {
468 Ok(None)
469 }
470 }
471 }