lutra_proc::spawn_detached starts a program through CreateProcessW with bInheritHandles = FALSE and null standard handles (DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP as before), so lutra's output pipe closes when lutra exits. launch.rs uses it. Helper roles detached-plain/-proc show the standard library keeping the pipe open and spawn_detached not. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
140 lines
4.9 KiB
Rust
140 lines
4.9 KiB
Rust
//! Finding and starting the desktop app when no Lutra is running.
|
|
|
|
use std::path::{Path, PathBuf};
|
|
use std::thread;
|
|
use std::time::{Duration, Instant};
|
|
|
|
use lutra_control::client::{self, Client};
|
|
|
|
/// Environment variable with the path of the desktop binary to start.
|
|
pub const DESKTOP_ENV: &str = "LUTRA_DESKTOP";
|
|
|
|
/// File name of the desktop binary.
|
|
const DESKTOP_NAME: &str = if cfg!(windows) {
|
|
"lutra-desktop.exe"
|
|
} else {
|
|
"lutra-desktop"
|
|
};
|
|
|
|
/// How long to wait for a started app to write its rendezvous file and
|
|
/// answer.
|
|
pub const START_TIMEOUT: Duration = Duration::from_secs(60);
|
|
|
|
/// Time between two looks at the rendezvous file while the app starts.
|
|
const POLL: Duration = Duration::from_millis(150);
|
|
|
|
/// Time to wait for one connection attempt while the app starts.
|
|
const PROBE: Duration = Duration::from_secs(2);
|
|
|
|
/// The desktop binary: `LUTRA_DESKTOP` if set, else `lutra-desktop` next to
|
|
/// this executable, else the first `lutra-desktop` on `PATH`. The executable
|
|
/// is resolved through symbolic links first, so a `lutra` linked onto
|
|
/// `PATH` from `Lutra.app/Contents/MacOS/` still finds the app next to its
|
|
/// target; if that fails, the unresolved path is used.
|
|
///
|
|
/// # Errors
|
|
/// A message naming the places that were tried.
|
|
pub fn find_desktop() -> Result<PathBuf, String> {
|
|
if let Some(path) = std::env::var_os(DESKTOP_ENV).filter(|v| !v.is_empty()) {
|
|
return Ok(PathBuf::from(path));
|
|
}
|
|
let sibling = std::env::current_exe()
|
|
.ok()
|
|
.map(resolve_link)
|
|
.and_then(|exe| Some(exe.parent()?.join(DESKTOP_NAME)))
|
|
.filter(|path| path.is_file());
|
|
if let Some(path) = sibling {
|
|
return Ok(path);
|
|
}
|
|
std::env::var_os("PATH")
|
|
.and_then(|paths| {
|
|
std::env::split_paths(&paths)
|
|
.map(|dir| dir.join(DESKTOP_NAME))
|
|
.find(|path| path.is_file())
|
|
})
|
|
.ok_or_else(|| {
|
|
format!(
|
|
"cannot find {DESKTOP_NAME}: set {DESKTOP_ENV}, or put it next to lutra or on PATH"
|
|
)
|
|
})
|
|
}
|
|
|
|
/// `path` resolved to its final target if it is a symbolic link, else
|
|
/// `path` itself, also when resolving fails.
|
|
fn resolve_link(path: PathBuf) -> PathBuf {
|
|
let is_link = std::fs::symlink_metadata(&path).is_ok_and(|m| m.file_type().is_symlink());
|
|
if !is_link {
|
|
return path;
|
|
}
|
|
std::fs::canonicalize(&path).unwrap_or(path)
|
|
}
|
|
|
|
/// Starts `desktop` detached from this terminal through
|
|
/// [`lutra_proc::spawn_detached`] (Windows: a detached process in a new
|
|
/// process group that inherits none of this process's handles, so a script
|
|
/// reading `lutra`'s output through a pipe gets end of file as soon as
|
|
/// `lutra` exits; Unix: a new process group, so a Ctrl-C or hangup aimed at
|
|
/// the terminal's foreground group does not reach it) and waits until it
|
|
/// answers on the rendezvous file in `dir`. A desktop that exits successfully may
|
|
/// have forwarded to an instance that started at the same time, so only a
|
|
/// failed exit ends the wait early.
|
|
///
|
|
/// # Errors
|
|
/// A message if it cannot be started, exits early, or does not answer
|
|
/// within [`START_TIMEOUT`].
|
|
pub fn start(desktop: &Path, dir: &Path) -> Result<Client, String> {
|
|
let mut child = lutra_proc::spawn_detached(desktop, &[])
|
|
.map_err(|e| format!("cannot start {}: {e}", desktop.display()))?;
|
|
let deadline = Instant::now() + START_TIMEOUT;
|
|
loop {
|
|
if let Ok((_, client)) = client::connect_live(dir, PROBE) {
|
|
return Ok(client);
|
|
}
|
|
if let Ok(Some(status)) = child.try_wait()
|
|
&& !status.success()
|
|
{
|
|
return Err(format!(
|
|
"{} exited before it was ready ({status})",
|
|
desktop.display()
|
|
));
|
|
}
|
|
if Instant::now() >= deadline {
|
|
return Err(format!(
|
|
"{} did not answer within {} s",
|
|
desktop.display(),
|
|
START_TIMEOUT.as_secs()
|
|
));
|
|
}
|
|
thread::sleep(POLL);
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn a_plain_file_stays_as_it_is() {
|
|
let tmp = tempfile::tempdir().unwrap();
|
|
let file = tmp.path().join("lutra");
|
|
std::fs::write(&file, "").unwrap();
|
|
assert_eq!(resolve_link(file.clone()), file);
|
|
let missing = tmp.path().join("missing");
|
|
assert_eq!(resolve_link(missing.clone()), missing);
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
#[test]
|
|
fn a_link_resolves_to_its_target() {
|
|
let tmp = tempfile::tempdir().unwrap();
|
|
let app = tmp.path().join("Lutra.app/Contents/MacOS");
|
|
std::fs::create_dir_all(&app).unwrap();
|
|
std::fs::write(app.join("lutra"), "").unwrap();
|
|
let link = tmp.path().join("lutra");
|
|
std::os::unix::fs::symlink(app.join("lutra"), &link).unwrap();
|
|
assert_eq!(
|
|
resolve_link(link),
|
|
std::fs::canonicalize(app.join("lutra")).unwrap()
|
|
);
|
|
}
|
|
}
|