Skip to main content

mdo_cli/
launch.rs

1//! Launch: browser openers. Non-blocking, fire-and-forget platform
2//! openers plus the xdg-open/gio fallback chain.
3
4use std::io;
5use std::path::Path;
6use std::time::Duration;
7/// Launch the platform's default handler for `path` (typically a web browser
8/// for `.html`). Non-blocking — the spawned process runs independently.
9pub fn launch_browser(path: &Path) -> std::io::Result<()> {
10    #[cfg(target_os = "windows")]
11    {
12        // SECURITY: open via the Win32 ShellExecuteW API (through the `opener`
13        // crate) rather than `cmd /C start`. `start` runs the path through
14        // cmd.exe's command-line parser, so cmd metacharacters (`&`, `^`, …) —
15        // which are legal in Windows filenames and reach us via the input
16        // file's stem in temp_output_for — would be interpreted as commands
17        // (e.g. opening `a&calc&.md` would launch calc.exe). ShellExecuteW
18        // takes the path as a single typed argument, so those characters stay
19        // inert. It is non-blocking, preserving the fire-and-forget behavior.
20        opener::open(path).map_err(io::Error::other)?;
21    }
22    #[cfg(target_os = "macos")]
23    {
24        // `open` returns promptly once Launch Services accepts the request,
25        // so waiting for it doesn't block on the browser itself — and a
26        // nonzero exit (no handler for the file) must surface as a launch
27        // failure rather than being discarded with the child handle.
28        let status = std::process::Command::new("open").arg(path).status()?;
29        if !status.success() {
30            return Err(io::Error::other(format!("open exited with {status}")));
31        }
32    }
33    #[cfg(all(unix, not(target_os = "macos")))]
34    {
35        launch_via_xdg_open(path)?;
36    }
37    Ok(())
38}
39
40/// Open `path` with the first available freedesktop opener. Falls back through
41/// common launchers when `xdg-open` (xdg-utils) is not installed, and reaps the
42/// launcher process in a detached thread so it does not linger as a zombie
43/// during long `--watch` sessions.
44///
45/// Spawning an opener is not the same as launching a browser: `xdg-open` can
46/// exist, start, and then exit nonzero because no browser handler is
47/// configured. We therefore listen for each opener's exit for a short window
48/// — a quick nonzero exit is an honest failure (and we fall through to the
49/// next opener), while an opener still running after the window has almost
50/// certainly handed off (or, in xdg-open's no-desktop fallback, IS the
51/// browser), so we detach and call it success. We never block on the browser
52/// itself beyond that window.
53#[cfg(all(unix, not(target_os = "macos")))]
54fn launch_via_xdg_open(path: &Path) -> std::io::Result<()> {
55    const OPENERS: &[(&str, &[&str])] = &[
56        ("xdg-open", &[]),
57        ("gio", &["open"]),
58        ("gnome-open", &[]),
59        ("kde-open5", &[]),
60        ("kde-open", &[]),
61        ("wslview", &[]),
62    ];
63    const LAUNCH_FAILURE_WINDOW: Duration = Duration::from_secs(2);
64
65    let mut last_failure: Option<String> = None;
66    for (program, leading) in OPENERS {
67        let mut command = std::process::Command::new(program);
68        command.args(*leading).arg(path);
69        let Ok(mut child) = command.spawn() else {
70            continue; // not installed; try the next opener
71        };
72
73        // The waiting thread doubles as the reaper for the detached-success
74        // case: it always waits the child to completion, we just stop
75        // listening for the result after the failure window.
76        let (tx, rx) = std::sync::mpsc::channel();
77        std::thread::spawn(move || {
78            let _ = tx.send(child.wait());
79        });
80
81        match rx.recv_timeout(LAUNCH_FAILURE_WINDOW) {
82            Ok(Ok(status)) if status.success() => return Ok(()),
83            Ok(Ok(status)) => {
84                last_failure = Some(format!("{program} exited with {status}"));
85            }
86            Ok(Err(e)) => {
87                last_failure = Some(format!("failed waiting on {program}: {e}"));
88            }
89            // Still running after the window: it handed off to (or is) the
90            // browser. The waiting thread reaps it eventually.
91            Err(_) => return Ok(()),
92        }
93    }
94
95    match last_failure {
96        Some(failure) => Err(io::Error::other(failure)),
97        None => Err(io::Error::new(
98            io::ErrorKind::NotFound,
99            "no desktop opener found (install xdg-utils)",
100        )),
101    }
102}