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