servoshell/
parser.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5#[cfg(not(any(target_os = "android", target_env = "ohos")))]
6use std::path::{Path, PathBuf};
7
8use servo::{ServoUrl, is_reg_domain};
9
10#[cfg(not(any(target_os = "android", target_env = "ohos")))]
11pub fn parse_url_or_filename(cwd: &Path, input: &str) -> Result<ServoUrl, ()> {
12    match ServoUrl::parse(input) {
13        Ok(url) => Ok(url),
14        Err(url::ParseError::RelativeUrlWithoutBase) => {
15            url::Url::from_file_path(&*cwd.join(input)).map(ServoUrl::from_url)
16        },
17        Err(_) => Err(()),
18    }
19}
20
21#[cfg(not(any(target_os = "android", target_env = "ohos")))]
22pub fn get_default_url(
23    url_opt: Option<&str>,
24    cwd: impl AsRef<Path>,
25    exists: impl FnOnce(&PathBuf) -> bool,
26    preferences: &crate::prefs::ServoShellPreferences,
27) -> ServoUrl {
28    // If the url is not provided, we fallback to the homepage in prefs,
29    // or a blank page in case the homepage is not set either.
30    let mut new_url = None;
31    let cmdline_url = url_opt.map(|s| s.to_string()).and_then(|url_string| {
32        parse_url_or_filename(cwd.as_ref(), &url_string)
33            .inspect_err(|&error| {
34                log::warn!("URL parsing failed ({:?}).", error);
35            })
36            .ok()
37    });
38
39    if let Some(url) = cmdline_url.clone() {
40        // Check if the URL path corresponds to a file
41        match (url.scheme(), url.host(), url.to_file_path()) {
42            ("file", None, Ok(ref path)) if exists(path) => {
43                new_url = cmdline_url;
44            },
45            _ => {},
46        }
47    }
48
49    #[allow(
50        clippy::collapsible_if,
51        reason = "let chains are not available in 1.85"
52    )]
53    if new_url.is_none() {
54        if let Some(url_opt) = url_opt {
55            new_url = location_bar_input_to_url(url_opt, &preferences.searchpage);
56        }
57    }
58
59    let pref_url = parse_url_or_filename(cwd.as_ref(), &preferences.homepage).ok();
60    let blank_url = ServoUrl::parse("about:blank").ok();
61
62    new_url.or(pref_url).or(blank_url).unwrap()
63}
64
65/// Interpret an input URL.
66///
67/// If this is not a valid URL, try to "fix" it by adding a scheme or if all else fails,
68/// interpret the string as a search term.
69pub(crate) fn location_bar_input_to_url(request: &str, searchpage: &str) -> Option<ServoUrl> {
70    let request = request.trim();
71    ServoUrl::parse(request)
72        .ok()
73        .or_else(|| try_as_file(request))
74        .or_else(|| try_as_domain(request))
75        .or_else(|| try_as_search_page(request, searchpage))
76}
77
78fn try_as_file(request: &str) -> Option<ServoUrl> {
79    if request.starts_with('/') {
80        return ServoUrl::parse(&format!("file://{}", request)).ok();
81    }
82    None
83}
84
85fn try_as_domain(request: &str) -> Option<ServoUrl> {
86    fn is_domain_like(s: &str) -> bool {
87        !s.starts_with('/') && s.contains('/') ||
88            (!s.contains(' ') && !s.starts_with('.') && s.split('.').count() > 1)
89    }
90
91    if !request.contains(' ') && is_reg_domain(request) || is_domain_like(request) {
92        return ServoUrl::parse(&format!("https://{}", request)).ok();
93    }
94    None
95}
96
97fn try_as_search_page(request: &str, searchpage: &str) -> Option<ServoUrl> {
98    if request.is_empty() {
99        return None;
100    }
101    ServoUrl::parse(&searchpage.replace("%s", request)).ok()
102}