use anyhow::Result;
use base64::{Engine as _, engine::general_purpose::STANDARD};
use std::io::{self, Write};
pub(crate) trait ClipboardWriter {
fn copy(&mut self, text: &str) -> Result<()>;
}
#[derive(Debug, Default)]
pub(crate) struct Osc52Clipboard;
impl ClipboardWriter for Osc52Clipboard {
fn copy(&mut self, text: &str) -> Result<()> {
write_osc52_copy(io::stdout(), text)
}
}
pub(crate) fn osc52_sequence(text: &str) -> String {
format!("\x1b]52;c;{}\x07", STANDARD.encode(text.as_bytes()))
}
fn write_osc52_copy(mut writer: impl Write, text: &str) -> Result<()> {
writer.write_all(osc52_sequence(text).as_bytes())?;
writer.flush()?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn osc52_payload_encodes_utf8_and_newlines() {
assert_eq!(osc52_sequence("hi\nλ"), "\x1b]52;c;aGkKzrs=\x07");
}
#[test]
fn adapter_writes_sequence() {
let mut bytes = Vec::new();
write_osc52_copy(&mut bytes, "copy me").unwrap();
assert_eq!(String::from_utf8(bytes).unwrap(), osc52_sequence("copy me"));
}
}