1use std::path::Path;
14use std::time::{Duration, SystemTime};
15
16use isothrum_runner::{HostOs, ProcessSpec, ShellCommand, capture};
17
18use crate::context::Context;
19
20#[cfg(test)]
21mod tests;
22
23pub const START_GRACE: Duration = Duration::from_millis(1500);
26
27const OPEN_LIMIT: Duration = Duration::from_secs(30);
29
30const QUIET_DOCKER: (&str, &str) = ("DOCKER_CLI_HINTS", "false");
32
33const LINUX_TERMINALS: [(&str, &[&str], &[&str]); 6] = [
36 ("x-terminal-emulator", &["-T"], &["-e"]),
37 ("gnome-terminal", &["--title"], &["--"]),
38 ("konsole", &["-p"], &["-e"]),
39 ("xfce4-terminal", &["-T"], &["-x"]),
40 ("alacritty", &["-t"], &["-e"]),
41 ("xterm", &["-T"], &["-e"]),
42];
43
44const SCRIPT_PREFIX: &str = "isothrum-terminal-";
46
47const SCRIPT_TTL: Duration = Duration::from_secs(10 * 60);
49
50#[derive(Debug)]
52#[non_exhaustive]
53pub enum NotOpened {
54 Automation {
57 said: String,
59 },
60 Failed {
62 program: String,
64 said: String,
66 },
67 NoTerminal {
69 tried: Vec<String>,
71 line: String,
73 },
74 Script(std::io::Error),
76}
77
78impl std::fmt::Display for NotOpened {
79 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80 match self {
81 NotOpened::Automation { said } => write!(f, "not allowed to control Terminal (Automation permission): {said}"),
82 NotOpened::Failed { program, said } => write!(f, "{program} couldn't open a terminal: {said}"),
83 NotOpened::NoTerminal { tried, line } => {
84 write!(f, "no terminal started (tried {}); run this yourself: {line}", tried.join(", "))
85 }
86 NotOpened::Script(e) => write!(f, "couldn't write the console's script: {e}"),
87 }
88 }
89}
90
91impl std::error::Error for NotOpened {}
92
93pub async fn open(cx: &Context, title: &str, command: &ShellCommand, scripts: &Path) -> Result<(), NotOpened> {
101 match cx.host.os {
102 HostOs::Macos => opened_by(cx, &ProcessSpec::new("osascript", ["-e".to_owned(), terminal_script(title, command)])).await,
103 HostOs::Linux => linux(cx, title, command).await,
104 HostOs::Windows => {
105 let name = write_script(scripts, title, command).map_err(NotOpened::Script)?;
106 opened_by(cx, &start_spec(scripts, &name)).await
107 }
108 }
109}
110
111async fn opened_by(cx: &Context, spec: &ProcessSpec) -> Result<(), NotOpened> {
113 let failed = |said: String| NotOpened::Failed {
114 program: spec.program.clone(),
115 said,
116 };
117 let captured = tokio::time::timeout(OPEN_LIMIT, capture(cx.runner.as_ref(), spec))
118 .await
119 .map_err(|_| failed(format!("no answer within {} s", OPEN_LIMIT.as_secs())))?
120 .map_err(|e| failed(e.to_string()))?;
121 if captured.success() {
122 return Ok(());
123 }
124 let said = captured.reason();
125 if said.contains("-1743") {
127 return Err(NotOpened::Automation { said });
128 }
129 Err(failed(said))
130}
131
132async fn linux(cx: &Context, title: &str, command: &ShellCommand) -> Result<(), NotOpened> {
134 let mut tried = Vec::new();
135 for (terminal, titled, runs) in LINUX_TERMINALS {
136 let spec = ProcessSpec::new("setsid", linux_args(terminal, titled, runs, title, command));
137 tried.push(terminal.to_owned());
138 match tokio::time::timeout(START_GRACE, capture(cx.runner.as_ref(), &spec)).await {
139 Err(_) => return Ok(()),
141 Ok(Ok(captured)) if captured.success() => return Ok(()),
143 Ok(Ok(_) | Err(_)) => {}
145 }
146 }
147 Err(NotOpened::NoTerminal {
148 tried,
149 line: command.sh_line(),
150 })
151}
152
153fn linux_args(terminal: &str, titled: &[&str], runs: &[&str], title: &str, command: &ShellCommand) -> Vec<String> {
157 let title = if terminal == "konsole" {
158 format!("tabtitle={title}")
159 } else {
160 title.to_owned()
161 };
162 let mut args: Vec<String> = vec!["-w".into(), terminal.into()];
163 args.extend(titled.iter().map(|s| (*s).to_owned()));
164 args.push(title);
165 args.extend(runs.iter().map(|s| (*s).to_owned()));
166 args.extend(["env".to_owned(), "-C".to_owned(), command.cwd.display().to_string()]);
167 args.push(format!("{}={}", QUIET_DOCKER.0, QUIET_DOCKER.1));
168 args.extend(command.env.iter().map(|(k, v)| format!("{k}={v}")));
169 args.push(command.program.clone());
170 args.extend(command.args.iter().cloned());
171 args
172}
173
174fn sh_word(s: &str) -> String {
176 let plain = |c: char| c.is_ascii_alphanumeric() || "_-.,/:@%+=".contains(c);
177 if !s.is_empty() && s.chars().all(plain) {
178 s.to_owned()
179 } else {
180 format!("'{}'", s.replace('\'', r"'\''"))
181 }
182}
183
184#[must_use]
187pub fn posix_line(command: &ShellCommand) -> String {
188 let quiet = format!("{}={}", QUIET_DOCKER.0, QUIET_DOCKER.1);
189 let words = std::iter::once("env".to_owned())
190 .chain(std::iter::once(quiet))
191 .chain(command.env.iter().map(|(k, v)| sh_word(&format!("{k}={v}"))))
192 .chain(std::iter::once(&command.program).chain(&command.args).map(|w| sh_word(w)));
193 format!(
194 "cd {} && exec {}",
195 sh_word(&command.cwd.display().to_string()),
196 words.collect::<Vec<_>>().join(" ")
197 )
198}
199
200fn applescript_string(s: &str) -> String {
202 s.replace('\\', "\\\\").replace('"', "\\\"")
203}
204
205fn terminal_script(title: &str, command: &ShellCommand) -> String {
209 let line = applescript_string(&format!(" clear; {}", posix_line(command)));
210 let title = applescript_string(title);
211 format!(
212 "tell application \"Terminal\"\nactivate\nset t to do script \"{line}\"\nset custom title of t to \"{title}\"\n\
213 set title displays custom title of t to true\nset title displays window size of t to false\n\
214 set title displays device name of t to false\nset title displays shell path of t to false\n\
215 set title displays file name of t to false\nend tell"
216 )
217}
218
219const CMD_SPECIAL: [char; 7] = ['&', '|', '<', '>', '^', '(', ')'];
221
222#[must_use]
226pub fn windows_line(command: &ShellCommand) -> String {
227 let quote = |w: &str| {
228 if w.is_empty() || w.contains([' ', '"']) || w.contains(CMD_SPECIAL) {
229 format!("\"{}\"", w.replace('"', "\"\""))
230 } else {
231 w.to_owned()
232 }
233 };
234 let mut run = std::iter::once(&command.program)
235 .chain(&command.args)
236 .map(|w| windows_word(w))
237 .collect::<Vec<_>>()
238 .join(" ");
239 for (name, value) in command.env.iter().rev() {
240 run = format!("set \"{name}={value}\" && {run}");
241 }
242 format!("cd /d {} && {run}", quote(&command.cwd.display().to_string()))
243}
244
245fn windows_word(w: &str) -> String {
253 if !(w.is_empty() || w.contains([' ', '\t', '"']) || w.contains(CMD_SPECIAL)) {
254 return w.to_owned();
255 }
256 let mut argv = String::from('"');
257 let mut backslashes = 0;
258 for c in w.chars() {
259 match c {
260 '\\' => backslashes += 1,
261 '"' => {
262 argv.extend(std::iter::repeat_n('\\', backslashes + 1));
263 backslashes = 0;
264 }
265 _ => backslashes = 0,
266 }
267 argv.push(c);
268 }
269 argv.extend(std::iter::repeat_n('\\', backslashes));
270 argv.push('"');
271 let mut line = String::with_capacity(argv.len());
272 let mut quoted = false;
273 for c in argv.chars() {
274 if c == '"' {
275 quoted = !quoted;
276 } else if !quoted && CMD_SPECIAL.contains(&c) {
277 line.push('^');
278 }
279 line.push(c);
280 }
281 line
282}
283
284fn script_text(title: &str, command: &ShellCommand) -> String {
289 let title: String = title
290 .chars()
291 .filter(|c| !c.is_control())
292 .flat_map(|c| if CMD_SPECIAL.contains(&c) { vec!['^', c] } else { vec![c] })
293 .collect();
294 let line = format!("set \"{}={}\" && {}", QUIET_DOCKER.0, QUIET_DOCKER.1, windows_line(command));
295 format!(
296 "@echo off\r\nchcp 65001 >nul\r\ntitle {}\r\ncls\r\n{}\r\n(goto) 2>nul & del \"%~f0\"\r\n",
297 title.replace('%', "%%"),
298 line.replace('%', "%%")
299 )
300}
301
302fn write_script(dir: &Path, title: &str, command: &ShellCommand) -> std::io::Result<String> {
305 static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
306 clear_old_scripts(dir, SCRIPT_TTL);
307 let nanos = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap_or_default().as_nanos();
308 let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
309 let name = format!("{SCRIPT_PREFIX}{}-{n}-{nanos}.cmd", std::process::id());
310 std::fs::create_dir_all(dir)?;
311 std::fs::write(dir.join(&name), script_text(title, command))?;
312 Ok(name)
313}
314
315fn start_spec(dir: &Path, name: &str) -> ProcessSpec {
318 let mut spec = ProcessSpec::new("cmd", ["/c", "start", "cmd", "/c", name]);
319 spec.cwd = Some(dir.to_path_buf());
320 spec.env = vec![(QUIET_DOCKER.0.to_owned(), QUIET_DOCKER.1.to_owned())];
321 spec
322}
323
324fn clear_old_scripts(dir: &Path, ttl: Duration) {
327 let Ok(entries) = std::fs::read_dir(dir) else { return };
328 for e in entries.flatten() {
329 let name = e.file_name().to_string_lossy().into_owned();
330 let ours = name.starts_with(SCRIPT_PREFIX) && Path::new(&name).extension().is_some_and(|x| x.eq_ignore_ascii_case("cmd"));
331 let old = e
332 .metadata()
333 .and_then(|m| m.modified())
334 .ok()
335 .and_then(|t| t.elapsed().ok())
336 .is_some_and(|age| age >= ttl);
337 if ours && old {
338 drop(std::fs::remove_file(e.path()));
340 }
341 }
342}
343
344#[cfg(test)]
346fn scripts_in(dir: &Path) -> Vec<std::path::PathBuf> {
347 std::fs::read_dir(dir).map(|it| it.flatten().map(|e| e.path()).collect()).unwrap_or_default()
348}