use std::{
ffi::OsStr,
io,
process::{ExitStatus, Stdio},
time::Duration,
};
#[cfg(target_os = "macos")]
const OPENER: &str = "open";
#[cfg(not(target_os = "macos"))]
const OPENER: &str = "xdg-open";
pub(crate) async fn open_desktop(
target: &OsStr,
deadline: Duration,
cancellation: &tokio_util::sync::CancellationToken,
) -> io::Result<()> {
let cwd = std::env::current_dir()?;
let program = crate::program::resolve(std::path::Path::new(OPENER), &cwd)?;
let mut command = tokio::process::Command::new(program);
command
.arg(target)
.env_clear()
.envs(crate::environment::user())
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
let status = crate::platform::process::handoff(&mut command, deadline, cancellation).await?;
if !opened(&status, is_wsl()) {
return Err(io::Error::other(format!(
"Desktop opener exited with {status}."
)));
}
Ok(())
}
const WSL_EXPLORER_STATUS: i32 = 4;
fn opened(status: &ExitStatus, wsl: bool) -> bool {
status.success() || (wsl && status.code() == Some(WSL_EXPLORER_STATUS))
}
fn is_wsl() -> bool {
cfg!(target_os = "linux")
&& std::fs::read_to_string("/proc/version")
.is_ok_and(|version| version.contains("microsoft"))
}
#[cfg(test)]
mod tests;