zc2 0.0.51

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
//! Copy to the clipboard from a full-screen app: the platform's own tool
//! when there is one (it works in every terminal, including over tmux),
//! else OSC 52, which most terminals honour and which also crosses SSH.

use base64::Engine;
use std::io::Write;
use std::process::{Command, Stdio};

pub fn osc52(text: &str) -> String {
    format!(
        "\u{1b}]52;c;{}\u{7}",
        base64::engine::general_purpose::STANDARD.encode(text)
    )
}

fn via(tool: &str, args: &[&str], text: &str) -> bool {
    let Ok(mut child) = Command::new(tool)
        .args(args)
        .stdin(Stdio::piped())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
    else {
        return false;
    };
    let wrote = child
        .stdin
        .take()
        .is_some_and(|mut i| i.write_all(text.as_bytes()).is_ok());
    wrote && child.wait().is_ok_and(|s| s.success())
}

/// Copy `text`; returns where it went, for the notice.
pub fn copy(text: &str) -> &'static str {
    let tools: &[(&str, &[&str])] = &[
        ("pbcopy", &[]),
        ("wl-copy", &[]),
        ("xclip", &["-selection", "clipboard"]),
        ("xsel", &["--clipboard", "--input"]),
    ];
    if tools.iter().any(|(t, a)| via(t, a, text)) {
        return "clipboard";
    }
    let mut out = std::io::stdout();
    let _ = out.write_all(osc52(text).as_bytes());
    let _ = out.flush();
    "terminal clipboard"
}

#[cfg(test)]
mod tests {
    #[test]
    fn osc52_wraps_base64_of_the_text() {
        assert_eq!(
            super::osc52("zc://node-ab"),
            "\u{1b}]52;c;emM6Ly9ub2RlLWFi\u{7}"
        );
    }
}