2021-08-08 14:25:22 +00:00
|
|
|
use anyhow::{anyhow, Result};
|
|
|
|
#[cfg(all(target_family = "unix", not(target_os = "macos")))]
|
|
|
|
use std::ffi::OsStr;
|
|
|
|
use std::io::Write;
|
|
|
|
use std::process::{Command, Stdio};
|
2021-07-09 06:51:08 +00:00
|
|
|
|
2021-08-08 14:25:22 +00:00
|
|
|
fn execute_copy_command(command: Command, text: &str) -> Result<()> {
|
|
|
|
let mut command = command;
|
2021-07-09 06:51:08 +00:00
|
|
|
|
2021-08-08 14:25:22 +00:00
|
|
|
let mut process = command
|
|
|
|
.stdin(Stdio::piped())
|
|
|
|
.stdout(Stdio::null())
|
|
|
|
.spawn()
|
|
|
|
.map_err(|e| anyhow!("`{:?}`: {}", command, e))?;
|
2021-07-09 06:51:08 +00:00
|
|
|
|
2021-08-08 14:25:22 +00:00
|
|
|
process
|
|
|
|
.stdin
|
|
|
|
.as_mut()
|
|
|
|
.ok_or_else(|| anyhow!("`{:?}`", command))?
|
|
|
|
.write_all(text.as_bytes())
|
|
|
|
.map_err(|e| anyhow!("`{:?}`: {}", command, e))?;
|
2021-07-09 06:51:08 +00:00
|
|
|
|
2021-08-08 14:25:22 +00:00
|
|
|
process
|
|
|
|
.wait()
|
|
|
|
.map_err(|e| anyhow!("`{:?}`: {}", command, e))?;
|
2021-07-09 06:51:08 +00:00
|
|
|
|
2021-08-08 14:25:22 +00:00
|
|
|
Ok(())
|
|
|
|
}
|
2021-07-09 06:51:08 +00:00
|
|
|
|
2021-08-08 14:25:22 +00:00
|
|
|
#[cfg(all(target_family = "unix", not(target_os = "macos")))]
|
|
|
|
fn gen_command(path: impl AsRef<OsStr>, xclip_syntax: bool) -> Command {
|
|
|
|
let mut c = Command::new(path);
|
|
|
|
if xclip_syntax {
|
|
|
|
c.arg("-selection");
|
|
|
|
c.arg("clipboard");
|
|
|
|
} else {
|
|
|
|
c.arg("--clipboard");
|
2021-07-09 06:51:08 +00:00
|
|
|
}
|
2021-08-08 14:25:22 +00:00
|
|
|
c
|
2021-07-09 06:51:08 +00:00
|
|
|
}
|
|
|
|
|
2021-08-08 14:25:22 +00:00
|
|
|
#[cfg(all(target_family = "unix", not(target_os = "macos")))]
|
|
|
|
pub fn copy_to_clipboard(string: &str) -> Result<()> {
|
|
|
|
use std::path::PathBuf;
|
|
|
|
use which::which;
|
|
|
|
let (path, xclip_syntax) = which("xclip").ok().map_or_else(
|
|
|
|
|| {
|
|
|
|
(
|
|
|
|
which("xsel").ok().unwrap_or_else(|| PathBuf::from("xsel")),
|
|
|
|
false,
|
|
|
|
)
|
|
|
|
},
|
|
|
|
|path| (path, true),
|
|
|
|
);
|
2021-07-09 06:51:08 +00:00
|
|
|
|
2021-08-08 14:25:22 +00:00
|
|
|
let cmd = gen_command(path, xclip_syntax);
|
|
|
|
execute_copy_command(cmd, string)
|
|
|
|
}
|
2021-07-09 06:51:08 +00:00
|
|
|
|
2021-08-08 14:25:22 +00:00
|
|
|
#[cfg(target_os = "macos")]
|
|
|
|
pub fn copy_to_clipboard(string: &str) -> Result<()> {
|
|
|
|
execute_copy_command(Command::new("pbcopy"), string)
|
|
|
|
}
|
2021-07-09 06:51:08 +00:00
|
|
|
|
2021-08-08 14:25:22 +00:00
|
|
|
#[cfg(windows)]
|
|
|
|
pub fn copy_to_clipboard(string: &str) -> Result<()> {
|
|
|
|
execute_copy_command(Command::new("clip"), string)
|
2021-07-09 06:51:08 +00:00
|
|
|
}
|