Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Escape URLs on Windows #11

Merged
merged 4 commits into from
Dec 17, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,16 @@ matrix:
- cargo update
- cargo test --all --locked --verbose
- cargo doc --verbose
- rustup component add rustfmt-preview
- cargo fmt -- --write-mode=diff
- rustup component add clippy rustfmt
- cargo clippy --all-targets -- -D warnings
- cargo fmt --all -- --check

- rust: nightly
script:
- cargo update
- cargo test --locked
- rustup component add rustfmt-preview
- rustup component add clippy rustfmt
- cargo clippy --all-targets -- -D warnings
- cargo fmt --all -- --check

branches:
Expand Down
4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,7 @@ repository = "https://github.com/amodm/webbrowser-rs"
readme = "README.md"
keywords = ["webbrowser", "browser"]
license = "MIT OR Apache-2.0"
edition = "2015"

[dependencies]
[target.'cfg(windows)'.dependencies]
winapi = { version = "0.3.6", features = ["combaseapi", "objbase", "shellapi", "winerror"] }
76 changes: 64 additions & 12 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,37 @@
//!
//! # Examples
//!
//! ```
//! ```no_run
//! use webbrowser;
//!
//! if webbrowser::open("http://github.com").is_ok() {
//! // ...
//! }
//! ```

#[cfg(windows)]
extern crate widestring;
#[cfg(windows)]
extern crate winapi;

use std::default::Default;
use std::error;
use std::fmt;
use std::io::{Error, ErrorKind, Result};
use std::process::{Command, Output};
use std::process::Output;
use std::str::FromStr;
use std::{error, fmt};

#[cfg(windows)]
use std::os::windows::process::ExitStatusExt;
#[cfg(windows)]
use std::process::ExitStatus;
#[cfg(windows)]
use std::ptr;

#[cfg(not(windows))]
use std::process::Command;

#[cfg(windows)]
use widestring::U16CString;

#[derive(Debug, Eq, PartialEq, Copy, Clone, Hash)]
/// Browser types available
Expand Down Expand Up @@ -112,14 +129,14 @@ impl FromStr for Browser {
/// there was an error in running the command, or if the browser was not found.
///
/// Equivalent to:
/// ```
/// ```no_run
/// # use webbrowser::{Browser, open_browser};
/// # let url = "http://example.com";
/// open_browser(Browser::Default, url);
/// ```
///
/// # Examples
/// ```
/// ```no_run
/// use webbrowser;
///
/// if webbrowser::open("http://github.com").is_ok() {
Expand All @@ -134,7 +151,7 @@ pub fn open(url: &str) -> Result<Output> {
/// the same as for [open](fn.open.html).
///
/// # Examples
/// ```
/// ```no_run
/// use webbrowser::{open_browser, Browser};
///
/// if open_browser(Browser::Firefox, "http://github.com").is_ok() {
Expand All @@ -145,12 +162,46 @@ pub fn open_browser(browser: Browser, url: &str) -> Result<Output> {
open_browser_internal(browser, url)
}

/// Deal with opening of browsers on Windows, using `start` command
/// Deal with opening of browsers on Windows, using [`ShellExecuteW`](
/// https://docs.microsoft.com/en-us/windows/desktop/api/shellapi/nf-shellapi-shellexecutew)
/// fucntion.
#[cfg(target_os = "windows")]
#[inline]
fn open_browser_internal(browser: Browser, url: &str) -> Result<Output> {
use winapi::um::combaseapi::CoInitializeEx;
use winapi::um::objbase::{COINIT_APARTMENTTHREADED, COINIT_DISABLE_OLE1DDE};
use winapi::um::shellapi::ShellExecuteW;
use winapi::um::winuser::SW_SHOWNORMAL;

match browser {
Browser::Default => Command::new("cmd").arg("/C").arg("start").arg(url).output(),
Browser::Default => {
static OPEN: &[u16] = &['o' as u16, 'p' as u16, 'e' as u16, 'n' as u16, 0x0000];
let url =
U16CString::from_str(url).map_err(|e| Error::new(ErrorKind::InvalidInput, e))?;
let code = unsafe {
let _ = CoInitializeEx(
ptr::null_mut(),
COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE,
);
ShellExecuteW(
ptr::null_mut(),
OPEN.as_ptr(),
url.as_ptr(),
ptr::null(),
ptr::null(),
SW_SHOWNORMAL,
) as usize as i32
};
if code > 32 {
Ok(Output {
status: ExitStatus::from_raw(0),
stdout: vec![],
stderr: vec![],
})
} else {
Err(Error::last_os_error())
}
}
_ => Err(Error::new(
ErrorKind::NotFound,
"Only the default browser is supported on this platform right now",
Expand Down Expand Up @@ -209,7 +260,7 @@ fn open_browser_internal(browser: Browser, url: &str) -> Result<Output> {
#[cfg(target_os = "linux")]
fn open_on_linux_using_browser_env(url: &str) -> Result<Output> {
let browsers = ::std::env::var("BROWSER")
.map_err(|_| -> Error { Error::new(ErrorKind::NotFound, format!("BROWSER env not set")) })?;
.map_err(|_| -> Error { Error::new(ErrorKind::NotFound, "BROWSER env not set") })?;
for browser in browsers.split(':') {
// $BROWSER can contain ':' delimited options, each representing a potential browser command line
if !browser.is_empty() {
Expand All @@ -233,10 +284,10 @@ fn open_on_linux_using_browser_env(url: &str) -> Result<Output> {
}
}
}
return Err(Error::new(
Err(Error::new(
ErrorKind::NotFound,
"No valid command in $BROWSER",
));
))
}

#[cfg(not(any(target_os = "windows", target_os = "macos", target_os = "linux")))]
Expand All @@ -245,6 +296,7 @@ compile_error!("Only Windows, Mac OS and Linux are currently supported");
#[test]
fn test_open_default() {
assert!(open("http://github.com").is_ok());
assert!(open("http://github.com?dummy_query1=0&dummy_query2=nonascii").is_ok());
}

#[test]
Expand Down