1use std::default::Default;
6use std::rc::Rc;
7
8use dom_struct::dom_struct;
9use js::context::JSContext;
10use js::rust::HandleObject;
11use net_traits::CoreResourceMsg;
12use net_traits::blob_url_store::parse_blob_url;
13use net_traits::filemanager_thread::FileManagerThreadMsg;
14use profile_traits::generic_channel;
15use script_bindings::cell::DomRefCell;
16use script_bindings::cformat;
17use script_bindings::reflector::{Reflector, reflect_weak_referenceable_dom_object_with_proto};
18use servo_base::generic_channel::GenericSend;
19use servo_url::{ImmutableOrigin, ServoUrl};
20use url::Url;
21use uuid::Uuid;
22
23use crate::dom::bindings::codegen::Bindings::URLBinding::URLMethods;
24use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
25use crate::dom::bindings::reflector::DomGlobal;
26use crate::dom::bindings::root::{DomRoot, MutNullableDom};
27use crate::dom::bindings::str::{DOMString, USVString};
28use crate::dom::blob::Blob;
29use crate::dom::globalscope::GlobalScope;
30use crate::dom::url::urlhelper::UrlHelper;
31use crate::dom::url::urlsearchparams::URLSearchParams;
32
33#[dom_struct]
35#[expect(clippy::upper_case_acronyms)]
36pub(crate) struct URL {
37 reflector_: Reflector,
38
39 #[no_trace]
41 url: DomRefCell<ServoUrl>,
42
43 search_params: MutNullableDom<URLSearchParams>,
45}
46
47impl URL {
48 fn new_inherited(url: ServoUrl) -> URL {
49 URL {
50 reflector_: Reflector::new(),
51 url: DomRefCell::new(url),
52 search_params: Default::default(),
53 }
54 }
55
56 fn new(
57 cx: &mut JSContext,
58 global: &GlobalScope,
59 proto: Option<HandleObject>,
60 url: ServoUrl,
61 ) -> DomRoot<URL> {
62 reflect_weak_referenceable_dom_object_with_proto(
63 cx,
64 Rc::new(URL::new_inherited(url)),
65 global,
66 proto,
67 )
68 }
69
70 pub(crate) fn query_pairs(&self) -> Vec<(String, String)> {
71 self.url
72 .borrow()
73 .as_url()
74 .query_pairs()
75 .into_owned()
76 .collect()
77 }
78
79 pub(crate) fn origin(&self) -> ImmutableOrigin {
80 self.url.borrow().origin()
81 }
82
83 pub(crate) fn set_query_pairs(&self, pairs: &[(String, String)]) {
84 let mut url = self.url.borrow_mut();
85
86 if pairs.is_empty() {
87 url.as_mut_url().set_query(None);
88 } else {
89 url.as_mut_url()
90 .query_pairs_mut()
91 .clear()
92 .extend_pairs(pairs);
93 }
94 }
95
96 fn unicode_serialization_blob_url(origin: &ImmutableOrigin, id: &Uuid) -> String {
98 let mut result = "blob:".to_string();
101
102 result.push_str(&origin.ascii_serialization());
109
110 result.push('/');
112
113 result.push_str(&id.to_string());
115
116 result
118 }
119}
120
121impl URLMethods<crate::DomTypeHolder> for URL {
122 fn Constructor(
124 cx: &mut JSContext,
125 global: &GlobalScope,
126 proto: Option<HandleObject>,
127 url: USVString,
128 base: Option<USVString>,
129 ) -> Fallible<DomRoot<URL>> {
130 let parsed_base = match base {
132 None => None,
133 Some(base) => {
134 match ServoUrl::parse(&base.0) {
135 Ok(base) => Some(base),
136 Err(error) => {
137 return Err(Error::Type(cformat!("could not parse base: {}", error)));
139 },
140 }
141 },
142 };
143 let parsed_url = match ServoUrl::parse_with_base(parsed_base.as_ref(), &url.0) {
144 Ok(url) => url,
145 Err(error) => {
146 return Err(Error::Type(cformat!("could not parse URL: {}", error)));
148 },
149 };
150
151 Ok(URL::new(cx, global, proto, parsed_url))
162 }
163
164 fn CanParse(_global: &GlobalScope, url: USVString, base: Option<USVString>) -> bool {
166 let parsed_url = run_api_url_parser(url, base);
168
169 parsed_url.is_ok()
172 }
173
174 fn Parse(
176 cx: &mut JSContext,
177 global: &GlobalScope,
178 url: USVString,
179 base: Option<USVString>,
180 ) -> Option<DomRoot<URL>> {
181 let parsed_url = run_api_url_parser(url, base).ok()?;
185
186 Some(URL::new(cx, global, None, ServoUrl::from_url(parsed_url)))
192 }
193
194 fn CreateObjectURL(global: &GlobalScope, blob: &Blob) -> DOMString {
196 let origin = global.origin();
199
200 let id = blob.get_blob_url_id();
201
202 DOMString::from(URL::unicode_serialization_blob_url(origin.immutable(), &id))
203 }
204
205 fn RevokeObjectURL(global: &GlobalScope, url: DOMString) {
207 let origin = global.origin().immutable().clone();
211
212 if let Ok(url) = ServoUrl::parse(&url.str()) &&
213 url.fragment().is_none() &&
214 let Ok((id, _)) = parse_blob_url(&url)
215 {
216 let resource_threads = global.resource_threads();
217 let (tx, rx) = generic_channel::channel(global.time_profiler_chan().clone()).unwrap();
218 let msg = FileManagerThreadMsg::RevokeBlobURL(id, origin, tx);
219 let _ = resource_threads.send(CoreResourceMsg::ToFileManager(msg));
220
221 let _ = rx.recv().unwrap();
222 }
223 }
224
225 fn Hash(&self) -> USVString {
227 UrlHelper::Hash(&self.url.borrow())
228 }
229
230 fn SetHash(&self, value: USVString) {
232 UrlHelper::SetHash(&mut self.url.borrow_mut(), value);
233 }
234
235 fn Host(&self) -> USVString {
237 UrlHelper::Host(&self.url.borrow())
238 }
239
240 fn SetHost(&self, value: USVString) {
242 UrlHelper::SetHost(&mut self.url.borrow_mut(), value);
243 }
244
245 fn Hostname(&self) -> USVString {
247 UrlHelper::Hostname(&self.url.borrow())
248 }
249
250 fn SetHostname(&self, value: USVString) {
252 UrlHelper::SetHostname(&mut self.url.borrow_mut(), value);
253 }
254
255 fn Href(&self) -> USVString {
257 UrlHelper::Href(&self.url.borrow())
258 }
259
260 fn SetHref(&self, value: USVString) -> ErrorResult {
262 match ServoUrl::parse(&value.0) {
263 Ok(url) => {
264 *self.url.borrow_mut() = url;
265 self.search_params.set(None); Ok(())
267 },
268 Err(error) => Err(Error::Type(cformat!("could not parse URL: {}", error))),
269 }
270 }
271
272 fn Password(&self) -> USVString {
274 UrlHelper::Password(&self.url.borrow())
275 }
276
277 fn SetPassword(&self, value: USVString) {
279 UrlHelper::SetPassword(&mut self.url.borrow_mut(), value);
280 }
281
282 fn Pathname(&self) -> USVString {
284 UrlHelper::Pathname(&self.url.borrow())
285 }
286
287 fn SetPathname(&self, value: USVString) {
289 UrlHelper::SetPathname(&mut self.url.borrow_mut(), value);
290 }
291
292 fn Port(&self) -> USVString {
294 UrlHelper::Port(&self.url.borrow())
295 }
296
297 fn SetPort(&self, value: USVString) {
299 UrlHelper::SetPort(&mut self.url.borrow_mut(), value);
300 }
301
302 fn Protocol(&self) -> USVString {
304 UrlHelper::Protocol(&self.url.borrow())
305 }
306
307 fn SetProtocol(&self, value: USVString) {
309 UrlHelper::SetProtocol(&mut self.url.borrow_mut(), value);
310 }
311
312 fn Origin(&self) -> USVString {
314 UrlHelper::Origin(&self.url.borrow())
315 }
316
317 fn Search(&self) -> USVString {
319 UrlHelper::Search(&self.url.borrow())
320 }
321
322 fn SetSearch(&self, value: USVString) {
324 UrlHelper::SetSearch(&mut self.url.borrow_mut(), value);
325 if let Some(search_params) = self.search_params.get() {
326 search_params.set_list(self.query_pairs());
327 }
328 }
329
330 fn SearchParams(&self, cx: &mut JSContext) -> DomRoot<URLSearchParams> {
332 self.search_params
333 .or_init(|| URLSearchParams::new(cx, &self.global(), Some(self)))
334 }
335
336 fn Username(&self) -> USVString {
338 UrlHelper::Username(&self.url.borrow())
339 }
340
341 fn SetUsername(&self, value: USVString) {
343 UrlHelper::SetUsername(&mut self.url.borrow_mut(), value);
344 }
345
346 fn ToJSON(&self) -> USVString {
348 self.Href()
349 }
350}
351
352fn run_api_url_parser(url: USVString, base: Option<USVString>) -> Result<Url, url::ParseError> {
354 let parsed_base = base.map(|base| Url::parse(&base.0)).transpose()?;
359
360 Url::options().base_url(parsed_base.as_ref()).parse(&url.0)
362}