|
| 1 | +use base64::{engine::general_purpose, Engine as _}; |
| 2 | +use copypasta_ext::prelude::*; |
| 3 | +#[cfg(target_os = "linux")] |
| 4 | +use copypasta_ext::wayland_bin::WaylandBinClipboardContext; |
| 5 | +use copypasta_ext::x11_bin::ClipboardContext as BinClipboardContext; |
| 6 | +use copypasta_ext::x11_fork::ClipboardContext as ForkClipboardContext; |
| 7 | +use crossterm::style::Print; |
| 8 | +use std::{env, io}; |
| 9 | + |
| 10 | +pub enum CopyType { |
| 11 | + Native, |
| 12 | + OSC52, |
| 13 | +} |
| 14 | + |
| 15 | +pub fn copy_string_to_clipboard(content: String) -> Result<CopyType, ()> { |
| 16 | + if ssh_clipboard(content.as_str()) { |
| 17 | + Ok(CopyType::OSC52) |
| 18 | + } else if wayland_clipboard(content.as_str()) || other_platform_clipboard(content.as_str()) { |
| 19 | + Ok(CopyType::Native) |
| 20 | + } else { |
| 21 | + Err(()) |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +fn ssh_clipboard(content: &str) -> bool { |
| 26 | + env_var_set("SSH_CONNECTION") |
| 27 | + // We do not use copypasta_ext::osc52 module because we have enabled terminal raw mode, so we print with crossterm utilities |
| 28 | + // Check https://github.com/timvisee/rust-clipboard-ext/blob/371df19d2f961882a21c957f396d1e24548d1f28/src/osc52.rs#L92 |
| 29 | + && crossterm::execute!( |
| 30 | + io::stdout(), |
| 31 | + Print(format!( |
| 32 | + "\x1B]52;c;{}\x07", |
| 33 | + general_purpose::STANDARD.encode(content) |
| 34 | + )) |
| 35 | + ) |
| 36 | + .is_ok() |
| 37 | +} |
| 38 | +#[cfg(target_os = "linux")] |
| 39 | +fn wayland_clipboard(content: &str) -> bool { |
| 40 | + env_var_set("WAYLAND_DISPLAY") |
| 41 | + && WaylandBinClipboardContext::new() |
| 42 | + .and_then(|mut ctx| ctx.set_contents(content.to_owned())) |
| 43 | + .is_ok() |
| 44 | +} |
| 45 | + |
| 46 | +#[cfg(not(target_os = "linux"))] |
| 47 | +fn wayland_clipboard(content: &str) -> bool { |
| 48 | + false |
| 49 | +} |
| 50 | + |
| 51 | +fn other_platform_clipboard(content: &str) -> bool { |
| 52 | + BinClipboardContext::new() |
| 53 | + .and_then(|mut ctx| ctx.set_contents(content.to_owned())) |
| 54 | + .is_ok() |
| 55 | + || ForkClipboardContext::new() |
| 56 | + .and_then(|mut ctx| ctx.set_contents(content.to_owned())) |
| 57 | + .is_ok() |
| 58 | +} |
| 59 | + |
| 60 | +fn env_var_set(env_var: &str) -> bool { |
| 61 | + env::var(env_var) |
| 62 | + .map(|v| !v.trim().is_empty()) |
| 63 | + .unwrap_or(false) |
| 64 | +} |
0 commit comments