ailloli_ui_winit/
external_url.rs

1//! Platform browser handoff for already validated HTTP(S) URLs.
2//!
3//! Unix-like systems spawn an opaque single argument without a shell; Windows
4//! calls `ShellExecuteW`. Success means launch was accepted, not that navigation
5//! completed. Unsupported targets return `Unavailable`.
6
7use ailloli_ui_runtime::app::{ExternalUrl, ExternalUrlOpener, OpenUrlError};
8
9/// Native, non-blocking external URL opener used by [`crate::UiApp`].
10///
11/// # Examples
12///
13/// ```
14/// use ailloli_ui_winit::SystemExternalUrlOpener;
15/// let opener = SystemExternalUrlOpener::new();
16/// assert_eq!(format!("{opener:?}"), "SystemExternalUrlOpener");
17/// ```
18#[derive(Clone, Copy, Debug, Default)]
19pub struct SystemExternalUrlOpener;
20
21/// Zero-state construction.
22impl SystemExternalUrlOpener {
23    /// Creates a stateless platform opener without launching a process.
24    ///
25    /// # Examples
26    ///
27    /// ```
28    /// use ailloli_ui_winit::SystemExternalUrlOpener;
29    /// let _: SystemExternalUrlOpener = SystemExternalUrlOpener::new();
30    /// ```
31    pub const fn new() -> Self {
32        Self
33    }
34}
35
36/// Delegates validated URLs to the platform-specific nonblocking launch path.
37impl ExternalUrlOpener for SystemExternalUrlOpener {
38    /// Delegates a validated URL to the platform opener implementation.
39    ///
40    /// # Errors
41    ///
42    /// Returns [`OpenUrlError::LaunchFailed`] when the native handoff is rejected,
43    /// or [`OpenUrlError::Unavailable`] on unsupported targets.
44    fn open(&self, url: &ExternalUrl) -> Result<(), OpenUrlError> {
45        open_system_url(url)
46    }
47}
48
49#[cfg(any(
50    target_os = "linux",
51    target_os = "freebsd",
52    target_os = "openbsd",
53    target_os = "netbsd",
54    target_os = "dragonfly"
55))]
56/// Launches `xdg-open` on Linux and supported BSD targets.
57///
58/// # Errors
59///
60/// Returns [`OpenUrlError::LaunchFailed`] when `xdg-open` cannot be spawned.
61fn open_system_url(url: &ExternalUrl) -> Result<(), OpenUrlError> {
62    spawn_opener("xdg-open", url)
63}
64
65#[cfg(target_os = "macos")]
66/// Launches the absolute macOS `/usr/bin/open` utility.
67///
68/// # Errors
69///
70/// Returns [`OpenUrlError::LaunchFailed`] when `/usr/bin/open` cannot be spawned.
71fn open_system_url(url: &ExternalUrl) -> Result<(), OpenUrlError> {
72    spawn_opener("/usr/bin/open", url)
73}
74
75#[cfg(any(
76    target_os = "linux",
77    target_os = "freebsd",
78    target_os = "openbsd",
79    target_os = "netbsd",
80    target_os = "dragonfly",
81    target_os = "macos"
82))]
83/// Spawns `program` with the URL as one opaque argument and does not wait.
84///
85/// # Errors
86///
87/// Returns [`OpenUrlError::LaunchFailed`] when process creation fails.
88fn spawn_opener(program: &str, url: &ExternalUrl) -> Result<(), OpenUrlError> {
89    std::process::Command::new(program)
90        .arg(url.as_str())
91        .spawn()
92        .map(|_| ())
93        .map_err(|_| OpenUrlError::LaunchFailed)
94}
95
96#[cfg(windows)]
97/// Passes a NUL-terminated UTF-16 URL to `ShellExecuteW` with operation `open`.
98///
99/// # Errors
100///
101/// Returns [`OpenUrlError::LaunchFailed`] when `ShellExecuteW` returns a value
102/// less than or equal to 32.
103fn open_system_url(url: &ExternalUrl) -> Result<(), OpenUrlError> {
104    use std::iter;
105    use std::ptr;
106    use windows_sys::Win32::UI::Shell::ShellExecuteW;
107    use windows_sys::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL;
108
109    let operation = "open"
110        .encode_utf16()
111        .chain(iter::once(0))
112        .collect::<Vec<_>>();
113    let target = url
114        .as_str()
115        .encode_utf16()
116        .chain(iter::once(0))
117        .collect::<Vec<_>>();
118    let result = unsafe {
119        ShellExecuteW(
120            ptr::null_mut(),
121            operation.as_ptr(),
122            target.as_ptr(),
123            ptr::null(),
124            ptr::null(),
125            SW_SHOWNORMAL,
126        )
127    };
128    if shell_execute_succeeded(result as isize) {
129        Ok(())
130    } else {
131        Err(OpenUrlError::LaunchFailed)
132    }
133}
134
135#[cfg(windows)]
136/// Applies the Win32 contract: values strictly greater than 32 mean success.
137fn shell_execute_succeeded(result: isize) -> bool {
138    result > 32
139}
140
141#[cfg(not(any(
142    target_os = "linux",
143    target_os = "freebsd",
144    target_os = "openbsd",
145    target_os = "netbsd",
146    target_os = "dragonfly",
147    target_os = "macos",
148    windows
149)))]
150/// Reports platform unavailability without side effects.
151///
152/// # Errors
153///
154/// Always returns [`OpenUrlError::Unavailable`] on unsupported targets.
155fn open_system_url(_url: &ExternalUrl) -> Result<(), OpenUrlError> {
156    Err(OpenUrlError::Unavailable)
157}
158
159#[cfg(test)]
160/// Command construction, Windows return-code, and opt-in real-launch scenarios.
161mod tests {
162    use super::*;
163
164    #[cfg(any(
165        target_os = "linux",
166        target_os = "freebsd",
167        target_os = "openbsd",
168        target_os = "netbsd",
169        target_os = "dragonfly"
170    ))]
171    #[test]
172    fn unix_plan_uses_xdg_open_with_an_opaque_argument() {
173        let url = ExternalUrl::parse("https://example.com/?q=a;b&x=$(ignored)").unwrap();
174        let mut command = std::process::Command::new("xdg-open");
175        command.arg(url.as_str());
176        assert_eq!(command.get_program(), "xdg-open");
177        assert_eq!(
178            command.get_args().collect::<Vec<_>>(),
179            [std::ffi::OsStr::new(url.as_str())]
180        );
181    }
182
183    #[cfg(windows)]
184    #[test]
185    fn shell_execute_success_contract_is_strictly_greater_than_32() {
186        assert!(!shell_execute_succeeded(32));
187        assert!(shell_execute_succeeded(33));
188    }
189
190    #[test]
191    #[ignore = "opens the configured browser; set AILLOLI_UI_OPEN_URL_REAL=1"]
192    fn native_external_url_smoke() {
193        if std::env::var("AILLOLI_UI_OPEN_URL_REAL").as_deref() != Ok("1") {
194            eprintln!("skipped: set AILLOLI_UI_OPEN_URL_REAL=1 to open a real browser");
195            return;
196        }
197        SystemExternalUrlOpener::new()
198            .open(&ExternalUrl::parse("https://example.com").unwrap())
199            .unwrap();
200    }
201}