sdl3/
url.rs

1//! Opening URLs in default system handlers
2
3use crate::get_error;
4use crate::Error;
5use std::error;
6use std::ffi::{CString, NulError};
7use std::fmt;
8use sys::misc::SDL_OpenURL;
9
10#[derive(Debug, Clone)]
11pub enum OpenUrlError {
12    InvalidUrl(NulError),
13    SdlError(Error),
14}
15
16impl fmt::Display for OpenUrlError {
17    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
18        use self::OpenUrlError::*;
19
20        match *self {
21            InvalidUrl(ref e) => write!(f, "Invalid URL: {}", e),
22            SdlError(ref e) => write!(f, "SDL error: {}", e),
23        }
24    }
25}
26
27impl error::Error for OpenUrlError {
28    fn description(&self) -> &str {
29        use self::OpenUrlError::*;
30
31        match *self {
32            InvalidUrl(_) => "invalid URL",
33            SdlError(ref e) => &e.0,
34        }
35    }
36}
37
38/// Opens a URL/URI in the default system-provided application.
39///
40/// This will most likely open a web browser for http:// and https:// links,
41/// the default handler application for file:// links, but this varies
42/// between platforms and is not supported on all of them.
43/// It might also cause your window to lose focus, or pause your process on mobile.
44///
45/// There is no way to tell if the system successfully opened the provided URL,
46/// an `Ok` result only means that something was launched to try to handle it.
47///
48/// # Examples
49///
50/// ```no_run
51/// use sdl3::url::open_url;
52///
53/// open_url("https://github.com/revmischa/sdl3-rs")
54///   .expect("Opening URLs not supported on this platform");
55/// ```
56#[doc(alias = "SDL_OpenURL")]
57pub fn open_url(url: &str) -> Result<(), OpenUrlError> {
58    use self::OpenUrlError::*;
59    let result = unsafe {
60        let url = match CString::new(url) {
61            Ok(s) => s,
62            Err(err) => return Err(InvalidUrl(err)),
63        };
64        SDL_OpenURL(url.as_ptr())
65    };
66
67    if result {
68        Ok(())
69    } else {
70        Err(SdlError(get_error()))
71    }
72}