Skip to main content

isothrum_machine/
terminal.rs

1//! Opening a command in this computer's own terminal, in a window of its own titled as the caller
2//! says: Terminal on macOS (`osascript`), the first terminal emulator that starts on Linux, a
3//! console window on Windows (`cmd /c start`). The command is a [`ShellCommand`] (a console the
4//! runner built, or the caller's own), run in its folder with its variables, quoted so its words
5//! reach it as they are: a folder with a space, a `'`, or a Windows profile folder with `&`.
6//!
7//! Every program starts through the runner ([`Context::runner`]). A terminal keeps running after
8//! this returns: on Linux it starts in a session of its own (`setsid`), so the runner ending the
9//! starter once the terminal is up leaves the window open; on macOS and Windows the starter
10//! (`osascript`, `cmd`) exits once the window is open, and what a tool started after exiting on
11//! its own is left alone.
12
13use 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
23/// How long a Linux terminal gets to fail on its own (one that can't start, zutty without its
24/// font, exits within a moment) before it counts as open.
25pub const START_GRACE: Duration = Duration::from_millis(1500);
26
27/// How long `osascript` or `cmd` may take to open the window.
28const OPEN_LIMIT: Duration = Duration::from_secs(30);
29
30/// The variable that turns off Docker's "What's next" hints when the command exits.
31const QUIET_DOCKER: (&str, &str) = ("DOCKER_CLI_HINTS", "false");
32
33/// The Linux terminal emulators tried, in order, each with the arguments that title its window
34/// and those that run a command (its program and arguments after them).
35const 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
44/// The scripts the Windows console runs: `isothrum-terminal-<unique>.cmd`.
45const SCRIPT_PREFIX: &str = "isothrum-terminal-";
46
47/// How long a console's script is kept: `cmd` read it long before.
48const SCRIPT_TTL: Duration = Duration::from_secs(10 * 60);
49
50/// Why the terminal didn't open.
51#[derive(Debug)]
52#[non_exhaustive]
53pub enum NotOpened {
54    /// macOS: this app isn't allowed to control Terminal (the Apple-event refusal `-1743`): the
55    /// Automation permission, in System Settings › Privacy & Security › Automation.
56    Automation {
57        /// What `osascript` said.
58        said: String,
59    },
60    /// The program that opens the window failed, or didn't start.
61    Failed {
62        /// The program.
63        program: String,
64        /// What it said, or why it didn't start.
65        said: String,
66    },
67    /// Linux: no terminal emulator started; `line` is the command to run by hand.
68    NoTerminal {
69        /// The terminals tried.
70        tried: Vec<String>,
71        /// The command as one line a POSIX shell runs.
72        line: String,
73    },
74    /// Windows: the console's script couldn't be written.
75    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
93/// Opens `command` in this computer's terminal, its window titled `title`. `scripts` is the folder
94/// the Windows console's script is written to (the temp folder; unused elsewhere): its path never
95/// goes through `cmd`'s own parsing, so a profile folder with `&` or a space is safe.
96///
97/// # Errors
98///
99/// [`NotOpened`]: why no window opened.
100pub 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
111/// Runs `spec`, a program that opens the window and exits.
112async 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    // Apple's "not authorized to send Apple events" (-1743), in any language.
126    if said.contains("-1743") {
127        return Err(NotOpened::Automation { said });
128    }
129    Err(failed(said))
130}
131
132/// Linux: the first of [`LINUX_TERMINALS`] that starts, in a session of its own.
133async 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            // Still running: its window is up (dropping the run ends `setsid` alone).
140            Err(_) => return Ok(()),
141            // A terminal that hands the window to its server and exits (gnome-terminal).
142            Ok(Ok(captured)) if captured.success() => return Ok(()),
143            // Not installed, refused, or it failed at once: the next one.
144            Ok(Ok(_) | Err(_)) => {}
145        }
146    }
147    Err(NotOpened::NoTerminal {
148        tried,
149        line: command.sh_line(),
150    })
151}
152
153/// `setsid`'s arguments for `terminal`: it waits for the terminal (`-w`, so a failed start is
154/// seen), which runs the command through `env` in its folder (`-C`) with its variables: no shell
155/// reads any of it.
156fn 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
174/// `s` single-quoted for a POSIX shell when it needs it.
175fn 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/// The POSIX line that runs `command` in its folder and replaces the shell with it (leaving the
185/// command ends the window's session): `cd <cwd> && exec env VAR=value… program args…`.
186#[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
200/// `s` as the text of a double-quoted string of Apple's scripting language.
201fn applescript_string(s: &str) -> String {
202    s.replace('\\', "\\\\").replace('"', "\\\"")
203}
204
205/// The script (Apple's scripting language) that opens a Terminal window on `command`, titled `title` alone (no size,
206/// device or shell path). The screen is cleared first, and the leading space keeps the line out
207/// of the shell's history where `HIST_IGNORE_SPACE` is on.
208fn 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
219/// The characters `cmd.exe` reads as its own outside double quotes.
220const CMD_SPECIAL: [char; 7] = ['&', '|', '<', '>', '^', '(', ')'];
221
222/// The `cmd.exe` line: `cd /d "<cwd>" && set "VAR=value" && program args`, each word
223/// double-quoted when it holds a space, a quote or a character `cmd.exe` reads as its own (a
224/// profile folder `C:\Users\Tom&Jerry`).
225#[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
245/// `w` as one argument of the program a `cmd.exe` line starts: double-quoted when it holds a
246/// space, a quote or a character `cmd.exe` reads as its own, as the C runtime (and PowerShell,
247/// Rust's std) read an argument back: a `"` as `\"`, the backslashes before it doubled. `cmd.exe`
248/// toggles its own quoting at every `"`, `\"` too, so each of its characters it would then read
249/// outside quotes is escaped with `^`. Doubling a quote (`""`) kept `cmd.exe`'s quoting whole but
250/// isn't how PowerShell reads one: `powershell -Command "... ""a"" ..."` failed with "The string
251/// is missing the terminator", and no command holding a quote opened.
252fn 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
284/// The console's script: UTF-8 read as such (`chcp 65001`, or `C:\Users\José` arrives garbled),
285/// the window titled, the screen cleared, the line run, then the script removed. A `%` starts a
286/// variable in a script, so the line's and the title's are doubled; the title's `cmd` characters
287/// are escaped with `^`.
288fn 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
302/// Writes the console's script into `dir` under a name no other console uses, made of plain
303/// characters alone, and clears the scripts earlier consoles left. Returns its file name.
304fn 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
315/// `cmd /c start cmd /c <name>`, run in the script's folder `dir`: the script is named by its
316/// plain file name, so no path `cmd` would split (`&`, a space) is ever on a command line.
317fn 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
324/// Removes the console scripts in `dir` older than `ttl` (a window closed mid-session never
325/// removed its own).
326fn 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            // One another process removed first is gone all the same.
339            drop(std::fs::remove_file(e.path()));
340        }
341    }
342}
343
344/// The scripts a test finds in `dir`.
345#[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}