//! Finding and starting the desktop app when no Lutra is running. use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; 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`. /// /// # Errors /// A message naming the places that were tried. pub fn find_desktop() -> Result { 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() .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" ) }) } /// Starts `desktop` detached from this terminal (Windows: a detached process /// in a new process group; 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 { let mut command = Command::new(desktop); command .stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(Stdio::null()); #[cfg(windows)] { use std::os::windows::process::CommandExt; const DETACHED_PROCESS: u32 = 0x0000_0008; const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200; command.creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP); } #[cfg(unix)] { use std::os::unix::process::CommandExt; command.process_group(0); } let mut child = command .spawn() .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); } }