script/dom/html/
htmllinkelement.rs

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