Skip to main content

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