### Open Browser in WSL Source: https://docs.rs/webbrowser/latest/src/webbrowser/unix.rs.html Attempts to open a URL in a WSL environment using various Windows commands like 'cmd.exe start', 'powershell.exe Start', or 'wsl-open'. It handles URL encoding for special characters. ```rust fn try_wsl(options: &BrowserOptions, target: &TargetType) -> Result<()> { match target.0.scheme() { "http" | "https" => { let url: &str = target; try_browser!( options, "cmd.exe", "/c", "start", url.replace('^', "^^^^").replace('&', "^&") ) .or_else(|_| { try_browser!( options, "powershell.exe", "Start", url.replace('&', "\"&\"") ) }) .or_else(|_| try_browser!(options, "wsl-open", url)) } #[cfg(all( target_os = "linux", not(feature = "hardened"), not(feature = "disable-wsl") ))] "file" => { // we'll need to detect the default browser and then invoke it // with wsl translated path let wc = wsl::get_wsl_win_config()?; let mut cmd = if wc.powershell_path.is_some() { wsl::get_wsl_windows_browser_ps(&wc, target) } else { wsl::get_wsl_windows_browser_cmd(&wc, target) } ?; run_command(&mut cmd, true, options) } _ => Err(Error::new(ErrorKind::NotFound, "invalid browser")), } } ``` -------------------------------- ### Check if any browser is available Source: https://docs.rs/webbrowser/latest/webbrowser/enum.Browser.html Returns true if the system likely has a browser installed. This is a general check before attempting to open a specific browser. ```rust pub fn is_available() -> bool ``` -------------------------------- ### Get WSL Windows Configuration in Rust Source: https://docs.rs/webbrowser/latest/src/webbrowser/unix.rs.html Retrieves the Windows configuration for WSL by iterating over PATH entries to find system32 and powershell.exe. This is crucial for interacting with Windows from WSL. ```rust let err_fn = || Error::new(ErrorKind::NotFound, "invalid windows config"); if let Some(path_env) = std::env::var_os("PATH") { let mut root: Option = None; let mut cmd_path: Option = None; let mut powershell_path: Option = None; for path in std::env::split_paths(&path_env) { let path_s = path.to_string_lossy().to_ascii_lowercase(); let path_s = path_s.trim_end_matches('/'); if path_s.ends_with("/windows/system32") { root = Some(std::fs::canonicalize(path.join("../.."))?); cmd_path = Some(path.join("cmd.exe")); break; } } if let Some(ref root) = root { for path in std::env::split_paths(&path_env) { if path.starts_with(root) { let pb = path.join("powershell.exe"); if pb.is_file() { powershell_path = Some(pb); } } } } if let Some(root) = root { let cmd_path = cmd_path.unwrap_or_else(|| (root).join("windows/system32/cmd.exe")); Ok(WindowsConfig { root, cmd_path, powershell_path, }) } else { Err(err_fn()) } } else { Err(err_fn()) } ``` -------------------------------- ### Get WSL Windows Browser Command in Rust Source: https://docs.rs/webbrowser/latest/src/webbrowser/unix.rs.html Attempts to construct a command to open a URL in the default Windows browser from WSL using PowerShell. This is part of the WSL-specific browser functionality. ```rust let err_fn = || Error::new(ErrorKind::NotFound, "powershell.exe error"); ``` -------------------------------- ### TargetType struct and its methods Source: https://docs.rs/webbrowser/latest/src/webbrowser/lib.rs.html Internal struct representing a URL, handling conversion from file paths and URL parsing. Includes methods for checking HTTP schemes and getting HTTP URLs. ```rust /// The link we're trying to open, represented as a URL. Local files get represented /// via `file://...` URLs struct TargetType(url::Url); impl TargetType { /// Returns true if this target represents an HTTP url, false otherwise #[cfg(any( feature = "hardened", target_os = "android", target_os = "ios", target_os = "tvos", target_os = "visionos", target_family = "wasm" ))] fn is_http(&self) -> bool { matches!(self.0.scheme(), "http" | "https") } /// If `target` represents a valid http/https url, return the str corresponding to it /// else return `std::io::Error` of kind `std::io::ErrorKind::InvalidInput` #[cfg(any( target_os = "android", target_os = "ios", target_os = "tvos", target_os = "visionos", target_family = "wasm" ))] fn get_http_url(&self) -> Result<&str> { if self.is_http() { Ok(self.0.as_str()) } else { Err(Error::new(ErrorKind::InvalidInput, "not an http url")) } } #[cfg(not(target_family = "wasm"))] fn from_file_path(value: &str) -> Result { let pb = std::path::PathBuf::from(value); let url = url::Url::from_file_path(if pb.is_relative() { std::env::current_dir()?.join(pb) } else { pb }) .map_err(|_| Error::new(ErrorKind::InvalidInput, "failed to convert path to url"))?; Ok(Self(url)) } } ``` -------------------------------- ### Determine Default XDG Browser Source: https://docs.rs/webbrowser/latest/src/webbrowser/unix.rs.html This function identifies the default web browser configured in XDG settings. It executes `xdg-settings get default-web-browser` and parses the output. Requires the `xdg-settings` command to be available. ```rust let browser_name_os = for_matching_path("xdg-settings", |pb| { Command::new(pb) .args(["get", "default-web-browser"]) .stdin(Stdio::null()) .stderr(Stdio::null()) .output() }) .map_err(|_| Error::new(ErrorKind::NotFound, "unable to determine xdg browser"))? .stdout; // convert browser name to a utf-8 string and trim off the trailing newline let browser_name = String::from_utf8(browser_name_os) .map_err(|_| Error::new(ErrorKind::NotFound, "invalid default browser name"))? .trim() .to_owned(); if browser_name.is_empty() { return Err(Error::new(ErrorKind::NotFound, "no default xdg browser")); } trace!("found xdg browser: {:?}", &browser_name); ``` -------------------------------- ### Check if a specific browser is available Source: https://docs.rs/webbrowser/latest/src/webbrowser/lib.rs.html This method checks if a particular browser (e.g., Firefox, Chrome) is installed and accessible on the system. It uses a dry-run option to test availability without actually opening a URL. ```rust pub fn exists(&self) -> bool { open_browser_with_options( *self, "https://rootnet.in", BrowserOptions::new().with_dry_run(true), ) .is_ok() } ``` -------------------------------- ### Get Type ID of a Type Source: https://docs.rs/webbrowser/latest/webbrowser/enum.Browser.html Gets the `TypeId` of a given type. This is a blanket implementation for any type that is 'static. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Create New BrowserOptions Instance Source: https://docs.rs/webbrowser/latest/src/webbrowser/lib.rs.html Creates a new `BrowserOptions` instance using the default configuration. Further customization can be done using `with_` methods. ```rust pub fn new() -> Self { Self::default() } ``` -------------------------------- ### Open Default Browser (Unix) Source: https://docs.rs/webbrowser/latest/src/webbrowser/unix.rs.html Opens the default web browser on Unix-like systems. It attempts to use the $BROWSER environment variable, then falls back to desktop-specific commands (xdg-open, gnome-open, kde-open, etc.), and finally tries 'x-www-browser'. Errors are mapped to 'NotFound' if no browser can be launched. ```rust pub(super) fn open_browser_internal( browser: Browser, target: &TargetType, options: &BrowserOptions, ) -> Result<()> { match browser { Browser::Default => open_browser_default(target, options), _ => Err(Error::new( ErrorKind::NotFound, "only default browser supported", )), } } ``` ```rust fn open_browser_default(target: &TargetType, options: &BrowserOptions) -> Result<()> { let url: &str = target; // we first try with the $BROWSER env try_with_browser_env(url, options) // allow for haiku's open specifically .or_else(|_| try_haiku(options, url)) // then we try with xdg configuration .or_else(|_| try_xdg(options, url)) // else do desktop specific stuff .or_else(|r| match guess_desktop_env() { "kde" => try_browser!(options, "kde-open", url) .or_else(|_| try_browser!(options, "kde-open5", url)) .or_else(|_| try_browser!(options, "kfmclient", "newTab", url)), "gnome" => try_browser!(options, "gio", "open", url) .or_else(|_| try_browser!(options, "gvfs-open", url)) .or_else(|_| try_browser!(options, "gnome-open", url)), "mate" => try_browser!(options, "gio", "open", url) .or_else(|_| try_browser!(options, "gvfs-open", url)) .or_else(|_| try_browser!(options, "mate-open", url)), "xfce" => try_browser!(options, "exo-open", url) .or_else(|_| try_browser!(options, "gio", "open", url)) .or_else(|_| try_browser!(options, "gvfs-open", url)), "wsl" => try_wsl(options, target), "flatpak" => try_flatpak(options, target), _ => Err(r), }) // at the end, we'll try x-www-browser and return the result as is .or_else(|_| try_browser!(options, "x-www-browser", url)) // if all above failed, map error to not found .map_err(|_| { Error::new( ErrorKind::NotFound, "No valid browsers detected. You can specify one in BROWSER environment variable", ) }) // and convert a successful result into a () .map(|_| ()) ``` -------------------------------- ### Webbrowser Crate - Basic Usage Source: https://docs.rs/webbrowser/latest/index.html Demonstrates the basic usage of the webbrowser crate to open a URL in the default browser. ```APIDOC ## open ### Description Opens the URL on the default browser of this platform. ### Method ``` use webbrowser; if webbrowser::open("http://github.com").is_ok() { // URL opened successfully } ``` ### Endpoint N/A (This is a library function, not an HTTP endpoint) ### Parameters None for the `open` function itself, but it takes a URL string as an argument. ### Request Example ```rust webbrowser::open("http://example.com"); ``` ### Response Returns `Result<(), Error>` indicating success or failure. ``` -------------------------------- ### Get WSL Distro Name in Rust Source: https://docs.rs/webbrowser/latest/src/webbrowser/unix.rs.html Retrieves the WSL distribution name from the WSL_DISTRO_NAME environment variable or by invoking PowerShell to inspect the current location. ```rust fn get_wsl_distro_name(wc: &WindowsConfig) -> Result { let err_fn = || Error::other("unable to determine wsl distro name"); // mostly we should be able to get it from the WSL_DISTRO_NAME env var if let Ok(wsl_hostname) = std::env::var("WSL_DISTRO_NAME") { Ok(wsl_hostname) } else { // but if not (e.g. if we were running as root), we can invoke // powershell.exe to determine pwd and from there infer the distro name let psexe = wc.powershell_path.as_ref().ok_or_else(err_fn)?; let mut cmd = Command::new(psexe); cmd.arg("-NoLogo") .arg("-NoProfile") .arg("-NonInteractive") .arg("-Command") .arg("$loc = Get-Location\nWrite-Output $loc.Path") .current_dir("/") .stdin(Stdio::null()) .stderr(Stdio::null()); log::debug!("running command: ${:?}", &cmd); let output_u8 = cmd.output()?.stdout; let output = String::from_utf8_lossy(&output_u8); let output = output.trim_end_matches('\\'); let idx = output.find("::\\").ok_or_else(err_fn)?; Ok((output[idx + 9..]).trim().to_string()) } } ``` -------------------------------- ### Try Opening URL on Haiku OS Source: https://docs.rs/webbrowser/latest/src/webbrowser/unix.rs.html This function attempts to open a URL using the default browser on Haiku OS. It checks the target operating system and uses a helper function `try_browser!` for the actual opening. Returns an error if not on Haiku. ```rust fn try_haiku(options: &BrowserOptions, url: &str) -> Result<()> { if cfg!(target_os = "haiku") { try_browser!(options, "open", url).map(|_| ()) } else { Err(Error::new(ErrorKind::NotFound, "Not on haiku")) } } ``` -------------------------------- ### Open URL with Custom Browser Options Source: https://docs.rs/webbrowser/latest/src/webbrowser/lib.rs.html Opens a URL in a specified browser with custom options, such as suppressing output. This provides more control over the browser launch. Returns a Result. ```rust /// Opens the specified URL on the specific browser (if available) requested, while overriding the /// default options. /// /// Return semantics are /// the same as for [open](fn.open.html). /// /// # Examples /// ```no_run /// use webbrowser::{open_browser_with_options, Browser, BrowserOptions}; /// /// if open_browser_with_options(Browser::Default, "http://github.com", BrowserOptions::new().with_suppress_output(false)).is_ok() { /// // ... /// } /// ``` pub fn open_browser_with_options( browser: Browser, url: &str, options: &BrowserOptions, ) -> Result<()> { let target = TargetType::try_from(url)?; // if feature:hardened is enabled, make sure we accept only HTTP(S) URLs #[cfg(feature = "hardened")] if !target.is_http() { return Err(Error::new( ErrorKind::InvalidInput, "only http/https urls allowed", )); } if cfg!(any( target_os = "ios", target_os = "tvos", target_os = "visionos", target_os = "macos", target_os = "android", target_family = "wasm", windows, unix, )) { os::open_browser_internal(browser, &target, options) } else { Err(Error::new(ErrorKind::NotFound, "unsupported platform")) } } ``` -------------------------------- ### BrowserOptions Configuration Source: https://docs.rs/webbrowser/latest/webbrowser/struct.BrowserOptions.html Methods for configuring the BrowserOptions instance to control how the browser is launched. ```APIDOC ## BrowserOptions Configuration ### Description Methods to configure the behavior of the browser execution. ### Methods - **new()** -> Self: Creates a new instance of BrowserOptions. - **with_suppress_output(suppress_output: bool)** -> &mut Self: Determines whether stdout/stderr of the browser command is suppressed. - **with_target_hint(target_hint: &str)** -> &mut Self: Provides a hint to the browser to open the URL in a specific target. - **with_dry_run(dry_run: bool)** -> &mut Self: If true, performs a dry run without actual execution, returning true if it would likely succeed. ``` -------------------------------- ### Open URL in Default Browser Source: https://docs.rs/webbrowser/latest/webbrowser/index.html Demonstrates how to open a URL in the default web browser of the platform. It returns a Result, indicating success or failure. ```APIDOC ## POST /api/users ### Description Opens the URL on the default browser of this platform. ### Method POST ### Endpoint /open ### Parameters #### Query Parameters - **url** (string) - Required - The URL to open. ### Request Example ```json { "url": "http://github.com" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates if the operation was successful. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Configure Target Hint for BrowserOptions Source: https://docs.rs/webbrowser/latest/src/webbrowser/lib.rs.html Sets a hint for the browser to open the URL in a specific target frame or window. This is a hint and may not always be honored, especially outside of WASM environments. ```rust pub fn with_target_hint(&mut self, target_hint: &str) -> &mut Self { self.target_hint = target_hint.to_owned(); self } ``` -------------------------------- ### Create XDG Desktop Entry File in Rust Source: https://docs.rs/webbrowser/latest/src/webbrowser/unix.rs.html Creates an XDG desktop entry file used to configure how applications are launched. It includes an Exec line that specifies the command to run, potentially with arguments. ```rust let config_path = get_temp_path("test_xdg", "desktop"); { let mut xdg_file = std::fs::File::create(&config_path).expect("failed to create xdg desktop file"); let _ = xdg_file.write_fmt(format_args!( r#"# this line should be ignored [Desktop Entry] Exec={} p1 %u p3 [Another Entry] Exec=/bin/ls # the above Exec line should be getting ignored "#, &browser_path )); } ``` -------------------------------- ### Open Firefox Browser Source: https://docs.rs/webbrowser/latest/src/webbrowser/lib.rs.html Tests opening the Firefox browser to a given URL. Asserts that the operation is successful. ```rust fn test_open_firefox() { assert!(open_browser(Browser::Firefox, "http://github.com").is_ok()); } ``` -------------------------------- ### Execute PowerShell for Browser Command Source: https://docs.rs/webbrowser/latest/src/webbrowser/unix.rs.html Spawns a PowerShell process to execute a script and retrieve the browser command line. ```rust let ps_exe = wc.powershell_path.as_ref().ok_or_else(err_fn)?; let mut cmd = Command::new(ps_exe); cmd.arg("-NoLogo") .arg("-NoProfile") .arg("-NonInteractive") .arg("-Command") .arg("-") .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::null()); log::debug!("running command: ${:?}", &cmd); let mut child = cmd.spawn()?; let mut stdin = child.stdin.take().ok_or_else(err_fn)?; std::io::Write::write_all(&mut stdin, WSL_PS_SCRIPT.as_bytes())?; drop(stdin); // flush to stdin, and close let output_u8 = child.wait_with_output()?; let output = String::from_utf8_lossy(&output_u8.stdout); let output = output.trim(); if output.is_empty() { Err(err_fn()) } else { parse_wsl_cmdline(wc, output, url) } } ``` -------------------------------- ### Define Text Browser List Source: https://docs.rs/webbrowser/latest/src/webbrowser/unix.rs.html Static array containing names of supported text-based web browsers. ```rust static TEXT_BROWSERS: [&str; 9] = [ "lynx", "links", "links2", "elinks", "w3m", "eww", "netrik", "retawq", "curl", ]; ``` -------------------------------- ### Open URL with Specific Browser and Options Source: https://docs.rs/webbrowser/latest/webbrowser/fn.open_browser_with_options.html Use this function to open a URL in the default browser while suppressing output. Ensure the operation is successful. ```rust use webbrowser::{open_browser_with_options, Browser, BrowserOptions}; if open_browser_with_options(Browser::Default, "http://github.com", BrowserOptions::new().with_suppress_output(false)).is_ok() { // ... } ``` -------------------------------- ### Find and Open URL using XDG Config Source: https://docs.rs/webbrowser/latest/src/webbrowser/unix.rs.html This function searches for the browser's XDG configuration file and attempts to open a URL using it. It handles variations in configuration paths, including replacing hyphens with slashes. If a config is found but opening fails with a non-NotFound error, it short-circuits. ```rust let mut config_found = false; let app_suffix = "applications"; for xdg_dir in get_xdg_dirs().iter_mut() { let mut config_path = xdg_dir.join(app_suffix).join(&browser_name); trace!("checking for xdg config at {config_path:?}"); let mut metadata = config_path.metadata(); if metadata.is_err() && browser_name.contains('-') { // as per the spec, we need to replace '-' with '/' let child_path = browser_name.replace('-', "/"); config_path = xdg_dir.join(app_suffix).join(child_path); metadata = config_path.metadata(); } if metadata.is_ok() { // we've found the config file, so we try running using that config_found = true; match open_using_xdg_config(&config_path, options, url) { Ok(x) => return Ok(x), // return if successful Err(err) => { // if we got an error other than NotFound, then we short // circuit, and do not try any more options, else we // continue to try more if err.kind() != ErrorKind::NotFound { return Err(err); } } } } } if config_found { Err(Error::other("xdg-open failed")) } else { Err(Error::new(ErrorKind::NotFound, "no valid xdg config found")) } ``` -------------------------------- ### Generic Command Execution Macro Source: https://docs.rs/webbrowser/latest/src/webbrowser/unix.rs.html A macro for simplifying the execution of browser commands. It takes browser options, the browser name, and arguments, then finds the executable path and runs it using `run_command`. This is used internally by various browser opening functions. ```rust macro_rules! try_browser { ( $options: expr, $name:expr, $( $arg:expr ),+ ) => { for_matching_path($name, |pb| { let mut cmd = Command::new(pb); $( cmd.arg($arg); )+ run_command(&mut cmd, !is_text_browser(&pb), $options) }) } } ``` -------------------------------- ### Webbrowser Crate - Advanced Usage Source: https://docs.rs/webbrowser/latest/index.html Details on opening specific browsers and overriding default options. ```APIDOC ## open_browser ### Description Opens the specified URL on the specific browser (if available) requested. Return semantics are the same as for `open`. ### Method ```rust use webbrowser::{Browser, BrowserOptions}; // Example: Open a URL in a specific browser (if available) if webbrowser::open_browser(Browser::Firefox, "http://example.com").is_ok() { // Firefox opened successfully } ``` ### Endpoint N/A (This is a library function, not an HTTP endpoint) ### Parameters - **browser** (Browser) - Required - The specific browser to open the URL with. - **url** (string) - Required - The URL to open. ### Request Example ```rust use webbrowser::Browser; webbrowser::open_browser(Browser::Chrome, "https://www.rust-lang.org"); ``` ### Response Returns `Result<(), Error>` indicating success or failure. ## open_browser_with_options ### Description Opens the specified URL on the specific browser (if available) requested, while overriding the default options. ### Method ```rust use webbrowser::{Browser, BrowserOptions}; let options = BrowserOptions::new(); // Create default options // Customize options if needed, e.g., options.with_hint("some_hint"); if webbrowser::open_browser_with_options(Browser::Edge, "http://example.com", &options).is_ok() { // Edge opened successfully with custom options } ``` ### Endpoint N/A (This is a library function, not an HTTP endpoint) ### Parameters - **browser** (Browser) - Required - The specific browser to open the URL with. - **url** (string) - Required - The URL to open. - **options** (*BrowserOptions) - Required - Options to override default behavior. ### Request Example ```rust use webbrowser::{Browser, BrowserOptions}; let options = BrowserOptions::new(); webbrowser::open_browser_with_options(Browser::Safari, "http://docs.rs", &options); ``` ### Response Returns `Result<(), Error>` indicating success or failure. ``` -------------------------------- ### Convert Linux Path to Windows Source: https://docs.rs/webbrowser/latest/src/webbrowser/unix.rs.html Translates a Linux path into a Windows-accessible path, using network paths if necessary. ```rust fn wsl_path_lin2win(wc: &WindowsConfig, path: impl AsRef) -> Result { let path = path.as_ref(); if let Ok(path) = path.strip_prefix(&wc.root) { // windows can access this path directly Ok(format!("C:\\{}", path.as_os_str().to_string_lossy()).replace('/', "\\")) } else { // windows needs to access it via network let wsl_hostname = get_wsl_distro_name(wc)?; Ok(format!( "\\\\wsl$\\{}{}", &wsl_hostname, path.as_os_str().to_string_lossy() ) } ``` -------------------------------- ### Open Browser in Flatpak Source: https://docs.rs/webbrowser/latest/src/webbrowser/unix.rs.html Opens an HTTP or HTTPS URL within a Flatpak environment using the 'xdg-open' command. Other URL schemes are not supported to maintain consistent behavior. ```rust fn try_flatpak(options: &BrowserOptions, target: &TargetType) -> Result<()> { match target.0.scheme() { "http" | "https" => { let url: &str = target; // we assume xdg-open to be present, given that it's a part of standard // runtime & SDK of flatpak try_browser!(options, "xdg-open", url) } // we support only http urls under Flatpak to adhere to the defined // Consistent Behaviour, as effectively DBUS is used interally, and // there doesn't seem to be a way for us to determine actual browser _ => Err(Error::new(ErrorKind::NotFound, "only http urls supported")), } } ``` -------------------------------- ### Open URL using XDG Config in Rust Source: https://docs.rs/webbrowser/latest/src/webbrowser/unix.rs.html Opens a URL using a specified XDG desktop configuration file. This function is asynchronous and requires waiting for a flag file to be created. ```rust let result = open_using_xdg_config( &PathBuf::from(&config_path), &BrowserOptions::default(), &txt_path, ); ``` -------------------------------- ### BrowserOptions Definition Source: https://docs.rs/webbrowser/latest/webbrowser/struct.BrowserOptions.html The structure definition for BrowserOptions. ```rust pub struct BrowserOptions { /* private fields */ } ``` -------------------------------- ### Convert Windows Path to Linux Source: https://docs.rs/webbrowser/latest/src/webbrowser/unix.rs.html Translates a Windows drive-letter path into a Linux-compatible PathBuf. ```rust fn wsl_path_win2lin(wc: &WindowsConfig, path: &str) -> Result { let err_fn = || Error::new(ErrorKind::NotFound, "invalid windows path"); if path.len() > 3 { let pfx = &path[..3]; if matches!(pfx, "C:\\" | "c:\\") { let win_path = path[3..].replace('\\', "/"); Ok(wc.root.join(win_path)) } else { Err(err_fn()) } } else { Err(err_fn()) } } ``` -------------------------------- ### Open URL in default browser Source: https://docs.rs/webbrowser/latest/webbrowser/fn.open.html Basic usage of the open function to navigate to a URL. Returns an error if the browser cannot be launched or if security constraints are violated. ```rust use webbrowser; if webbrowser::open("http://github.com").is_ok() { // ... } ``` -------------------------------- ### webbrowser::open Source: https://docs.rs/webbrowser/latest/webbrowser Opens the specified URL or local file path in the system's default web browser. ```APIDOC ## Function: webbrowser::open ### Description Opens the provided URL or local file path using the platform's default web browser. This function is non-blocking for GUI browsers and blocking for text-based browsers. ### Parameters - **url** (&str) - Required - The URL or file path to open. ### Response - **Result<(), Box>** - Returns Ok(()) if the browser was successfully triggered, or an error if the operation failed. ``` -------------------------------- ### open_browser_with_options Source: https://docs.rs/webbrowser/latest/webbrowser/fn.open_browser_with_options.html Opens the specified URL on the specific browser (if available) requested, while overriding the default options. Return semantics are the same as for open. ```APIDOC ## open_browser_with_options ### Description Opens the specified URL on the specific browser (if available) requested, while overriding the default options. Return semantics are the same as for open. ### Method ``` pub fn open_browser_with_options( browser: Browser, url: &str, options: &BrowserOptions, ) -> Result<()> ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use webbrowser::{open_browser_with_options, Browser, BrowserOptions}; if open_browser_with_options(Browser::Default, "http://github.com", BrowserOptions::new().with_suppress_output(false)).is_ok() { // ... } ``` ### Response #### Success Response (200) Indicates success if the browser was opened as requested. The exact return type is `Result<()>`, so a successful operation returns `Ok(())`. #### Response Example ```rust // Success Ok(()) // Failure example (if the browser could not be opened) // Err(Error::new("Failed to open browser")) ``` ``` -------------------------------- ### Resolve File Path for WSL Source: https://docs.rs/webbrowser/latest/src/webbrowser/unix.rs.html Converts a URL into a Windows-compatible path format for use within WSL. ```rust fn wsl_get_filepath_from_url(wc: &WindowsConfig, target: &TargetType) -> Result { let url = &target.0; if url.scheme() == "file" { if url.host().is_none() { let path = url .to_file_path() .map_err(|_| Error::new(ErrorKind::NotFound, "invalid path"))?; wsl_path_lin2win(wc, path) } else { Ok(format!("\\\\wsl${}", url.path().replace('/', "\\"))) } } else { Ok(url.as_str().to_string()) } } ``` -------------------------------- ### Open URL in Default Browser Source: https://docs.rs/webbrowser/latest/src/webbrowser/lib.rs.html Use this function to open a given URL in the system's default web browser. It returns a Result indicating success or failure. ```rust /// if webbrowser::open("http://github.com").is_ok() { /// // ... /// } pub fn open(url: &str) -> Result<()> { open_browser(Browser::Default, url) } ``` -------------------------------- ### Function open_browser Source: https://docs.rs/webbrowser/latest/webbrowser/fn.open_browser.html Opens the specified URL on the specific browser (if available) requested. Return semantics are the same as for open. ```APIDOC ## Function open_browser ### Description Opens the specified URL on the specific browser (if available) requested. Return semantics are the same as for open. ### Signature ```rust pub fn open_browser(browser: Browser, url: &str) -> Result<()> ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) Indicates the browser was successfully opened. #### Response Example None ### Examples ```rust use webbrowser::{open_browser, Browser}; if open_browser(Browser::Firefox, "http://github.com").is_ok() { // ... } ``` ``` -------------------------------- ### Open URL in Firefox Source: https://docs.rs/webbrowser/latest/webbrowser/fn.open_browser.html Use the open_browser function to attempt opening a URL in Firefox. Check the result for success. ```rust use webbrowser::{open_browser, Browser}; if open_browser(Browser::Firefox, "http://github.com").is_ok() { // ... } ``` -------------------------------- ### Open Safari Browser Source: https://docs.rs/webbrowser/latest/src/webbrowser/lib.rs.html Tests opening the Safari browser to a given URL. This test is ignored by default and requires manual execution. ```rust fn test_open_safari() { assert!(open_browser(Browser::Safari, "http://github.com").is_ok()); } ``` -------------------------------- ### Default Implementation for BrowserOptions Source: https://docs.rs/webbrowser/latest/src/webbrowser/lib.rs.html Provides default values for `BrowserOptions`, including suppressing output and setting a target hint from an environment variable or defaulting to '_blank'. ```rust impl std::default::Default for BrowserOptions { fn default() -> Self { let target_hint = String::from(option_env!("WEBBROWSER_WASM_TARGET").unwrap_or("_blank")); BrowserOptions { suppress_output: true, target_hint, dry_run: false, #[cfg(target_os = "macos")] dont_switch: false, } } } ``` -------------------------------- ### webbrowser::open_browser_with_options Source: https://docs.rs/webbrowser/latest/webbrowser Opens a URL in a specific browser while overriding default execution options. ```APIDOC ## Function: webbrowser::open_browser_with_options ### Description Opens a URL in a specific browser with custom configuration options, such as overriding default output suppression. ### Parameters - **browser** (Browser) - Required - The specific browser to use. - **url** (&str) - Required - The URL or file path to open. - **options** (BrowserOptions) - Required - Configuration options to override default behavior. ``` -------------------------------- ### TryFrom implementation for TargetType Source: https://docs.rs/webbrowser/latest/src/webbrowser/lib.rs.html Handles the conversion of string slices into TargetType, supporting both URL parsing and file path conversion, with platform-specific logic for Windows. ```rust impl std::convert::TryFrom<&str> for TargetType { type Error = Error; #[cfg(target_family = "wasm")] fn try_from(value: &str) -> Result { url::Url::parse(value) .map(|u| Ok(Self(u))) .map_err(|_| Error::new(ErrorKind::InvalidInput, "invalid url for wasm"))? } #[cfg(not(target_family = "wasm"))] fn try_from(value: &str) -> Result { match url::Url::parse(value) { Ok(u) => { if u.scheme().len() == 1 && cfg!(windows) { // this can happen in windows that C:\abc.html gets parsed as scheme "C" Self::from_file_path(value) } else { Ok(Self(u)) } } Err(_) => Self::from_file_path(value), } } } ``` -------------------------------- ### Webbrowser Crate - Features Source: https://docs.rs/webbrowser/latest/index.html Information about the configurable features of the webbrowser crate. ```APIDOC ## Crate Features `webbrowser` optionally allows the following features to be configured: - **`hardened`**: This disables handling of non-http(s) urls (e.g. `file:///`) as a hard security precaution. - **`disable-wsl`**: This disables WSL `file` implementation (`http` still works). - **`wasm-console`**: This enables logging to wasm console (valid only on wasm platform). ``` -------------------------------- ### Guess Desktop Environment Source: https://docs.rs/webbrowser/latest/src/webbrowser/unix.rs.html Infers the current desktop environment by checking environment variables like XDG_CURRENT_DESKTOP and DESKTOP_SESSION. It prioritizes specific environments like Flatpak, GNOME, KDE, MATE, XFCE, and WSL. ```rust fn guess_desktop_env() -> &'static str { let unknown = "unknown"; let xcd: String = std::env::var("XDG_CURRENT_DESKTOP") .unwrap_or_else(|_| unknown.into()) .to_ascii_lowercase(); let dsession: String = std::env::var("DESKTOP_SESSION") .unwrap_or_else(|_| unknown.into()) .to_ascii_lowercase(); if is_flatpak() { "flatpak" } else if xcd.contains("gnome") || xcd.contains("cinnamon") || dsession.contains("gnome") { // GNOME and its derivatives "gnome" } else if xcd.contains("kde") || std::env::var("KDE_FULL_SESSION").is_ok() || std::env::var("KDE_SESSION_VERSION").is_ok() { // KDE: https://userbase.kde.org/KDE_System_Administration/Environment_Variables#Automatically_Set_Variables "kde" } else if xcd.contains("mate") || dsession.contains("mate") { // We'll treat MATE as distinct from GNOME due to mate-open "mate" } else if xcd.contains("xfce") || dsession.contains("xfce") { // XFCE "xfce" } else if is_wsl() { // WSL "wsl" } else { // All others unknown } } ``` -------------------------------- ### Webbrowser Structs Source: https://docs.rs/webbrowser/latest/webbrowser/all.html This section details the structs available in the webbrowser crate. ```APIDOC ### Structs #### BrowserOptions Options for configuring browser behavior. #### ParseBrowserError Represents an error that can occur during browser parsing. ``` -------------------------------- ### Open URL with Custom Browser Options Source: https://docs.rs/webbrowser Provides the ability to open a URL in a specific browser while overriding default options. This allows for more granular control over how the browser is launched. ```APIDOC ## POST /api/users ### Description Opens the specified URL on the specific browser (if available) requested, while overriding the default options. ### Method GET ### Endpoint webbrowser::open_browser_with_options(browser: Browser, options: &BrowserOptions, url: &str) ### Parameters #### Path Parameters - **browser** (Browser) - Required - The specific browser to use. - **options** (BrowserOptions) - Required - An instance of BrowserOptions to override default behaviors. - **url** (string) - Required - The URL to open. ### Request Example ```rust use webbrowser::{Browser, BrowserOptions, open_browser_with_options}; let options = BrowserOptions::new(); // Create default options // Customize options as needed, e.g., options.with_hint("private", "true"); if open_browser_with_options(Browser::Firefox, &options, "https://example.com").is_ok() { // Firefox opened with custom options } else { // Failed to open Firefox with custom options } ``` ### Response #### Success Response (200) Indicates that the operation to open the specified browser with the URL and custom options was initiated successfully. #### Response Example ``` Ok(()) ``` #### Error Response (500) Indicates that an error occurred during the process of opening the specified browser with custom options. #### Response Example ``` Err(Error::new("Failed to open browser with options")) ``` ``` -------------------------------- ### Retrieve XDG Data Directories Source: https://docs.rs/webbrowser/latest/src/webbrowser/unix.rs.html Collects search paths for desktop files based on XDG_DATA_HOME and XDG_DATA_DIRS environment variables. ```rust fn get_xdg_dirs() -> Vec { let mut xdg_dirs: Vec = Vec::new(); #[allow(deprecated)] let data_home = std::env::var("XDG_DATA_HOME") .ok() .map(PathBuf::from) .filter(|path| path.is_absolute()) .or_else(|| std::env::home_dir().map(|path| path.join(".local/share"))); if let Some(data_home) = data_home { xdg_dirs.push(data_home); } if let Ok(data_dirs) = std::env::var("XDG_DATA_DIRS") { for d in data_dirs.split(':') { xdg_dirs.push(PathBuf::from(d)); } } else { xdg_dirs.push(PathBuf::from("/usr/local/share")); xdg_dirs.push(PathBuf::from("/usr/share")); } xdg_dirs } ``` -------------------------------- ### Handle $BROWSER Environment Variable Source: https://docs.rs/webbrowser/latest/src/webbrowser/unix.rs.html Parses the $BROWSER environment variable, which can contain colon-delimited browser commands. It replaces placeholders like %s with the URL and handles command-line arguments. The function attempts to execute the browser command and returns Ok(()) if successful. ```rust fn try_with_browser_env(url: &str, options: &BrowserOptions) -> Result<()> { // $BROWSER can contain ':' delimited options, each representing a potential browser command line for browser in std::env::var("BROWSER") .unwrap_or_else(|_| String::from("")) .split(':') { if !browser.is_empty() { // each browser command can have %s to represent URL, while %c needs to be replaced // with ':' and %% with '%' let cmdline = browser .replace("%s", url) .replace("%c", ":") .replace("%%", "% "); let cmdarr: Vec<&str> = cmdline.split_ascii_whitespace().collect(); let browser_cmd = cmdarr[0]; let env_exit = for_matching_path(browser_cmd, |pb| { let mut cmd = Command::new(pb); for arg in cmdarr.iter().skip(1) { cmd.arg(arg); } if !browser.contains("%s") { // append the url as an argument only if it was not already set via %s cmd.arg(url); } run_command(&mut cmd, !is_text_browser(pb), options) }); if env_exit.is_ok() { return Ok(()); } } } Err(Error::new(ErrorKind::NotFound, "$BROWSER not set or invalid")) } ``` -------------------------------- ### Parse WSL Command Line Source: https://docs.rs/webbrowser/latest/src/webbrowser/unix.rs.html Parses a raw command line string, replacing placeholders with file paths and preparing a Command object. ```rust fn parse_wsl_cmdline(wc: &WindowsConfig, cmdline: &str, url: &TargetType) -> Result { let mut tokens: Vec = Vec::new(); let filepath = wsl_get_filepath_from_url(wc, url)?; let fp = &filepath; for_each_token(cmdline, |token: &str| { if matches!(token, "%0" | "%1") { tokens.push(fp.to_owned()); } else { tokens.push(token.to_string()); } }); if tokens.is_empty() { Err(Error::new(ErrorKind::NotFound, "invalid command")) } else { let progpath = wsl_path_win2lin(wc, &tokens[0])?; let mut cmd = Command::new(progpath); if tokens.len() > 1 { cmd.args(&tokens[1..]); } Ok(cmd) } } ``` -------------------------------- ### Open WebPositive Browser Source: https://docs.rs/webbrowser/latest/src/webbrowser/lib.rs.html Tests opening the WebPositive browser to a given URL. This test is ignored by default and requires manual execution. ```rust fn test_open_webpositive() { assert!(open_browser(Browser::WebPositive, "http://github.com").is_ok()); } ``` -------------------------------- ### Webbrowser Functions Source: https://docs.rs/webbrowser/latest/webbrowser/all.html This section details the functions available in the webbrowser crate for opening web browsers. ```APIDOC ## Functions ### open Opens the default web browser to the specified URL. ### open_browser Opens the specified web browser to the given URL. ### open_browser_with_options Opens a web browser with custom options to a specific URL. ``` -------------------------------- ### Open URL with Custom Options Source: https://docs.rs/webbrowser/latest/webbrowser/index.html Enables opening a URL in a specific browser while overriding default options. This provides more control over how the browser is launched. ```APIDOC ## POST /api/users ### Description Opens the specified URL on the specific browser (if available) requested, while overriding the default options. ### Method POST ### Endpoint /open_browser_with_options ### Parameters #### Query Parameters - **url** (string) - Required - The URL to open. - **browser** (string) - Required - The name of the browser to use. - **options** (object) - Optional - BrowserOptions to override default behavior. - **suppress_output** (boolean) - Optional - Whether to suppress stdout/stderr. - **new_tab** (boolean) - Optional - Whether to open in a new tab. ### Request Example ```json { "url": "http://github.com", "browser": "firefox", "options": { "suppress_output": true, "new_tab": true } } ``` ### Response #### Success Response (200) - **status** (string) - Indicates if the operation was successful. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### try_into Method Source: https://docs.rs/webbrowser/latest/webbrowser/struct.BrowserOptions.html Provides the `try_into` method for attempting conversions that may fail. ```APIDOC ## Method: try_into ### Description Attempts to perform a conversion from the current type `T` to a target type `U`. This method returns a `Result` which is `Ok(U)` on success or `Err(>::Error)` on failure. ### Method `fn try_into(self) -> Result>::Error>` ### Parameters None (operates on `self`) ### Returns - `Result>::Error>`: An `Ok` variant containing the converted value of type `U` if successful, or an `Err` variant containing the specific error if the conversion fails. ``` -------------------------------- ### Retrieve Browser Command via cmd.exe Source: https://docs.rs/webbrowser/latest/src/webbrowser/unix.rs.html Queries the Windows ftype registry setting using cmd.exe to determine the default browser command. ```rust pub(super) fn get_wsl_windows_browser_cmd( wc: &WindowsConfig, url: &TargetType, ) -> Result { let err_fn = || Error::new(ErrorKind::NotFound, "cmd.exe error"); let mut cmd = Command::new(&wc.cmd_path); cmd.arg("/Q") .arg("/C") .arg("ftype http") .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::null()); log::debug!("running command: ${:?}", &cmd); let output_u8 = cmd.output()?; let output = String::from_utf8_lossy(&output_u8.stdout); let output = output.trim(); if output.is_empty() { Err(err_fn()) } else { parse_wsl_cmdline(wc, output, url) } } ```