1use 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 rel_list: MutNullableDom<DOMTokenList>,
78
79 #[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 parser_inserted: Cell<bool>,
94 pending_loads: Cell<u32>,
97 any_failed_load: Cell<bool>,
99 request_generation_id: Cell<RequestGenerationId>,
101 is_explicitly_enabled: Cell<bool>,
103 previous_type_matched: Cell<bool>,
105 previous_media_environment_matched: Cell<bool>,
107 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 #[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, None, sheet,
186 None, 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 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 if self.relations.get().contains(LinkRelations::PREFETCH) {
267 self.fetch_and_process_prefetch_link(&attr.value());
268 }
269
270 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 if self.relations.get().contains(LinkRelations::PREFETCH) {
285 self.fetch_and_process_prefetch_link(&attr.value());
286 }
287
288 if self.relations.get().contains(LinkRelations::STYLESHEET) {
292 self.handle_stylesheet_url(&attr.value());
293 }
294 },
295 local_name!("as") => {
296 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 if self.relations.get().contains(LinkRelations::STYLESHEET) {
314 self.handle_stylesheet_url(&attr.value());
315 }
316
317 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 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 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 fn processing_options(&self) -> LinkProcessingOptions {
420 let element = self.upcast::<Element>();
421
422 let document = self.upcast::<Node>().owner_doc();
424
425 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, 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 if let Some(href_attribute) = element.get_attribute(&ns!(), &local_name!("href")) {
444 options.href = (**href_attribute.value()).to_owned();
445 }
446
447 if let Some(integrity_attribute) = element.get_attribute(&ns!(), &local_name!("integrity"))
450 {
451 options.integrity = (**integrity_attribute.value()).to_owned();
452 }
453
454 if let Some(type_attribute) = element.get_attribute(&ns!(), &local_name!("type")) {
456 options.link_type = (**type_attribute.value()).to_owned();
457 }
458
459 assert!(!options.href.is_empty() || options.source_set.is_some());
461
462 options
464 }
465
466 fn default_fetch_and_process_the_linked_resource(&self) -> Option<RequestBuilder> {
471 let options = self.processing_options();
473
474 let Some(request) = options.create_link_request(self.owner_window().webview_id()) else {
476 return None;
478 };
479 let mut request = request.synchronous(true);
481
482 if !self.linked_resource_fetch_setup(&mut request) {
484 return None;
485 }
486
487 Some(request)
493 }
494
495 fn linked_resource_fetch_setup(&self, request: &mut RequestBuilder) -> bool {
497 if self.relations.get().contains(LinkRelations::ICON) {
498 request.destination = Destination::Image;
500
501 return true;
503 }
504
505 true
506 }
507
508 fn fetch_and_process_prefetch_link(&self, href: &str) {
510 if href.is_empty() {
512 return;
513 }
514
515 let mut options = self.processing_options();
517
518 options.destination = Destination::None;
520
521 let Some(request) = options.create_link_request(self.owner_window().webview_id()) else {
523 return;
525 };
526 let url = request.url.clone();
527
528 let request = request.initiator(Initiator::Prefetch);
530
531 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 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 if href.is_empty() {
556 return;
557 }
558
559 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 let cors_setting = cors_setting_for_element(element);
572
573 let mq_attribute = element.get_attribute(&ns!(), &local_name!("media"));
574 let value = mq_attribute.as_ref().map(|a| a.value());
575 let mq_str = match value {
576 Some(ref value) => &***value,
577 None => "",
578 };
579
580 if !MediaList::matches_environment(&document, mq_str) {
581 return;
582 }
583
584 let media = MediaList::parse_media_list(mq_str, document.window());
585 let media = Arc::new(document.style_shared_lock().wrap(media));
586
587 let im_attribute = element.get_attribute(&ns!(), &local_name!("integrity"));
588 let integrity_val = im_attribute.as_ref().map(|a| a.value());
589 let integrity_metadata = match integrity_val {
590 Some(ref value) => &***value,
591 None => "",
592 };
593
594 self.request_generation_id
595 .set(self.request_generation_id.get().increment());
596
597 let loader = ElementStylesheetLoader::new(self.upcast());
598 loader.load(
599 StylesheetContextSource::LinkElement,
600 media,
601 link_url,
602 cors_setting,
603 integrity_metadata.to_owned(),
604 );
605 }
606
607 fn handle_disabled_attribute_change(&self, disabled: bool) {
609 if !disabled {
610 self.is_explicitly_enabled.set(true);
611 }
612 if let Some(stylesheet) = self.get_stylesheet() {
613 if stylesheet.set_disabled(disabled) {
614 self.stylesheet_list_owner().invalidate_stylesheets();
615 }
616 }
617 }
618
619 fn handle_favicon_url(&self) {
620 let window = self.owner_window();
623 if !window.is_top_level() {
624 return;
625 }
626 let Ok(href) = self.Href().parse() else {
627 return;
628 };
629
630 self.request_generation_id
632 .set(self.request_generation_id.get().increment());
633
634 let cache_result = window.image_cache().get_cached_image_status(
635 href,
636 window.origin().immutable().clone(),
637 cors_setting_for_element(self.upcast()),
638 );
639
640 match cache_result {
641 ImageCacheResult::Available(ImageOrMetadataAvailable::ImageAvailable {
642 image, ..
643 }) => {
644 self.process_favicon_response(image);
645 },
646 ImageCacheResult::Available(ImageOrMetadataAvailable::MetadataAvailable(_, id)) |
647 ImageCacheResult::Pending(id) => {
648 let sender = self.register_image_cache_callback(id);
649 window.image_cache().add_listener(ImageLoadListener::new(
650 sender,
651 window.pipeline_id(),
652 id,
653 ));
654 },
655 ImageCacheResult::ReadyForRequest(id) => {
656 let Some(request) = self.default_fetch_and_process_the_linked_resource() else {
657 return;
658 };
659
660 let sender = self.register_image_cache_callback(id);
661 window.image_cache().add_listener(ImageLoadListener::new(
662 sender,
663 window.pipeline_id(),
664 id,
665 ));
666
667 let document = self.upcast::<Node>().owner_doc();
668 let fetch_context = FaviconFetchContext {
669 url: self.owner_document().base_url(),
670 image_cache: window.image_cache(),
671 id,
672 link: Trusted::new(self),
673 };
674 document.fetch_background(request, fetch_context);
675 },
676 ImageCacheResult::FailedToLoadOrDecode => {},
677 };
678 }
679
680 fn register_image_cache_callback(&self, id: PendingImageId) -> ImageCacheResponseCallback {
681 let trusted_node = Trusted::new(self);
682 let window = self.owner_window();
683 let request_generation_id = self.get_request_generation_id();
684 window.register_image_cache_listener(id, move |response| {
685 let trusted_node = trusted_node.clone();
686 let link_element = trusted_node.root();
687 let window = link_element.owner_window();
688
689 let ImageResponse::Loaded(image, _) = response.response else {
690 return;
692 };
693
694 if request_generation_id != link_element.get_request_generation_id() {
695 return;
697 };
698
699 window
700 .as_global_scope()
701 .task_manager()
702 .networking_task_source()
703 .queue(task!(process_favicon_response: move || {
704 let element = trusted_node.root();
705
706 if request_generation_id != element.get_request_generation_id() {
707 return;
709 };
710
711 element.process_favicon_response(image);
712 }));
713 })
714 }
715
716 fn process_favicon_response(&self, image: Image) {
718 let window = self.owner_window();
720 let document = self.owner_document();
721
722 let send_rasterized_favicon_to_embedder = |raster_image: &pixels::RasterImage| {
723 let frame = raster_image.first_frame();
725
726 let format = match raster_image.format {
727 PixelFormat::K8 => embedder_traits::PixelFormat::K8,
728 PixelFormat::KA8 => embedder_traits::PixelFormat::KA8,
729 PixelFormat::RGB8 => embedder_traits::PixelFormat::RGB8,
730 PixelFormat::RGBA8 => embedder_traits::PixelFormat::RGBA8,
731 PixelFormat::BGRA8 => embedder_traits::PixelFormat::BGRA8,
732 };
733
734 let embedder_image = embedder_traits::Image::new(
735 frame.width,
736 frame.height,
737 std::sync::Arc::new(IpcSharedMemory::from_bytes(&raster_image.bytes)),
738 raster_image.frames[0].byte_range.clone(),
739 format,
740 );
741 document.set_favicon(embedder_image);
742 };
743
744 match image {
745 Image::Raster(raster_image) => send_rasterized_favicon_to_embedder(&raster_image),
746 Image::Vector(vector_image) => {
747 let size = DeviceIntSize::new(250, 250);
749
750 let image_cache = window.image_cache();
751 if let Some(raster_image) =
752 image_cache.rasterize_vector_image(vector_image.id, size)
753 {
754 send_rasterized_favicon_to_embedder(&raster_image);
755 } else {
756 let image_cache_sender = self.register_image_cache_callback(vector_image.id);
759 image_cache.add_rasterization_complete_listener(
760 window.pipeline_id(),
761 vector_image.id,
762 size,
763 image_cache_sender,
764 );
765 }
766 },
767 }
768 }
769
770 fn handle_preload_url(&self) {
773 let mut options = self.processing_options();
777 let Some(destination) = self.compute_destination_for_attribute() else {
780 return;
782 };
783 options.destination = destination;
785 {
787 let type_matches_destination = options.type_matches_destination();
789 self.previous_type_matched.set(type_matches_destination);
790 if !type_matches_destination {
791 return;
792 }
793 }
794 let document = self.upcast::<Node>().owner_doc();
796 options.preload(
797 self.owner_window().webview_id(),
798 Some(Trusted::new(self)),
799 &document,
800 );
801 }
802
803 pub(crate) fn fire_event_after_response(
805 &self,
806 response: Result<ResourceFetchTiming, NetworkError>,
807 can_gc: CanGc,
808 ) {
809 if response.is_err() {
812 self.upcast::<EventTarget>()
813 .fire_event(atom!("error"), can_gc);
814 } else {
815 self.upcast::<EventTarget>()
816 .fire_event(atom!("load"), can_gc);
817 }
818 }
819}
820
821impl StylesheetOwner for HTMLLinkElement {
822 fn increment_pending_loads_count(&self) {
823 self.pending_loads.set(self.pending_loads.get() + 1)
824 }
825
826 fn load_finished(&self, succeeded: bool) -> Option<bool> {
827 assert!(self.pending_loads.get() > 0, "What finished?");
828 if !succeeded {
829 self.any_failed_load.set(true);
830 }
831
832 self.pending_loads.set(self.pending_loads.get() - 1);
833 if self.pending_loads.get() != 0 {
834 return None;
835 }
836
837 let any_failed = self.any_failed_load.get();
838 self.any_failed_load.set(false);
839 Some(any_failed)
840 }
841
842 fn parser_inserted(&self) -> bool {
843 self.parser_inserted.get()
844 }
845
846 fn referrer_policy(&self) -> ReferrerPolicy {
847 if self.RelList(CanGc::note()).Contains("noreferrer".into()) {
848 return ReferrerPolicy::NoReferrer;
849 }
850
851 ReferrerPolicy::EmptyString
852 }
853
854 fn set_origin_clean(&self, origin_clean: bool) {
855 if let Some(stylesheet) = self.get_cssom_stylesheet(CanGc::note()) {
856 stylesheet.set_origin_clean(origin_clean);
857 }
858 }
859}
860
861impl HTMLLinkElementMethods<crate::DomTypeHolder> for HTMLLinkElement {
862 make_url_getter!(Href, "href");
864
865 make_url_setter!(SetHref, "href");
867
868 make_getter!(Rel, "rel");
870
871 fn SetRel(&self, rel: DOMString, can_gc: CanGc) {
873 self.upcast::<Element>()
874 .set_tokenlist_attribute(&local_name!("rel"), rel, can_gc);
875 }
876
877 make_enumerated_getter!(
879 As,
880 "as",
881 "fetch" | "audio" | "audioworklet" | "document" | "embed" | "font" | "frame"
882 | "iframe" | "image" | "json" | "manifest" | "object" | "paintworklet"
883 | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "track"
884 | "video" | "webidentity" | "worker" | "xslt",
885 missing => "",
886 invalid => ""
887 );
888
889 make_setter!(SetAs, "as");
891
892 make_getter!(Media, "media");
894
895 make_setter!(SetMedia, "media");
897
898 make_getter!(Integrity, "integrity");
900
901 make_setter!(SetIntegrity, "integrity");
903
904 make_getter!(Hreflang, "hreflang");
906
907 make_setter!(SetHreflang, "hreflang");
909
910 make_getter!(Type, "type");
912
913 make_setter!(SetType, "type");
915
916 make_bool_getter!(Disabled, "disabled");
918
919 make_bool_setter!(SetDisabled, "disabled");
921
922 fn RelList(&self, can_gc: CanGc) -> DomRoot<DOMTokenList> {
924 self.rel_list.or_init(|| {
925 DOMTokenList::new(
926 self.upcast(),
927 &local_name!("rel"),
928 Some(vec![
929 Atom::from("alternate"),
930 Atom::from("apple-touch-icon"),
931 Atom::from("apple-touch-icon-precomposed"),
932 Atom::from("canonical"),
933 Atom::from("dns-prefetch"),
934 Atom::from("icon"),
935 Atom::from("import"),
936 Atom::from("manifest"),
937 Atom::from("modulepreload"),
938 Atom::from("next"),
939 Atom::from("preconnect"),
940 Atom::from("prefetch"),
941 Atom::from("preload"),
942 Atom::from("prerender"),
943 Atom::from("stylesheet"),
944 ]),
945 can_gc,
946 )
947 })
948 }
949
950 make_getter!(Charset, "charset");
952
953 make_setter!(SetCharset, "charset");
955
956 make_getter!(Rev, "rev");
958
959 make_setter!(SetRev, "rev");
961
962 make_getter!(Target, "target");
964
965 make_setter!(SetTarget, "target");
967
968 fn GetCrossOrigin(&self) -> Option<DOMString> {
970 reflect_cross_origin_attribute(self.upcast::<Element>())
971 }
972
973 fn SetCrossOrigin(&self, value: Option<DOMString>, can_gc: CanGc) {
975 set_cross_origin_attribute(self.upcast::<Element>(), value, can_gc);
976 }
977
978 fn ReferrerPolicy(&self) -> DOMString {
980 reflect_referrer_policy_attribute(self.upcast::<Element>())
981 }
982
983 make_setter!(SetReferrerPolicy, "referrerpolicy");
985
986 fn GetSheet(&self, can_gc: CanGc) -> Option<DomRoot<DOMStyleSheet>> {
988 self.get_cssom_stylesheet(can_gc).map(DomRoot::upcast)
989 }
990}
991
992struct FaviconFetchContext {
993 link: Trusted<HTMLLinkElement>,
995 image_cache: std::sync::Arc<dyn ImageCache>,
996 id: PendingImageId,
997
998 url: ServoUrl,
1000}
1001
1002impl FetchResponseListener for FaviconFetchContext {
1003 fn process_request_body(&mut self, _: RequestId) {}
1004
1005 fn process_request_eof(&mut self, _: RequestId) {}
1006
1007 fn process_response(
1008 &mut self,
1009 request_id: RequestId,
1010 metadata: Result<FetchMetadata, NetworkError>,
1011 ) {
1012 self.image_cache.notify_pending_response(
1013 self.id,
1014 FetchResponseMsg::ProcessResponse(request_id, metadata.clone()),
1015 );
1016 }
1017
1018 fn process_response_chunk(&mut self, request_id: RequestId, chunk: Vec<u8>) {
1019 self.image_cache.notify_pending_response(
1020 self.id,
1021 FetchResponseMsg::ProcessResponseChunk(request_id, chunk.into()),
1022 );
1023 }
1024
1025 fn process_response_eof(
1026 self,
1027 request_id: RequestId,
1028 response: Result<ResourceFetchTiming, NetworkError>,
1029 ) {
1030 self.image_cache.notify_pending_response(
1031 self.id,
1032 FetchResponseMsg::ProcessResponseEOF(request_id, response.clone()),
1033 );
1034 if let Ok(response) = response {
1035 submit_timing(&self, &response, CanGc::note());
1036 }
1037 }
1038
1039 fn process_csp_violations(&mut self, _request_id: RequestId, violations: Vec<Violation>) {
1040 let global = &self.resource_timing_global();
1041 let link = self.link.root();
1042 let source_position = link
1043 .upcast::<Element>()
1044 .compute_source_position(link.line_number as u32);
1045 global.report_csp_violations(violations, None, Some(source_position));
1046 }
1047}
1048
1049impl ResourceTimingListener for FaviconFetchContext {
1050 fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
1051 (
1052 InitiatorType::LocalName("link".to_string()),
1053 self.url.clone(),
1054 )
1055 }
1056
1057 fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
1058 self.link.root().upcast::<Node>().owner_doc().global()
1059 }
1060}