1use std::borrow::{Borrow, ToOwned};
6use std::cell::Cell;
7use std::default::Default;
8use std::str::FromStr;
9
10use bytes::{Bytes, BytesMut};
11use dom_struct::dom_struct;
12use html5ever::{LocalName, Prefix, local_name};
13use js::context::{JSContext, NoGC};
14use js::rust::HandleObject;
15use net_traits::image_cache::{
16 Image, ImageCache, ImageCacheResponseCallback, ImageCacheResult, ImageLoadListener,
17 ImageOrMetadataAvailable, ImageResponse, PendingImageId,
18};
19use net_traits::request::{Destination, Initiator, ParserMetadata, RequestBuilder, RequestId};
20use net_traits::{
21 FetchMetadata, FetchResponseMsg, NetworkError, ReferrerPolicy, ResourceFetchTiming,
22};
23use pixels::PixelFormat;
24use script_bindings::cell::DomRefCell;
25use script_bindings::root::Dom;
26use servo_arc::Arc;
27use servo_base::generic_channel::GenericSharedMemory;
28use servo_url::ServoUrl;
29use style::attr::AttrValue;
30use style::media_queries::MediaList as StyleMediaList;
31use style::stylesheets::Stylesheet;
32use stylo_atoms::Atom;
33use webrender_api::units::DeviceIntSize;
34
35use crate::css::stylesheet_loader::{
36 ElementStylesheetLoader, StylesheetContextSource, StylesheetOwner,
37};
38use crate::dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenList_Binding::DOMTokenListMethods;
39use crate::dom::bindings::codegen::Bindings::HTMLLinkElementBinding::HTMLLinkElementMethods;
40use crate::dom::bindings::inheritance::Castable;
41use crate::dom::bindings::refcounted::Trusted;
42use crate::dom::bindings::reflector::DomGlobal;
43use crate::dom::bindings::root::{DomRoot, MutNullableDom};
44use crate::dom::bindings::str::{DOMString, USVString};
45use crate::dom::csp::{GlobalCspReporting, Violation};
46use crate::dom::css::cssstylesheet::CSSStyleSheet;
47use crate::dom::css::stylesheet::StyleSheet as DOMStyleSheet;
48use crate::dom::document::Document;
49use crate::dom::documentorshadowroot::StylesheetSource;
50use crate::dom::domtokenlist::DOMTokenList;
51use crate::dom::element::attributes::storage::AttrRef;
52use crate::dom::element::{
53 AttributeMutation, Element, ElementCreator, cors_setting_for_element,
54 cors_settings_attribute_credential_mode, referrer_policy_for_element,
55 reflect_cross_origin_attribute, reflect_referrer_policy_attribute, set_cross_origin_attribute,
56};
57use crate::dom::html::document_metadata::processingoptions::{
58 LinkFetchContext, LinkFetchContextType, LinkProcessingOptions,
59};
60use crate::dom::html::htmlelement::HTMLElement;
61use crate::dom::html::links::relations::LinkRelations;
62use crate::dom::medialist::MediaList;
63use crate::dom::node::virtualmethods::VirtualMethods;
64use crate::dom::node::{BindContext, Node, NodeTraits, UnbindContext};
65use crate::dom::performance::performanceresourcetiming::InitiatorType;
66use crate::dom::srcset::SourceSet;
67use crate::dom::types::{EventTarget, GlobalScope};
68use crate::fetch::network_listener::{
69 FetchResponseListener, ResourceTimingListener, submit_timing,
70};
71use crate::modules::script_module::{ScriptFetchOptions, fetch_a_modulepreload_module};
72use crate::url::ensure_blob_referenced_by_url_is_kept_alive;
73
74#[derive(Clone, Copy, JSTraceable, MallocSizeOf, PartialEq)]
75pub(crate) struct RequestGenerationId(u32);
76
77impl RequestGenerationId {
78 fn increment(self) -> RequestGenerationId {
79 RequestGenerationId(self.0 + 1)
80 }
81}
82
83#[dom_struct]
84pub(crate) struct HTMLLinkElement {
85 htmlelement: HTMLElement,
86 rel_list: MutNullableDom<DOMTokenList>,
88
89 #[no_trace]
95 relations: Cell<LinkRelations>,
96
97 #[conditional_malloc_size_of]
98 #[no_trace]
99 stylesheet: DomRefCell<Option<Arc<Stylesheet>>>,
100 cssom_stylesheet: MutNullableDom<CSSStyleSheet>,
101
102 parser_inserted: Cell<bool>,
104 any_failed_load: Cell<bool>,
106 is_explicitly_enabled: Cell<bool>,
108 previous_type_matched: Cell<bool>,
110 pending_loads: Cell<u32>,
113 request_generation_id: Cell<RequestGenerationId>,
115
116 previous_media_environment_matched: Cell<bool>,
118 line_number: u64,
120 source_set: DomRefCell<SourceSet>,
122 blocking: MutNullableDom<DOMTokenList>,
124}
125
126impl HTMLLinkElement {
127 fn new_inherited(
128 local_name: LocalName,
129 prefix: Option<Prefix>,
130 document: &Document,
131 creator: ElementCreator,
132 ) -> HTMLLinkElement {
133 HTMLLinkElement {
134 htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
135 rel_list: Default::default(),
136 relations: Cell::new(LinkRelations::empty()),
137 parser_inserted: Cell::new(creator.is_parser_created()),
138 stylesheet: DomRefCell::new(None),
139 cssom_stylesheet: MutNullableDom::new(None),
140 pending_loads: Cell::new(0),
141 any_failed_load: Cell::new(false),
142 request_generation_id: Cell::new(RequestGenerationId(0)),
143 is_explicitly_enabled: Cell::new(false),
144 previous_type_matched: Cell::new(true),
145 previous_media_environment_matched: Cell::new(true),
146 line_number: creator.return_line_number(),
147 source_set: DomRefCell::new(SourceSet::new()),
148 blocking: Default::default(),
149 }
150 }
151
152 pub(crate) fn new(
153 cx: &mut js::context::JSContext,
154 local_name: LocalName,
155 prefix: Option<Prefix>,
156 document: &Document,
157 proto: Option<HandleObject>,
158 creator: ElementCreator,
159 ) -> DomRoot<HTMLLinkElement> {
160 Node::reflect_node_with_proto(
161 cx,
162 Box::new(HTMLLinkElement::new_inherited(
163 local_name, prefix, document, creator,
164 )),
165 document,
166 proto,
167 )
168 }
169
170 pub(crate) fn get_request_generation_id(&self) -> RequestGenerationId {
171 self.request_generation_id.get()
172 }
173
174 #[cfg_attr(crown, expect(crown::unrooted_must_root))]
175 fn remove_stylesheet(&self, no_gc: &NoGC) {
176 if let Some(stylesheet) = self.stylesheet.borrow_mut().take() {
177 let owner = self.stylesheet_list_owner();
178 owner.remove_stylesheet(
179 StylesheetSource::Element(Dom::from_ref(self.upcast())),
180 &stylesheet,
181 );
182 self.clean_stylesheet_ownership();
183 owner.invalidate_stylesheets(no_gc);
184 }
185 }
186
187 #[cfg_attr(crown, expect(crown::unrooted_must_root))]
190 pub(crate) fn set_stylesheet(&self, no_gc: &NoGC, new_stylesheet: Arc<Stylesheet>) {
191 let owner = self.stylesheet_list_owner();
192 if let Some(old_stylesheet) = self.stylesheet.borrow_mut().replace(new_stylesheet.clone()) {
193 owner.remove_stylesheet(
194 StylesheetSource::Element(Dom::from_ref(self.upcast())),
195 &old_stylesheet,
196 );
197 }
198 owner.add_owned_stylesheet(no_gc, self.upcast(), new_stylesheet);
199 }
200
201 pub(crate) fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> {
202 self.stylesheet.borrow().clone()
203 }
204
205 pub(crate) fn get_cssom_stylesheet(
206 &self,
207 cx: &mut JSContext,
208 ) -> Option<DomRoot<CSSStyleSheet>> {
209 self.get_stylesheet().map(|sheet| {
210 self.cssom_stylesheet.or_init(|| {
211 CSSStyleSheet::new(
212 cx,
213 &self.owner_window(),
214 Some(self.upcast::<Element>()),
215 DOMString::from_static("text/css"),
216 Some(self.Href().into()),
217 None, sheet,
219 None, )
221 })
222 })
223 }
224
225 pub(crate) fn is_alternate(&self) -> bool {
226 self.relations.get().contains(LinkRelations::ALTERNATE) &&
227 !self
228 .upcast::<Element>()
229 .get_string_attribute(&local_name!("title"))
230 .is_empty()
231 }
232
233 pub(crate) fn is_effectively_disabled(&self) -> bool {
234 (self.is_alternate() && !self.is_explicitly_enabled.get()) ||
235 self.upcast::<Element>()
236 .has_attribute(&local_name!("disabled"))
237 }
238
239 fn clean_stylesheet_ownership(&self) {
240 if let Some(cssom_stylesheet) = self.cssom_stylesheet.get() {
241 cssom_stylesheet.set_owner_node(None);
242 }
243 self.cssom_stylesheet.set(None);
244 }
245}
246
247impl VirtualMethods for HTMLLinkElement {
248 fn super_type(&self) -> Option<&dyn VirtualMethods> {
249 Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
250 }
251
252 fn attribute_mutated(
253 &self,
254 cx: &mut js::context::JSContext,
255 attr: AttrRef<'_>,
256 mutation: AttributeMutation,
257 ) {
258 self.super_type()
259 .unwrap()
260 .attribute_mutated(cx, attr, mutation);
261
262 let local_name = attr.local_name();
263 let is_removal = mutation.is_removal();
264 match *local_name {
265 local_name!("disabled") => {
266 self.handle_disabled_attribute_change(cx.no_gc(), is_removal);
267 return;
268 },
269 local_name!("rel") | local_name!("rev") => {
270 let previous_relations = self.relations.get();
271 self.relations
272 .set(LinkRelations::for_element(self.upcast()));
273
274 if previous_relations == self.relations.get() {
276 return;
277 }
278 },
279 _ => {},
280 }
281
282 let node = self.upcast::<Node>();
283 if !node.is_connected() {
284 return;
285 }
286
287 if self.relations.get().contains(LinkRelations::STYLESHEET) &&
290 let AttributeMutation::Set(Some(previous_value)) = mutation &&
291 **previous_value == **attr.value()
292 {
293 return;
294 }
295
296 match *local_name {
297 local_name!("rel") | local_name!("rev") => {
298 if self.relations.get().contains(LinkRelations::STYLESHEET) {
301 self.handle_stylesheet_url(cx);
302 } else {
303 self.remove_stylesheet(cx.no_gc());
304 }
305
306 if self.relations.get().contains(LinkRelations::MODULE_PRELOAD) {
307 self.fetch_and_process_modulepreload(cx);
308 }
309 },
310 local_name!("href") => {
311 if is_removal {
314 if self.relations.get().contains(LinkRelations::STYLESHEET) {
315 self.remove_stylesheet(cx.no_gc());
316 }
317 return;
318 }
319 if self.relations.get().contains(LinkRelations::STYLESHEET) {
323 self.handle_stylesheet_url(cx);
324 }
325
326 if self.relations.get().contains(LinkRelations::ICON) {
327 self.handle_favicon_url(&attr.value());
328 }
329
330 if self.relations.get().contains(LinkRelations::PREFETCH) {
334 self.fetch_and_process_prefetch_link(&attr.value());
335 }
336
337 if self.relations.get().contains(LinkRelations::PRELOAD) {
341 self.handle_preload_url(cx.no_gc());
342 }
343
344 if self.relations.get().contains(LinkRelations::MODULE_PRELOAD) {
346 self.fetch_and_process_modulepreload(cx);
347 }
348 },
349 local_name!("imagesrcset") => {
350 self.source_set
351 .borrow_mut()
352 .update_source_set(cx.no_gc(), self.upcast::<Element>());
353 },
354 local_name!("imagesizes") => {
355 if self
356 .upcast::<Element>()
357 .has_attribute(&local_name!("imagesrcset"))
358 {
359 self.source_set
360 .borrow_mut()
361 .update_source_set(cx.no_gc(), self.upcast::<Element>());
362 }
363 },
364 local_name!("sizes") if self.relations.get().contains(LinkRelations::ICON) => {
365 self.handle_favicon_url(&attr.value());
366 },
367 local_name!("crossorigin") => {
368 if self.relations.get().contains(LinkRelations::PREFETCH) {
372 self.fetch_and_process_prefetch_link(&attr.value());
373 }
374
375 if self.relations.get().contains(LinkRelations::STYLESHEET) {
379 self.handle_stylesheet_url(cx);
380 }
381 },
382 local_name!("as") => {
383 if self.relations.get().contains(LinkRelations::PRELOAD) &&
387 let AttributeMutation::Set(Some(_)) = mutation
388 {
389 self.handle_preload_url(cx.no_gc());
390 }
391 },
392 local_name!("type") => {
393 if self.relations.get().contains(LinkRelations::STYLESHEET) {
401 self.handle_stylesheet_url(cx);
402 }
403
404 if self.relations.get().contains(LinkRelations::PRELOAD) &&
410 !self.previous_type_matched.get()
411 {
412 self.handle_preload_url(cx.no_gc());
413 }
414 },
415 local_name!("media") => {
416 if self.relations.get().contains(LinkRelations::PRELOAD) &&
421 !self.previous_media_environment_matched.get()
422 {
423 match mutation {
424 AttributeMutation::Removed | AttributeMutation::Set(Some(_)) => {
425 self.handle_preload_url(cx.no_gc())
426 },
427 _ => {},
428 };
429 } else if self.relations.get().contains(LinkRelations::STYLESHEET) &&
430 let Some(ref stylesheet) = *self.stylesheet.borrow_mut()
431 {
432 let document = self.owner_document();
433 let shared_lock = document.style_shared_author_lock().clone();
434 let mut guard = shared_lock.write();
435 let media = stylesheet.media.write_with(&mut guard);
436 match mutation {
437 AttributeMutation::Set(_) => {
438 *media = MediaList::parse_media_list(&attr.value(), document.window())
439 },
440 AttributeMutation::Removed => *media = StyleMediaList::empty(),
441 };
442 self.owner_document().invalidate_stylesheets(cx.no_gc());
443 }
444
445 let matches_media_environment =
446 MediaList::matches_environment(&self.owner_document(), &attr.value());
447 self.previous_media_environment_matched
448 .set(matches_media_environment);
449 },
450 _ => {},
451 }
452 }
453
454 fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
455 match name {
456 &local_name!("rel") => AttrValue::from_serialized_tokenlist(value.into()),
457 _ => self
458 .super_type()
459 .unwrap()
460 .parse_plain_attribute(name, value),
461 }
462 }
463
464 fn bind_to_tree(&self, cx: &mut JSContext, context: &BindContext) {
465 if let Some(s) = self.super_type() {
466 s.bind_to_tree(cx, context);
467 }
468
469 let element = self.upcast::<Element>();
470 let href = element.get_attribute_string_value(&local_name!("href"));
471
472 if context.tree_connected &&
473 (href.as_ref().is_some_and(|x| !x.is_empty()) ||
474 element.has_attribute(&local_name!("imagesrcset")))
475 {
476 let relations = self.relations.get();
477 if let Some(href) = href {
480 if relations.contains(LinkRelations::STYLESHEET) {
481 self.handle_stylesheet_url(cx);
482 }
483
484 if relations.contains(LinkRelations::ICON) {
485 self.handle_favicon_url(&href);
486 }
487
488 if relations.contains(LinkRelations::PREFETCH) {
489 self.fetch_and_process_prefetch_link(&href);
490 }
491
492 if relations.contains(LinkRelations::MODULE_PRELOAD) {
494 let link = DomRoot::from_ref(self);
495 self.owner_document().add_delayed_task(
496 task!(FetchModulePreload: |cx, link: DomRoot<HTMLLinkElement>| {
497 link.fetch_and_process_modulepreload(cx);
498 }),
499 );
500 }
501 }
502
503 if relations.contains(LinkRelations::PRELOAD) {
504 self.handle_preload_url(cx.no_gc());
505 }
506 }
507 }
508
509 fn unbind_from_tree(&self, cx: &mut js::context::JSContext, context: &UnbindContext) {
510 if let Some(s) = self.super_type() {
511 s.unbind_from_tree(cx, context);
512 }
513
514 self.remove_stylesheet(cx.no_gc());
515 }
516}
517
518impl HTMLLinkElement {
519 fn compute_destination_for_attribute(&self) -> Option<Destination> {
520 let element = self.upcast::<Element>();
523 element
524 .get_attribute_string_ref(&local_name!("as"))
525 .and_then(|attr| {
526 let attr = attr.as_attr_ref().value();
527 LinkProcessingOptions::translate_a_preload_destination(&attr)
528 })
529 }
530
531 fn processing_options(&self) -> LinkProcessingOptions {
533 let element = self.upcast::<Element>();
534
535 let document = self.upcast::<Node>().owner_doc();
537 let global = document.owner_global();
538
539 let mut options = LinkProcessingOptions {
541 href: String::new(),
542 destination: Destination::None,
543 integrity: String::new(),
544 link_type: String::new(),
545 cryptographic_nonce_metadata: self.upcast::<Element>().nonce_value(),
546 cross_origin: cors_setting_for_element(element),
547 referrer_policy: referrer_policy_for_element(element),
548 policy_container: document.policy_container().clone(),
549 source_set: Some(self.source_set.borrow().clone()),
550 origin: document.borrow().origin().immutable().to_owned(),
551 base_url: document.borrow().base_url(),
552 request_client: global.request_client(None),
553 referrer: global.get_referrer(),
554 };
555
556 if let Some(href_attribute) = element.get_attribute_string_value(&local_name!("href")) {
558 options.href = href_attribute;
559 }
560
561 if let Some(integrity_attribute) =
564 element.get_attribute_string_value(&local_name!("integrity"))
565 {
566 options.integrity = integrity_attribute;
567 }
568
569 if let Some(type_attribute) = element.get_attribute_string_value(&local_name!("type")) {
571 options.link_type = type_attribute;
572 }
573
574 assert!(!options.href.is_empty() || options.source_set.is_some());
576
577 options
579 }
580
581 fn default_fetch_and_process_the_linked_resource(&self) -> Option<RequestBuilder> {
586 let options = self.processing_options();
588
589 let Some(request) = options.create_link_request(self.owner_window().webview_id()) else {
591 return None;
593 };
594 let mut request = request.synchronous(true);
596
597 if !self.linked_resource_fetch_setup(&mut request) {
599 return None;
600 }
601
602 Some(request)
608 }
609
610 fn linked_resource_fetch_setup(&self, request: &mut RequestBuilder) -> bool {
612 if self.relations.get().contains(LinkRelations::ICON) {
614 request.destination = Destination::Image;
616
617 }
621
622 if self.relations.get().contains(LinkRelations::STYLESHEET) {
624 if self
626 .upcast::<Element>()
627 .has_attribute(&local_name!("disabled"))
628 {
629 return false;
630 }
631 }
646
647 true
648 }
649
650 fn fetch_and_process_prefetch_link(&self, href: &str) {
652 if href.is_empty() {
654 return;
655 }
656
657 let mut options = self.processing_options();
659
660 options.destination = Destination::None;
662
663 let Some(request) = options.create_link_request(self.owner_window().webview_id()) else {
665 return;
667 };
668 let url = request.url.url();
669
670 let request = request.initiator(Initiator::Prefetch);
672
673 let document = self.upcast::<Node>().owner_doc();
677 let fetch_context = LinkFetchContext {
678 url,
679 link: Some(Trusted::new(self)),
680 global: Trusted::new(&document.global()),
681 type_: LinkFetchContextType::Prefetch,
682 response_body: BytesMut::new(),
683 };
684
685 document.fetch_background(request, fetch_context);
686 }
687
688 fn handle_stylesheet_url(&self, cx: &mut js::context::JSContext) {
690 let document = self.owner_document();
691 if document.browsing_context().is_none() {
692 return;
693 }
694
695 let element = self.upcast::<Element>();
696
697 let type_ = element.get_string_attribute(&local_name!("type"));
704 if !type_.is_empty() && type_ != "text/css" {
705 return;
706 }
707
708 let href = element.get_string_attribute(&local_name!("href"));
710 if href.is_empty() {
711 return;
712 }
713
714 let link_url = match document.base_url().join(&href.str()) {
716 Ok(url) => url,
717 Err(e) => {
718 debug!("Parsing url {} failed: {}", href, e);
719 return;
720 },
721 };
722
723 let cors_setting = cors_setting_for_element(element);
725
726 let media_query_string = element
727 .get_attribute_string_ref(&local_name!("media"))
728 .unwrap_or_default();
729 let media = MediaList::parse_media_list(
730 &media_query_string.as_attr_ref().value(),
731 document.window(),
732 );
733 let media = Arc::new(document.style_shared_author_lock().wrap(media));
734
735 let integrity_metadata = element
736 .get_attribute_string_value(&local_name!("integrity"))
737 .unwrap_or_default();
738
739 self.request_generation_id
740 .set(self.request_generation_id.get().increment());
741 self.pending_loads.set(0);
742
743 ElementStylesheetLoader::load_with_element(
744 cx,
745 self.upcast(),
746 StylesheetContextSource::LinkElement,
747 media,
748 link_url,
749 cors_setting,
750 integrity_metadata,
751 );
752 }
753
754 fn handle_disabled_attribute_change(&self, no_gc: &NoGC, is_removal: bool) {
756 if is_removal {
758 self.is_explicitly_enabled.set(true);
759 }
760 if let Some(stylesheet) = self.get_stylesheet() &&
761 stylesheet.set_disabled(!is_removal)
762 {
763 self.stylesheet_list_owner().invalidate_stylesheets(no_gc);
764 }
765 }
766
767 fn handle_favicon_url(&self, href: &str) {
768 if href.is_empty() {
770 return;
771 }
772
773 let window = self.owner_window();
776 if !window.is_top_level() {
777 return;
778 }
779 let Ok(href) = self.Href().parse() else {
780 return;
781 };
782
783 self.request_generation_id
785 .set(self.request_generation_id.get().increment());
786
787 let cache_result = window.image_cache().get_cached_image_status(
788 href,
789 window.origin().immutable().clone(),
790 cors_setting_for_element(self.upcast()),
791 );
792
793 match cache_result {
794 ImageCacheResult::Available(ImageOrMetadataAvailable::ImageAvailable {
795 image, ..
796 }) => {
797 self.process_favicon_response(image);
798 },
799 ImageCacheResult::Available(ImageOrMetadataAvailable::MetadataAvailable(_, id)) |
800 ImageCacheResult::Pending(id) => {
801 let sender = self.register_image_cache_callback(id);
802 window.image_cache().add_listener(ImageLoadListener::new(
803 sender,
804 window.pipeline_id(),
805 id,
806 ));
807 },
808 ImageCacheResult::ReadyForRequest(id) => {
809 let Some(request) = self.default_fetch_and_process_the_linked_resource() else {
810 return;
811 };
812
813 let sender = self.register_image_cache_callback(id);
814 window.image_cache().add_listener(ImageLoadListener::new(
815 sender,
816 window.pipeline_id(),
817 id,
818 ));
819
820 let document = self.upcast::<Node>().owner_doc();
821 let fetch_context = FaviconFetchContext {
822 url: self.owner_document().base_url(),
823 image_cache: window.image_cache(),
824 id,
825 link: Trusted::new(self),
826 };
827 document.fetch_background(request, fetch_context);
828 },
829 ImageCacheResult::FailedToLoadOrDecode => {},
830 };
831 }
832
833 fn register_image_cache_callback(&self, id: PendingImageId) -> ImageCacheResponseCallback {
834 let trusted_node = Trusted::new(self);
835 let window = self.owner_window();
836 let request_generation_id = self.get_request_generation_id();
837 window.register_image_cache_listener(id, move |response, _| {
838 let trusted_node = trusted_node.clone();
839 let link_element = trusted_node.root();
840 let window = link_element.owner_window();
841
842 let ImageResponse::Loaded(image, _) = response.response else {
843 return;
845 };
846
847 if request_generation_id != link_element.get_request_generation_id() {
848 return;
850 };
851
852 window
853 .as_global_scope()
854 .task_manager()
855 .networking_task_source()
856 .queue(task!(process_favicon_response: move || {
857 let element = trusted_node.root();
858
859 if request_generation_id != element.get_request_generation_id() {
860 return;
862 };
863
864 element.process_favicon_response(image);
865 }));
866 })
867 }
868
869 fn process_favicon_response(&self, image: Image) {
871 let window = self.owner_window();
873 let document = self.owner_document();
874
875 let send_rasterized_favicon_to_embedder = |raster_image: &pixels::RasterImage| {
876 let frame = raster_image.first_frame();
878
879 let format = match raster_image.format {
880 PixelFormat::K8 => embedder_traits::PixelFormat::K8,
881 PixelFormat::KA8 => embedder_traits::PixelFormat::KA8,
882 PixelFormat::RGB8 => embedder_traits::PixelFormat::RGB8,
883 PixelFormat::RGBA8 => embedder_traits::PixelFormat::RGBA8,
884 PixelFormat::BGRA8 => embedder_traits::PixelFormat::BGRA8,
885 };
886
887 let embedder_image = embedder_traits::Image::new(
888 frame.width,
889 frame.height,
890 std::sync::Arc::new(GenericSharedMemory::from_arc_vec(
891 raster_image.bytes.clone(),
892 )),
893 raster_image.frames[0].byte_range.clone(),
894 format,
895 );
896 document.set_favicon(embedder_image);
897 };
898
899 match image {
900 Image::Raster(raster_image) => send_rasterized_favicon_to_embedder(&raster_image),
901 Image::Vector(vector_image) => {
902 let size = DeviceIntSize::new(250, 250);
904
905 let image_cache = window.image_cache();
906 if let Some(raster_image) =
907 image_cache.rasterize_vector_image(vector_image.id, size, None)
908 {
909 send_rasterized_favicon_to_embedder(&raster_image);
910 } else {
911 let image_cache_sender = self.register_image_cache_callback(vector_image.id);
914 image_cache.add_rasterization_complete_listener(
915 window.pipeline_id(),
916 vector_image.id,
917 size,
918 image_cache_sender,
919 );
920 }
921 },
922 }
923 }
924
925 fn handle_preload_url(&self, no_gc: &NoGC) {
928 self.source_set
930 .borrow_mut()
931 .update_source_set(no_gc, self.upcast::<Element>());
932 let mut options = self.processing_options();
934 let Some(destination) = self.compute_destination_for_attribute() else {
937 return;
939 };
940 options.destination = destination;
942 {
944 let type_matches_destination = options.type_matches_destination();
946 self.previous_type_matched.set(type_matches_destination);
947 if !type_matches_destination {
948 return;
949 }
950 }
951 let document = self.upcast::<Node>().owner_doc();
953 options.preload(
954 self.owner_window().webview_id(),
955 Some(Trusted::new(self)),
956 &document,
957 );
958 }
959
960 pub(crate) fn fire_event_after_response(
962 &self,
963 cx: &mut JSContext,
964 response: Result<(), NetworkError>,
965 ) {
966 if response.is_err() {
969 self.upcast::<EventTarget>().fire_event(cx, atom!("error"));
970 } else {
971 self.upcast::<EventTarget>().fire_event(cx, atom!("load"));
972 }
973 }
974
975 fn fetch_and_process_modulepreload(&self, cx: &mut JSContext) {
977 let el = self.upcast::<Element>();
978 let href_attribute_value = el.get_string_attribute(&local_name!("href"));
979
980 if href_attribute_value.is_empty() {
982 return;
983 }
984
985 let destination = el
987 .get_attribute_string_value(&local_name!("as"))
988 .map(|mut value| {
989 value.make_ascii_lowercase();
990 value
991 })
992 .and_then(|value| match value.as_str() {
993 "" => None,
995 "fetch" => Some(Destination::None),
997 _ => Destination::from_str(&value).ok(),
998 })
999 .unwrap_or(Destination::Script);
1000
1001 let document = self.owner_document();
1002 let global = document.global();
1003
1004 let is_a_modulepreload_destination = match destination {
1006 Destination::Json | Destination::Style | Destination::Text => true,
1007 Destination::Xslt => false,
1010 d => d.is_script_like(),
1011 };
1012
1013 if !is_a_modulepreload_destination {
1016 return global
1017 .task_manager()
1018 .networking_task_source()
1019 .queue_simple_event(self.upcast(), atom!("error"));
1020 }
1021
1022 let Ok(url) = document.encoding_parse_a_url(&href_attribute_value.str()) else {
1025 return;
1026 };
1027 let url = ensure_blob_referenced_by_url_is_kept_alive(&global, url);
1028
1029 let credentials_mode = cors_settings_attribute_credential_mode(el);
1033
1034 let cryptographic_nonce = el.nonce_value();
1036
1037 let integrity_metadata = el
1041 .get_attribute_string_value(&local_name!("integrity"))
1042 .unwrap_or_else(|| {
1043 global
1044 .import_map()
1045 .resolve_a_module_integrity_metadata(&url.url())
1046 });
1047
1048 let referrer_policy = referrer_policy_for_element(el);
1050
1051 let options = ScriptFetchOptions {
1057 cryptographic_nonce,
1058 integrity_metadata,
1059 parser_metadata: ParserMetadata::NotParserInserted,
1060 credentials_mode,
1061 referrer_policy,
1062 render_blocking: false,
1063 };
1064
1065 let link = DomRoot::from_ref(self);
1066
1067 fetch_a_modulepreload_module(
1070 cx,
1071 url,
1072 destination,
1073 &global,
1074 options,
1075 move |cx, fetch_failed| {
1076 let event = match fetch_failed {
1079 true => atom!("error"),
1080 false => atom!("load"),
1081 };
1082
1083 link.upcast::<EventTarget>().fire_event(cx, event);
1084 },
1085 );
1086 }
1087}
1088
1089impl StylesheetOwner for HTMLLinkElement {
1090 fn increment_pending_loads_count(&self) {
1091 self.pending_loads.set(self.pending_loads.get() + 1)
1092 }
1093
1094 fn load_finished(&self, succeeded: bool) -> Option<bool> {
1095 assert!(self.pending_loads.get() > 0, "What finished?");
1096 if !succeeded {
1097 self.any_failed_load.set(true);
1098 }
1099
1100 self.pending_loads.set(self.pending_loads.get() - 1);
1101 if self.pending_loads.get() != 0 {
1102 return None;
1103 }
1104
1105 let any_failed = self.any_failed_load.get();
1106 self.any_failed_load.set(false);
1107 Some(any_failed)
1108 }
1109
1110 fn parser_inserted(&self) -> bool {
1111 self.parser_inserted.get()
1112 }
1113
1114 fn potentially_render_blocking(&self) -> bool {
1116 self.parser_inserted() ||
1123 self.blocking
1124 .get()
1125 .is_some_and(|list| list.Contains(DOMString::from_static("render")))
1126 }
1127
1128 fn referrer_policy(&self, cx: &mut js::context::JSContext) -> ReferrerPolicy {
1129 if self
1130 .RelList(cx)
1131 .Contains(DOMString::from_static("noreferrer"))
1132 {
1133 return ReferrerPolicy::NoReferrer;
1134 }
1135
1136 ReferrerPolicy::EmptyString
1137 }
1138
1139 fn set_origin_clean(&self, cx: &mut js::context::JSContext, origin_clean: bool) {
1140 if let Some(stylesheet) = self.get_cssom_stylesheet(cx) {
1141 stylesheet.set_origin_clean(origin_clean);
1142 }
1143 }
1144}
1145
1146impl HTMLLinkElementMethods<crate::DomTypeHolder> for HTMLLinkElement {
1147 make_url_getter!(Href, "href");
1149
1150 make_url_setter!(SetHref, "href");
1152
1153 make_getter!(Rel, "rel");
1155
1156 fn SetRel(&self, cx: &mut JSContext, rel: DOMString) {
1158 self.upcast::<Element>()
1159 .set_tokenlist_attribute(cx, &local_name!("rel"), rel);
1160 }
1161
1162 make_enumerated_getter!(
1164 As,
1165 "as",
1166 "fetch" | "audio" | "audioworklet" | "document" | "embed" | "font" | "frame"
1167 | "iframe" | "image" | "json" | "manifest" | "object" | "paintworklet"
1168 | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "track"
1169 | "video" | "webidentity" | "worker" | "xslt",
1170 missing => "",
1171 invalid => ""
1172 );
1173
1174 make_setter!(SetAs, "as");
1176
1177 make_getter!(Media, "media");
1179
1180 make_setter!(SetMedia, "media");
1182
1183 make_getter!(Integrity, "integrity");
1185
1186 make_setter!(SetIntegrity, "integrity");
1188
1189 make_getter!(Hreflang, "hreflang");
1191
1192 make_setter!(SetHreflang, "hreflang");
1194
1195 make_getter!(Type, "type");
1197
1198 make_setter!(SetType, "type");
1200
1201 make_url_getter!(ImageSrcset, "imagesrcset");
1203
1204 make_url_setter!(SetImageSrcset, "imagesrcset");
1206
1207 make_getter!(ImageSizes, "imagesizes");
1209
1210 make_setter!(SetImageSizes, "imagesizes");
1212
1213 make_bool_getter!(Disabled, "disabled");
1215
1216 make_bool_setter!(SetDisabled, "disabled");
1218
1219 fn RelList(&self, cx: &mut js::context::JSContext) -> DomRoot<DOMTokenList> {
1221 self.rel_list.or_init(|| {
1222 DOMTokenList::new(
1223 cx,
1224 self.upcast(),
1225 &local_name!("rel"),
1226 Some(vec![
1227 Atom::from("alternate"),
1228 Atom::from("apple-touch-icon"),
1229 Atom::from("apple-touch-icon-precomposed"),
1230 Atom::from("canonical"),
1231 Atom::from("dns-prefetch"),
1232 Atom::from("icon"),
1233 Atom::from("import"),
1234 Atom::from("manifest"),
1235 Atom::from("modulepreload"),
1236 Atom::from("next"),
1237 Atom::from("preconnect"),
1238 Atom::from("prefetch"),
1239 Atom::from("preload"),
1240 Atom::from("prerender"),
1241 Atom::from("stylesheet"),
1242 ]),
1243 )
1244 })
1245 }
1246
1247 make_getter!(Charset, "charset");
1249
1250 make_setter!(SetCharset, "charset");
1252
1253 make_getter!(Rev, "rev");
1255
1256 make_setter!(SetRev, "rev");
1258
1259 make_getter!(Target, "target");
1261
1262 make_setter!(SetTarget, "target");
1264
1265 fn Blocking(&self, cx: &mut js::context::JSContext) -> DomRoot<DOMTokenList> {
1267 self.blocking.or_init(|| {
1268 DOMTokenList::new(
1269 cx,
1270 self.upcast(),
1271 &local_name!("blocking"),
1272 Some(vec![Atom::from("render")]),
1273 )
1274 })
1275 }
1276
1277 fn GetCrossOrigin(&self) -> Option<DOMString> {
1279 reflect_cross_origin_attribute(self.upcast::<Element>())
1280 }
1281
1282 fn SetCrossOrigin(&self, cx: &mut JSContext, value: Option<DOMString>) {
1284 set_cross_origin_attribute(cx, self.upcast::<Element>(), value);
1285 }
1286
1287 fn ReferrerPolicy(&self) -> DOMString {
1289 reflect_referrer_policy_attribute(self.upcast::<Element>())
1290 }
1291
1292 make_setter!(SetReferrerPolicy, "referrerpolicy");
1294
1295 fn GetSheet(&self, cx: &mut JSContext) -> Option<DomRoot<DOMStyleSheet>> {
1297 self.get_cssom_stylesheet(cx).map(DomRoot::upcast)
1298 }
1299}
1300
1301struct FaviconFetchContext {
1302 link: Trusted<HTMLLinkElement>,
1304 image_cache: std::sync::Arc<dyn ImageCache>,
1305 id: PendingImageId,
1306
1307 url: ServoUrl,
1309}
1310
1311impl FetchResponseListener for FaviconFetchContext {
1312 fn process_request_body(&mut self, _: RequestId) {}
1313
1314 fn process_response(
1315 &mut self,
1316 _: &mut js::context::JSContext,
1317 request_id: RequestId,
1318 metadata: Result<FetchMetadata, NetworkError>,
1319 ) {
1320 self.image_cache.notify_pending_response(
1321 self.id,
1322 FetchResponseMsg::ProcessResponse(request_id, metadata),
1323 );
1324 }
1325
1326 fn process_response_chunk(
1327 &mut self,
1328 _: &mut js::context::JSContext,
1329 request_id: RequestId,
1330 chunk: Bytes,
1331 ) {
1332 self.image_cache.notify_pending_response(
1333 self.id,
1334 FetchResponseMsg::ProcessResponseChunk(request_id, chunk),
1335 );
1336 }
1337
1338 fn process_response_eof(
1339 self,
1340 cx: &mut js::context::JSContext,
1341 request_id: RequestId,
1342 response: Result<(), NetworkError>,
1343 timing: ResourceFetchTiming,
1344 ) {
1345 self.image_cache.notify_pending_response(
1346 self.id,
1347 FetchResponseMsg::ProcessResponseEOF(request_id, response.clone(), timing.clone()),
1348 );
1349 submit_timing(cx, &self, &response, &timing);
1350 }
1351
1352 fn process_csp_violations(
1353 &mut self,
1354 cx: &mut js::context::JSContext,
1355 _request_id: RequestId,
1356 violations: Vec<Violation>,
1357 ) {
1358 let global = &self.resource_timing_global();
1359 global.report_csp_violations(cx, violations, None, None);
1360 }
1361
1362 fn process_content_length(&mut self, request_id: RequestId, size: usize) {
1363 self.image_cache.notify_pending_response(
1364 self.id,
1365 FetchResponseMsg::ProcessContentLength(request_id, size),
1366 )
1367 }
1368}
1369
1370impl ResourceTimingListener for FaviconFetchContext {
1371 fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
1372 (
1373 InitiatorType::LocalName("link".to_string()),
1374 self.url.clone(),
1375 )
1376 }
1377
1378 fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
1379 self.link.root().upcast::<Node>().owner_doc().global()
1380 }
1381}