use std::io::Write;
use std::process::{Command, Stdio};
use std::time::Duration;
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as BASE64;
const MAX_BYTES: usize = 64 * 1024;
const TMUX_TIMEOUT: Duration = Duration::from_secs(2);
#[derive(Debug, PartialEq, Eq)]
pub enum Copy {
Sequence(String),
Done,
}
pub fn copy(text: &str) -> Result<Copy, &'static str> {
if text.is_empty() {
return Err("nothing to copy");
}
if text.len() > MAX_BYTES {
return Err("too much to copy");
}
if in_tmux() && tmux_copy(text) {
return Ok(Copy::Done);
}
Ok(Copy::Sequence(osc52(text)))
}
pub fn osc52(text: &str) -> String {
format!("\x1b]52;c;{}\x07", BASE64.encode(text))
}
fn in_tmux() -> bool {
std::env::var_os("TMUX").is_some()
}
fn tmux_copy(text: &str) -> bool {
let Ok(mut child) = Command::new("tmux")
.args(["load-buffer", "-w", "-"])
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
else {
return false;
};
if let Some(stdin) = child.stdin.as_mut() {
if stdin.write_all(text.as_bytes()).is_err() {
return false;
}
}
drop(child.stdin.take());
matches!(super::tmux::wait_within(&mut child, TMUX_TIMEOUT), Some(status) if status.success())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_sequence_carries_the_text_as_base64() {
assert_eq!(osc52("hi"), "\x1b]52;c;aGk=\x07");
let sequence = osc52("echo \"one\"\necho 'two'\n");
assert!(sequence.starts_with("\x1b]52;c;"));
assert!(sequence.ends_with('\x07'));
let payload = sequence
.trim_start_matches("\x1b]52;c;")
.trim_end_matches('\x07');
assert_eq!(
String::from_utf8(BASE64.decode(payload).unwrap()).unwrap(),
"echo \"one\"\necho 'two'\n"
);
}
#[test]
fn nothing_and_too_much_are_refused() {
assert!(copy("").is_err());
assert!(copy(&"x".repeat(MAX_BYTES + 1)).is_err());
}
#[test]
fn a_reasonable_block_is_accepted() {
assert!(copy("cargo install termmd").is_ok());
}
}