use std::path::Path;
use std::time::{Duration, SystemTime};
use isothrum_runner::{HostOs, ProcessSpec, ShellCommand, capture};
use crate::context::Context;
#[cfg(test)]
mod tests;
pub const START_GRACE: Duration = Duration::from_millis(1500);
const OPEN_LIMIT: Duration = Duration::from_secs(30);
const QUIET_DOCKER: (&str, &str) = ("DOCKER_CLI_HINTS", "false");
const LINUX_TERMINALS: [(&str, &[&str], &[&str]); 6] = [
("x-terminal-emulator", &["-T"], &["-e"]),
("gnome-terminal", &["--title"], &["--"]),
("konsole", &["-p"], &["-e"]),
("xfce4-terminal", &["-T"], &["-x"]),
("alacritty", &["-t"], &["-e"]),
("xterm", &["-T"], &["-e"]),
];
const SCRIPT_PREFIX: &str = "isothrum-terminal-";
const SCRIPT_TTL: Duration = Duration::from_secs(10 * 60);
#[derive(Debug)]
#[non_exhaustive]
pub enum NotOpened {
Automation {
said: String,
},
Failed {
program: String,
said: String,
},
NoTerminal {
tried: Vec<String>,
line: String,
},
Script(std::io::Error),
}
impl std::fmt::Display for NotOpened {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
NotOpened::Automation { said } => write!(f, "not allowed to control Terminal (Automation permission): {said}"),
NotOpened::Failed { program, said } => write!(f, "{program} couldn't open a terminal: {said}"),
NotOpened::NoTerminal { tried, line } => {
write!(f, "no terminal started (tried {}); run this yourself: {line}", tried.join(", "))
}
NotOpened::Script(e) => write!(f, "couldn't write the console's script: {e}"),
}
}
}
impl std::error::Error for NotOpened {}
pub async fn open(cx: &Context, title: &str, command: &ShellCommand, scripts: &Path) -> Result<(), NotOpened> {
match cx.host.os {
HostOs::Macos => opened_by(cx, &ProcessSpec::new("osascript", ["-e".to_owned(), terminal_script(title, command)])).await,
HostOs::Linux => linux(cx, title, command).await,
HostOs::Windows => {
let name = write_script(scripts, title, command).map_err(NotOpened::Script)?;
opened_by(cx, &start_spec(scripts, &name)).await
}
}
}
async fn opened_by(cx: &Context, spec: &ProcessSpec) -> Result<(), NotOpened> {
let failed = |said: String| NotOpened::Failed {
program: spec.program.clone(),
said,
};
let captured = tokio::time::timeout(OPEN_LIMIT, capture(cx.runner.as_ref(), spec))
.await
.map_err(|_| failed(format!("no answer within {} s", OPEN_LIMIT.as_secs())))?
.map_err(|e| failed(e.to_string()))?;
if captured.success() {
return Ok(());
}
let said = captured.reason();
if said.contains("-1743") {
return Err(NotOpened::Automation { said });
}
Err(failed(said))
}
async fn linux(cx: &Context, title: &str, command: &ShellCommand) -> Result<(), NotOpened> {
let mut tried = Vec::new();
for (terminal, titled, runs) in LINUX_TERMINALS {
let spec = ProcessSpec::new("setsid", linux_args(terminal, titled, runs, title, command));
tried.push(terminal.to_owned());
match tokio::time::timeout(START_GRACE, capture(cx.runner.as_ref(), &spec)).await {
Err(_) => return Ok(()),
Ok(Ok(captured)) if captured.success() => return Ok(()),
Ok(Ok(_) | Err(_)) => {}
}
}
Err(NotOpened::NoTerminal {
tried,
line: command.sh_line(),
})
}
fn linux_args(terminal: &str, titled: &[&str], runs: &[&str], title: &str, command: &ShellCommand) -> Vec<String> {
let title = if terminal == "konsole" {
format!("tabtitle={title}")
} else {
title.to_owned()
};
let mut args: Vec<String> = vec!["-w".into(), terminal.into()];
args.extend(titled.iter().map(|s| (*s).to_owned()));
args.push(title);
args.extend(runs.iter().map(|s| (*s).to_owned()));
args.extend(["env".to_owned(), "-C".to_owned(), command.cwd.display().to_string()]);
args.push(format!("{}={}", QUIET_DOCKER.0, QUIET_DOCKER.1));
args.extend(command.env.iter().map(|(k, v)| format!("{k}={v}")));
args.push(command.program.clone());
args.extend(command.args.iter().cloned());
args
}
fn sh_word(s: &str) -> String {
let plain = |c: char| c.is_ascii_alphanumeric() || "_-.,/:@%+=".contains(c);
if !s.is_empty() && s.chars().all(plain) {
s.to_owned()
} else {
format!("'{}'", s.replace('\'', r"'\''"))
}
}
#[must_use]
pub fn posix_line(command: &ShellCommand) -> String {
let quiet = format!("{}={}", QUIET_DOCKER.0, QUIET_DOCKER.1);
let words = std::iter::once("env".to_owned())
.chain(std::iter::once(quiet))
.chain(command.env.iter().map(|(k, v)| sh_word(&format!("{k}={v}"))))
.chain(std::iter::once(&command.program).chain(&command.args).map(|w| sh_word(w)));
format!(
"cd {} && exec {}",
sh_word(&command.cwd.display().to_string()),
words.collect::<Vec<_>>().join(" ")
)
}
fn applescript_string(s: &str) -> String {
s.replace('\\', "\\\\").replace('"', "\\\"")
}
fn terminal_script(title: &str, command: &ShellCommand) -> String {
let line = applescript_string(&format!(" clear; {}", posix_line(command)));
let title = applescript_string(title);
format!(
"tell application \"Terminal\"\nactivate\nset t to do script \"{line}\"\nset custom title of t to \"{title}\"\n\
set title displays custom title of t to true\nset title displays window size of t to false\n\
set title displays device name of t to false\nset title displays shell path of t to false\n\
set title displays file name of t to false\nend tell"
)
}
const CMD_SPECIAL: [char; 7] = ['&', '|', '<', '>', '^', '(', ')'];
#[must_use]
pub fn windows_line(command: &ShellCommand) -> String {
let quote = |w: &str| {
if w.is_empty() || w.contains([' ', '"']) || w.contains(CMD_SPECIAL) {
format!("\"{}\"", w.replace('"', "\"\""))
} else {
w.to_owned()
}
};
let mut run = std::iter::once(&command.program)
.chain(&command.args)
.map(|w| windows_word(w))
.collect::<Vec<_>>()
.join(" ");
for (name, value) in command.env.iter().rev() {
run = format!("set \"{name}={value}\" && {run}");
}
format!("cd /d {} && {run}", quote(&command.cwd.display().to_string()))
}
fn windows_word(w: &str) -> String {
if !(w.is_empty() || w.contains([' ', '\t', '"']) || w.contains(CMD_SPECIAL)) {
return w.to_owned();
}
let mut argv = String::from('"');
let mut backslashes = 0;
for c in w.chars() {
match c {
'\\' => backslashes += 1,
'"' => {
argv.extend(std::iter::repeat_n('\\', backslashes + 1));
backslashes = 0;
}
_ => backslashes = 0,
}
argv.push(c);
}
argv.extend(std::iter::repeat_n('\\', backslashes));
argv.push('"');
let mut line = String::with_capacity(argv.len());
let mut quoted = false;
for c in argv.chars() {
if c == '"' {
quoted = !quoted;
} else if !quoted && CMD_SPECIAL.contains(&c) {
line.push('^');
}
line.push(c);
}
line
}
fn script_text(title: &str, command: &ShellCommand) -> String {
let title: String = title
.chars()
.filter(|c| !c.is_control())
.flat_map(|c| if CMD_SPECIAL.contains(&c) { vec!['^', c] } else { vec![c] })
.collect();
let line = format!("set \"{}={}\" && {}", QUIET_DOCKER.0, QUIET_DOCKER.1, windows_line(command));
format!(
"@echo off\r\nchcp 65001 >nul\r\ntitle {}\r\ncls\r\n{}\r\n(goto) 2>nul & del \"%~f0\"\r\n",
title.replace('%', "%%"),
line.replace('%', "%%")
)
}
fn write_script(dir: &Path, title: &str, command: &ShellCommand) -> std::io::Result<String> {
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
clear_old_scripts(dir, SCRIPT_TTL);
let nanos = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap_or_default().as_nanos();
let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let name = format!("{SCRIPT_PREFIX}{}-{n}-{nanos}.cmd", std::process::id());
std::fs::create_dir_all(dir)?;
std::fs::write(dir.join(&name), script_text(title, command))?;
Ok(name)
}
fn start_spec(dir: &Path, name: &str) -> ProcessSpec {
let mut spec = ProcessSpec::new("cmd", ["/c", "start", "cmd", "/c", name]);
spec.cwd = Some(dir.to_path_buf());
spec.env = vec![(QUIET_DOCKER.0.to_owned(), QUIET_DOCKER.1.to_owned())];
spec
}
fn clear_old_scripts(dir: &Path, ttl: Duration) {
let Ok(entries) = std::fs::read_dir(dir) else { return };
for e in entries.flatten() {
let name = e.file_name().to_string_lossy().into_owned();
let ours = name.starts_with(SCRIPT_PREFIX) && Path::new(&name).extension().is_some_and(|x| x.eq_ignore_ascii_case("cmd"));
let old = e
.metadata()
.and_then(|m| m.modified())
.ok()
.and_then(|t| t.elapsed().ok())
.is_some_and(|age| age >= ttl);
if ours && old {
drop(std::fs::remove_file(e.path()));
}
}
}
#[cfg(test)]
fn scripts_in(dir: &Path) -> Vec<std::path::PathBuf> {
std::fs::read_dir(dir).map(|it| it.flatten().map(|e| e.path()).collect()).unwrap_or_default()
}