1#[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 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 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
65pub(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}