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 seperate 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 { media },
600            link_url,
601            cors_setting,
602            integrity_metadata.to_owned(),
603        );
604    }
605
606    /// <https://html.spec.whatwg.org/multipage/#attr-link-disabled>
607    fn handle_disabled_attribute_change(&self, disabled: bool) {
608        if !disabled {
609            self.is_explicitly_enabled.set(true);
610        }
611        if let Some(stylesheet) = self.get_stylesheet() {
612            if stylesheet.set_disabled(disabled) {
613                self.stylesheet_list_owner().invalidate_stylesheets();
614            }
615        }
616    }
617
618    fn handle_favicon_url(&self) {
619        // The spec does not specify this, but we don't fetch favicons for iframes, as
620        // they won't be displayed anyways.
621        let window = self.owner_window();
622        if !window.is_top_level() {
623            return;
624        }
625        let Ok(href) = self.Href().parse() else {
626            return;
627        };
628
629        // Ignore all previous fetch operations
630        self.request_generation_id
631            .set(self.request_generation_id.get().increment());
632
633        let cache_result = window.image_cache().get_cached_image_status(
634            href,
635            window.origin().immutable().clone(),
636            cors_setting_for_element(self.upcast()),
637        );
638
639        match cache_result {
640            ImageCacheResult::Available(ImageOrMetadataAvailable::ImageAvailable {
641                image, ..
642            }) => {
643                self.process_favicon_response(image);
644            },
645            ImageCacheResult::Available(ImageOrMetadataAvailable::MetadataAvailable(_, id)) |
646            ImageCacheResult::Pending(id) => {
647                let sender = self.register_image_cache_callback(id);
648                window.image_cache().add_listener(ImageLoadListener::new(
649                    sender,
650                    window.pipeline_id(),
651                    id,
652                ));
653            },
654            ImageCacheResult::ReadyForRequest(id) => {
655                let Some(request) = self.default_fetch_and_process_the_linked_resource() else {
656                    return;
657                };
658
659                let sender = self.register_image_cache_callback(id);
660                window.image_cache().add_listener(ImageLoadListener::new(
661                    sender,
662                    window.pipeline_id(),
663                    id,
664                ));
665
666                let document = self.upcast::<Node>().owner_doc();
667                let fetch_context = FaviconFetchContext {
668                    url: self.owner_document().base_url(),
669                    image_cache: window.image_cache(),
670                    id,
671                    link: Trusted::new(self),
672                };
673                document.fetch_background(request, fetch_context);
674            },
675            ImageCacheResult::FailedToLoadOrDecode => {},
676        };
677    }
678
679    fn register_image_cache_callback(&self, id: PendingImageId) -> ImageCacheResponseCallback {
680        let trusted_node = Trusted::new(self);
681        let window = self.owner_window();
682        let request_generation_id = self.get_request_generation_id();
683        window.register_image_cache_listener(id, move |response| {
684            let trusted_node = trusted_node.clone();
685            let link_element = trusted_node.root();
686            let window = link_element.owner_window();
687
688            let ImageResponse::Loaded(image, _) = response.response else {
689                // We don't care about metadata and such for favicons.
690                return;
691            };
692
693            if request_generation_id != link_element.get_request_generation_id() {
694                // This load is no longer relevant.
695                return;
696            };
697
698            window
699                .as_global_scope()
700                .task_manager()
701                .networking_task_source()
702                .queue(task!(process_favicon_response: move || {
703                    let element = trusted_node.root();
704
705                    if request_generation_id != element.get_request_generation_id() {
706                        // This load is no longer relevant.
707                        return;
708                    };
709
710                    element.process_favicon_response(image);
711                }));
712        })
713    }
714
715    /// Rasterizes a loaded favicon file if necessary and notifies the embedder about it.
716    fn process_favicon_response(&self, image: Image) {
717        // TODO: Include the size attribute here
718        let window = self.owner_window();
719        let document = self.owner_document();
720
721        let send_rasterized_favicon_to_embedder = |raster_image: &pixels::RasterImage| {
722            // Let's not worry about animated favicons...
723            let frame = raster_image.first_frame();
724
725            let format = match raster_image.format {
726                PixelFormat::K8 => embedder_traits::PixelFormat::K8,
727                PixelFormat::KA8 => embedder_traits::PixelFormat::KA8,
728                PixelFormat::RGB8 => embedder_traits::PixelFormat::RGB8,
729                PixelFormat::RGBA8 => embedder_traits::PixelFormat::RGBA8,
730                PixelFormat::BGRA8 => embedder_traits::PixelFormat::BGRA8,
731            };
732
733            let embedder_image = embedder_traits::Image::new(
734                frame.width,
735                frame.height,
736                std::sync::Arc::new(IpcSharedMemory::from_bytes(&raster_image.bytes)),
737                raster_image.frames[0].byte_range.clone(),
738                format,
739            );
740            document.set_favicon(embedder_image);
741        };
742
743        match image {
744            Image::Raster(raster_image) => send_rasterized_favicon_to_embedder(&raster_image),
745            Image::Vector(vector_image) => {
746                // This size is completely arbitrary.
747                let size = DeviceIntSize::new(250, 250);
748
749                let image_cache = window.image_cache();
750                if let Some(raster_image) =
751                    image_cache.rasterize_vector_image(vector_image.id, size)
752                {
753                    send_rasterized_favicon_to_embedder(&raster_image);
754                } else {
755                    // The rasterization callback will end up calling "process_favicon_response" again,
756                    // but this time with a raster image.
757                    let image_cache_sender = self.register_image_cache_callback(vector_image.id);
758                    image_cache.add_rasterization_complete_listener(
759                        window.pipeline_id(),
760                        vector_image.id,
761                        size,
762                        image_cache_sender,
763                    );
764                }
765            },
766        }
767    }
768
769    /// <https://html.spec.whatwg.org/multipage/#link-type-preload:fetch-and-process-the-linked-resource-2>
770    /// and type matching destination steps of <https://html.spec.whatwg.org/multipage/#preload>
771    fn handle_preload_url(&self) {
772        // Step 1. Update the source set for el.
773        // TODO
774        // Step 2. Let options be the result of creating link options from el.
775        let mut options = self.processing_options();
776        // Step 3. Let destination be the result of translating the keyword
777        // representing the state of el's as attribute.
778        let Some(destination) = self.compute_destination_for_attribute() else {
779            // Step 4. If destination is null, then return.
780            return;
781        };
782        // Step 5. Set options's destination to destination.
783        options.destination = destination;
784        // Steps for https://html.spec.whatwg.org/multipage/#preload
785        {
786            // Step 1. If options's type doesn't match options's destination, then return.
787            let type_matches_destination = options.type_matches_destination();
788            self.previous_type_matched.set(type_matches_destination);
789            if !type_matches_destination {
790                return;
791            }
792        }
793        // Step 6. Preload options, with the following steps given a response response:
794        let document = self.upcast::<Node>().owner_doc();
795        options.preload(
796            self.owner_window().webview_id(),
797            Some(Trusted::new(self)),
798            &document,
799        );
800    }
801
802    /// <https://html.spec.whatwg.org/multipage/#link-type-preload:fetch-and-process-the-linked-resource-2>
803    pub(crate) fn fire_event_after_response(
804        &self,
805        response: Result<ResourceFetchTiming, NetworkError>,
806        can_gc: CanGc,
807    ) {
808        // Step 3.1 If response is a network error, fire an event named error at el.
809        // Otherwise, fire an event named load at el.
810        if response.is_err() {
811            self.upcast::<EventTarget>()
812                .fire_event(atom!("error"), can_gc);
813        } else {
814            self.upcast::<EventTarget>()
815                .fire_event(atom!("load"), can_gc);
816        }
817    }
818}
819
820impl StylesheetOwner for HTMLLinkElement {
821    fn increment_pending_loads_count(&self) {
822        self.pending_loads.set(self.pending_loads.get() + 1)
823    }
824
825    fn load_finished(&self, succeeded: bool) -> Option<bool> {
826        assert!(self.pending_loads.get() > 0, "What finished?");
827        if !succeeded {
828            self.any_failed_load.set(true);
829        }
830
831        self.pending_loads.set(self.pending_loads.get() - 1);
832        if self.pending_loads.get() != 0 {
833            return None;
834        }
835
836        let any_failed = self.any_failed_load.get();
837        self.any_failed_load.set(false);
838        Some(any_failed)
839    }
840
841    fn parser_inserted(&self) -> bool {
842        self.parser_inserted.get()
843    }
844
845    fn referrer_policy(&self) -> ReferrerPolicy {
846        if self.RelList(CanGc::note()).Contains("noreferrer".into()) {
847            return ReferrerPolicy::NoReferrer;
848        }
849
850        ReferrerPolicy::EmptyString
851    }
852
853    fn set_origin_clean(&self, origin_clean: bool) {
854        if let Some(stylesheet) = self.get_cssom_stylesheet(CanGc::note()) {
855            stylesheet.set_origin_clean(origin_clean);
856        }
857    }
858}
859
860impl HTMLLinkElementMethods<crate::DomTypeHolder> for HTMLLinkElement {
861    // https://html.spec.whatwg.org/multipage/#dom-link-href
862    make_url_getter!(Href, "href");
863
864    // https://html.spec.whatwg.org/multipage/#dom-link-href
865    make_url_setter!(SetHref, "href");
866
867    // https://html.spec.whatwg.org/multipage/#dom-link-rel
868    make_getter!(Rel, "rel");
869
870    /// <https://html.spec.whatwg.org/multipage/#dom-link-rel>
871    fn SetRel(&self, rel: DOMString, can_gc: CanGc) {
872        self.upcast::<Element>()
873            .set_tokenlist_attribute(&local_name!("rel"), rel, can_gc);
874    }
875
876    // https://html.spec.whatwg.org/multipage/#dom-link-as
877    make_enumerated_getter!(
878        As,
879        "as",
880        "fetch" | "audio" | "audioworklet" | "document" | "embed" | "font" | "frame"
881            | "iframe" | "image" | "json" | "manifest" | "object" | "paintworklet"
882            | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "track"
883            | "video" | "webidentity" | "worker" | "xslt",
884        missing => "",
885        invalid => ""
886    );
887
888    // https://html.spec.whatwg.org/multipage/#dom-link-as
889    make_setter!(SetAs, "as");
890
891    // https://html.spec.whatwg.org/multipage/#dom-link-media
892    make_getter!(Media, "media");
893
894    // https://html.spec.whatwg.org/multipage/#dom-link-media
895    make_setter!(SetMedia, "media");
896
897    // https://html.spec.whatwg.org/multipage/#dom-link-integrity
898    make_getter!(Integrity, "integrity");
899
900    // https://html.spec.whatwg.org/multipage/#dom-link-integrity
901    make_setter!(SetIntegrity, "integrity");
902
903    // https://html.spec.whatwg.org/multipage/#dom-link-hreflang
904    make_getter!(Hreflang, "hreflang");
905
906    // https://html.spec.whatwg.org/multipage/#dom-link-hreflang
907    make_setter!(SetHreflang, "hreflang");
908
909    // https://html.spec.whatwg.org/multipage/#dom-link-type
910    make_getter!(Type, "type");
911
912    // https://html.spec.whatwg.org/multipage/#dom-link-type
913    make_setter!(SetType, "type");
914
915    // https://html.spec.whatwg.org/multipage/#dom-link-disabled
916    make_bool_getter!(Disabled, "disabled");
917
918    // https://html.spec.whatwg.org/multipage/#dom-link-disabled
919    make_bool_setter!(SetDisabled, "disabled");
920
921    /// <https://html.spec.whatwg.org/multipage/#dom-link-rellist>
922    fn RelList(&self, can_gc: CanGc) -> DomRoot<DOMTokenList> {
923        self.rel_list.or_init(|| {
924            DOMTokenList::new(
925                self.upcast(),
926                &local_name!("rel"),
927                Some(vec![
928                    Atom::from("alternate"),
929                    Atom::from("apple-touch-icon"),
930                    Atom::from("apple-touch-icon-precomposed"),
931                    Atom::from("canonical"),
932                    Atom::from("dns-prefetch"),
933                    Atom::from("icon"),
934                    Atom::from("import"),
935                    Atom::from("manifest"),
936                    Atom::from("modulepreload"),
937                    Atom::from("next"),
938                    Atom::from("preconnect"),
939                    Atom::from("prefetch"),
940                    Atom::from("preload"),
941                    Atom::from("prerender"),
942                    Atom::from("stylesheet"),
943                ]),
944                can_gc,
945            )
946        })
947    }
948
949    // https://html.spec.whatwg.org/multipage/#dom-link-charset
950    make_getter!(Charset, "charset");
951
952    // https://html.spec.whatwg.org/multipage/#dom-link-charset
953    make_setter!(SetCharset, "charset");
954
955    // https://html.spec.whatwg.org/multipage/#dom-link-rev
956    make_getter!(Rev, "rev");
957
958    // https://html.spec.whatwg.org/multipage/#dom-link-rev
959    make_setter!(SetRev, "rev");
960
961    // https://html.spec.whatwg.org/multipage/#dom-link-target
962    make_getter!(Target, "target");
963
964    // https://html.spec.whatwg.org/multipage/#dom-link-target
965    make_setter!(SetTarget, "target");
966
967    /// <https://html.spec.whatwg.org/multipage/#dom-link-crossorigin>
968    fn GetCrossOrigin(&self) -> Option<DOMString> {
969        reflect_cross_origin_attribute(self.upcast::<Element>())
970    }
971
972    /// <https://html.spec.whatwg.org/multipage/#dom-link-crossorigin>
973    fn SetCrossOrigin(&self, value: Option<DOMString>, can_gc: CanGc) {
974        set_cross_origin_attribute(self.upcast::<Element>(), value, can_gc);
975    }
976
977    /// <https://html.spec.whatwg.org/multipage/#dom-link-referrerpolicy>
978    fn ReferrerPolicy(&self) -> DOMString {
979        reflect_referrer_policy_attribute(self.upcast::<Element>())
980    }
981
982    // https://html.spec.whatwg.org/multipage/#dom-link-referrerpolicy
983    make_setter!(SetReferrerPolicy, "referrerpolicy");
984
985    /// <https://drafts.csswg.org/cssom/#dom-linkstyle-sheet>
986    fn GetSheet(&self, can_gc: CanGc) -> Option<DomRoot<DOMStyleSheet>> {
987        self.get_cssom_stylesheet(can_gc).map(DomRoot::upcast)
988    }
989}
990
991struct FaviconFetchContext {
992    /// The `<link>` element that caused this fetch operation
993    link: Trusted<HTMLLinkElement>,
994    image_cache: std::sync::Arc<dyn ImageCache>,
995    id: PendingImageId,
996
997    /// The base url of the document that the `<link>` element belongs to.
998    url: ServoUrl,
999}
1000
1001impl FetchResponseListener for FaviconFetchContext {
1002    fn process_request_body(&mut self, _: RequestId) {}
1003
1004    fn process_request_eof(&mut self, _: RequestId) {}
1005
1006    fn process_response(
1007        &mut self,
1008        request_id: RequestId,
1009        metadata: Result<FetchMetadata, NetworkError>,
1010    ) {
1011        self.image_cache.notify_pending_response(
1012            self.id,
1013            FetchResponseMsg::ProcessResponse(request_id, metadata.clone()),
1014        );
1015    }
1016
1017    fn process_response_chunk(&mut self, request_id: RequestId, chunk: Vec<u8>) {
1018        self.image_cache.notify_pending_response(
1019            self.id,
1020            FetchResponseMsg::ProcessResponseChunk(request_id, chunk.into()),
1021        );
1022    }
1023
1024    fn process_response_eof(
1025        self,
1026        request_id: RequestId,
1027        response: Result<ResourceFetchTiming, NetworkError>,
1028    ) {
1029        self.image_cache.notify_pending_response(
1030            self.id,
1031            FetchResponseMsg::ProcessResponseEOF(request_id, response.clone()),
1032        );
1033        if let Ok(response) = response {
1034            submit_timing(&self, &response, CanGc::note());
1035        }
1036    }
1037
1038    fn process_csp_violations(&mut self, _request_id: RequestId, violations: Vec<Violation>) {
1039        let global = &self.resource_timing_global();
1040        let link = self.link.root();
1041        let source_position = link
1042            .upcast::<Element>()
1043            .compute_source_position(link.line_number as u32);
1044        global.report_csp_violations(violations, None, Some(source_position));
1045    }
1046}
1047
1048impl ResourceTimingListener for FaviconFetchContext {
1049    fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
1050        (
1051            InitiatorType::LocalName("link".to_string()),
1052            self.url.clone(),
1053        )
1054    }
1055
1056    fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
1057        self.link.root().upcast::<Node>().owner_doc().global()
1058    }
1059}