1use std::borrow::{Borrow, ToOwned};
6use std::cell::Cell;
7use std::default::Default;
8use std::str::FromStr;
9
10use dom_struct::dom_struct;
11use html5ever::{LocalName, Prefix, local_name};
12use js::context::JSContext;
13use js::rust::HandleObject;
14use net_traits::image_cache::{
15 Image, ImageCache, ImageCacheResponseCallback, ImageCacheResult, ImageLoadListener,
16 ImageOrMetadataAvailable, ImageResponse, PendingImageId,
17};
18use net_traits::request::{Destination, Initiator, ParserMetadata, RequestBuilder, RequestId};
19use net_traits::{
20 FetchMetadata, FetchResponseMsg, NetworkError, ReferrerPolicy, ResourceFetchTiming,
21};
22use pixels::PixelFormat;
23use script_bindings::cell::DomRefCell;
24use script_bindings::root::Dom;
25use servo_arc::Arc;
26use servo_base::generic_channel::GenericSharedMemory;
27use servo_url::ServoUrl;
28use style::attr::AttrValue;
29use style::media_queries::MediaList as StyleMediaList;
30use style::stylesheets::Stylesheet;
31use stylo_atoms::Atom;
32use webrender_api::units::DeviceIntSize;
33
34use crate::dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenList_Binding::DOMTokenListMethods;
35use crate::dom::bindings::codegen::Bindings::HTMLLinkElementBinding::HTMLLinkElementMethods;
36use crate::dom::bindings::inheritance::Castable;
37use crate::dom::bindings::refcounted::Trusted;
38use crate::dom::bindings::reflector::DomGlobal;
39use crate::dom::bindings::root::{DomRoot, MutNullableDom};
40use crate::dom::bindings::str::{DOMString, USVString};
41use crate::dom::csp::{GlobalCspReporting, Violation};
42use crate::dom::css::cssstylesheet::CSSStyleSheet;
43use crate::dom::css::stylesheet::StyleSheet as DOMStyleSheet;
44use crate::dom::document::Document;
45use crate::dom::documentorshadowroot::StylesheetSource;
46use crate::dom::domtokenlist::DOMTokenList;
47use crate::dom::element::attributes::storage::AttrRef;
48use crate::dom::element::{
49 AttributeMutation, Element, ElementCreator, cors_setting_for_element,
50 cors_settings_attribute_credential_mode, referrer_policy_for_element,
51 reflect_cross_origin_attribute, reflect_referrer_policy_attribute, set_cross_origin_attribute,
52};
53use crate::dom::html::htmlelement::HTMLElement;
54use crate::dom::medialist::MediaList;
55use crate::dom::node::{BindContext, Node, NodeTraits, UnbindContext};
56use crate::dom::performance::performanceresourcetiming::InitiatorType;
57use crate::dom::processingoptions::{
58 LinkFetchContext, LinkFetchContextType, LinkProcessingOptions,
59};
60use crate::dom::types::{EventTarget, GlobalScope};
61use crate::dom::virtualmethods::VirtualMethods;
62use crate::links::LinkRelations;
63use crate::network_listener::{FetchResponseListener, ResourceTimingListener, submit_timing};
64use crate::script_module::{ScriptFetchOptions, fetch_a_modulepreload_module};
65use crate::script_runtime::CanGc;
66use crate::stylesheet_loader::{ElementStylesheetLoader, StylesheetContextSource, StylesheetOwner};
67
68#[derive(Clone, Copy, JSTraceable, MallocSizeOf, PartialEq)]
69pub(crate) struct RequestGenerationId(u32);
70
71impl RequestGenerationId {
72 fn increment(self) -> RequestGenerationId {
73 RequestGenerationId(self.0 + 1)
74 }
75}
76
77#[dom_struct]
78pub(crate) struct HTMLLinkElement {
79 htmlelement: HTMLElement,
80 rel_list: MutNullableDom<DOMTokenList>,
82
83 #[no_trace]
89 relations: Cell<LinkRelations>,
90
91 #[conditional_malloc_size_of]
92 #[no_trace]
93 stylesheet: DomRefCell<Option<Arc<Stylesheet>>>,
94 cssom_stylesheet: MutNullableDom<CSSStyleSheet>,
95
96 parser_inserted: Cell<bool>,
98 pending_loads: Cell<u32>,
101 any_failed_load: Cell<bool>,
103 request_generation_id: Cell<RequestGenerationId>,
105 is_explicitly_enabled: Cell<bool>,
107 previous_type_matched: Cell<bool>,
109 previous_media_environment_matched: Cell<bool>,
111 line_number: u64,
113 blocking: MutNullableDom<DOMTokenList>,
115}
116
117impl HTMLLinkElement {
118 fn new_inherited(
119 local_name: LocalName,
120 prefix: Option<Prefix>,
121 document: &Document,
122 creator: ElementCreator,
123 ) -> HTMLLinkElement {
124 HTMLLinkElement {
125 htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
126 rel_list: Default::default(),
127 relations: Cell::new(LinkRelations::empty()),
128 parser_inserted: Cell::new(creator.is_parser_created()),
129 stylesheet: DomRefCell::new(None),
130 cssom_stylesheet: MutNullableDom::new(None),
131 pending_loads: Cell::new(0),
132 any_failed_load: Cell::new(false),
133 request_generation_id: Cell::new(RequestGenerationId(0)),
134 is_explicitly_enabled: Cell::new(false),
135 previous_type_matched: Cell::new(true),
136 previous_media_environment_matched: Cell::new(true),
137 line_number: creator.return_line_number(),
138 blocking: Default::default(),
139 }
140 }
141
142 pub(crate) fn new(
143 cx: &mut js::context::JSContext,
144 local_name: LocalName,
145 prefix: Option<Prefix>,
146 document: &Document,
147 proto: Option<HandleObject>,
148 creator: ElementCreator,
149 ) -> DomRoot<HTMLLinkElement> {
150 Node::reflect_node_with_proto(
151 cx,
152 Box::new(HTMLLinkElement::new_inherited(
153 local_name, prefix, document, creator,
154 )),
155 document,
156 proto,
157 )
158 }
159
160 pub(crate) fn get_request_generation_id(&self) -> RequestGenerationId {
161 self.request_generation_id.get()
162 }
163
164 #[cfg_attr(crown, expect(crown::unrooted_must_root))]
165 fn remove_stylesheet(&self) {
166 if let Some(stylesheet) = self.stylesheet.borrow_mut().take() {
167 let owner = self.stylesheet_list_owner();
168 owner.remove_stylesheet(
169 StylesheetSource::Element(Dom::from_ref(self.upcast())),
170 &stylesheet,
171 );
172 self.clean_stylesheet_ownership();
173 owner.invalidate_stylesheets();
174 }
175 }
176
177 #[cfg_attr(crown, expect(crown::unrooted_must_root))]
180 pub(crate) fn set_stylesheet(
181 &self,
182 cx: &mut js::context::JSContext,
183 new_stylesheet: Arc<Stylesheet>,
184 ) {
185 let owner = self.stylesheet_list_owner();
186 if let Some(old_stylesheet) = self.stylesheet.borrow_mut().replace(new_stylesheet.clone()) {
187 owner.remove_stylesheet(
188 StylesheetSource::Element(Dom::from_ref(self.upcast())),
189 &old_stylesheet,
190 );
191 }
192 owner.add_owned_stylesheet(cx, self.upcast(), new_stylesheet);
193 }
194
195 pub(crate) fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> {
196 self.stylesheet.borrow().clone()
197 }
198
199 pub(crate) fn get_cssom_stylesheet(&self, can_gc: CanGc) -> Option<DomRoot<CSSStyleSheet>> {
200 self.get_stylesheet().map(|sheet| {
201 self.cssom_stylesheet.or_init(|| {
202 CSSStyleSheet::new(
203 &self.owner_window(),
204 Some(self.upcast::<Element>()),
205 "text/css".into(),
206 Some(self.Href().into()),
207 None, sheet,
209 None, can_gc,
211 )
212 })
213 })
214 }
215
216 pub(crate) fn is_alternate(&self) -> bool {
217 self.relations.get().contains(LinkRelations::ALTERNATE) &&
218 !self
219 .upcast::<Element>()
220 .get_string_attribute(&local_name!("title"))
221 .is_empty()
222 }
223
224 pub(crate) fn is_effectively_disabled(&self) -> bool {
225 (self.is_alternate() && !self.is_explicitly_enabled.get()) ||
226 self.upcast::<Element>()
227 .has_attribute(&local_name!("disabled"))
228 }
229
230 fn clean_stylesheet_ownership(&self) {
231 if let Some(cssom_stylesheet) = self.cssom_stylesheet.get() {
232 cssom_stylesheet.set_owner_node(None);
233 }
234 self.cssom_stylesheet.set(None);
235 }
236}
237
238impl VirtualMethods for HTMLLinkElement {
239 fn super_type(&self) -> Option<&dyn VirtualMethods> {
240 Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
241 }
242
243 fn attribute_mutated(
244 &self,
245 cx: &mut js::context::JSContext,
246 attr: AttrRef<'_>,
247 mutation: AttributeMutation,
248 ) {
249 self.super_type()
250 .unwrap()
251 .attribute_mutated(cx, attr, mutation);
252
253 let local_name = attr.local_name();
254 let is_removal = mutation.is_removal();
255 match *local_name {
256 local_name!("disabled") => {
257 self.handle_disabled_attribute_change(is_removal);
258 return;
259 },
260 local_name!("rel") | local_name!("rev") => {
261 let previous_relations = self.relations.get();
262 self.relations
263 .set(LinkRelations::for_element(self.upcast()));
264
265 if previous_relations == self.relations.get() {
267 return;
268 }
269 },
270 _ => {},
271 }
272
273 let node = self.upcast::<Node>();
274 if !node.is_connected() {
275 return;
276 }
277
278 if self.relations.get().contains(LinkRelations::STYLESHEET) &&
281 let AttributeMutation::Set(Some(previous_value), _) = mutation &&
282 **previous_value == **attr.value()
283 {
284 return;
285 }
286
287 match *local_name {
288 local_name!("rel") | local_name!("rev") => {
289 if self.relations.get().contains(LinkRelations::STYLESHEET) {
292 self.handle_stylesheet_url(cx);
293 } else {
294 self.remove_stylesheet();
295 }
296
297 if self.relations.get().contains(LinkRelations::MODULE_PRELOAD) {
298 self.fetch_and_process_modulepreload(cx);
299 }
300 },
301 local_name!("href") => {
302 if is_removal {
305 if self.relations.get().contains(LinkRelations::STYLESHEET) {
306 self.remove_stylesheet();
307 }
308 return;
309 }
310 if self.relations.get().contains(LinkRelations::STYLESHEET) {
314 self.handle_stylesheet_url(cx);
315 }
316
317 if self.relations.get().contains(LinkRelations::ICON) {
318 self.handle_favicon_url(&attr.value());
319 }
320
321 if self.relations.get().contains(LinkRelations::PREFETCH) {
325 self.fetch_and_process_prefetch_link(&attr.value());
326 }
327
328 if self.relations.get().contains(LinkRelations::PRELOAD) {
332 self.handle_preload_url();
333 }
334
335 if self.relations.get().contains(LinkRelations::MODULE_PRELOAD) {
337 self.fetch_and_process_modulepreload(cx);
338 }
339 },
340 local_name!("sizes") if self.relations.get().contains(LinkRelations::ICON) => {
341 self.handle_favicon_url(&attr.value());
342 },
343 local_name!("crossorigin") => {
344 if self.relations.get().contains(LinkRelations::PREFETCH) {
348 self.fetch_and_process_prefetch_link(&attr.value());
349 }
350
351 if self.relations.get().contains(LinkRelations::STYLESHEET) {
355 self.handle_stylesheet_url(cx);
356 }
357 },
358 local_name!("as") => {
359 if self.relations.get().contains(LinkRelations::PRELOAD) &&
363 let AttributeMutation::Set(Some(_), _) = mutation
364 {
365 self.handle_preload_url();
366 }
367 },
368 local_name!("type") => {
369 if self.relations.get().contains(LinkRelations::STYLESHEET) {
377 self.handle_stylesheet_url(cx);
378 }
379
380 if self.relations.get().contains(LinkRelations::PRELOAD) &&
386 !self.previous_type_matched.get()
387 {
388 self.handle_preload_url();
389 }
390 },
391 local_name!("media") => {
392 if self.relations.get().contains(LinkRelations::PRELOAD) &&
397 !self.previous_media_environment_matched.get()
398 {
399 match mutation {
400 AttributeMutation::Removed | AttributeMutation::Set(Some(_), _) => {
401 self.handle_preload_url()
402 },
403 _ => {},
404 };
405 } else if self.relations.get().contains(LinkRelations::STYLESHEET) &&
406 let Some(ref stylesheet) = *self.stylesheet.borrow_mut()
407 {
408 let document = self.owner_document();
409 let shared_lock = document.style_shared_author_lock().clone();
410 let mut guard = shared_lock.write();
411 let media = stylesheet.media.write_with(&mut guard);
412 match mutation {
413 AttributeMutation::Set(..) => {
414 *media = MediaList::parse_media_list(&attr.value(), document.window())
415 },
416 AttributeMutation::Removed => *media = StyleMediaList::empty(),
417 };
418 self.owner_document().invalidate_stylesheets();
419 }
420
421 let matches_media_environment =
422 MediaList::matches_environment(&self.owner_document(), &attr.value());
423 self.previous_media_environment_matched
424 .set(matches_media_environment);
425 },
426 _ => {},
427 }
428 }
429
430 fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
431 match name {
432 &local_name!("rel") => AttrValue::from_serialized_tokenlist(value.into()),
433 _ => self
434 .super_type()
435 .unwrap()
436 .parse_plain_attribute(name, value),
437 }
438 }
439
440 fn bind_to_tree(&self, cx: &mut JSContext, context: &BindContext) {
441 if let Some(s) = self.super_type() {
442 s.bind_to_tree(cx, context);
443 }
444
445 if context.tree_connected &&
446 let Some(href) = self
447 .upcast::<Element>()
448 .get_attribute_string_value(&local_name!("href"))
449 {
450 let relations = self.relations.get();
451 if relations.contains(LinkRelations::STYLESHEET) {
454 self.handle_stylesheet_url(cx);
455 }
456
457 if relations.contains(LinkRelations::ICON) {
458 self.handle_favicon_url(&href);
459 }
460
461 if relations.contains(LinkRelations::PREFETCH) {
462 self.fetch_and_process_prefetch_link(&href);
463 }
464
465 if relations.contains(LinkRelations::PRELOAD) {
466 self.handle_preload_url();
467 }
468
469 if relations.contains(LinkRelations::MODULE_PRELOAD) {
471 let link = DomRoot::from_ref(self);
472 self.owner_document().add_delayed_task(
473 task!(FetchModulePreload: |cx, link: DomRoot<HTMLLinkElement>| {
474 link.fetch_and_process_modulepreload(cx);
475 }),
476 );
477 }
478 }
479 }
480
481 fn unbind_from_tree(&self, cx: &mut js::context::JSContext, context: &UnbindContext) {
482 if let Some(s) = self.super_type() {
483 s.unbind_from_tree(cx, context);
484 }
485
486 self.remove_stylesheet();
487 }
488}
489
490impl HTMLLinkElement {
491 fn compute_destination_for_attribute(&self) -> Option<Destination> {
492 let element = self.upcast::<Element>();
495 element
496 .get_attribute_string_value(&local_name!("as"))
497 .and_then(|attr| LinkProcessingOptions::translate_a_preload_destination(&attr))
498 }
499
500 fn processing_options(&self) -> LinkProcessingOptions {
502 let element = self.upcast::<Element>();
503
504 let document = self.upcast::<Node>().owner_doc();
506 let global = document.owner_global();
507
508 let mut options = LinkProcessingOptions {
510 href: String::new(),
511 destination: Destination::None,
512 integrity: String::new(),
513 link_type: String::new(),
514 cryptographic_nonce_metadata: self.upcast::<Element>().nonce_value(),
515 cross_origin: cors_setting_for_element(element),
516 referrer_policy: referrer_policy_for_element(element),
517 policy_container: document.policy_container().to_owned(),
518 source_set: None, origin: document.borrow().origin().immutable().to_owned(),
520 base_url: document.borrow().base_url(),
521 insecure_requests_policy: document.insecure_requests_policy(),
522 has_trustworthy_ancestor_origin: document.has_trustworthy_ancestor_or_current_origin(),
523 request_client: global.request_client(),
524 referrer: global.get_referrer(),
525 };
526
527 if let Some(href_attribute) = element.get_attribute_string_value(&local_name!("href")) {
529 options.href = href_attribute;
530 }
531
532 if let Some(integrity_attribute) =
535 element.get_attribute_string_value(&local_name!("integrity"))
536 {
537 options.integrity = integrity_attribute;
538 }
539
540 if let Some(type_attribute) = element.get_attribute_string_value(&local_name!("type")) {
542 options.link_type = type_attribute;
543 }
544
545 assert!(!options.href.is_empty() || options.source_set.is_some());
547
548 options
550 }
551
552 fn default_fetch_and_process_the_linked_resource(&self) -> Option<RequestBuilder> {
557 let options = self.processing_options();
559
560 let Some(request) = options.create_link_request(self.owner_window().webview_id()) else {
562 return None;
564 };
565 let mut request = request.synchronous(true);
567
568 if !self.linked_resource_fetch_setup(&mut request) {
570 return None;
571 }
572
573 Some(request)
579 }
580
581 fn linked_resource_fetch_setup(&self, request: &mut RequestBuilder) -> bool {
583 if self.relations.get().contains(LinkRelations::ICON) {
585 request.destination = Destination::Image;
587
588 }
592
593 if self.relations.get().contains(LinkRelations::STYLESHEET) {
595 if self
597 .upcast::<Element>()
598 .has_attribute(&local_name!("disabled"))
599 {
600 return false;
601 }
602 }
617
618 true
619 }
620
621 fn fetch_and_process_prefetch_link(&self, href: &str) {
623 if href.is_empty() {
625 return;
626 }
627
628 let mut options = self.processing_options();
630
631 options.destination = Destination::None;
633
634 let Some(request) = options.create_link_request(self.owner_window().webview_id()) else {
636 return;
638 };
639 let url = request.url.url();
640
641 let request = request.initiator(Initiator::Prefetch);
643
644 let document = self.upcast::<Node>().owner_doc();
648 let fetch_context = LinkFetchContext {
649 url,
650 link: Some(Trusted::new(self)),
651 document: Trusted::new(&document),
652 global: Trusted::new(&document.global()),
653 type_: LinkFetchContextType::Prefetch,
654 response_body: vec![],
655 };
656
657 document.fetch_background(request, fetch_context);
658 }
659
660 fn handle_stylesheet_url(&self, cx: &mut js::context::JSContext) {
662 let document = self.owner_document();
663 if document.browsing_context().is_none() {
664 return;
665 }
666
667 let element = self.upcast::<Element>();
668
669 let type_ = element.get_string_attribute(&local_name!("type"));
676 if !type_.is_empty() && type_ != "text/css" {
677 return;
678 }
679
680 let href = element.get_string_attribute(&local_name!("href"));
682 if href.is_empty() {
683 return;
684 }
685
686 let link_url = match document.base_url().join(&href.str()) {
688 Ok(url) => url,
689 Err(e) => {
690 debug!("Parsing url {} failed: {}", href, e);
691 return;
692 },
693 };
694
695 let cors_setting = cors_setting_for_element(element);
697
698 let mq_str = element
699 .get_attribute_string_value(&local_name!("media"))
700 .unwrap_or_default();
701 let media = MediaList::parse_media_list(&mq_str, document.window());
702 let media = Arc::new(document.style_shared_author_lock().wrap(media));
703
704 let integrity_metadata = element
705 .get_attribute_string_value(&local_name!("integrity"))
706 .unwrap_or_default();
707
708 self.request_generation_id
709 .set(self.request_generation_id.get().increment());
710 self.pending_loads.set(0);
711
712 ElementStylesheetLoader::load_with_element(
713 cx,
714 self.upcast(),
715 StylesheetContextSource::LinkElement,
716 media,
717 link_url,
718 cors_setting,
719 integrity_metadata,
720 );
721 }
722
723 fn handle_disabled_attribute_change(&self, is_removal: bool) {
725 if is_removal {
727 self.is_explicitly_enabled.set(true);
728 }
729 if let Some(stylesheet) = self.get_stylesheet() &&
730 stylesheet.set_disabled(!is_removal)
731 {
732 self.stylesheet_list_owner().invalidate_stylesheets();
733 }
734 }
735
736 fn handle_favicon_url(&self, href: &str) {
737 if href.is_empty() {
739 return;
740 }
741
742 let window = self.owner_window();
745 if !window.is_top_level() {
746 return;
747 }
748 let Ok(href) = self.Href().parse() else {
749 return;
750 };
751
752 self.request_generation_id
754 .set(self.request_generation_id.get().increment());
755
756 let cache_result = window.image_cache().get_cached_image_status(
757 href,
758 window.origin().immutable().clone(),
759 cors_setting_for_element(self.upcast()),
760 );
761
762 match cache_result {
763 ImageCacheResult::Available(ImageOrMetadataAvailable::ImageAvailable {
764 image, ..
765 }) => {
766 self.process_favicon_response(image);
767 },
768 ImageCacheResult::Available(ImageOrMetadataAvailable::MetadataAvailable(_, id)) |
769 ImageCacheResult::Pending(id) => {
770 let sender = self.register_image_cache_callback(id);
771 window.image_cache().add_listener(ImageLoadListener::new(
772 sender,
773 window.pipeline_id(),
774 id,
775 ));
776 },
777 ImageCacheResult::ReadyForRequest(id) => {
778 let Some(request) = self.default_fetch_and_process_the_linked_resource() else {
779 return;
780 };
781
782 let sender = self.register_image_cache_callback(id);
783 window.image_cache().add_listener(ImageLoadListener::new(
784 sender,
785 window.pipeline_id(),
786 id,
787 ));
788
789 let document = self.upcast::<Node>().owner_doc();
790 let fetch_context = FaviconFetchContext {
791 url: self.owner_document().base_url(),
792 image_cache: window.image_cache(),
793 id,
794 link: Trusted::new(self),
795 };
796 document.fetch_background(request, fetch_context);
797 },
798 ImageCacheResult::FailedToLoadOrDecode => {},
799 };
800 }
801
802 fn register_image_cache_callback(&self, id: PendingImageId) -> ImageCacheResponseCallback {
803 let trusted_node = Trusted::new(self);
804 let window = self.owner_window();
805 let request_generation_id = self.get_request_generation_id();
806 window.register_image_cache_listener(id, move |response, _| {
807 let trusted_node = trusted_node.clone();
808 let link_element = trusted_node.root();
809 let window = link_element.owner_window();
810
811 let ImageResponse::Loaded(image, _) = response.response else {
812 return;
814 };
815
816 if request_generation_id != link_element.get_request_generation_id() {
817 return;
819 };
820
821 window
822 .as_global_scope()
823 .task_manager()
824 .networking_task_source()
825 .queue(task!(process_favicon_response: move || {
826 let element = trusted_node.root();
827
828 if request_generation_id != element.get_request_generation_id() {
829 return;
831 };
832
833 element.process_favicon_response(image);
834 }));
835 })
836 }
837
838 fn process_favicon_response(&self, image: Image) {
840 let window = self.owner_window();
842 let document = self.owner_document();
843
844 let send_rasterized_favicon_to_embedder = |raster_image: &pixels::RasterImage| {
845 let frame = raster_image.first_frame();
847
848 let format = match raster_image.format {
849 PixelFormat::K8 => embedder_traits::PixelFormat::K8,
850 PixelFormat::KA8 => embedder_traits::PixelFormat::KA8,
851 PixelFormat::RGB8 => embedder_traits::PixelFormat::RGB8,
852 PixelFormat::RGBA8 => embedder_traits::PixelFormat::RGBA8,
853 PixelFormat::BGRA8 => embedder_traits::PixelFormat::BGRA8,
854 };
855
856 let embedder_image = embedder_traits::Image::new(
857 frame.width,
858 frame.height,
859 std::sync::Arc::new(GenericSharedMemory::from_arc_vec(
860 raster_image.bytes.clone(),
861 )),
862 raster_image.frames[0].byte_range.clone(),
863 format,
864 );
865 document.set_favicon(embedder_image);
866 };
867
868 match image {
869 Image::Raster(raster_image) => send_rasterized_favicon_to_embedder(&raster_image),
870 Image::Vector(vector_image) => {
871 let size = DeviceIntSize::new(250, 250);
873
874 let image_cache = window.image_cache();
875 if let Some(raster_image) =
876 image_cache.rasterize_vector_image(vector_image.id, size, None)
877 {
878 send_rasterized_favicon_to_embedder(&raster_image);
879 } else {
880 let image_cache_sender = self.register_image_cache_callback(vector_image.id);
883 image_cache.add_rasterization_complete_listener(
884 window.pipeline_id(),
885 vector_image.id,
886 size,
887 image_cache_sender,
888 );
889 }
890 },
891 }
892 }
893
894 fn handle_preload_url(&self) {
897 let mut options = self.processing_options();
901 let Some(destination) = self.compute_destination_for_attribute() else {
904 return;
906 };
907 options.destination = destination;
909 {
911 let type_matches_destination = options.type_matches_destination();
913 self.previous_type_matched.set(type_matches_destination);
914 if !type_matches_destination {
915 return;
916 }
917 }
918 let document = self.upcast::<Node>().owner_doc();
920 options.preload(
921 self.owner_window().webview_id(),
922 Some(Trusted::new(self)),
923 &document,
924 );
925 }
926
927 pub(crate) fn fire_event_after_response(
929 &self,
930 cx: &mut JSContext,
931 response: Result<(), NetworkError>,
932 ) {
933 if response.is_err() {
936 self.upcast::<EventTarget>().fire_event(cx, atom!("error"));
937 } else {
938 self.upcast::<EventTarget>().fire_event(cx, atom!("load"));
939 }
940 }
941
942 fn fetch_and_process_modulepreload(&self, cx: &mut JSContext) {
944 let el = self.upcast::<Element>();
945 let href_attribute_value = el.get_string_attribute(&local_name!("href"));
946
947 if href_attribute_value.is_empty() {
949 return;
950 }
951
952 let destination = el
954 .get_attribute_string_value(&local_name!("as"))
955 .map(|value| value.to_ascii_lowercase())
956 .and_then(|value| match value.as_str() {
957 "" => None,
959 "fetch" => Some(Destination::None),
961 _ => Destination::from_str(&value).ok(),
962 })
963 .unwrap_or(Destination::Script);
964
965 let document = self.owner_document();
966 let global = document.global();
967
968 let is_a_modulepreload_destination = match destination {
970 Destination::Json | Destination::Style => true,
971 Destination::Xslt => false,
974 d => d.is_script_like(),
975 };
976
977 if !is_a_modulepreload_destination {
980 return global
981 .task_manager()
982 .networking_task_source()
983 .queue_simple_event(self.upcast(), atom!("error"));
984 }
985
986 let Ok(url) = document.encoding_parse_a_url(&href_attribute_value.str()) else {
989 return;
990 };
991
992 let credentials_mode = cors_settings_attribute_credential_mode(el);
996
997 let cryptographic_nonce = el.nonce_value();
999
1000 let integrity_metadata = el
1004 .get_attribute_string_value(&local_name!("integrity"))
1005 .unwrap_or_else(|| {
1006 global
1007 .import_map()
1008 .resolve_a_module_integrity_metadata(&url)
1009 });
1010
1011 let referrer_policy = referrer_policy_for_element(el);
1013
1014 let options = ScriptFetchOptions {
1020 cryptographic_nonce,
1021 integrity_metadata,
1022 parser_metadata: ParserMetadata::NotParserInserted,
1023 credentials_mode,
1024 referrer_policy,
1025 render_blocking: false,
1026 };
1027
1028 let link = DomRoot::from_ref(self);
1029
1030 fetch_a_modulepreload_module(
1033 cx,
1034 url,
1035 destination,
1036 &global,
1037 options,
1038 move |cx, fetch_failed| {
1039 let event = match fetch_failed {
1042 true => atom!("error"),
1043 false => atom!("load"),
1044 };
1045
1046 link.upcast::<EventTarget>().fire_event(cx, event);
1047 },
1048 );
1049 }
1050}
1051
1052impl StylesheetOwner for HTMLLinkElement {
1053 fn increment_pending_loads_count(&self) {
1054 self.pending_loads.set(self.pending_loads.get() + 1)
1055 }
1056
1057 fn load_finished(&self, succeeded: bool) -> Option<bool> {
1058 assert!(self.pending_loads.get() > 0, "What finished?");
1059 if !succeeded {
1060 self.any_failed_load.set(true);
1061 }
1062
1063 self.pending_loads.set(self.pending_loads.get() - 1);
1064 if self.pending_loads.get() != 0 {
1065 return None;
1066 }
1067
1068 let any_failed = self.any_failed_load.get();
1069 self.any_failed_load.set(false);
1070 Some(any_failed)
1071 }
1072
1073 fn parser_inserted(&self) -> bool {
1074 self.parser_inserted.get()
1075 }
1076
1077 fn potentially_render_blocking(&self) -> bool {
1079 self.parser_inserted() ||
1086 self.blocking
1087 .get()
1088 .is_some_and(|list| list.Contains("render".into()))
1089 }
1090
1091 fn referrer_policy(&self, cx: &mut js::context::JSContext) -> ReferrerPolicy {
1092 if self.RelList(cx).Contains("noreferrer".into()) {
1093 return ReferrerPolicy::NoReferrer;
1094 }
1095
1096 ReferrerPolicy::EmptyString
1097 }
1098
1099 fn set_origin_clean(&self, origin_clean: bool) {
1100 if let Some(stylesheet) = self.get_cssom_stylesheet(CanGc::deprecated_note()) {
1101 stylesheet.set_origin_clean(origin_clean);
1102 }
1103 }
1104}
1105
1106impl HTMLLinkElementMethods<crate::DomTypeHolder> for HTMLLinkElement {
1107 make_url_getter!(Href, "href");
1109
1110 make_url_setter!(SetHref, "href");
1112
1113 make_getter!(Rel, "rel");
1115
1116 fn SetRel(&self, cx: &mut JSContext, rel: DOMString) {
1118 self.upcast::<Element>()
1119 .set_tokenlist_attribute(cx, &local_name!("rel"), rel);
1120 }
1121
1122 make_enumerated_getter!(
1124 As,
1125 "as",
1126 "fetch" | "audio" | "audioworklet" | "document" | "embed" | "font" | "frame"
1127 | "iframe" | "image" | "json" | "manifest" | "object" | "paintworklet"
1128 | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "track"
1129 | "video" | "webidentity" | "worker" | "xslt",
1130 missing => "",
1131 invalid => ""
1132 );
1133
1134 make_setter!(SetAs, "as");
1136
1137 make_getter!(Media, "media");
1139
1140 make_setter!(SetMedia, "media");
1142
1143 make_getter!(Integrity, "integrity");
1145
1146 make_setter!(SetIntegrity, "integrity");
1148
1149 make_getter!(Hreflang, "hreflang");
1151
1152 make_setter!(SetHreflang, "hreflang");
1154
1155 make_getter!(Type, "type");
1157
1158 make_setter!(SetType, "type");
1160
1161 make_bool_getter!(Disabled, "disabled");
1163
1164 make_bool_setter!(SetDisabled, "disabled");
1166
1167 fn RelList(&self, cx: &mut js::context::JSContext) -> DomRoot<DOMTokenList> {
1169 self.rel_list.or_init(|| {
1170 DOMTokenList::new(
1171 cx,
1172 self.upcast(),
1173 &local_name!("rel"),
1174 Some(vec![
1175 Atom::from("alternate"),
1176 Atom::from("apple-touch-icon"),
1177 Atom::from("apple-touch-icon-precomposed"),
1178 Atom::from("canonical"),
1179 Atom::from("dns-prefetch"),
1180 Atom::from("icon"),
1181 Atom::from("import"),
1182 Atom::from("manifest"),
1183 Atom::from("modulepreload"),
1184 Atom::from("next"),
1185 Atom::from("preconnect"),
1186 Atom::from("prefetch"),
1187 Atom::from("preload"),
1188 Atom::from("prerender"),
1189 Atom::from("stylesheet"),
1190 ]),
1191 )
1192 })
1193 }
1194
1195 make_getter!(Charset, "charset");
1197
1198 make_setter!(SetCharset, "charset");
1200
1201 make_getter!(Rev, "rev");
1203
1204 make_setter!(SetRev, "rev");
1206
1207 make_getter!(Target, "target");
1209
1210 make_setter!(SetTarget, "target");
1212
1213 fn Blocking(&self, cx: &mut js::context::JSContext) -> DomRoot<DOMTokenList> {
1215 self.blocking.or_init(|| {
1216 DOMTokenList::new(
1217 cx,
1218 self.upcast(),
1219 &local_name!("blocking"),
1220 Some(vec![Atom::from("render")]),
1221 )
1222 })
1223 }
1224
1225 fn GetCrossOrigin(&self) -> Option<DOMString> {
1227 reflect_cross_origin_attribute(self.upcast::<Element>())
1228 }
1229
1230 fn SetCrossOrigin(&self, cx: &mut JSContext, value: Option<DOMString>) {
1232 set_cross_origin_attribute(cx, self.upcast::<Element>(), value);
1233 }
1234
1235 fn ReferrerPolicy(&self) -> DOMString {
1237 reflect_referrer_policy_attribute(self.upcast::<Element>())
1238 }
1239
1240 make_setter!(SetReferrerPolicy, "referrerpolicy");
1242
1243 fn GetSheet(&self, can_gc: CanGc) -> Option<DomRoot<DOMStyleSheet>> {
1245 self.get_cssom_stylesheet(can_gc).map(DomRoot::upcast)
1246 }
1247}
1248
1249struct FaviconFetchContext {
1250 link: Trusted<HTMLLinkElement>,
1252 image_cache: std::sync::Arc<dyn ImageCache>,
1253 id: PendingImageId,
1254
1255 url: ServoUrl,
1257}
1258
1259impl FetchResponseListener for FaviconFetchContext {
1260 fn process_request_body(&mut self, _: RequestId) {}
1261
1262 fn process_response(
1263 &mut self,
1264 _: &mut js::context::JSContext,
1265 request_id: RequestId,
1266 metadata: Result<FetchMetadata, NetworkError>,
1267 ) {
1268 self.image_cache.notify_pending_response(
1269 self.id,
1270 FetchResponseMsg::ProcessResponse(request_id, metadata),
1271 );
1272 }
1273
1274 fn process_response_chunk(
1275 &mut self,
1276 _: &mut js::context::JSContext,
1277 request_id: RequestId,
1278 chunk: Vec<u8>,
1279 ) {
1280 self.image_cache.notify_pending_response(
1281 self.id,
1282 FetchResponseMsg::ProcessResponseChunk(request_id, chunk.into()),
1283 );
1284 }
1285
1286 fn process_response_eof(
1287 self,
1288 cx: &mut js::context::JSContext,
1289 request_id: RequestId,
1290 response: Result<(), NetworkError>,
1291 timing: ResourceFetchTiming,
1292 ) {
1293 self.image_cache.notify_pending_response(
1294 self.id,
1295 FetchResponseMsg::ProcessResponseEOF(request_id, response.clone(), timing.clone()),
1296 );
1297 submit_timing(cx, &self, &response, &timing);
1298 }
1299
1300 fn process_csp_violations(&mut self, _request_id: RequestId, violations: Vec<Violation>) {
1301 let global = &self.resource_timing_global();
1302 global.report_csp_violations(violations, None, None);
1303 }
1304}
1305
1306impl ResourceTimingListener for FaviconFetchContext {
1307 fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
1308 (
1309 InitiatorType::LocalName("link".to_string()),
1310 self.url.clone(),
1311 )
1312 }
1313
1314 fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
1315 self.link.root().upcast::<Node>().owner_doc().global()
1316 }
1317}