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();
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(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(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();
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();
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()
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();
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_value(&local_name!("as"))
525            .and_then(|attr| LinkProcessingOptions::translate_a_preload_destination(&attr))
526    }
527
528    /// <https://html.spec.whatwg.org/multipage/#create-link-options-from-element>
529    fn processing_options(&self) -> LinkProcessingOptions {
530        let element = self.upcast::<Element>();
531
532        // Step 1. Let document be el's node document.
533        let document = self.upcast::<Node>().owner_doc();
534        let global = document.owner_global();
535
536        // Step 2. Let options be a new link processing options
537        let mut options = LinkProcessingOptions {
538            href: String::new(),
539            destination: Destination::None,
540            integrity: String::new(),
541            link_type: String::new(),
542            cryptographic_nonce_metadata: self.upcast::<Element>().nonce_value(),
543            cross_origin: cors_setting_for_element(element),
544            referrer_policy: referrer_policy_for_element(element),
545            policy_container: document.policy_container().to_owned(),
546            source_set: Some(self.source_set.borrow().clone()),
547            origin: document.borrow().origin().immutable().to_owned(),
548            base_url: document.borrow().base_url(),
549            request_client: global.request_client(None),
550            referrer: global.get_referrer(),
551        };
552
553        // Step 3. If el has an href attribute, then set options's href to the value of el's href attribute.
554        if let Some(href_attribute) = element.get_attribute_string_value(&local_name!("href")) {
555            options.href = href_attribute;
556        }
557
558        // Step 4. If el has an integrity attribute, then set options's integrity
559        //         to the value of el's integrity content attribute.
560        if let Some(integrity_attribute) =
561            element.get_attribute_string_value(&local_name!("integrity"))
562        {
563            options.integrity = integrity_attribute;
564        }
565
566        // Step 5. If el has a type attribute, then set options's type to the value of el's type attribute.
567        if let Some(type_attribute) = element.get_attribute_string_value(&local_name!("type")) {
568            options.link_type = type_attribute;
569        }
570
571        // Step 6. Assert: options's href is not the empty string, or options's source set is not null.
572        assert!(!options.href.is_empty() || options.source_set.is_some());
573
574        // Step 7. Return options.
575        options
576    }
577
578    /// <https://html.spec.whatwg.org/multipage/#default-fetch-and-process-the-linked-resource>
579    ///
580    /// This method does not implement Step 7 (fetching the request) and instead returns the [RequestBuilder],
581    /// as the fetch context that should be used depends on the link type.
582    fn default_fetch_and_process_the_linked_resource(&self) -> Option<RequestBuilder> {
583        // Step 1. Let options be the result of creating link options from el.
584        let options = self.processing_options();
585
586        // Step 2. Let request be the result of creating a link request given options.
587        let Some(request) = options.create_link_request(self.owner_window().webview_id()) else {
588            // Step 3. If request is null, then return.
589            return None;
590        };
591        // Step 4. Set request's synchronous flag.
592        let mut request = request.synchronous(true);
593
594        // Step 5. Run the linked resource fetch setup steps, given el and request. If the result is false, then return.
595        if !self.linked_resource_fetch_setup(&mut request) {
596            return None;
597        }
598
599        // TODO Step 6. Set request's initiator type to "css" if el's rel attribute
600        // contains the keyword stylesheet; "link" otherwise.
601
602        // Step 7. Fetch request with processResponseConsumeBody set to the following steps given response response and null,
603        // failure, or a byte sequence bodyBytes: [..]
604        Some(request)
605    }
606
607    /// <https://html.spec.whatwg.org/multipage/#linked-resource-fetch-setup-steps>
608    fn linked_resource_fetch_setup(&self, request: &mut RequestBuilder) -> bool {
609        // https://html.spec.whatwg.org/multipage/#rel-icon:linked-resource-fetch-setup-steps
610        if self.relations.get().contains(LinkRelations::ICON) {
611            // Step 1. Set request's destination to "image".
612            request.destination = Destination::Image;
613
614            // Step 2. Return true.
615            //
616            // Fall-through
617        }
618
619        // https://html.spec.whatwg.org/multipage/#link-type-stylesheet:linked-resource-fetch-setup-steps
620        if self.relations.get().contains(LinkRelations::STYLESHEET) {
621            // Step 1. If el's disabled attribute is set, then return false.
622            if self
623                .upcast::<Element>()
624                .has_attribute(&local_name!("disabled"))
625            {
626                return false;
627            }
628            // Step 2. If el contributes a script-blocking style sheet, append el to its node document's script-blocking style sheet set.
629            //
630            // Implemented in `ElementStylesheetLoader::load_with_element`.
631
632            // Step 3. If el's media attribute's value matches the environment and el is potentially render-blocking, then block rendering on el.
633            //
634            // Implemented in `ElementStylesheetLoader::load_with_element`.
635
636            // Step 4. If el is currently render-blocking, then set request's render-blocking to true.
637            // TODO
638
639            // Step 5. Return true.
640            //
641            // Fall-through
642        }
643
644        true
645    }
646
647    /// The `fetch and process the linked resource` algorithm for [`rel="prefetch"`](https://html.spec.whatwg.org/multipage/#link-type-prefetch)
648    fn fetch_and_process_prefetch_link(&self, href: &str) {
649        // Step 1. If el's href attribute's value is the empty string, then return.
650        if href.is_empty() {
651            return;
652        }
653
654        // Step 2. Let options be the result of creating link options from el.
655        let mut options = self.processing_options();
656
657        // Step 3. Set options's destination to the empty string.
658        options.destination = Destination::None;
659
660        // Step 4. Let request be the result of creating a link request given options.
661        let Some(request) = options.create_link_request(self.owner_window().webview_id()) else {
662            // Step 5. If request is null, then return.
663            return;
664        };
665        let url = request.url.url();
666
667        // Step 6. Set request's initiator to "prefetch".
668        let request = request.initiator(Initiator::Prefetch);
669
670        // (Step 7, firing load/error events is handled in the FetchResponseListener impl for LinkFetchContext)
671
672        // Step 8. The user agent should fetch request, with processResponseConsumeBody set to processPrefetchResponse.
673        let document = self.upcast::<Node>().owner_doc();
674        let fetch_context = LinkFetchContext {
675            url,
676            link: Some(Trusted::new(self)),
677            global: Trusted::new(&document.global()),
678            type_: LinkFetchContextType::Prefetch,
679            response_body: BytesMut::new(),
680        };
681
682        document.fetch_background(request, fetch_context);
683    }
684
685    /// <https://html.spec.whatwg.org/multipage/#concept-link-obtain>
686    fn handle_stylesheet_url(&self, cx: &mut js::context::JSContext) {
687        let document = self.owner_document();
688        if document.browsing_context().is_none() {
689            return;
690        }
691
692        let element = self.upcast::<Element>();
693
694        // https://html.spec.whatwg.org/multipage/#processing-the-type-attribute
695        // > If the UA does not support the given MIME type for the given link relationship,
696        // > then the UA should not fetch and process the linked resource
697        //
698        // https://html.spec.whatwg.org/multipage/#link-type-stylesheet
699        // > The default type for resources given by the stylesheet keyword is text/css.
700        let type_ = element.get_string_attribute(&local_name!("type"));
701        if !type_.is_empty() && type_ != "text/css" {
702            return;
703        }
704
705        // Step 1.
706        let href = element.get_string_attribute(&local_name!("href"));
707        if href.is_empty() {
708            return;
709        }
710
711        // Step 2.
712        let link_url = match document.base_url().join(&href.str()) {
713            Ok(url) => url,
714            Err(e) => {
715                debug!("Parsing url {} failed: {}", href, e);
716                return;
717            },
718        };
719
720        // Step 3
721        let cors_setting = cors_setting_for_element(element);
722
723        let mq_str = element
724            .get_attribute_string_value(&local_name!("media"))
725            .unwrap_or_default();
726        let media = MediaList::parse_media_list(&mq_str, document.window());
727        let media = Arc::new(document.style_shared_author_lock().wrap(media));
728
729        let integrity_metadata = element
730            .get_attribute_string_value(&local_name!("integrity"))
731            .unwrap_or_default();
732
733        self.request_generation_id
734            .set(self.request_generation_id.get().increment());
735        self.pending_loads.set(0);
736
737        ElementStylesheetLoader::load_with_element(
738            cx,
739            self.upcast(),
740            StylesheetContextSource::LinkElement,
741            media,
742            link_url,
743            cors_setting,
744            integrity_metadata,
745        );
746    }
747
748    /// <https://html.spec.whatwg.org/multipage/#attr-link-disabled>
749    fn handle_disabled_attribute_change(&self, no_gc: &NoGC, is_removal: bool) {
750        // > Whenever the disabled attribute is removed, set the link element's explicitly enabled attribute to true.
751        if is_removal {
752            self.is_explicitly_enabled.set(true);
753        }
754        if let Some(stylesheet) = self.get_stylesheet() &&
755            stylesheet.set_disabled(!is_removal)
756        {
757            self.stylesheet_list_owner().invalidate_stylesheets(no_gc);
758        }
759    }
760
761    fn handle_favicon_url(&self, href: &str) {
762        // If el's href attribute's value is the empty string, then return.
763        if href.is_empty() {
764            return;
765        }
766
767        // The spec does not specify this, but we don't fetch favicons for iframes, as
768        // they won't be displayed anyways.
769        let window = self.owner_window();
770        if !window.is_top_level() {
771            return;
772        }
773        let Ok(href) = self.Href().parse() else {
774            return;
775        };
776
777        // Ignore all previous fetch operations
778        self.request_generation_id
779            .set(self.request_generation_id.get().increment());
780
781        let cache_result = window.image_cache().get_cached_image_status(
782            href,
783            window.origin().immutable().clone(),
784            cors_setting_for_element(self.upcast()),
785        );
786
787        match cache_result {
788            ImageCacheResult::Available(ImageOrMetadataAvailable::ImageAvailable {
789                image, ..
790            }) => {
791                self.process_favicon_response(image);
792            },
793            ImageCacheResult::Available(ImageOrMetadataAvailable::MetadataAvailable(_, id)) |
794            ImageCacheResult::Pending(id) => {
795                let sender = self.register_image_cache_callback(id);
796                window.image_cache().add_listener(ImageLoadListener::new(
797                    sender,
798                    window.pipeline_id(),
799                    id,
800                ));
801            },
802            ImageCacheResult::ReadyForRequest(id) => {
803                let Some(request) = self.default_fetch_and_process_the_linked_resource() else {
804                    return;
805                };
806
807                let sender = self.register_image_cache_callback(id);
808                window.image_cache().add_listener(ImageLoadListener::new(
809                    sender,
810                    window.pipeline_id(),
811                    id,
812                ));
813
814                let document = self.upcast::<Node>().owner_doc();
815                let fetch_context = FaviconFetchContext {
816                    url: self.owner_document().base_url(),
817                    image_cache: window.image_cache(),
818                    id,
819                    link: Trusted::new(self),
820                };
821                document.fetch_background(request, fetch_context);
822            },
823            ImageCacheResult::FailedToLoadOrDecode => {},
824        };
825    }
826
827    fn register_image_cache_callback(&self, id: PendingImageId) -> ImageCacheResponseCallback {
828        let trusted_node = Trusted::new(self);
829        let window = self.owner_window();
830        let request_generation_id = self.get_request_generation_id();
831        window.register_image_cache_listener(id, move |response, _| {
832            let trusted_node = trusted_node.clone();
833            let link_element = trusted_node.root();
834            let window = link_element.owner_window();
835
836            let ImageResponse::Loaded(image, _) = response.response else {
837                // We don't care about metadata and such for favicons.
838                return;
839            };
840
841            if request_generation_id != link_element.get_request_generation_id() {
842                // This load is no longer relevant.
843                return;
844            };
845
846            window
847                .as_global_scope()
848                .task_manager()
849                .networking_task_source()
850                .queue(task!(process_favicon_response: move || {
851                    let element = trusted_node.root();
852
853                    if request_generation_id != element.get_request_generation_id() {
854                        // This load is no longer relevant.
855                        return;
856                    };
857
858                    element.process_favicon_response(image);
859                }));
860        })
861    }
862
863    /// Rasterizes a loaded favicon file if necessary and notifies the embedder about it.
864    fn process_favicon_response(&self, image: Image) {
865        // TODO: Include the size attribute here
866        let window = self.owner_window();
867        let document = self.owner_document();
868
869        let send_rasterized_favicon_to_embedder = |raster_image: &pixels::RasterImage| {
870            // Let's not worry about animated favicons...
871            let frame = raster_image.first_frame();
872
873            let format = match raster_image.format {
874                PixelFormat::K8 => embedder_traits::PixelFormat::K8,
875                PixelFormat::KA8 => embedder_traits::PixelFormat::KA8,
876                PixelFormat::RGB8 => embedder_traits::PixelFormat::RGB8,
877                PixelFormat::RGBA8 => embedder_traits::PixelFormat::RGBA8,
878                PixelFormat::BGRA8 => embedder_traits::PixelFormat::BGRA8,
879            };
880
881            let embedder_image = embedder_traits::Image::new(
882                frame.width,
883                frame.height,
884                std::sync::Arc::new(GenericSharedMemory::from_arc_vec(
885                    raster_image.bytes.clone(),
886                )),
887                raster_image.frames[0].byte_range.clone(),
888                format,
889            );
890            document.set_favicon(embedder_image);
891        };
892
893        match image {
894            Image::Raster(raster_image) => send_rasterized_favicon_to_embedder(&raster_image),
895            Image::Vector(vector_image) => {
896                // This size is completely arbitrary.
897                let size = DeviceIntSize::new(250, 250);
898
899                let image_cache = window.image_cache();
900                if let Some(raster_image) =
901                    image_cache.rasterize_vector_image(vector_image.id, size, None)
902                {
903                    send_rasterized_favicon_to_embedder(&raster_image);
904                } else {
905                    // The rasterization callback will end up calling "process_favicon_response" again,
906                    // but this time with a raster image.
907                    let image_cache_sender = self.register_image_cache_callback(vector_image.id);
908                    image_cache.add_rasterization_complete_listener(
909                        window.pipeline_id(),
910                        vector_image.id,
911                        size,
912                        image_cache_sender,
913                    );
914                }
915            },
916        }
917    }
918
919    /// <https://html.spec.whatwg.org/multipage/#link-type-preload:fetch-and-process-the-linked-resource-2>
920    /// and type matching destination steps of <https://html.spec.whatwg.org/multipage/#preload>
921    fn handle_preload_url(&self) {
922        // Step 1. Update the source set for el.
923        self.source_set
924            .borrow_mut()
925            .update_source_set(self.upcast::<Element>());
926        // Step 2. Let options be the result of creating link options from el.
927        let mut options = self.processing_options();
928        // Step 3. Let destination be the result of translating the keyword
929        // representing the state of el's as attribute.
930        let Some(destination) = self.compute_destination_for_attribute() else {
931            // Step 4. If destination is null, then return.
932            return;
933        };
934        // Step 5. Set options's destination to destination.
935        options.destination = destination;
936        // Steps for https://html.spec.whatwg.org/multipage/#preload
937        {
938            // Step 1. If options's type doesn't match options's destination, then return.
939            let type_matches_destination = options.type_matches_destination();
940            self.previous_type_matched.set(type_matches_destination);
941            if !type_matches_destination {
942                return;
943            }
944        }
945        // Step 6. Preload options, with the following steps given a response response:
946        let document = self.upcast::<Node>().owner_doc();
947        options.preload(
948            self.owner_window().webview_id(),
949            Some(Trusted::new(self)),
950            &document,
951        );
952    }
953
954    /// <https://html.spec.whatwg.org/multipage/#link-type-preload:fetch-and-process-the-linked-resource-2>
955    pub(crate) fn fire_event_after_response(
956        &self,
957        cx: &mut JSContext,
958        response: Result<(), NetworkError>,
959    ) {
960        // Step 3.1 If response is a network error, fire an event named error at el.
961        // Otherwise, fire an event named load at el.
962        if response.is_err() {
963            self.upcast::<EventTarget>().fire_event(cx, atom!("error"));
964        } else {
965            self.upcast::<EventTarget>().fire_event(cx, atom!("load"));
966        }
967    }
968
969    /// <https://html.spec.whatwg.org/multipage/#link-type-modulepreload:fetch-and-process-the-linked-resource-2>
970    fn fetch_and_process_modulepreload(&self, cx: &mut JSContext) {
971        let el = self.upcast::<Element>();
972        let href_attribute_value = el.get_string_attribute(&local_name!("href"));
973
974        // Step 1. If el's href attribute's value is the empty string, then return.
975        if href_attribute_value.is_empty() {
976            return;
977        }
978
979        // Step 2. Let destination be the current state of el's as attribute (a destination), or "script" if it is in no state.
980        let destination = el
981            .get_attribute_string_value(&local_name!("as"))
982            .map(|value| value.to_ascii_lowercase())
983            .and_then(|value| match value.as_str() {
984                // `Destination::from_str` will map an empty string to `Destination::None`
985                "" => None,
986                // "fetch" is a valid preload destination, but not for modules
987                "fetch" => Some(Destination::None),
988                _ => Destination::from_str(&value).ok(),
989            })
990            .unwrap_or(Destination::Script);
991
992        let document = self.owner_document();
993        let global = document.global();
994
995        // A module preload destination is "json", "style", "text" or a script-like destination.
996        let is_a_modulepreload_destination = match destination {
997            Destination::Json | Destination::Style | Destination::Text => true,
998            // https://fetch.spec.whatwg.org/#ref-for-request-destination-script-like
999            // While "xslt" can cause script execution, it is not relevant here.
1000            Destination::Xslt => false,
1001            d => d.is_script_like(),
1002        };
1003
1004        // Step 3. If destination is not a module preload destination, then queue an element task on the
1005        // networking task source given el to fire an event named error at el, and return.
1006        if !is_a_modulepreload_destination {
1007            return global
1008                .task_manager()
1009                .networking_task_source()
1010                .queue_simple_event(self.upcast(), atom!("error"));
1011        }
1012
1013        // 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.
1014        // Step 5. If url is failure, then return.
1015        let Ok(url) = document.encoding_parse_a_url(&href_attribute_value.str()) else {
1016            return;
1017        };
1018        let url = ensure_blob_referenced_by_url_is_kept_alive(&global, url);
1019
1020        // Step 6. Let settings object be el's node document's relevant settings object.
1021
1022        // Step 7. Let credentials mode be the CORS settings attribute credentials mode for el's crossorigin attribute.
1023        let credentials_mode = cors_settings_attribute_credential_mode(el);
1024
1025        // Step 8. Let cryptographic nonce be el.[[CryptographicNonce]].
1026        let cryptographic_nonce = el.nonce_value();
1027
1028        // Step 9. Let integrity metadata be the value of el's integrity attribute, if it is specified, or the empty string otherwise.
1029        // Step 10. If el does not have an integrity attribute, then set integrity metadata to
1030        // the result of resolving a module integrity metadata with url and settings object.
1031        let integrity_metadata = el
1032            .get_attribute_string_value(&local_name!("integrity"))
1033            .unwrap_or_else(|| {
1034                global
1035                    .import_map()
1036                    .resolve_a_module_integrity_metadata(&url.url())
1037            });
1038
1039        // Step 11. Let referrer policy be the current state of el's referrerpolicy attribute.
1040        let referrer_policy = referrer_policy_for_element(el);
1041
1042        // TODO Step 12. Let fetch priority be the current state of el's fetchpriority attribute.
1043
1044        // Step 13. Let options be a script fetch options whose cryptographic nonce is cryptographic nonce,
1045        // integrity metadata is integrity metadata, parser metadata is "not-parser-inserted",
1046        // credentials mode is credentials mode, referrer policy is referrer policy, and fetch priority is fetch priority.
1047        let options = ScriptFetchOptions {
1048            cryptographic_nonce,
1049            integrity_metadata,
1050            parser_metadata: ParserMetadata::NotParserInserted,
1051            credentials_mode,
1052            referrer_policy,
1053            render_blocking: false,
1054        };
1055
1056        let link = DomRoot::from_ref(self);
1057
1058        // Step 14. Fetch a modulepreload module script graph given url, destination, settings object, options,
1059        // and with the following steps given result:
1060        fetch_a_modulepreload_module(
1061            cx,
1062            url,
1063            destination,
1064            &global,
1065            options,
1066            move |cx, fetch_failed| {
1067                // Step 1. If result is null, then fire an event named error at el, and return.
1068                // Step 2. Fire an event named load at el.
1069                let event = match fetch_failed {
1070                    true => atom!("error"),
1071                    false => atom!("load"),
1072                };
1073
1074                link.upcast::<EventTarget>().fire_event(cx, event);
1075            },
1076        );
1077    }
1078}
1079
1080impl StylesheetOwner for HTMLLinkElement {
1081    fn increment_pending_loads_count(&self) {
1082        self.pending_loads.set(self.pending_loads.get() + 1)
1083    }
1084
1085    fn load_finished(&self, succeeded: bool) -> Option<bool> {
1086        assert!(self.pending_loads.get() > 0, "What finished?");
1087        if !succeeded {
1088            self.any_failed_load.set(true);
1089        }
1090
1091        self.pending_loads.set(self.pending_loads.get() - 1);
1092        if self.pending_loads.get() != 0 {
1093            return None;
1094        }
1095
1096        let any_failed = self.any_failed_load.get();
1097        self.any_failed_load.set(false);
1098        Some(any_failed)
1099    }
1100
1101    fn parser_inserted(&self) -> bool {
1102        self.parser_inserted.get()
1103    }
1104
1105    /// <https://html.spec.whatwg.org/multipage/#potentially-render-blocking>
1106    fn potentially_render_blocking(&self) -> bool {
1107        // An element is potentially render-blocking if its blocking tokens set contains "render",
1108        // or if it is implicitly potentially render-blocking, which will be defined at the individual elements.
1109        // By default, an element is not implicitly potentially render-blocking.
1110        //
1111        // https://html.spec.whatwg.org/multipage/#link-type-stylesheet:implicitly-potentially-render-blocking
1112        // > A link element of this type is implicitly potentially render-blocking if the element was created by its node document's parser.
1113        self.parser_inserted() ||
1114            self.blocking
1115                .get()
1116                .is_some_and(|list| list.Contains(DOMString::from_static("render")))
1117    }
1118
1119    fn referrer_policy(&self, cx: &mut js::context::JSContext) -> ReferrerPolicy {
1120        if self
1121            .RelList(cx)
1122            .Contains(DOMString::from_static("noreferrer"))
1123        {
1124            return ReferrerPolicy::NoReferrer;
1125        }
1126
1127        ReferrerPolicy::EmptyString
1128    }
1129
1130    fn set_origin_clean(&self, cx: &mut js::context::JSContext, origin_clean: bool) {
1131        if let Some(stylesheet) = self.get_cssom_stylesheet(cx) {
1132            stylesheet.set_origin_clean(origin_clean);
1133        }
1134    }
1135}
1136
1137impl HTMLLinkElementMethods<crate::DomTypeHolder> for HTMLLinkElement {
1138    // https://html.spec.whatwg.org/multipage/#dom-link-href
1139    make_url_getter!(Href, "href");
1140
1141    // https://html.spec.whatwg.org/multipage/#dom-link-href
1142    make_url_setter!(SetHref, "href");
1143
1144    // https://html.spec.whatwg.org/multipage/#dom-link-rel
1145    make_getter!(Rel, "rel");
1146
1147    /// <https://html.spec.whatwg.org/multipage/#dom-link-rel>
1148    fn SetRel(&self, cx: &mut JSContext, rel: DOMString) {
1149        self.upcast::<Element>()
1150            .set_tokenlist_attribute(cx, &local_name!("rel"), rel);
1151    }
1152
1153    // https://html.spec.whatwg.org/multipage/#dom-link-as
1154    make_enumerated_getter!(
1155        As,
1156        "as",
1157        "fetch" | "audio" | "audioworklet" | "document" | "embed" | "font" | "frame"
1158            | "iframe" | "image" | "json" | "manifest" | "object" | "paintworklet"
1159            | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "track"
1160            | "video" | "webidentity" | "worker" | "xslt",
1161        missing => "",
1162        invalid => ""
1163    );
1164
1165    // https://html.spec.whatwg.org/multipage/#dom-link-as
1166    make_setter!(SetAs, "as");
1167
1168    // https://html.spec.whatwg.org/multipage/#dom-link-media
1169    make_getter!(Media, "media");
1170
1171    // https://html.spec.whatwg.org/multipage/#dom-link-media
1172    make_setter!(SetMedia, "media");
1173
1174    // https://html.spec.whatwg.org/multipage/#dom-link-integrity
1175    make_getter!(Integrity, "integrity");
1176
1177    // https://html.spec.whatwg.org/multipage/#dom-link-integrity
1178    make_setter!(SetIntegrity, "integrity");
1179
1180    // https://html.spec.whatwg.org/multipage/#dom-link-hreflang
1181    make_getter!(Hreflang, "hreflang");
1182
1183    // https://html.spec.whatwg.org/multipage/#dom-link-hreflang
1184    make_setter!(SetHreflang, "hreflang");
1185
1186    // https://html.spec.whatwg.org/multipage/#dom-link-type
1187    make_getter!(Type, "type");
1188
1189    // https://html.spec.whatwg.org/multipage/#dom-link-type
1190    make_setter!(SetType, "type");
1191
1192    // https://html.spec.whatwg.org/multipage/#dom-link-imagesrcset
1193    make_url_getter!(ImageSrcset, "imagesrcset");
1194
1195    // https://html.spec.whatwg.org/multipage/#dom-link-imagesrcset
1196    make_url_setter!(SetImageSrcset, "imagesrcset");
1197
1198    // https://html.spec.whatwg.org/multipage/#dom-link-imagesizes
1199    make_getter!(ImageSizes, "imagesizes");
1200
1201    // https://html.spec.whatwg.org/multipage/#dom-link-imagesizes
1202    make_setter!(SetImageSizes, "imagesizes");
1203
1204    // https://html.spec.whatwg.org/multipage/#dom-link-disabled
1205    make_bool_getter!(Disabled, "disabled");
1206
1207    // https://html.spec.whatwg.org/multipage/#dom-link-disabled
1208    make_bool_setter!(SetDisabled, "disabled");
1209
1210    /// <https://html.spec.whatwg.org/multipage/#dom-link-rellist>
1211    fn RelList(&self, cx: &mut js::context::JSContext) -> DomRoot<DOMTokenList> {
1212        self.rel_list.or_init(|| {
1213            DOMTokenList::new(
1214                cx,
1215                self.upcast(),
1216                &local_name!("rel"),
1217                Some(vec![
1218                    Atom::from("alternate"),
1219                    Atom::from("apple-touch-icon"),
1220                    Atom::from("apple-touch-icon-precomposed"),
1221                    Atom::from("canonical"),
1222                    Atom::from("dns-prefetch"),
1223                    Atom::from("icon"),
1224                    Atom::from("import"),
1225                    Atom::from("manifest"),
1226                    Atom::from("modulepreload"),
1227                    Atom::from("next"),
1228                    Atom::from("preconnect"),
1229                    Atom::from("prefetch"),
1230                    Atom::from("preload"),
1231                    Atom::from("prerender"),
1232                    Atom::from("stylesheet"),
1233                ]),
1234            )
1235        })
1236    }
1237
1238    // https://html.spec.whatwg.org/multipage/#dom-link-charset
1239    make_getter!(Charset, "charset");
1240
1241    // https://html.spec.whatwg.org/multipage/#dom-link-charset
1242    make_setter!(SetCharset, "charset");
1243
1244    // https://html.spec.whatwg.org/multipage/#dom-link-rev
1245    make_getter!(Rev, "rev");
1246
1247    // https://html.spec.whatwg.org/multipage/#dom-link-rev
1248    make_setter!(SetRev, "rev");
1249
1250    // https://html.spec.whatwg.org/multipage/#dom-link-target
1251    make_getter!(Target, "target");
1252
1253    // https://html.spec.whatwg.org/multipage/#dom-link-target
1254    make_setter!(SetTarget, "target");
1255
1256    /// <https://html.spec.whatwg.org/multipage/#attr-link-blocking>
1257    fn Blocking(&self, cx: &mut js::context::JSContext) -> DomRoot<DOMTokenList> {
1258        self.blocking.or_init(|| {
1259            DOMTokenList::new(
1260                cx,
1261                self.upcast(),
1262                &local_name!("blocking"),
1263                Some(vec![Atom::from("render")]),
1264            )
1265        })
1266    }
1267
1268    /// <https://html.spec.whatwg.org/multipage/#dom-link-crossorigin>
1269    fn GetCrossOrigin(&self) -> Option<DOMString> {
1270        reflect_cross_origin_attribute(self.upcast::<Element>())
1271    }
1272
1273    /// <https://html.spec.whatwg.org/multipage/#dom-link-crossorigin>
1274    fn SetCrossOrigin(&self, cx: &mut JSContext, value: Option<DOMString>) {
1275        set_cross_origin_attribute(cx, self.upcast::<Element>(), value);
1276    }
1277
1278    /// <https://html.spec.whatwg.org/multipage/#dom-link-referrerpolicy>
1279    fn ReferrerPolicy(&self) -> DOMString {
1280        reflect_referrer_policy_attribute(self.upcast::<Element>())
1281    }
1282
1283    // https://html.spec.whatwg.org/multipage/#dom-link-referrerpolicy
1284    make_setter!(SetReferrerPolicy, "referrerpolicy");
1285
1286    /// <https://drafts.csswg.org/cssom/#dom-linkstyle-sheet>
1287    fn GetSheet(&self, cx: &mut JSContext) -> Option<DomRoot<DOMStyleSheet>> {
1288        self.get_cssom_stylesheet(cx).map(DomRoot::upcast)
1289    }
1290}
1291
1292struct FaviconFetchContext {
1293    /// The `<link>` element that caused this fetch operation
1294    link: Trusted<HTMLLinkElement>,
1295    image_cache: std::sync::Arc<dyn ImageCache>,
1296    id: PendingImageId,
1297
1298    /// The base url of the document that the `<link>` element belongs to.
1299    url: ServoUrl,
1300}
1301
1302impl FetchResponseListener for FaviconFetchContext {
1303    fn process_request_body(&mut self, _: RequestId) {}
1304
1305    fn process_response(
1306        &mut self,
1307        _: &mut js::context::JSContext,
1308        request_id: RequestId,
1309        metadata: Result<FetchMetadata, NetworkError>,
1310    ) {
1311        self.image_cache.notify_pending_response(
1312            self.id,
1313            FetchResponseMsg::ProcessResponse(request_id, metadata),
1314        );
1315    }
1316
1317    fn process_response_chunk(
1318        &mut self,
1319        _: &mut js::context::JSContext,
1320        request_id: RequestId,
1321        chunk: Bytes,
1322    ) {
1323        self.image_cache.notify_pending_response(
1324            self.id,
1325            FetchResponseMsg::ProcessResponseChunk(request_id, chunk),
1326        );
1327    }
1328
1329    fn process_response_eof(
1330        self,
1331        cx: &mut js::context::JSContext,
1332        request_id: RequestId,
1333        response: Result<(), NetworkError>,
1334        timing: ResourceFetchTiming,
1335    ) {
1336        self.image_cache.notify_pending_response(
1337            self.id,
1338            FetchResponseMsg::ProcessResponseEOF(request_id, response.clone(), timing.clone()),
1339        );
1340        submit_timing(cx, &self, &response, &timing);
1341    }
1342
1343    fn process_csp_violations(
1344        &mut self,
1345        cx: &mut js::context::JSContext,
1346        _request_id: RequestId,
1347        violations: Vec<Violation>,
1348    ) {
1349        let global = &self.resource_timing_global();
1350        global.report_csp_violations(cx, violations, None, None);
1351    }
1352
1353    fn process_content_length(&mut self, request_id: RequestId, size: usize) {
1354        self.image_cache.notify_pending_response(
1355            self.id,
1356            FetchResponseMsg::ProcessContentLength(request_id, size),
1357        )
1358    }
1359}
1360
1361impl ResourceTimingListener for FaviconFetchContext {
1362    fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
1363        (
1364            InitiatorType::LocalName("link".to_string()),
1365            self.url.clone(),
1366        )
1367    }
1368
1369    fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
1370        self.link.root().upcast::<Node>().owner_doc().global()
1371    }
1372}