use std::io;
use std::path::Path;
use std::time::Duration;
pub fn launch_browser(path: &Path) -> std::io::Result<()> {
#[cfg(target_os = "windows")]
{
opener::open(path).map_err(io::Error::other)?;
}
#[cfg(target_os = "macos")]
{
let status = std::process::Command::new("open").arg(path).status()?;
if !status.success() {
return Err(io::Error::other(format!("open exited with {status}")));
}
}
#[cfg(all(unix, not(target_os = "macos")))]
{
launch_via_xdg_open(path)?;
}
Ok(())
}
#[cfg(all(unix, not(target_os = "macos")))]
fn launch_via_xdg_open(path: &Path) -> std::io::Result<()> {
const OPENERS: &[(&str, &[&str])] = &[
("xdg-open", &[]),
("gio", &["open"]),
("gnome-open", &[]),
("kde-open5", &[]),
("kde-open", &[]),
("wslview", &[]),
];
const LAUNCH_FAILURE_WINDOW: Duration = Duration::from_secs(2);
let mut last_failure: Option<String> = None;
for (program, leading) in OPENERS {
let mut command = std::process::Command::new(program);
command.args(*leading).arg(path);
let Ok(mut child) = command.spawn() else {
continue; };
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let _ = tx.send(child.wait());
});
match rx.recv_timeout(LAUNCH_FAILURE_WINDOW) {
Ok(Ok(status)) if status.success() => return Ok(()),
Ok(Ok(status)) => {
last_failure = Some(format!("{program} exited with {status}"));
}
Ok(Err(e)) => {
last_failure = Some(format!("failed waiting on {program}: {e}"));
}
Err(_) => return Ok(()),
}
}
match last_failure {
Some(failure) => Err(io::Error::other(failure)),
None => Err(io::Error::new(
io::ErrorKind::NotFound,
"no desktop opener found (install xdg-utils)",
)),
}
}