#![deny(unsafe_code)]
use std::path::{Path, PathBuf};
use crate::plat::{dirs, Platform};
use crate::term::{base64, osc52_sequence, ClipReport, MAX_CLIPBOARD_BYTES};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mux {
None,
Tmux,
Screen,
}
pub const SCREEN_CHUNK: usize = 768;
pub fn detect_mux(tmux: bool, sty: bool, term: Option<&str>) -> Mux {
if tmux {
return Mux::Tmux;
}
if sty || term.map(|t| t.starts_with("screen")).unwrap_or(false) {
return Mux::Screen;
}
Mux::None
}
pub fn mux_from_env() -> Mux {
detect_mux(
std::env::var_os("TMUX").is_some(),
std::env::var_os("STY").is_some(),
std::env::var("TERM").ok().as_deref(),
)
}
pub fn clipboard_sequence(text: &str, mux: Mux) -> (String, ClipReport) {
match mux {
Mux::None => osc52_sequence(text, false),
Mux::Tmux => osc52_sequence(text, true),
Mux::Screen => screen_sequence(text),
}
}
fn screen_sequence(text: &str) -> (String, ClipReport) {
let mut cut = text.len().min(MAX_CLIPBOARD_BYTES);
while cut > 0 && !text.is_char_boundary(cut) {
cut -= 1;
}
let report = ClipReport { sent: cut, truncated: cut < text.len() };
let inner = format!("\x1b]52;c;{}\x07", base64(&text.as_bytes()[..cut]));
let mut out = String::with_capacity(inner.len() + 64);
let bytes = inner.as_bytes();
let mut at = 0;
while at < bytes.len() {
let end = (at + SCREEN_CHUNK).min(bytes.len());
out.push_str("\x1bP");
out.push_str(&inner[at..end]);
out.push_str("\x1b\\");
at = end;
}
(out, report)
}
pub fn fallback_path(env: &dirs::Env) -> Option<PathBuf> {
dirs::yank_fallback(Platform::HOST, env)
}
pub fn write_fallback(text: &str) -> Option<PathBuf> {
let path = fallback_path(&dirs::Env::from_process())?;
let dir = path.parent()?;
std::fs::create_dir_all(dir).ok()?;
std::fs::write(&path, text.as_bytes()).ok()?;
Some(path)
}
pub fn display_path(path: &Path, home: Option<&Path>) -> String {
dirs::display_path(
Platform::HOST,
&path.to_string_lossy(),
home.map(|h| h.to_string_lossy()).as_deref(),
)
}
pub fn yank_message(what: &str, report: Option<ClipReport>, fallback: Option<&str>) -> String {
let saved = fallback.map(|p| format!(" \u{b7} saved to {p}"));
match report {
Some(r) if r.truncated => match fallback {
Some(p) => format!(
"yanked {what} \u{2014} clipboard truncated to {} bytes; full text in {p}",
r.sent
),
None => format!(
"yanked {what} \u{2014} clipboard truncated to {} bytes",
r.sent
),
},
Some(_) => format!("yanked {what}{}", saved.unwrap_or_default()),
None => match fallback {
Some(p) => format!("clipboard refused the copy \u{2014} {what} saved to {p}"),
None => format!("could not copy {what}: no clipboard and no cache file"),
},
}
}
pub fn line_count(n: usize) -> String {
match n {
1 => "1 line".to_string(),
_ => format!("{n} lines"),
}
}