script/dom/html/
htmllinkelement.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
5use std::borrow::{Borrow, ToOwned};
6use std::cell::Cell;
7use std::default::Default;
8use std::str::FromStr;
9
10use dom_struct::dom_struct;
11use html5ever::{LocalName, Prefix, local_name};
12use js::context::JSContext;
13use js::rust::HandleObject;
14use net_traits::image_cache::{
15    Image, ImageCache, ImageCacheResponseCallback, ImageCacheResult, ImageLoadListener,
16    ImageOrMetadataAvailable, ImageResponse, PendingImageId,
17};
18use net_traits::request::{Destination, Initiator, ParserMetadata, RequestBuilder, RequestId};
19use net_traits::{
20    FetchMetadata, FetchResponseMsg, NetworkError, ReferrerPolicy, ResourceFetchTiming,
21};
22use pixels::PixelFormat;
23use script_bindings::root::Dom;
24use servo_arc::Arc;
25use servo_base::generic_channel::GenericSharedMemory;
26use servo_url::ServoUrl;
27use style::attr::AttrValue;
28use style::media_queries::MediaList as StyleMediaList;
29use style::stylesheets::Stylesheet;
30use stylo_atoms::Atom;
31use webrender_api::units::DeviceIntSize;
32
33use crate::dom::attr::Attr;
34use crate::dom::bindings::cell::DomRefCell;
35use crate::dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenList_Binding::DOMTokenListMethods;
36use crate::dom::bindings::codegen::Bindings::HTMLLinkElementBinding::HTMLLinkElementMethods;
37use crate::dom::bindings::inheritance::Castable;
38use crate::dom::bindings::refcounted::Trusted;
39use crate::dom::bindings::reflector::DomGlobal;
40use crate::dom::bindings::root::{DomRoot, MutNullableDom};
41use crate::dom::bindings::str::{DOMString, USVString};
42use crate::dom::csp::{GlobalCspReporting, Violation};
43use crate::dom::css::cssstylesheet::CSSStyleSheet;
44use crate::dom::css::stylesheet::StyleSheet as DOMStyleSheet;
45use crate::dom::document::Document;
46use crate::dom::documentorshadowroot::StylesheetSource;
47use crate::dom::domtokenlist::DOMTokenList;
48use crate::dom::element::{
49    AttributeMutation, Element, ElementCreator, cors_setting_for_element,
50    cors_settings_attribute_credential_mode, referrer_policy_for_element,
51    reflect_cross_origin_attribute, reflect_referrer_policy_attribute, set_cross_origin_attribute,
52};
53use crate::dom::html::htmlelement::HTMLElement;
54use crate::dom::medialist::MediaList;
55use crate::dom::node::{BindContext, Node, NodeTraits, UnbindContext};
56use crate::dom::performance::performanceresourcetiming::InitiatorType;
57use crate::dom::processingoptions::{
58    LinkFetchContext, LinkFetchContextType, LinkProcessingOptions,
59};
60use crate::dom::types::{EventTarget, GlobalScope};
61use crate::dom::virtualmethods::VirtualMethods;
62use crate::links::LinkRelations;
63use crate::network_listener::{FetchResponseListener, ResourceTimingListener, submit_timing};
64use crate::script_module::{ScriptFetchOptions, fetch_a_modulepreload_module};
65use crate::script_runtime::CanGc;
66use crate::stylesheet_loader::{ElementStylesheetLoader, StylesheetContextSource, StylesheetOwner};
67
68#[derive(Clone, Copy, JSTraceable, MallocSizeOf, PartialEq)]
69pub(crate) struct RequestGenerationId(u32);
70
71impl RequestGenerationId {
72    fn increment(self) -> RequestGenerationId {
73        RequestGenerationId(self.0 + 1)
74    }
75}
76
77#[dom_struct]
78pub(crate) struct HTMLLinkElement {
79    htmlelement: HTMLElement,
80    /// The relations as specified by the "rel" attribute
81    rel_list: MutNullableDom<DOMTokenList>,
82
83    /// The link relations as they are used in practice.
84    ///
85    /// The reason this is separate from [HTMLLinkElement::rel_list] is that
86    /// a literal list is a bit unwieldy and that there are corner cases to consider
87    /// (Like `rev="made"` implying an author relationship that is not represented in rel_list)
88    #[no_trace]
89    relations: Cell<LinkRelations>,
90
91    #[conditional_malloc_size_of]
92    #[no_trace]
93    stylesheet: DomRefCell<Option<Arc<Stylesheet>>>,
94    cssom_stylesheet: MutNullableDom<CSSStyleSheet>,
95
96    /// <https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts>
97    parser_inserted: Cell<bool>,
98    /// The number of loads that this link element has triggered (could be more
99    /// than one because of imports) and have not yet finished.
100    pending_loads: Cell<u32>,
101    /// Whether any of the loads have failed.
102    any_failed_load: Cell<bool>,
103    /// A monotonically increasing counter that keeps track of which stylesheet to apply.
104    request_generation_id: Cell<RequestGenerationId>,
105    /// <https://html.spec.whatwg.org/multipage/#explicitly-enabled>
106    is_explicitly_enabled: Cell<bool>,
107    /// Whether the previous type matched with the destination
108    previous_type_matched: Cell<bool>,
109    /// Whether the previous media environment matched with the media query
110    previous_media_environment_matched: Cell<bool>,
111    /// Line number this element was created on
112    line_number: u64,
113    /// <https://html.spec.whatwg.org/multipage/#dom-link-blocking>
114    blocking: MutNullableDom<DOMTokenList>,
115}
116
117impl HTMLLinkElement {
118    fn new_inherited(
119        local_name: LocalName,
120        prefix: Option<Prefix>,
121        document: &Document,
122        creator: ElementCreator,
123    ) -> HTMLLinkElement {
124        HTMLLinkElement {
125            htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
126            rel_list: Default::default(),
127            relations: Cell::new(LinkRelations::empty()),
128            parser_inserted: Cell::new(creator.is_parser_created()),
129            stylesheet: DomRefCell::new(None),
130            cssom_stylesheet: MutNullableDom::new(None),
131            pending_loads: Cell::new(0),
132            any_failed_load: Cell::new(false),
133            request_generation_id: Cell::new(RequestGenerationId(0)),
134            is_explicitly_enabled: Cell::new(false),
135            previous_type_matched: Cell::new(true),
136            previous_media_environment_matched: Cell::new(true),
137            line_number: creator.return_line_number(),
138            blocking: Default::default(),
139        }
140    }
141
142    pub(crate) fn new(
143        cx: &mut js::context::JSContext,
144        local_name: LocalName,
145        prefix: Option<Prefix>,
146        document: &Document,
147        proto: Option<HandleObject>,
148        creator: ElementCreator,
149    ) -> DomRoot<HTMLLinkElement> {
150        Node::reflect_node_with_proto(
151            cx,
152            Box::new(HTMLLinkElement::new_inherited(
153                local_name, prefix, document, creator,
154            )),
155            document,
156            proto,
157        )
158    }
159
160    pub(crate) fn get_request_generation_id(&self) -> RequestGenerationId {
161        self.request_generation_id.get()
162    }
163
164    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
165    fn remove_stylesheet(&self) {
166        if let Some(stylesheet) = self.stylesheet.borrow_mut().take() {
167            let owner = self.stylesheet_list_owner();
168            owner.remove_stylesheet(
169                StylesheetSource::Element(Dom::from_ref(self.upcast())),
170                &stylesheet,
171            );
172            self.clean_stylesheet_ownership();
173            owner.invalidate_stylesheets();
174        }
175    }
176
177    // FIXME(emilio): These methods are duplicated with
178    // HTMLStyleElement::set_stylesheet.
179    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
180    pub(crate) fn set_stylesheet(&self, new_stylesheet: Arc<Stylesheet>) {
181        let owner = self.stylesheet_list_owner();
182        if let Some(old_stylesheet) = self.stylesheet.borrow_mut().replace(new_stylesheet.clone()) {
183            owner.remove_stylesheet(
184                StylesheetSource::Element(Dom::from_ref(self.upcast())),
185                &old_stylesheet,
186            );
187        }
188        owner.add_owned_stylesheet(self.upcast(), new_stylesheet);
189    }
190
191    pub(crate) fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> {
192        self.stylesheet.borrow().clone()
193    }
194
195    pub(crate) fn get_cssom_stylesheet(&self, can_gc: CanGc) -> Option<DomRoot<CSSStyleSheet>> {
196        self.get_stylesheet().map(|sheet| {
197            self.cssom_stylesheet.or_init(|| {
198                CSSStyleSheet::new(
199                    &self.owner_window(),
200                    Some(self.upcast::<Element>()),
201                    "text/css".into(),
202                    Some(self.Href().into()),
203                    None, // todo handle title
204                    sheet,
205                    None, // constructor_document
206                    can_gc,
207                )
208            })
209        })
210    }
211
212    pub(crate) fn is_alternate(&self) -> bool {
213        self.relations.get().contains(LinkRelations::ALTERNATE) &&
214            !self
215                .upcast::<Element>()
216                .get_string_attribute(&local_name!("title"))
217                .is_empty()
218    }
219
220    pub(crate) fn is_effectively_disabled(&self) -> bool {
221        (self.is_alternate() && !self.is_explicitly_enabled.get()) ||
222            self.upcast::<Element>()
223                .has_attribute(&local_name!("disabled"))
224    }
225
226    fn clean_stylesheet_ownership(&self) {
227        if let Some(cssom_stylesheet) = self.cssom_stylesheet.get() {
228            cssom_stylesheet.set_owner_node(None);
229        }
230        self.cssom_stylesheet.set(None);
231    }
232}
233
234fn get_attr(element: &Element, local_name: &LocalName) -> Option<String> {
235    let elem = element.get_attribute(local_name);
236    elem.map(|e| {
237        let value = e.value();
238        (**value).to_owned()
239    })
240}
241
242impl VirtualMethods for HTMLLinkElement {
243    fn super_type(&self) -> Option<&dyn VirtualMethods> {
244        Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
245    }
246
247    fn attribute_mutated(
248        &self,
249        cx: &mut js::context::JSContext,
250        attr: &Attr,
251        mutation: AttributeMutation,
252    ) {
253        self.super_type()
254            .unwrap()
255            .attribute_mutated(cx, attr, mutation);
256
257        let local_name = attr.local_name();
258        let is_removal = mutation.is_removal();
259        if *local_name == local_name!("disabled") {
260            self.handle_disabled_attribute_change(is_removal);
261            return;
262        }
263        let node = self.upcast::<Node>();
264
265        if !node.is_connected() {
266            return;
267        }
268
269        // For stylesheets, we should only refetch when the actual attribute value
270        // has been changed.
271        if self.relations.get().contains(LinkRelations::STYLESHEET) {
272            if let AttributeMutation::Set(Some(previous_value), _) = mutation {
273                if **previous_value == **attr.value() {
274                    return;
275                }
276            }
277        }
278
279        match *local_name {
280            local_name!("rel") | local_name!("rev") => {
281                let previous_relations = self.relations.get();
282                self.relations
283                    .set(LinkRelations::for_element(self.upcast()));
284
285                // If relations haven't changed, we shouldn't do anything
286                if previous_relations == self.relations.get() {
287                    return;
288                }
289
290                // https://html.spec.whatwg.org/multipage/#link-type-stylesheet:fetch-and-process-the-linked-resource
291                // > When the external resource link is created on a link element that is already browsing-context connected.
292                if self.relations.get().contains(LinkRelations::STYLESHEET) {
293                    self.handle_stylesheet_url();
294                } else {
295                    self.remove_stylesheet();
296                }
297
298                if self.relations.get().contains(LinkRelations::MODULE_PRELOAD) {
299                    self.fetch_and_process_modulepreload(cx);
300                }
301            },
302            local_name!("href") => {
303                // https://html.spec.whatwg.org/multipage/#attr-link-href
304                // > If both the href and imagesrcset attributes are absent, then the element does not define a link.
305                if is_removal {
306                    if self.relations.get().contains(LinkRelations::STYLESHEET) {
307                        self.remove_stylesheet();
308                    }
309                    return;
310                }
311                // https://html.spec.whatwg.org/multipage/#link-type-stylesheet:fetch-and-process-the-linked-resource
312                // > When the href attribute of the link element of an external resource link
313                // > that is already browsing-context connected is changed.
314                if self.relations.get().contains(LinkRelations::STYLESHEET) {
315                    self.handle_stylesheet_url();
316                }
317
318                if self.relations.get().contains(LinkRelations::ICON) {
319                    self.handle_favicon_url(&attr.value());
320                }
321
322                // https://html.spec.whatwg.org/multipage/#link-type-prefetch
323                // When the href attribute of the link element of an external resource link
324                // that is already browsing-context connected is changed.
325                if self.relations.get().contains(LinkRelations::PREFETCH) {
326                    self.fetch_and_process_prefetch_link(&attr.value());
327                }
328
329                // https://html.spec.whatwg.org/multipage/#link-type-preload
330                // When the href attribute of the link element of an external resource link
331                // that is already browsing-context connected is changed.
332                if self.relations.get().contains(LinkRelations::PRELOAD) {
333                    self.handle_preload_url();
334                }
335
336                // https://html.spec.whatwg.org/multipage/#link-type-modulepreload
337                if self.relations.get().contains(LinkRelations::MODULE_PRELOAD) {
338                    self.fetch_and_process_modulepreload(cx);
339                }
340            },
341            local_name!("sizes") if self.relations.get().contains(LinkRelations::ICON) => {
342                self.handle_favicon_url(&attr.value());
343            },
344            local_name!("crossorigin") => {
345                // https://html.spec.whatwg.org/multipage/#link-type-prefetch
346                // When the crossorigin attribute of the link element of an external resource link
347                // that is already browsing-context connected is set, changed, or removed.
348                if self.relations.get().contains(LinkRelations::PREFETCH) {
349                    self.fetch_and_process_prefetch_link(&attr.value());
350                }
351
352                // https://html.spec.whatwg.org/multipage/#link-type-stylesheet
353                // When the crossorigin attribute of the link element of an external resource link
354                // that is already browsing-context connected is set, changed, or removed.
355                if self.relations.get().contains(LinkRelations::STYLESHEET) {
356                    self.handle_stylesheet_url();
357                }
358            },
359            local_name!("as") => {
360                // https://html.spec.whatwg.org/multipage/#link-type-preload
361                // When the as attribute of the link element of an external resource link
362                // that is already browsing-context connected is changed.
363                if self.relations.get().contains(LinkRelations::PRELOAD) {
364                    if let AttributeMutation::Set(Some(_), _) = mutation {
365                        self.handle_preload_url();
366                    }
367                }
368            },
369            local_name!("type") => {
370                // https://html.spec.whatwg.org/multipage/#link-type-stylesheet:fetch-and-process-the-linked-resource
371                // When the type attribute of the link element of an external resource link that
372                // is already browsing-context connected is set or changed to a value that does
373                // not or no longer matches the Content-Type metadata of the previous obtained
374                // external resource, if any.
375                //
376                // TODO: Match Content-Type metadata to check if it needs to be updated
377                if self.relations.get().contains(LinkRelations::STYLESHEET) {
378                    self.handle_stylesheet_url();
379                }
380
381                // https://html.spec.whatwg.org/multipage/#link-type-preload
382                // When the type attribute of the link element of an external resource link that
383                // is already browsing-context connected, but was previously not obtained due to
384                // the type attribute specifying an unsupported type for the request destination,
385                // is set, removed, or changed.
386                if self.relations.get().contains(LinkRelations::PRELOAD) &&
387                    !self.previous_type_matched.get()
388                {
389                    self.handle_preload_url();
390                }
391            },
392            local_name!("media") => {
393                // https://html.spec.whatwg.org/multipage/#link-type-preload
394                // When the media attribute of the link element of an external resource link that
395                // is already browsing-context connected, but was previously not obtained due to
396                // the media attribute not matching the environment, is changed or removed.
397                if self.relations.get().contains(LinkRelations::PRELOAD) &&
398                    !self.previous_media_environment_matched.get()
399                {
400                    match mutation {
401                        AttributeMutation::Removed | AttributeMutation::Set(Some(_), _) => {
402                            self.handle_preload_url()
403                        },
404                        _ => {},
405                    };
406                } else if self.relations.get().contains(LinkRelations::STYLESHEET) {
407                    if let Some(ref stylesheet) = *self.stylesheet.borrow_mut() {
408                        let document = self.owner_document();
409                        let shared_lock = document.style_shared_lock().clone();
410                        let mut guard = shared_lock.write();
411                        let media = stylesheet.media.write_with(&mut guard);
412                        match mutation {
413                            AttributeMutation::Set(..) => {
414                                *media =
415                                    MediaList::parse_media_list(&attr.value(), document.window())
416                            },
417                            AttributeMutation::Removed => *media = StyleMediaList::empty(),
418                        };
419                        self.owner_document().invalidate_stylesheets();
420                    }
421                }
422
423                let matches_media_environment =
424                    MediaList::matches_environment(&self.owner_document(), &attr.value());
425                self.previous_media_environment_matched
426                    .set(matches_media_environment);
427            },
428            _ => {},
429        }
430    }
431
432    fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
433        match name {
434            &local_name!("rel") => AttrValue::from_serialized_tokenlist(value.into()),
435            _ => self
436                .super_type()
437                .unwrap()
438                .parse_plain_attribute(name, value),
439        }
440    }
441
442    fn bind_to_tree(&self, cx: &mut JSContext, context: &BindContext) {
443        if let Some(s) = self.super_type() {
444            s.bind_to_tree(cx, context);
445        }
446
447        self.relations
448            .set(LinkRelations::for_element(self.upcast()));
449
450        if context.tree_connected {
451            let element = self.upcast();
452
453            if let Some(href) = get_attr(element, &local_name!("href")) {
454                let relations = self.relations.get();
455                // https://html.spec.whatwg.org/multipage/#link-type-stylesheet:fetch-and-process-the-linked-resource
456                // > When the external resource link's link element becomes browsing-context connected.
457                if relations.contains(LinkRelations::STYLESHEET) {
458                    self.handle_stylesheet_url();
459                }
460
461                if relations.contains(LinkRelations::ICON) {
462                    self.handle_favicon_url(&href);
463                }
464
465                if relations.contains(LinkRelations::PREFETCH) {
466                    self.fetch_and_process_prefetch_link(&href);
467                }
468
469                if relations.contains(LinkRelations::PRELOAD) {
470                    self.handle_preload_url();
471                }
472
473                // https://html.spec.whatwg.org/multipage/#link-type-modulepreload
474                if relations.contains(LinkRelations::MODULE_PRELOAD) {
475                    let link = DomRoot::from_ref(self);
476                    self.owner_document().add_delayed_task(
477                        task!(FetchModulePreload: |cx, link: DomRoot<HTMLLinkElement>| {
478                            link.fetch_and_process_modulepreload(cx);
479                        }),
480                    );
481                }
482            }
483        }
484    }
485
486    fn unbind_from_tree(&self, context: &UnbindContext, can_gc: CanGc) {
487        if let Some(s) = self.super_type() {
488            s.unbind_from_tree(context, can_gc);
489        }
490
491        self.remove_stylesheet();
492    }
493}
494
495impl HTMLLinkElement {
496    fn compute_destination_for_attribute(&self) -> Option<Destination> {
497        // Let destination be the result of translating the keyword
498        // representing the state of el's as attribute.
499        let element = self.upcast::<Element>();
500        element
501            .get_attribute(&local_name!("as"))
502            .and_then(|attr| LinkProcessingOptions::translate_a_preload_destination(&attr.value()))
503    }
504
505    /// <https://html.spec.whatwg.org/multipage/#create-link-options-from-element>
506    fn processing_options(&self) -> LinkProcessingOptions {
507        let element = self.upcast::<Element>();
508
509        // Step 1. Let document be el's node document.
510        let document = self.upcast::<Node>().owner_doc();
511        let global = document.owner_global();
512
513        // Step 2. Let options be a new link processing options
514        let mut options = LinkProcessingOptions {
515            href: String::new(),
516            destination: Destination::None,
517            integrity: String::new(),
518            link_type: String::new(),
519            cryptographic_nonce_metadata: self.upcast::<Element>().nonce_value(),
520            cross_origin: cors_setting_for_element(element),
521            referrer_policy: referrer_policy_for_element(element),
522            policy_container: document.policy_container().to_owned(),
523            source_set: None, // FIXME
524            origin: document.borrow().origin().immutable().to_owned(),
525            base_url: document.borrow().base_url(),
526            insecure_requests_policy: document.insecure_requests_policy(),
527            has_trustworthy_ancestor_origin: document.has_trustworthy_ancestor_or_current_origin(),
528            request_client: global.request_client(),
529            referrer: global.get_referrer(),
530        };
531
532        // Step 3. If el has an href attribute, then set options's href to the value of el's href attribute.
533        if let Some(href_attribute) = element.get_attribute(&local_name!("href")) {
534            options.href = (**href_attribute.value()).to_owned();
535        }
536
537        // Step 4. If el has an integrity attribute, then set options's integrity
538        //         to the value of el's integrity content attribute.
539        if let Some(integrity_attribute) = element.get_attribute(&local_name!("integrity")) {
540            options.integrity = (**integrity_attribute.value()).to_owned();
541        }
542
543        // Step 5. If el has a type attribute, then set options's type to the value of el's type attribute.
544        if let Some(type_attribute) = element.get_attribute(&local_name!("type")) {
545            options.link_type = (**type_attribute.value()).to_owned();
546        }
547
548        // Step 6. Assert: options's href is not the empty string, or options's source set is not null.
549        assert!(!options.href.is_empty() || options.source_set.is_some());
550
551        // Step 7. Return options.
552        options
553    }
554
555    /// <https://html.spec.whatwg.org/multipage/#default-fetch-and-process-the-linked-resource>
556    ///
557    /// This method does not implement Step 7 (fetching the request) and instead returns the [RequestBuilder],
558    /// as the fetch context that should be used depends on the link type.
559    fn default_fetch_and_process_the_linked_resource(&self) -> Option<RequestBuilder> {
560        // Step 1. Let options be the result of creating link options from el.
561        let options = self.processing_options();
562
563        // Step 2. Let request be the result of creating a link request given options.
564        let Some(request) = options.create_link_request(self.owner_window().webview_id()) else {
565            // Step 3. If request is null, then return.
566            return None;
567        };
568        // Step 4. Set request's synchronous flag.
569        let mut request = request.synchronous(true);
570
571        // Step 5. Run the linked resource fetch setup steps, given el and request. If the result is false, then return.
572        if !self.linked_resource_fetch_setup(&mut request) {
573            return None;
574        }
575
576        // TODO Step 6. Set request's initiator type to "css" if el's rel attribute
577        // contains the keyword stylesheet; "link" otherwise.
578
579        // Step 7. Fetch request with processResponseConsumeBody set to the following steps given response response and null,
580        // failure, or a byte sequence bodyBytes: [..]
581        Some(request)
582    }
583
584    /// <https://html.spec.whatwg.org/multipage/#linked-resource-fetch-setup-steps>
585    fn linked_resource_fetch_setup(&self, request: &mut RequestBuilder) -> bool {
586        // https://html.spec.whatwg.org/multipage/#rel-icon:linked-resource-fetch-setup-steps
587        if self.relations.get().contains(LinkRelations::ICON) {
588            // Step 1. Set request's destination to "image".
589            request.destination = Destination::Image;
590
591            // Step 2. Return true.
592            //
593            // Fall-through
594        }
595
596        // https://html.spec.whatwg.org/multipage/#link-type-stylesheet:linked-resource-fetch-setup-steps
597        if self.relations.get().contains(LinkRelations::STYLESHEET) {
598            // Step 1. If el's disabled attribute is set, then return false.
599            if self
600                .upcast::<Element>()
601                .has_attribute(&local_name!("disabled"))
602            {
603                return false;
604            }
605            // Step 2. If el contributes a script-blocking style sheet, append el to its node document's script-blocking style sheet set.
606            //
607            // Implemented in `ElementStylesheetLoader::load_with_element`.
608
609            // Step 3. If el's media attribute's value matches the environment and el is potentially render-blocking, then block rendering on el.
610            //
611            // Implemented in `ElementStylesheetLoader::load_with_element`.
612
613            // Step 4. If el is currently render-blocking, then set request's render-blocking to true.
614            // TODO
615
616            // Step 5. Return true.
617            //
618            // Fall-through
619        }
620
621        true
622    }
623
624    /// The `fetch and process the linked resource` algorithm for [`rel="prefetch"`](https://html.spec.whatwg.org/multipage/#link-type-prefetch)
625    fn fetch_and_process_prefetch_link(&self, href: &str) {
626        // Step 1. If el's href attribute's value is the empty string, then return.
627        if href.is_empty() {
628            return;
629        }
630
631        // Step 2. Let options be the result of creating link options from el.
632        let mut options = self.processing_options();
633
634        // Step 3. Set options's destination to the empty string.
635        options.destination = Destination::None;
636
637        // Step 4. Let request be the result of creating a link request given options.
638        let Some(request) = options.create_link_request(self.owner_window().webview_id()) else {
639            // Step 5. If request is null, then return.
640            return;
641        };
642        let url = request.url.url();
643
644        // Step 6. Set request's initiator to "prefetch".
645        let request = request.initiator(Initiator::Prefetch);
646
647        // (Step 7, firing load/error events is handled in the FetchResponseListener impl for LinkFetchContext)
648
649        // Step 8. The user agent should fetch request, with processResponseConsumeBody set to processPrefetchResponse.
650        let document = self.upcast::<Node>().owner_doc();
651        let fetch_context = LinkFetchContext {
652            url,
653            link: Some(Trusted::new(self)),
654            document: Trusted::new(&document),
655            global: Trusted::new(&document.global()),
656            type_: LinkFetchContextType::Prefetch,
657            response_body: vec![],
658        };
659
660        document.fetch_background(request, fetch_context);
661    }
662
663    /// <https://html.spec.whatwg.org/multipage/#concept-link-obtain>
664    fn handle_stylesheet_url(&self) {
665        let document = self.owner_document();
666        if document.browsing_context().is_none() {
667            return;
668        }
669
670        let element = self.upcast::<Element>();
671
672        // https://html.spec.whatwg.org/multipage/#processing-the-type-attribute
673        // > If the UA does not support the given MIME type for the given link relationship,
674        // > then the UA should not fetch and process the linked resource
675        //
676        // https://html.spec.whatwg.org/multipage/#link-type-stylesheet
677        // > The default type for resources given by the stylesheet keyword is text/css.
678        let type_ = element.get_string_attribute(&local_name!("type"));
679        if !type_.is_empty() && type_ != "text/css" {
680            return;
681        }
682
683        // Step 1.
684        let href = element.get_string_attribute(&local_name!("href"));
685        if href.is_empty() {
686            return;
687        }
688
689        // Step 2.
690        let link_url = match document.base_url().join(&href.str()) {
691            Ok(url) => url,
692            Err(e) => {
693                debug!("Parsing url {} failed: {}", href, e);
694                return;
695            },
696        };
697
698        // Step 3
699        let cors_setting = cors_setting_for_element(element);
700
701        let mq_attribute = element.get_attribute(&local_name!("media"));
702        let value = mq_attribute.as_ref().map(|a| a.value());
703        let mq_str = match value {
704            Some(ref value) => &***value,
705            None => "",
706        };
707
708        let media = MediaList::parse_media_list(mq_str, document.window());
709        let media = Arc::new(document.style_shared_lock().wrap(media));
710
711        let im_attribute = element.get_attribute(&local_name!("integrity"));
712        let integrity_val = im_attribute.as_ref().map(|a| a.value());
713        let integrity_metadata = match integrity_val {
714            Some(ref value) => &***value,
715            None => "",
716        };
717
718        self.request_generation_id
719            .set(self.request_generation_id.get().increment());
720        self.pending_loads.set(0);
721
722        ElementStylesheetLoader::load_with_element(
723            self.upcast(),
724            StylesheetContextSource::LinkElement,
725            media,
726            link_url,
727            cors_setting,
728            integrity_metadata.to_owned(),
729        );
730    }
731
732    /// <https://html.spec.whatwg.org/multipage/#attr-link-disabled>
733    fn handle_disabled_attribute_change(&self, is_removal: bool) {
734        // > Whenever the disabled attribute is removed, set the link element's explicitly enabled attribute to true.
735        if is_removal {
736            self.is_explicitly_enabled.set(true);
737        }
738        if let Some(stylesheet) = self.get_stylesheet() {
739            if stylesheet.set_disabled(!is_removal) {
740                self.stylesheet_list_owner().invalidate_stylesheets();
741            }
742        }
743    }
744
745    fn handle_favicon_url(&self, href: &str) {
746        // If el's href attribute's value is the empty string, then return.
747        if href.is_empty() {
748            return;
749        }
750
751        // The spec does not specify this, but we don't fetch favicons for iframes, as
752        // they won't be displayed anyways.
753        let window = self.owner_window();
754        if !window.is_top_level() {
755            return;
756        }
757        let Ok(href) = self.Href().parse() else {
758            return;
759        };
760
761        // Ignore all previous fetch operations
762        self.request_generation_id
763            .set(self.request_generation_id.get().increment());
764
765        let cache_result = window.image_cache().get_cached_image_status(
766            href,
767            window.origin().immutable().clone(),
768            cors_setting_for_element(self.upcast()),
769        );
770
771        match cache_result {
772            ImageCacheResult::Available(ImageOrMetadataAvailable::ImageAvailable {
773                image, ..
774            }) => {
775                self.process_favicon_response(image);
776            },
777            ImageCacheResult::Available(ImageOrMetadataAvailable::MetadataAvailable(_, id)) |
778            ImageCacheResult::Pending(id) => {
779                let sender = self.register_image_cache_callback(id);
780                window.image_cache().add_listener(ImageLoadListener::new(
781                    sender,
782                    window.pipeline_id(),
783                    id,
784                ));
785            },
786            ImageCacheResult::ReadyForRequest(id) => {
787                let Some(request) = self.default_fetch_and_process_the_linked_resource() else {
788                    return;
789                };
790
791                let sender = self.register_image_cache_callback(id);
792                window.image_cache().add_listener(ImageLoadListener::new(
793                    sender,
794                    window.pipeline_id(),
795                    id,
796                ));
797
798                let document = self.upcast::<Node>().owner_doc();
799                let fetch_context = FaviconFetchContext {
800                    url: self.owner_document().base_url(),
801                    image_cache: window.image_cache(),
802                    id,
803                    link: Trusted::new(self),
804                };
805                document.fetch_background(request, fetch_context);
806            },
807            ImageCacheResult::FailedToLoadOrDecode => {},
808        };
809    }
810
811    fn register_image_cache_callback(&self, id: PendingImageId) -> ImageCacheResponseCallback {
812        let trusted_node = Trusted::new(self);
813        let window = self.owner_window();
814        let request_generation_id = self.get_request_generation_id();
815        window.register_image_cache_listener(id, move |response, _| {
816            let trusted_node = trusted_node.clone();
817            let link_element = trusted_node.root();
818            let window = link_element.owner_window();
819
820            let ImageResponse::Loaded(image, _) = response.response else {
821                // We don't care about metadata and such for favicons.
822                return;
823            };
824
825            if request_generation_id != link_element.get_request_generation_id() {
826                // This load is no longer relevant.
827                return;
828            };
829
830            window
831                .as_global_scope()
832                .task_manager()
833                .networking_task_source()
834                .queue(task!(process_favicon_response: move || {
835                    let element = trusted_node.root();
836
837                    if request_generation_id != element.get_request_generation_id() {
838                        // This load is no longer relevant.
839                        return;
840                    };
841
842                    element.process_favicon_response(image);
843                }));
844        })
845    }
846
847    /// Rasterizes a loaded favicon file if necessary and notifies the embedder about it.
848    fn process_favicon_response(&self, image: Image) {
849        // TODO: Include the size attribute here
850        let window = self.owner_window();
851        let document = self.owner_document();
852
853        let send_rasterized_favicon_to_embedder = |raster_image: &pixels::RasterImage| {
854            // Let's not worry about animated favicons...
855            let frame = raster_image.first_frame();
856
857            let format = match raster_image.format {
858                PixelFormat::K8 => embedder_traits::PixelFormat::K8,
859                PixelFormat::KA8 => embedder_traits::PixelFormat::KA8,
860                PixelFormat::RGB8 => embedder_traits::PixelFormat::RGB8,
861                PixelFormat::RGBA8 => embedder_traits::PixelFormat::RGBA8,
862                PixelFormat::BGRA8 => embedder_traits::PixelFormat::BGRA8,
863            };
864
865            let embedder_image = embedder_traits::Image::new(
866                frame.width,
867                frame.height,
868                std::sync::Arc::new(GenericSharedMemory::from_bytes(&raster_image.bytes)),
869                raster_image.frames[0].byte_range.clone(),
870                format,
871            );
872            document.set_favicon(embedder_image);
873        };
874
875        match image {
876            Image::Raster(raster_image) => send_rasterized_favicon_to_embedder(&raster_image),
877            Image::Vector(vector_image) => {
878                // This size is completely arbitrary.
879                let size = DeviceIntSize::new(250, 250);
880
881                let image_cache = window.image_cache();
882                if let Some(raster_image) =
883                    image_cache.rasterize_vector_image(vector_image.id, size, None)
884                {
885                    send_rasterized_favicon_to_embedder(&raster_image);
886                } else {
887                    // The rasterization callback will end up calling "process_favicon_response" again,
888                    // but this time with a raster image.
889                    let image_cache_sender = self.register_image_cache_callback(vector_image.id);
890                    image_cache.add_rasterization_complete_listener(
891                        window.pipeline_id(),
892                        vector_image.id,
893                        size,
894                        image_cache_sender,
895                    );
896                }
897            },
898        }
899    }
900
901    /// <https://html.spec.whatwg.org/multipage/#link-type-preload:fetch-and-process-the-linked-resource-2>
902    /// and type matching destination steps of <https://html.spec.whatwg.org/multipage/#preload>
903    fn handle_preload_url(&self) {
904        // Step 1. Update the source set for el.
905        // TODO
906        // Step 2. Let options be the result of creating link options from el.
907        let mut options = self.processing_options();
908        // Step 3. Let destination be the result of translating the keyword
909        // representing the state of el's as attribute.
910        let Some(destination) = self.compute_destination_for_attribute() else {
911            // Step 4. If destination is null, then return.
912            return;
913        };
914        // Step 5. Set options's destination to destination.
915        options.destination = destination;
916        // Steps for https://html.spec.whatwg.org/multipage/#preload
917        {
918            // Step 1. If options's type doesn't match options's destination, then return.
919            let type_matches_destination = options.type_matches_destination();
920            self.previous_type_matched.set(type_matches_destination);
921            if !type_matches_destination {
922                return;
923            }
924        }
925        // Step 6. Preload options, with the following steps given a response response:
926        let document = self.upcast::<Node>().owner_doc();
927        options.preload(
928            self.owner_window().webview_id(),
929            Some(Trusted::new(self)),
930            &document,
931        );
932    }
933
934    /// <https://html.spec.whatwg.org/multipage/#link-type-preload:fetch-and-process-the-linked-resource-2>
935    pub(crate) fn fire_event_after_response(
936        &self,
937        response: Result<(), NetworkError>,
938        can_gc: CanGc,
939    ) {
940        // Step 3.1 If response is a network error, fire an event named error at el.
941        // Otherwise, fire an event named load at el.
942        if response.is_err() {
943            self.upcast::<EventTarget>()
944                .fire_event(atom!("error"), can_gc);
945        } else {
946            self.upcast::<EventTarget>()
947                .fire_event(atom!("load"), can_gc);
948        }
949    }
950
951    /// <https://html.spec.whatwg.org/multipage/#link-type-modulepreload:fetch-and-process-the-linked-resource-2>
952    fn fetch_and_process_modulepreload(&self, cx: &mut JSContext) {
953        let el = self.upcast::<Element>();
954        let href_attribute_value = el.get_string_attribute(&local_name!("href"));
955
956        // Step 1. If el's href attribute's value is the empty string, then return.
957        if href_attribute_value.is_empty() {
958            return;
959        }
960
961        // Step 2. Let destination be the current state of el's as attribute (a destination), or "script" if it is in no state.
962        let destination = el
963            .get_attribute(&local_name!("as"))
964            .map(|attr| attr.value().to_ascii_lowercase())
965            .and_then(|value| match value.as_str() {
966                // `Destination::from_str` will map an empty string to `Destination::None`
967                "" => None,
968                // "fetch" is a valid preload destination, but not for modules
969                "fetch" => Some(Destination::None),
970                _ => Destination::from_str(&value).ok(),
971            })
972            .unwrap_or(Destination::Script);
973
974        let document = self.owner_document();
975        let global = document.global();
976
977        // A module preload destination is "json", "style", or a script-like destination.
978        let is_a_modulepreload_destination = match destination {
979            Destination::Json | Destination::Style => true,
980            // https://fetch.spec.whatwg.org/#ref-for-request-destination-script-like
981            // While "xslt" can cause script execution, it is not relevant here.
982            Destination::Xslt => false,
983            d => d.is_script_like(),
984        };
985
986        // Step 3. If destination is not a module preload destination, then queue an element task on the
987        // networking task source given el to fire an event named error at el, and return.
988        if !is_a_modulepreload_destination {
989            return global
990                .task_manager()
991                .networking_task_source()
992                .queue_simple_event(self.upcast(), atom!("error"));
993        }
994
995        // Step 4. Let url be the result of encoding-parsing a URL given el's href attribute's value, relative to el's node document.
996        // Step 5. If url is failure, then return.
997        let Ok(url) = document.encoding_parse_a_url(&href_attribute_value.str()) else {
998            return;
999        };
1000
1001        // Step 6. Let settings object be el's node document's relevant settings object.
1002
1003        // Step 7. Let credentials mode be the CORS settings attribute credentials mode for el's crossorigin attribute.
1004        let credentials_mode = cors_settings_attribute_credential_mode(el);
1005
1006        // Step 8. Let cryptographic nonce be el.[[CryptographicNonce]].
1007        let cryptographic_nonce = el.nonce_value();
1008
1009        // Step 9. Let integrity metadata be the value of el's integrity attribute, if it is specified, or the empty string otherwise.
1010        let integrity_attribute = el.get_attribute(&local_name!("integrity"));
1011        let integrity_value = integrity_attribute.as_ref().map(|attr| attr.value());
1012        let integrity_metadata = match integrity_value {
1013            Some(ref value) => (***value).to_owned(),
1014            // Step 10. If el does not have an integrity attribute, then set integrity metadata to
1015            // the result of resolving a module integrity metadata with url and settings object.
1016            None => global
1017                .import_map()
1018                .resolve_a_module_integrity_metadata(&url),
1019        };
1020
1021        // Step 11. Let referrer policy be the current state of el's referrerpolicy attribute.
1022        let referrer_policy = referrer_policy_for_element(el);
1023
1024        // TODO Step 12. Let fetch priority be the current state of el's fetchpriority attribute.
1025
1026        // Step 13. Let options be a script fetch options whose cryptographic nonce is cryptographic nonce,
1027        // integrity metadata is integrity metadata, parser metadata is "not-parser-inserted",
1028        // credentials mode is credentials mode, referrer policy is referrer policy, and fetch priority is fetch priority.
1029        let options = ScriptFetchOptions {
1030            cryptographic_nonce,
1031            integrity_metadata,
1032            parser_metadata: ParserMetadata::NotParserInserted,
1033            credentials_mode,
1034            referrer_policy,
1035            render_blocking: false,
1036        };
1037
1038        let link = DomRoot::from_ref(self);
1039
1040        // Step 14. Fetch a modulepreload module script graph given url, destination, settings object, options,
1041        // and with the following steps given result:
1042        fetch_a_modulepreload_module(
1043            cx,
1044            url,
1045            destination,
1046            &global,
1047            options,
1048            move |cx, fetch_failed| {
1049                // Step 1. If result is null, then fire an event named error at el, and return.
1050                // Step 2. Fire an event named load at el.
1051                let event = match fetch_failed {
1052                    true => atom!("error"),
1053                    false => atom!("load"),
1054                };
1055
1056                link.upcast::<EventTarget>()
1057                    .fire_event(event, CanGc::from_cx(cx));
1058            },
1059        );
1060    }
1061}
1062
1063impl StylesheetOwner for HTMLLinkElement {
1064    fn increment_pending_loads_count(&self) {
1065        self.pending_loads.set(self.pending_loads.get() + 1)
1066    }
1067
1068    fn load_finished(&self, succeeded: bool) -> Option<bool> {
1069        assert!(self.pending_loads.get() > 0, "What finished?");
1070        if !succeeded {
1071            self.any_failed_load.set(true);
1072        }
1073
1074        self.pending_loads.set(self.pending_loads.get() - 1);
1075        if self.pending_loads.get() != 0 {
1076            return None;
1077        }
1078
1079        let any_failed = self.any_failed_load.get();
1080        self.any_failed_load.set(false);
1081        Some(any_failed)
1082    }
1083
1084    fn parser_inserted(&self) -> bool {
1085        self.parser_inserted.get()
1086    }
1087
1088    /// <https://html.spec.whatwg.org/multipage/#potentially-render-blocking>
1089    fn potentially_render_blocking(&self) -> bool {
1090        // An element is potentially render-blocking if its blocking tokens set contains "render",
1091        // or if it is implicitly potentially render-blocking, which will be defined at the individual elements.
1092        // By default, an element is not implicitly potentially render-blocking.
1093        //
1094        // https://html.spec.whatwg.org/multipage/#link-type-stylesheet:implicitly-potentially-render-blocking
1095        // > A link element of this type is implicitly potentially render-blocking if the element was created by its node document's parser.
1096        self.parser_inserted() ||
1097            self.blocking
1098                .get()
1099                .is_some_and(|list| list.Contains("render".into()))
1100    }
1101
1102    fn referrer_policy(&self) -> ReferrerPolicy {
1103        if self.RelList(CanGc::note()).Contains("noreferrer".into()) {
1104            return ReferrerPolicy::NoReferrer;
1105        }
1106
1107        ReferrerPolicy::EmptyString
1108    }
1109
1110    fn set_origin_clean(&self, origin_clean: bool) {
1111        if let Some(stylesheet) = self.get_cssom_stylesheet(CanGc::note()) {
1112            stylesheet.set_origin_clean(origin_clean);
1113        }
1114    }
1115}
1116
1117impl HTMLLinkElementMethods<crate::DomTypeHolder> for HTMLLinkElement {
1118    // https://html.spec.whatwg.org/multipage/#dom-link-href
1119    make_url_getter!(Href, "href");
1120
1121    // https://html.spec.whatwg.org/multipage/#dom-link-href
1122    make_url_setter!(SetHref, "href");
1123
1124    // https://html.spec.whatwg.org/multipage/#dom-link-rel
1125    make_getter!(Rel, "rel");
1126
1127    /// <https://html.spec.whatwg.org/multipage/#dom-link-rel>
1128    fn SetRel(&self, rel: DOMString, can_gc: CanGc) {
1129        self.upcast::<Element>()
1130            .set_tokenlist_attribute(&local_name!("rel"), rel, can_gc);
1131    }
1132
1133    // https://html.spec.whatwg.org/multipage/#dom-link-as
1134    make_enumerated_getter!(
1135        As,
1136        "as",
1137        "fetch" | "audio" | "audioworklet" | "document" | "embed" | "font" | "frame"
1138            | "iframe" | "image" | "json" | "manifest" | "object" | "paintworklet"
1139            | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "track"
1140            | "video" | "webidentity" | "worker" | "xslt",
1141        missing => "",
1142        invalid => ""
1143    );
1144
1145    // https://html.spec.whatwg.org/multipage/#dom-link-as
1146    make_setter!(SetAs, "as");
1147
1148    // https://html.spec.whatwg.org/multipage/#dom-link-media
1149    make_getter!(Media, "media");
1150
1151    // https://html.spec.whatwg.org/multipage/#dom-link-media
1152    make_setter!(SetMedia, "media");
1153
1154    // https://html.spec.whatwg.org/multipage/#dom-link-integrity
1155    make_getter!(Integrity, "integrity");
1156
1157    // https://html.spec.whatwg.org/multipage/#dom-link-integrity
1158    make_setter!(SetIntegrity, "integrity");
1159
1160    // https://html.spec.whatwg.org/multipage/#dom-link-hreflang
1161    make_getter!(Hreflang, "hreflang");
1162
1163    // https://html.spec.whatwg.org/multipage/#dom-link-hreflang
1164    make_setter!(SetHreflang, "hreflang");
1165
1166    // https://html.spec.whatwg.org/multipage/#dom-link-type
1167    make_getter!(Type, "type");
1168
1169    // https://html.spec.whatwg.org/multipage/#dom-link-type
1170    make_setter!(SetType, "type");
1171
1172    // https://html.spec.whatwg.org/multipage/#dom-link-disabled
1173    make_bool_getter!(Disabled, "disabled");
1174
1175    // https://html.spec.whatwg.org/multipage/#dom-link-disabled
1176    make_bool_setter!(SetDisabled, "disabled");
1177
1178    /// <https://html.spec.whatwg.org/multipage/#dom-link-rellist>
1179    fn RelList(&self, can_gc: CanGc) -> DomRoot<DOMTokenList> {
1180        self.rel_list.or_init(|| {
1181            DOMTokenList::new(
1182                self.upcast(),
1183                &local_name!("rel"),
1184                Some(vec![
1185                    Atom::from("alternate"),
1186                    Atom::from("apple-touch-icon"),
1187                    Atom::from("apple-touch-icon-precomposed"),
1188                    Atom::from("canonical"),
1189                    Atom::from("dns-prefetch"),
1190                    Atom::from("icon"),
1191                    Atom::from("import"),
1192                    Atom::from("manifest"),
1193                    Atom::from("modulepreload"),
1194                    Atom::from("next"),
1195                    Atom::from("preconnect"),
1196                    Atom::from("prefetch"),
1197                    Atom::from("preload"),
1198                    Atom::from("prerender"),
1199                    Atom::from("stylesheet"),
1200                ]),
1201                can_gc,
1202            )
1203        })
1204    }
1205
1206    // https://html.spec.whatwg.org/multipage/#dom-link-charset
1207    make_getter!(Charset, "charset");
1208
1209    // https://html.spec.whatwg.org/multipage/#dom-link-charset
1210    make_setter!(SetCharset, "charset");
1211
1212    // https://html.spec.whatwg.org/multipage/#dom-link-rev
1213    make_getter!(Rev, "rev");
1214
1215    // https://html.spec.whatwg.org/multipage/#dom-link-rev
1216    make_setter!(SetRev, "rev");
1217
1218    // https://html.spec.whatwg.org/multipage/#dom-link-target
1219    make_getter!(Target, "target");
1220
1221    // https://html.spec.whatwg.org/multipage/#dom-link-target
1222    make_setter!(SetTarget, "target");
1223
1224    /// <https://html.spec.whatwg.org/multipage/#attr-link-blocking>
1225    fn Blocking(&self, can_gc: CanGc) -> DomRoot<DOMTokenList> {
1226        self.blocking.or_init(|| {
1227            DOMTokenList::new(
1228                self.upcast(),
1229                &local_name!("blocking"),
1230                Some(vec![Atom::from("render")]),
1231                can_gc,
1232            )
1233        })
1234    }
1235
1236    /// <https://html.spec.whatwg.org/multipage/#dom-link-crossorigin>
1237    fn GetCrossOrigin(&self) -> Option<DOMString> {
1238        reflect_cross_origin_attribute(self.upcast::<Element>())
1239    }
1240
1241    /// <https://html.spec.whatwg.org/multipage/#dom-link-crossorigin>
1242    fn SetCrossOrigin(&self, cx: &mut JSContext, value: Option<DOMString>) {
1243        set_cross_origin_attribute(cx, self.upcast::<Element>(), value);
1244    }
1245
1246    /// <https://html.spec.whatwg.org/multipage/#dom-link-referrerpolicy>
1247    fn ReferrerPolicy(&self) -> DOMString {
1248        reflect_referrer_policy_attribute(self.upcast::<Element>())
1249    }
1250
1251    // https://html.spec.whatwg.org/multipage/#dom-link-referrerpolicy
1252    make_setter!(SetReferrerPolicy, "referrerpolicy");
1253
1254    /// <https://drafts.csswg.org/cssom/#dom-linkstyle-sheet>
1255    fn GetSheet(&self, can_gc: CanGc) -> Option<DomRoot<DOMStyleSheet>> {
1256        self.get_cssom_stylesheet(can_gc).map(DomRoot::upcast)
1257    }
1258}
1259
1260struct FaviconFetchContext {
1261    /// The `<link>` element that caused this fetch operation
1262    link: Trusted<HTMLLinkElement>,
1263    image_cache: std::sync::Arc<dyn ImageCache>,
1264    id: PendingImageId,
1265
1266    /// The base url of the document that the `<link>` element belongs to.
1267    url: ServoUrl,
1268}
1269
1270impl FetchResponseListener for FaviconFetchContext {
1271    fn process_request_body(&mut self, _: RequestId) {}
1272
1273    fn process_response(
1274        &mut self,
1275        _: &mut js::context::JSContext,
1276        request_id: RequestId,
1277        metadata: Result<FetchMetadata, NetworkError>,
1278    ) {
1279        self.image_cache.notify_pending_response(
1280            self.id,
1281            FetchResponseMsg::ProcessResponse(request_id, metadata),
1282        );
1283    }
1284
1285    fn process_response_chunk(
1286        &mut self,
1287        _: &mut js::context::JSContext,
1288        request_id: RequestId,
1289        chunk: Vec<u8>,
1290    ) {
1291        self.image_cache.notify_pending_response(
1292            self.id,
1293            FetchResponseMsg::ProcessResponseChunk(request_id, chunk.into()),
1294        );
1295    }
1296
1297    fn process_response_eof(
1298        self,
1299        cx: &mut js::context::JSContext,
1300        request_id: RequestId,
1301        response: Result<(), NetworkError>,
1302        timing: ResourceFetchTiming,
1303    ) {
1304        self.image_cache.notify_pending_response(
1305            self.id,
1306            FetchResponseMsg::ProcessResponseEOF(request_id, response.clone(), timing.clone()),
1307        );
1308        submit_timing(cx, &self, &response, &timing);
1309    }
1310
1311    fn process_csp_violations(&mut self, _request_id: RequestId, violations: Vec<Violation>) {
1312        let global = &self.resource_timing_global();
1313        global.report_csp_violations(violations, None, None);
1314    }
1315}
1316
1317impl ResourceTimingListener for FaviconFetchContext {
1318    fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
1319        (
1320            InitiatorType::LocalName("link".to_string()),
1321            self.url.clone(),
1322        )
1323    }
1324
1325    fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
1326        self.link.root().upcast::<Node>().owner_doc().global()
1327    }
1328}