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