[go: up one dir, main page]

sdl2/
url.rs

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