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 { media },
600 link_url,
601 cors_setting,
602 integrity_metadata.to_owned(),
603 );
604 }
605
606 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 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 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 return;
691 };
692
693 if request_generation_id != link_element.get_request_generation_id() {
694 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 return;
708 };
709
710 element.process_favicon_response(image);
711 }));
712 })
713 }
714
715 fn process_favicon_response(&self, image: Image) {
717 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 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 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 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 fn handle_preload_url(&self) {
772 let mut options = self.processing_options();
776 let Some(destination) = self.compute_destination_for_attribute() else {
779 return;
781 };
782 options.destination = destination;
784 {
786 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 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 pub(crate) fn fire_event_after_response(
804 &self,
805 response: Result<ResourceFetchTiming, NetworkError>,
806 can_gc: CanGc,
807 ) {
808 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 make_url_getter!(Href, "href");
863
864 make_url_setter!(SetHref, "href");
866
867 make_getter!(Rel, "rel");
869
870 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 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 make_setter!(SetAs, "as");
890
891 make_getter!(Media, "media");
893
894 make_setter!(SetMedia, "media");
896
897 make_getter!(Integrity, "integrity");
899
900 make_setter!(SetIntegrity, "integrity");
902
903 make_getter!(Hreflang, "hreflang");
905
906 make_setter!(SetHreflang, "hreflang");
908
909 make_getter!(Type, "type");
911
912 make_setter!(SetType, "type");
914
915 make_bool_getter!(Disabled, "disabled");
917
918 make_bool_setter!(SetDisabled, "disabled");
920
921 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 make_getter!(Charset, "charset");
951
952 make_setter!(SetCharset, "charset");
954
955 make_getter!(Rev, "rev");
957
958 make_setter!(SetRev, "rev");
960
961 make_getter!(Target, "target");
963
964 make_setter!(SetTarget, "target");
966
967 fn GetCrossOrigin(&self) -> Option<DOMString> {
969 reflect_cross_origin_attribute(self.upcast::<Element>())
970 }
971
972 fn SetCrossOrigin(&self, value: Option<DOMString>, can_gc: CanGc) {
974 set_cross_origin_attribute(self.upcast::<Element>(), value, can_gc);
975 }
976
977 fn ReferrerPolicy(&self) -> DOMString {
979 reflect_referrer_policy_attribute(self.upcast::<Element>())
980 }
981
982 make_setter!(SetReferrerPolicy, "referrerpolicy");
984
985 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 link: Trusted<HTMLLinkElement>,
994 image_cache: std::sync::Arc<dyn ImageCache>,
995 id: PendingImageId,
996
997 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}