Skip to main content

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