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();
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(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(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();
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();
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()
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();
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_value(&local_name!("as"))
525 .and_then(|attr| LinkProcessingOptions::translate_a_preload_destination(&attr))
526 }
527
528 fn processing_options(&self) -> LinkProcessingOptions {
530 let element = self.upcast::<Element>();
531
532 let document = self.upcast::<Node>().owner_doc();
534 let global = document.owner_global();
535
536 let mut options = LinkProcessingOptions {
538 href: String::new(),
539 destination: Destination::None,
540 integrity: String::new(),
541 link_type: String::new(),
542 cryptographic_nonce_metadata: self.upcast::<Element>().nonce_value(),
543 cross_origin: cors_setting_for_element(element),
544 referrer_policy: referrer_policy_for_element(element),
545 policy_container: document.policy_container().to_owned(),
546 source_set: Some(self.source_set.borrow().clone()),
547 origin: document.borrow().origin().immutable().to_owned(),
548 base_url: document.borrow().base_url(),
549 request_client: global.request_client(None),
550 referrer: global.get_referrer(),
551 };
552
553 if let Some(href_attribute) = element.get_attribute_string_value(&local_name!("href")) {
555 options.href = href_attribute;
556 }
557
558 if let Some(integrity_attribute) =
561 element.get_attribute_string_value(&local_name!("integrity"))
562 {
563 options.integrity = integrity_attribute;
564 }
565
566 if let Some(type_attribute) = element.get_attribute_string_value(&local_name!("type")) {
568 options.link_type = type_attribute;
569 }
570
571 assert!(!options.href.is_empty() || options.source_set.is_some());
573
574 options
576 }
577
578 fn default_fetch_and_process_the_linked_resource(&self) -> Option<RequestBuilder> {
583 let options = self.processing_options();
585
586 let Some(request) = options.create_link_request(self.owner_window().webview_id()) else {
588 return None;
590 };
591 let mut request = request.synchronous(true);
593
594 if !self.linked_resource_fetch_setup(&mut request) {
596 return None;
597 }
598
599 Some(request)
605 }
606
607 fn linked_resource_fetch_setup(&self, request: &mut RequestBuilder) -> bool {
609 if self.relations.get().contains(LinkRelations::ICON) {
611 request.destination = Destination::Image;
613
614 }
618
619 if self.relations.get().contains(LinkRelations::STYLESHEET) {
621 if self
623 .upcast::<Element>()
624 .has_attribute(&local_name!("disabled"))
625 {
626 return false;
627 }
628 }
643
644 true
645 }
646
647 fn fetch_and_process_prefetch_link(&self, href: &str) {
649 if href.is_empty() {
651 return;
652 }
653
654 let mut options = self.processing_options();
656
657 options.destination = Destination::None;
659
660 let Some(request) = options.create_link_request(self.owner_window().webview_id()) else {
662 return;
664 };
665 let url = request.url.url();
666
667 let request = request.initiator(Initiator::Prefetch);
669
670 let document = self.upcast::<Node>().owner_doc();
674 let fetch_context = LinkFetchContext {
675 url,
676 link: Some(Trusted::new(self)),
677 global: Trusted::new(&document.global()),
678 type_: LinkFetchContextType::Prefetch,
679 response_body: BytesMut::new(),
680 };
681
682 document.fetch_background(request, fetch_context);
683 }
684
685 fn handle_stylesheet_url(&self, cx: &mut js::context::JSContext) {
687 let document = self.owner_document();
688 if document.browsing_context().is_none() {
689 return;
690 }
691
692 let element = self.upcast::<Element>();
693
694 let type_ = element.get_string_attribute(&local_name!("type"));
701 if !type_.is_empty() && type_ != "text/css" {
702 return;
703 }
704
705 let href = element.get_string_attribute(&local_name!("href"));
707 if href.is_empty() {
708 return;
709 }
710
711 let link_url = match document.base_url().join(&href.str()) {
713 Ok(url) => url,
714 Err(e) => {
715 debug!("Parsing url {} failed: {}", href, e);
716 return;
717 },
718 };
719
720 let cors_setting = cors_setting_for_element(element);
722
723 let mq_str = element
724 .get_attribute_string_value(&local_name!("media"))
725 .unwrap_or_default();
726 let media = MediaList::parse_media_list(&mq_str, document.window());
727 let media = Arc::new(document.style_shared_author_lock().wrap(media));
728
729 let integrity_metadata = element
730 .get_attribute_string_value(&local_name!("integrity"))
731 .unwrap_or_default();
732
733 self.request_generation_id
734 .set(self.request_generation_id.get().increment());
735 self.pending_loads.set(0);
736
737 ElementStylesheetLoader::load_with_element(
738 cx,
739 self.upcast(),
740 StylesheetContextSource::LinkElement,
741 media,
742 link_url,
743 cors_setting,
744 integrity_metadata,
745 );
746 }
747
748 fn handle_disabled_attribute_change(&self, no_gc: &NoGC, is_removal: bool) {
750 if is_removal {
752 self.is_explicitly_enabled.set(true);
753 }
754 if let Some(stylesheet) = self.get_stylesheet() &&
755 stylesheet.set_disabled(!is_removal)
756 {
757 self.stylesheet_list_owner().invalidate_stylesheets(no_gc);
758 }
759 }
760
761 fn handle_favicon_url(&self, href: &str) {
762 if href.is_empty() {
764 return;
765 }
766
767 let window = self.owner_window();
770 if !window.is_top_level() {
771 return;
772 }
773 let Ok(href) = self.Href().parse() else {
774 return;
775 };
776
777 self.request_generation_id
779 .set(self.request_generation_id.get().increment());
780
781 let cache_result = window.image_cache().get_cached_image_status(
782 href,
783 window.origin().immutable().clone(),
784 cors_setting_for_element(self.upcast()),
785 );
786
787 match cache_result {
788 ImageCacheResult::Available(ImageOrMetadataAvailable::ImageAvailable {
789 image, ..
790 }) => {
791 self.process_favicon_response(image);
792 },
793 ImageCacheResult::Available(ImageOrMetadataAvailable::MetadataAvailable(_, id)) |
794 ImageCacheResult::Pending(id) => {
795 let sender = self.register_image_cache_callback(id);
796 window.image_cache().add_listener(ImageLoadListener::new(
797 sender,
798 window.pipeline_id(),
799 id,
800 ));
801 },
802 ImageCacheResult::ReadyForRequest(id) => {
803 let Some(request) = self.default_fetch_and_process_the_linked_resource() else {
804 return;
805 };
806
807 let sender = self.register_image_cache_callback(id);
808 window.image_cache().add_listener(ImageLoadListener::new(
809 sender,
810 window.pipeline_id(),
811 id,
812 ));
813
814 let document = self.upcast::<Node>().owner_doc();
815 let fetch_context = FaviconFetchContext {
816 url: self.owner_document().base_url(),
817 image_cache: window.image_cache(),
818 id,
819 link: Trusted::new(self),
820 };
821 document.fetch_background(request, fetch_context);
822 },
823 ImageCacheResult::FailedToLoadOrDecode => {},
824 };
825 }
826
827 fn register_image_cache_callback(&self, id: PendingImageId) -> ImageCacheResponseCallback {
828 let trusted_node = Trusted::new(self);
829 let window = self.owner_window();
830 let request_generation_id = self.get_request_generation_id();
831 window.register_image_cache_listener(id, move |response, _| {
832 let trusted_node = trusted_node.clone();
833 let link_element = trusted_node.root();
834 let window = link_element.owner_window();
835
836 let ImageResponse::Loaded(image, _) = response.response else {
837 return;
839 };
840
841 if request_generation_id != link_element.get_request_generation_id() {
842 return;
844 };
845
846 window
847 .as_global_scope()
848 .task_manager()
849 .networking_task_source()
850 .queue(task!(process_favicon_response: move || {
851 let element = trusted_node.root();
852
853 if request_generation_id != element.get_request_generation_id() {
854 return;
856 };
857
858 element.process_favicon_response(image);
859 }));
860 })
861 }
862
863 fn process_favicon_response(&self, image: Image) {
865 let window = self.owner_window();
867 let document = self.owner_document();
868
869 let send_rasterized_favicon_to_embedder = |raster_image: &pixels::RasterImage| {
870 let frame = raster_image.first_frame();
872
873 let format = match raster_image.format {
874 PixelFormat::K8 => embedder_traits::PixelFormat::K8,
875 PixelFormat::KA8 => embedder_traits::PixelFormat::KA8,
876 PixelFormat::RGB8 => embedder_traits::PixelFormat::RGB8,
877 PixelFormat::RGBA8 => embedder_traits::PixelFormat::RGBA8,
878 PixelFormat::BGRA8 => embedder_traits::PixelFormat::BGRA8,
879 };
880
881 let embedder_image = embedder_traits::Image::new(
882 frame.width,
883 frame.height,
884 std::sync::Arc::new(GenericSharedMemory::from_arc_vec(
885 raster_image.bytes.clone(),
886 )),
887 raster_image.frames[0].byte_range.clone(),
888 format,
889 );
890 document.set_favicon(embedder_image);
891 };
892
893 match image {
894 Image::Raster(raster_image) => send_rasterized_favicon_to_embedder(&raster_image),
895 Image::Vector(vector_image) => {
896 let size = DeviceIntSize::new(250, 250);
898
899 let image_cache = window.image_cache();
900 if let Some(raster_image) =
901 image_cache.rasterize_vector_image(vector_image.id, size, None)
902 {
903 send_rasterized_favicon_to_embedder(&raster_image);
904 } else {
905 let image_cache_sender = self.register_image_cache_callback(vector_image.id);
908 image_cache.add_rasterization_complete_listener(
909 window.pipeline_id(),
910 vector_image.id,
911 size,
912 image_cache_sender,
913 );
914 }
915 },
916 }
917 }
918
919 fn handle_preload_url(&self) {
922 self.source_set
924 .borrow_mut()
925 .update_source_set(self.upcast::<Element>());
926 let mut options = self.processing_options();
928 let Some(destination) = self.compute_destination_for_attribute() else {
931 return;
933 };
934 options.destination = destination;
936 {
938 let type_matches_destination = options.type_matches_destination();
940 self.previous_type_matched.set(type_matches_destination);
941 if !type_matches_destination {
942 return;
943 }
944 }
945 let document = self.upcast::<Node>().owner_doc();
947 options.preload(
948 self.owner_window().webview_id(),
949 Some(Trusted::new(self)),
950 &document,
951 );
952 }
953
954 pub(crate) fn fire_event_after_response(
956 &self,
957 cx: &mut JSContext,
958 response: Result<(), NetworkError>,
959 ) {
960 if response.is_err() {
963 self.upcast::<EventTarget>().fire_event(cx, atom!("error"));
964 } else {
965 self.upcast::<EventTarget>().fire_event(cx, atom!("load"));
966 }
967 }
968
969 fn fetch_and_process_modulepreload(&self, cx: &mut JSContext) {
971 let el = self.upcast::<Element>();
972 let href_attribute_value = el.get_string_attribute(&local_name!("href"));
973
974 if href_attribute_value.is_empty() {
976 return;
977 }
978
979 let destination = el
981 .get_attribute_string_value(&local_name!("as"))
982 .map(|value| value.to_ascii_lowercase())
983 .and_then(|value| match value.as_str() {
984 "" => None,
986 "fetch" => Some(Destination::None),
988 _ => Destination::from_str(&value).ok(),
989 })
990 .unwrap_or(Destination::Script);
991
992 let document = self.owner_document();
993 let global = document.global();
994
995 let is_a_modulepreload_destination = match destination {
997 Destination::Json | Destination::Style | Destination::Text => true,
998 Destination::Xslt => false,
1001 d => d.is_script_like(),
1002 };
1003
1004 if !is_a_modulepreload_destination {
1007 return global
1008 .task_manager()
1009 .networking_task_source()
1010 .queue_simple_event(self.upcast(), atom!("error"));
1011 }
1012
1013 let Ok(url) = document.encoding_parse_a_url(&href_attribute_value.str()) else {
1016 return;
1017 };
1018 let url = ensure_blob_referenced_by_url_is_kept_alive(&global, url);
1019
1020 let credentials_mode = cors_settings_attribute_credential_mode(el);
1024
1025 let cryptographic_nonce = el.nonce_value();
1027
1028 let integrity_metadata = el
1032 .get_attribute_string_value(&local_name!("integrity"))
1033 .unwrap_or_else(|| {
1034 global
1035 .import_map()
1036 .resolve_a_module_integrity_metadata(&url.url())
1037 });
1038
1039 let referrer_policy = referrer_policy_for_element(el);
1041
1042 let options = ScriptFetchOptions {
1048 cryptographic_nonce,
1049 integrity_metadata,
1050 parser_metadata: ParserMetadata::NotParserInserted,
1051 credentials_mode,
1052 referrer_policy,
1053 render_blocking: false,
1054 };
1055
1056 let link = DomRoot::from_ref(self);
1057
1058 fetch_a_modulepreload_module(
1061 cx,
1062 url,
1063 destination,
1064 &global,
1065 options,
1066 move |cx, fetch_failed| {
1067 let event = match fetch_failed {
1070 true => atom!("error"),
1071 false => atom!("load"),
1072 };
1073
1074 link.upcast::<EventTarget>().fire_event(cx, event);
1075 },
1076 );
1077 }
1078}
1079
1080impl StylesheetOwner for HTMLLinkElement {
1081 fn increment_pending_loads_count(&self) {
1082 self.pending_loads.set(self.pending_loads.get() + 1)
1083 }
1084
1085 fn load_finished(&self, succeeded: bool) -> Option<bool> {
1086 assert!(self.pending_loads.get() > 0, "What finished?");
1087 if !succeeded {
1088 self.any_failed_load.set(true);
1089 }
1090
1091 self.pending_loads.set(self.pending_loads.get() - 1);
1092 if self.pending_loads.get() != 0 {
1093 return None;
1094 }
1095
1096 let any_failed = self.any_failed_load.get();
1097 self.any_failed_load.set(false);
1098 Some(any_failed)
1099 }
1100
1101 fn parser_inserted(&self) -> bool {
1102 self.parser_inserted.get()
1103 }
1104
1105 fn potentially_render_blocking(&self) -> bool {
1107 self.parser_inserted() ||
1114 self.blocking
1115 .get()
1116 .is_some_and(|list| list.Contains(DOMString::from_static("render")))
1117 }
1118
1119 fn referrer_policy(&self, cx: &mut js::context::JSContext) -> ReferrerPolicy {
1120 if self
1121 .RelList(cx)
1122 .Contains(DOMString::from_static("noreferrer"))
1123 {
1124 return ReferrerPolicy::NoReferrer;
1125 }
1126
1127 ReferrerPolicy::EmptyString
1128 }
1129
1130 fn set_origin_clean(&self, cx: &mut js::context::JSContext, origin_clean: bool) {
1131 if let Some(stylesheet) = self.get_cssom_stylesheet(cx) {
1132 stylesheet.set_origin_clean(origin_clean);
1133 }
1134 }
1135}
1136
1137impl HTMLLinkElementMethods<crate::DomTypeHolder> for HTMLLinkElement {
1138 make_url_getter!(Href, "href");
1140
1141 make_url_setter!(SetHref, "href");
1143
1144 make_getter!(Rel, "rel");
1146
1147 fn SetRel(&self, cx: &mut JSContext, rel: DOMString) {
1149 self.upcast::<Element>()
1150 .set_tokenlist_attribute(cx, &local_name!("rel"), rel);
1151 }
1152
1153 make_enumerated_getter!(
1155 As,
1156 "as",
1157 "fetch" | "audio" | "audioworklet" | "document" | "embed" | "font" | "frame"
1158 | "iframe" | "image" | "json" | "manifest" | "object" | "paintworklet"
1159 | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "track"
1160 | "video" | "webidentity" | "worker" | "xslt",
1161 missing => "",
1162 invalid => ""
1163 );
1164
1165 make_setter!(SetAs, "as");
1167
1168 make_getter!(Media, "media");
1170
1171 make_setter!(SetMedia, "media");
1173
1174 make_getter!(Integrity, "integrity");
1176
1177 make_setter!(SetIntegrity, "integrity");
1179
1180 make_getter!(Hreflang, "hreflang");
1182
1183 make_setter!(SetHreflang, "hreflang");
1185
1186 make_getter!(Type, "type");
1188
1189 make_setter!(SetType, "type");
1191
1192 make_url_getter!(ImageSrcset, "imagesrcset");
1194
1195 make_url_setter!(SetImageSrcset, "imagesrcset");
1197
1198 make_getter!(ImageSizes, "imagesizes");
1200
1201 make_setter!(SetImageSizes, "imagesizes");
1203
1204 make_bool_getter!(Disabled, "disabled");
1206
1207 make_bool_setter!(SetDisabled, "disabled");
1209
1210 fn RelList(&self, cx: &mut js::context::JSContext) -> DomRoot<DOMTokenList> {
1212 self.rel_list.or_init(|| {
1213 DOMTokenList::new(
1214 cx,
1215 self.upcast(),
1216 &local_name!("rel"),
1217 Some(vec![
1218 Atom::from("alternate"),
1219 Atom::from("apple-touch-icon"),
1220 Atom::from("apple-touch-icon-precomposed"),
1221 Atom::from("canonical"),
1222 Atom::from("dns-prefetch"),
1223 Atom::from("icon"),
1224 Atom::from("import"),
1225 Atom::from("manifest"),
1226 Atom::from("modulepreload"),
1227 Atom::from("next"),
1228 Atom::from("preconnect"),
1229 Atom::from("prefetch"),
1230 Atom::from("preload"),
1231 Atom::from("prerender"),
1232 Atom::from("stylesheet"),
1233 ]),
1234 )
1235 })
1236 }
1237
1238 make_getter!(Charset, "charset");
1240
1241 make_setter!(SetCharset, "charset");
1243
1244 make_getter!(Rev, "rev");
1246
1247 make_setter!(SetRev, "rev");
1249
1250 make_getter!(Target, "target");
1252
1253 make_setter!(SetTarget, "target");
1255
1256 fn Blocking(&self, cx: &mut js::context::JSContext) -> DomRoot<DOMTokenList> {
1258 self.blocking.or_init(|| {
1259 DOMTokenList::new(
1260 cx,
1261 self.upcast(),
1262 &local_name!("blocking"),
1263 Some(vec![Atom::from("render")]),
1264 )
1265 })
1266 }
1267
1268 fn GetCrossOrigin(&self) -> Option<DOMString> {
1270 reflect_cross_origin_attribute(self.upcast::<Element>())
1271 }
1272
1273 fn SetCrossOrigin(&self, cx: &mut JSContext, value: Option<DOMString>) {
1275 set_cross_origin_attribute(cx, self.upcast::<Element>(), value);
1276 }
1277
1278 fn ReferrerPolicy(&self) -> DOMString {
1280 reflect_referrer_policy_attribute(self.upcast::<Element>())
1281 }
1282
1283 make_setter!(SetReferrerPolicy, "referrerpolicy");
1285
1286 fn GetSheet(&self, cx: &mut JSContext) -> Option<DomRoot<DOMStyleSheet>> {
1288 self.get_cssom_stylesheet(cx).map(DomRoot::upcast)
1289 }
1290}
1291
1292struct FaviconFetchContext {
1293 link: Trusted<HTMLLinkElement>,
1295 image_cache: std::sync::Arc<dyn ImageCache>,
1296 id: PendingImageId,
1297
1298 url: ServoUrl,
1300}
1301
1302impl FetchResponseListener for FaviconFetchContext {
1303 fn process_request_body(&mut self, _: RequestId) {}
1304
1305 fn process_response(
1306 &mut self,
1307 _: &mut js::context::JSContext,
1308 request_id: RequestId,
1309 metadata: Result<FetchMetadata, NetworkError>,
1310 ) {
1311 self.image_cache.notify_pending_response(
1312 self.id,
1313 FetchResponseMsg::ProcessResponse(request_id, metadata),
1314 );
1315 }
1316
1317 fn process_response_chunk(
1318 &mut self,
1319 _: &mut js::context::JSContext,
1320 request_id: RequestId,
1321 chunk: Bytes,
1322 ) {
1323 self.image_cache.notify_pending_response(
1324 self.id,
1325 FetchResponseMsg::ProcessResponseChunk(request_id, chunk),
1326 );
1327 }
1328
1329 fn process_response_eof(
1330 self,
1331 cx: &mut js::context::JSContext,
1332 request_id: RequestId,
1333 response: Result<(), NetworkError>,
1334 timing: ResourceFetchTiming,
1335 ) {
1336 self.image_cache.notify_pending_response(
1337 self.id,
1338 FetchResponseMsg::ProcessResponseEOF(request_id, response.clone(), timing.clone()),
1339 );
1340 submit_timing(cx, &self, &response, &timing);
1341 }
1342
1343 fn process_csp_violations(
1344 &mut self,
1345 cx: &mut js::context::JSContext,
1346 _request_id: RequestId,
1347 violations: Vec<Violation>,
1348 ) {
1349 let global = &self.resource_timing_global();
1350 global.report_csp_violations(cx, violations, None, None);
1351 }
1352
1353 fn process_content_length(&mut self, request_id: RequestId, size: usize) {
1354 self.image_cache.notify_pending_response(
1355 self.id,
1356 FetchResponseMsg::ProcessContentLength(request_id, size),
1357 )
1358 }
1359}
1360
1361impl ResourceTimingListener for FaviconFetchContext {
1362 fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
1363 (
1364 InitiatorType::LocalName("link".to_string()),
1365 self.url.clone(),
1366 )
1367 }
1368
1369 fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
1370 self.link.root().upcast::<Node>().owner_doc().global()
1371 }
1372}