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(&self, new_stylesheet: Arc<Stylesheet>) {
181 let owner = self.stylesheet_list_owner();
182 if let Some(old_stylesheet) = self.stylesheet.borrow_mut().replace(new_stylesheet.clone()) {
183 owner.remove_stylesheet(
184 StylesheetSource::Element(Dom::from_ref(self.upcast())),
185 &old_stylesheet,
186 );
187 }
188 owner.add_owned_stylesheet(self.upcast(), new_stylesheet);
189 }
190
191 pub(crate) fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> {
192 self.stylesheet.borrow().clone()
193 }
194
195 pub(crate) fn get_cssom_stylesheet(&self, can_gc: CanGc) -> Option<DomRoot<CSSStyleSheet>> {
196 self.get_stylesheet().map(|sheet| {
197 self.cssom_stylesheet.or_init(|| {
198 CSSStyleSheet::new(
199 &self.owner_window(),
200 Some(self.upcast::<Element>()),
201 "text/css".into(),
202 Some(self.Href().into()),
203 None, sheet,
205 None, can_gc,
207 )
208 })
209 })
210 }
211
212 pub(crate) fn is_alternate(&self) -> bool {
213 self.relations.get().contains(LinkRelations::ALTERNATE) &&
214 !self
215 .upcast::<Element>()
216 .get_string_attribute(&local_name!("title"))
217 .is_empty()
218 }
219
220 pub(crate) fn is_effectively_disabled(&self) -> bool {
221 (self.is_alternate() && !self.is_explicitly_enabled.get()) ||
222 self.upcast::<Element>()
223 .has_attribute(&local_name!("disabled"))
224 }
225
226 fn clean_stylesheet_ownership(&self) {
227 if let Some(cssom_stylesheet) = self.cssom_stylesheet.get() {
228 cssom_stylesheet.set_owner_node(None);
229 }
230 self.cssom_stylesheet.set(None);
231 }
232}
233
234fn get_attr(element: &Element, local_name: &LocalName) -> Option<String> {
235 let elem = element.get_attribute(local_name);
236 elem.map(|e| {
237 let value = e.value();
238 (**value).to_owned()
239 })
240}
241
242impl VirtualMethods for HTMLLinkElement {
243 fn super_type(&self) -> Option<&dyn VirtualMethods> {
244 Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
245 }
246
247 fn attribute_mutated(
248 &self,
249 cx: &mut js::context::JSContext,
250 attr: AttrRef<'_>,
251 mutation: AttributeMutation,
252 ) {
253 self.super_type()
254 .unwrap()
255 .attribute_mutated(cx, attr, mutation);
256
257 let local_name = attr.local_name();
258 let is_removal = mutation.is_removal();
259 match *local_name {
260 local_name!("disabled") => {
261 self.handle_disabled_attribute_change(is_removal);
262 return;
263 },
264 local_name!("rel") | local_name!("rev") => {
265 let previous_relations = self.relations.get();
266 self.relations
267 .set(LinkRelations::for_element(self.upcast()));
268
269 if previous_relations == self.relations.get() {
271 return;
272 }
273 },
274 _ => {},
275 }
276
277 let node = self.upcast::<Node>();
278 if !node.is_connected() {
279 return;
280 }
281
282 if self.relations.get().contains(LinkRelations::STYLESHEET) &&
285 let AttributeMutation::Set(Some(previous_value), _) = mutation &&
286 **previous_value == **attr.value()
287 {
288 return;
289 }
290
291 match *local_name {
292 local_name!("rel") | local_name!("rev") => {
293 if self.relations.get().contains(LinkRelations::STYLESHEET) {
296 self.handle_stylesheet_url(cx);
297 } else {
298 self.remove_stylesheet();
299 }
300
301 if self.relations.get().contains(LinkRelations::MODULE_PRELOAD) {
302 self.fetch_and_process_modulepreload(cx);
303 }
304 },
305 local_name!("href") => {
306 if is_removal {
309 if self.relations.get().contains(LinkRelations::STYLESHEET) {
310 self.remove_stylesheet();
311 }
312 return;
313 }
314 if self.relations.get().contains(LinkRelations::STYLESHEET) {
318 self.handle_stylesheet_url(cx);
319 }
320
321 if self.relations.get().contains(LinkRelations::ICON) {
322 self.handle_favicon_url(&attr.value());
323 }
324
325 if self.relations.get().contains(LinkRelations::PREFETCH) {
329 self.fetch_and_process_prefetch_link(&attr.value());
330 }
331
332 if self.relations.get().contains(LinkRelations::PRELOAD) {
336 self.handle_preload_url();
337 }
338
339 if self.relations.get().contains(LinkRelations::MODULE_PRELOAD) {
341 self.fetch_and_process_modulepreload(cx);
342 }
343 },
344 local_name!("sizes") if self.relations.get().contains(LinkRelations::ICON) => {
345 self.handle_favicon_url(&attr.value());
346 },
347 local_name!("crossorigin") => {
348 if self.relations.get().contains(LinkRelations::PREFETCH) {
352 self.fetch_and_process_prefetch_link(&attr.value());
353 }
354
355 if self.relations.get().contains(LinkRelations::STYLESHEET) {
359 self.handle_stylesheet_url(cx);
360 }
361 },
362 local_name!("as") => {
363 if self.relations.get().contains(LinkRelations::PRELOAD) &&
367 let AttributeMutation::Set(Some(_), _) = mutation
368 {
369 self.handle_preload_url();
370 }
371 },
372 local_name!("type") => {
373 if self.relations.get().contains(LinkRelations::STYLESHEET) {
381 self.handle_stylesheet_url(cx);
382 }
383
384 if self.relations.get().contains(LinkRelations::PRELOAD) &&
390 !self.previous_type_matched.get()
391 {
392 self.handle_preload_url();
393 }
394 },
395 local_name!("media") => {
396 if self.relations.get().contains(LinkRelations::PRELOAD) &&
401 !self.previous_media_environment_matched.get()
402 {
403 match mutation {
404 AttributeMutation::Removed | AttributeMutation::Set(Some(_), _) => {
405 self.handle_preload_url()
406 },
407 _ => {},
408 };
409 } else if self.relations.get().contains(LinkRelations::STYLESHEET) &&
410 let Some(ref stylesheet) = *self.stylesheet.borrow_mut()
411 {
412 let document = self.owner_document();
413 let shared_lock = document.style_shared_author_lock().clone();
414 let mut guard = shared_lock.write();
415 let media = stylesheet.media.write_with(&mut guard);
416 match mutation {
417 AttributeMutation::Set(..) => {
418 *media = MediaList::parse_media_list(&attr.value(), document.window())
419 },
420 AttributeMutation::Removed => *media = StyleMediaList::empty(),
421 };
422 self.owner_document().invalidate_stylesheets();
423 }
424
425 let matches_media_environment =
426 MediaList::matches_environment(&self.owner_document(), &attr.value());
427 self.previous_media_environment_matched
428 .set(matches_media_environment);
429 },
430 _ => {},
431 }
432 }
433
434 fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
435 match name {
436 &local_name!("rel") => AttrValue::from_serialized_tokenlist(value.into()),
437 _ => self
438 .super_type()
439 .unwrap()
440 .parse_plain_attribute(name, value),
441 }
442 }
443
444 fn bind_to_tree(&self, cx: &mut JSContext, context: &BindContext) {
445 if let Some(s) = self.super_type() {
446 s.bind_to_tree(cx, context);
447 }
448
449 if context.tree_connected {
450 let element = self.upcast();
451
452 if let Some(href) = get_attr(element, &local_name!("href")) {
453 let relations = self.relations.get();
454 if relations.contains(LinkRelations::STYLESHEET) {
457 self.handle_stylesheet_url(cx);
458 }
459
460 if relations.contains(LinkRelations::ICON) {
461 self.handle_favicon_url(&href);
462 }
463
464 if relations.contains(LinkRelations::PREFETCH) {
465 self.fetch_and_process_prefetch_link(&href);
466 }
467
468 if relations.contains(LinkRelations::PRELOAD) {
469 self.handle_preload_url();
470 }
471
472 if relations.contains(LinkRelations::MODULE_PRELOAD) {
474 let link = DomRoot::from_ref(self);
475 self.owner_document().add_delayed_task(
476 task!(FetchModulePreload: |cx, link: DomRoot<HTMLLinkElement>| {
477 link.fetch_and_process_modulepreload(cx);
478 }),
479 );
480 }
481 }
482 }
483 }
484
485 fn unbind_from_tree(&self, cx: &mut js::context::JSContext, context: &UnbindContext) {
486 if let Some(s) = self.super_type() {
487 s.unbind_from_tree(cx, context);
488 }
489
490 self.remove_stylesheet();
491 }
492}
493
494impl HTMLLinkElement {
495 fn compute_destination_for_attribute(&self) -> Option<Destination> {
496 let element = self.upcast::<Element>();
499 element
500 .get_attribute(&local_name!("as"))
501 .and_then(|attr| LinkProcessingOptions::translate_a_preload_destination(&attr.value()))
502 }
503
504 fn processing_options(&self) -> LinkProcessingOptions {
506 let element = self.upcast::<Element>();
507
508 let document = self.upcast::<Node>().owner_doc();
510 let global = document.owner_global();
511
512 let mut options = LinkProcessingOptions {
514 href: String::new(),
515 destination: Destination::None,
516 integrity: String::new(),
517 link_type: String::new(),
518 cryptographic_nonce_metadata: self.upcast::<Element>().nonce_value(),
519 cross_origin: cors_setting_for_element(element),
520 referrer_policy: referrer_policy_for_element(element),
521 policy_container: document.policy_container().to_owned(),
522 source_set: None, origin: document.borrow().origin().immutable().to_owned(),
524 base_url: document.borrow().base_url(),
525 insecure_requests_policy: document.insecure_requests_policy(),
526 has_trustworthy_ancestor_origin: document.has_trustworthy_ancestor_or_current_origin(),
527 request_client: global.request_client(),
528 referrer: global.get_referrer(),
529 };
530
531 if let Some(href_attribute) = element.get_attribute(&local_name!("href")) {
533 options.href = (**href_attribute.value()).to_owned();
534 }
535
536 if let Some(integrity_attribute) = element.get_attribute(&local_name!("integrity")) {
539 options.integrity = (**integrity_attribute.value()).to_owned();
540 }
541
542 if let Some(type_attribute) = element.get_attribute(&local_name!("type")) {
544 options.link_type = (**type_attribute.value()).to_owned();
545 }
546
547 assert!(!options.href.is_empty() || options.source_set.is_some());
549
550 options
552 }
553
554 fn default_fetch_and_process_the_linked_resource(&self) -> Option<RequestBuilder> {
559 let options = self.processing_options();
561
562 let Some(request) = options.create_link_request(self.owner_window().webview_id()) else {
564 return None;
566 };
567 let mut request = request.synchronous(true);
569
570 if !self.linked_resource_fetch_setup(&mut request) {
572 return None;
573 }
574
575 Some(request)
581 }
582
583 fn linked_resource_fetch_setup(&self, request: &mut RequestBuilder) -> bool {
585 if self.relations.get().contains(LinkRelations::ICON) {
587 request.destination = Destination::Image;
589
590 }
594
595 if self.relations.get().contains(LinkRelations::STYLESHEET) {
597 if self
599 .upcast::<Element>()
600 .has_attribute(&local_name!("disabled"))
601 {
602 return false;
603 }
604 }
619
620 true
621 }
622
623 fn fetch_and_process_prefetch_link(&self, href: &str) {
625 if href.is_empty() {
627 return;
628 }
629
630 let mut options = self.processing_options();
632
633 options.destination = Destination::None;
635
636 let Some(request) = options.create_link_request(self.owner_window().webview_id()) else {
638 return;
640 };
641 let url = request.url.url();
642
643 let request = request.initiator(Initiator::Prefetch);
645
646 let document = self.upcast::<Node>().owner_doc();
650 let fetch_context = LinkFetchContext {
651 url,
652 link: Some(Trusted::new(self)),
653 document: Trusted::new(&document),
654 global: Trusted::new(&document.global()),
655 type_: LinkFetchContextType::Prefetch,
656 response_body: vec![],
657 };
658
659 document.fetch_background(request, fetch_context);
660 }
661
662 fn handle_stylesheet_url(&self, cx: &mut js::context::JSContext) {
664 let document = self.owner_document();
665 if document.browsing_context().is_none() {
666 return;
667 }
668
669 let element = self.upcast::<Element>();
670
671 let type_ = element.get_string_attribute(&local_name!("type"));
678 if !type_.is_empty() && type_ != "text/css" {
679 return;
680 }
681
682 let href = element.get_string_attribute(&local_name!("href"));
684 if href.is_empty() {
685 return;
686 }
687
688 let link_url = match document.base_url().join(&href.str()) {
690 Ok(url) => url,
691 Err(e) => {
692 debug!("Parsing url {} failed: {}", href, e);
693 return;
694 },
695 };
696
697 let cors_setting = cors_setting_for_element(element);
699
700 let mq_attribute = element.get_attribute(&local_name!("media"));
701 let value = mq_attribute.as_ref().map(|a| a.value());
702 let mq_str = match value {
703 Some(ref value) => &***value,
704 None => "",
705 };
706
707 let media = MediaList::parse_media_list(mq_str, document.window());
708 let media = Arc::new(document.style_shared_author_lock().wrap(media));
709
710 let im_attribute = element.get_attribute(&local_name!("integrity"));
711 let integrity_val = im_attribute.as_ref().map(|a| a.value());
712 let integrity_metadata = match integrity_val {
713 Some(ref value) => &***value,
714 None => "",
715 };
716
717 self.request_generation_id
718 .set(self.request_generation_id.get().increment());
719 self.pending_loads.set(0);
720
721 ElementStylesheetLoader::load_with_element(
722 cx,
723 self.upcast(),
724 StylesheetContextSource::LinkElement,
725 media,
726 link_url,
727 cors_setting,
728 integrity_metadata.to_owned(),
729 );
730 }
731
732 fn handle_disabled_attribute_change(&self, is_removal: bool) {
734 if is_removal {
736 self.is_explicitly_enabled.set(true);
737 }
738 if let Some(stylesheet) = self.get_stylesheet() &&
739 stylesheet.set_disabled(!is_removal)
740 {
741 self.stylesheet_list_owner().invalidate_stylesheets();
742 }
743 }
744
745 fn handle_favicon_url(&self, href: &str) {
746 if href.is_empty() {
748 return;
749 }
750
751 let window = self.owner_window();
754 if !window.is_top_level() {
755 return;
756 }
757 let Ok(href) = self.Href().parse() else {
758 return;
759 };
760
761 self.request_generation_id
763 .set(self.request_generation_id.get().increment());
764
765 let cache_result = window.image_cache().get_cached_image_status(
766 href,
767 window.origin().immutable().clone(),
768 cors_setting_for_element(self.upcast()),
769 );
770
771 match cache_result {
772 ImageCacheResult::Available(ImageOrMetadataAvailable::ImageAvailable {
773 image, ..
774 }) => {
775 self.process_favicon_response(image);
776 },
777 ImageCacheResult::Available(ImageOrMetadataAvailable::MetadataAvailable(_, id)) |
778 ImageCacheResult::Pending(id) => {
779 let sender = self.register_image_cache_callback(id);
780 window.image_cache().add_listener(ImageLoadListener::new(
781 sender,
782 window.pipeline_id(),
783 id,
784 ));
785 },
786 ImageCacheResult::ReadyForRequest(id) => {
787 let Some(request) = self.default_fetch_and_process_the_linked_resource() else {
788 return;
789 };
790
791 let sender = self.register_image_cache_callback(id);
792 window.image_cache().add_listener(ImageLoadListener::new(
793 sender,
794 window.pipeline_id(),
795 id,
796 ));
797
798 let document = self.upcast::<Node>().owner_doc();
799 let fetch_context = FaviconFetchContext {
800 url: self.owner_document().base_url(),
801 image_cache: window.image_cache(),
802 id,
803 link: Trusted::new(self),
804 };
805 document.fetch_background(request, fetch_context);
806 },
807 ImageCacheResult::FailedToLoadOrDecode => {},
808 };
809 }
810
811 fn register_image_cache_callback(&self, id: PendingImageId) -> ImageCacheResponseCallback {
812 let trusted_node = Trusted::new(self);
813 let window = self.owner_window();
814 let request_generation_id = self.get_request_generation_id();
815 window.register_image_cache_listener(id, move |response, _| {
816 let trusted_node = trusted_node.clone();
817 let link_element = trusted_node.root();
818 let window = link_element.owner_window();
819
820 let ImageResponse::Loaded(image, _) = response.response else {
821 return;
823 };
824
825 if request_generation_id != link_element.get_request_generation_id() {
826 return;
828 };
829
830 window
831 .as_global_scope()
832 .task_manager()
833 .networking_task_source()
834 .queue(task!(process_favicon_response: move || {
835 let element = trusted_node.root();
836
837 if request_generation_id != element.get_request_generation_id() {
838 return;
840 };
841
842 element.process_favicon_response(image);
843 }));
844 })
845 }
846
847 fn process_favicon_response(&self, image: Image) {
849 let window = self.owner_window();
851 let document = self.owner_document();
852
853 let send_rasterized_favicon_to_embedder = |raster_image: &pixels::RasterImage| {
854 let frame = raster_image.first_frame();
856
857 let format = match raster_image.format {
858 PixelFormat::K8 => embedder_traits::PixelFormat::K8,
859 PixelFormat::KA8 => embedder_traits::PixelFormat::KA8,
860 PixelFormat::RGB8 => embedder_traits::PixelFormat::RGB8,
861 PixelFormat::RGBA8 => embedder_traits::PixelFormat::RGBA8,
862 PixelFormat::BGRA8 => embedder_traits::PixelFormat::BGRA8,
863 };
864
865 let embedder_image = embedder_traits::Image::new(
866 frame.width,
867 frame.height,
868 std::sync::Arc::new(GenericSharedMemory::from_bytes(&raster_image.bytes)),
869 raster_image.frames[0].byte_range.clone(),
870 format,
871 );
872 document.set_favicon(embedder_image);
873 };
874
875 match image {
876 Image::Raster(raster_image) => send_rasterized_favicon_to_embedder(&raster_image),
877 Image::Vector(vector_image) => {
878 let size = DeviceIntSize::new(250, 250);
880
881 let image_cache = window.image_cache();
882 if let Some(raster_image) =
883 image_cache.rasterize_vector_image(vector_image.id, size, None)
884 {
885 send_rasterized_favicon_to_embedder(&raster_image);
886 } else {
887 let image_cache_sender = self.register_image_cache_callback(vector_image.id);
890 image_cache.add_rasterization_complete_listener(
891 window.pipeline_id(),
892 vector_image.id,
893 size,
894 image_cache_sender,
895 );
896 }
897 },
898 }
899 }
900
901 fn handle_preload_url(&self) {
904 let mut options = self.processing_options();
908 let Some(destination) = self.compute_destination_for_attribute() else {
911 return;
913 };
914 options.destination = destination;
916 {
918 let type_matches_destination = options.type_matches_destination();
920 self.previous_type_matched.set(type_matches_destination);
921 if !type_matches_destination {
922 return;
923 }
924 }
925 let document = self.upcast::<Node>().owner_doc();
927 options.preload(
928 self.owner_window().webview_id(),
929 Some(Trusted::new(self)),
930 &document,
931 );
932 }
933
934 pub(crate) fn fire_event_after_response(
936 &self,
937 cx: &mut JSContext,
938 response: Result<(), NetworkError>,
939 ) {
940 if response.is_err() {
943 self.upcast::<EventTarget>().fire_event(cx, atom!("error"));
944 } else {
945 self.upcast::<EventTarget>().fire_event(cx, atom!("load"));
946 }
947 }
948
949 fn fetch_and_process_modulepreload(&self, cx: &mut JSContext) {
951 let el = self.upcast::<Element>();
952 let href_attribute_value = el.get_string_attribute(&local_name!("href"));
953
954 if href_attribute_value.is_empty() {
956 return;
957 }
958
959 let destination = el
961 .get_attribute(&local_name!("as"))
962 .map(|attr| attr.value().to_ascii_lowercase())
963 .and_then(|value| match value.as_str() {
964 "" => None,
966 "fetch" => Some(Destination::None),
968 _ => Destination::from_str(&value).ok(),
969 })
970 .unwrap_or(Destination::Script);
971
972 let document = self.owner_document();
973 let global = document.global();
974
975 let is_a_modulepreload_destination = match destination {
977 Destination::Json | Destination::Style => true,
978 Destination::Xslt => false,
981 d => d.is_script_like(),
982 };
983
984 if !is_a_modulepreload_destination {
987 return global
988 .task_manager()
989 .networking_task_source()
990 .queue_simple_event(self.upcast(), atom!("error"));
991 }
992
993 let Ok(url) = document.encoding_parse_a_url(&href_attribute_value.str()) else {
996 return;
997 };
998
999 let credentials_mode = cors_settings_attribute_credential_mode(el);
1003
1004 let cryptographic_nonce = el.nonce_value();
1006
1007 let integrity_attribute = el.get_attribute(&local_name!("integrity"));
1009 let integrity_value = integrity_attribute.as_ref().map(|attr| attr.value());
1010 let integrity_metadata = match integrity_value {
1011 Some(ref value) => (***value).to_owned(),
1012 None => global
1015 .import_map()
1016 .resolve_a_module_integrity_metadata(&url),
1017 };
1018
1019 let referrer_policy = referrer_policy_for_element(el);
1021
1022 let options = ScriptFetchOptions {
1028 cryptographic_nonce,
1029 integrity_metadata,
1030 parser_metadata: ParserMetadata::NotParserInserted,
1031 credentials_mode,
1032 referrer_policy,
1033 render_blocking: false,
1034 };
1035
1036 let link = DomRoot::from_ref(self);
1037
1038 fetch_a_modulepreload_module(
1041 cx,
1042 url,
1043 destination,
1044 &global,
1045 options,
1046 move |cx, fetch_failed| {
1047 let event = match fetch_failed {
1050 true => atom!("error"),
1051 false => atom!("load"),
1052 };
1053
1054 link.upcast::<EventTarget>().fire_event(cx, event);
1055 },
1056 );
1057 }
1058}
1059
1060impl StylesheetOwner for HTMLLinkElement {
1061 fn increment_pending_loads_count(&self) {
1062 self.pending_loads.set(self.pending_loads.get() + 1)
1063 }
1064
1065 fn load_finished(&self, succeeded: bool) -> Option<bool> {
1066 assert!(self.pending_loads.get() > 0, "What finished?");
1067 if !succeeded {
1068 self.any_failed_load.set(true);
1069 }
1070
1071 self.pending_loads.set(self.pending_loads.get() - 1);
1072 if self.pending_loads.get() != 0 {
1073 return None;
1074 }
1075
1076 let any_failed = self.any_failed_load.get();
1077 self.any_failed_load.set(false);
1078 Some(any_failed)
1079 }
1080
1081 fn parser_inserted(&self) -> bool {
1082 self.parser_inserted.get()
1083 }
1084
1085 fn potentially_render_blocking(&self) -> bool {
1087 self.parser_inserted() ||
1094 self.blocking
1095 .get()
1096 .is_some_and(|list| list.Contains("render".into()))
1097 }
1098
1099 fn referrer_policy(&self, cx: &mut js::context::JSContext) -> ReferrerPolicy {
1100 if self.RelList(cx).Contains("noreferrer".into()) {
1101 return ReferrerPolicy::NoReferrer;
1102 }
1103
1104 ReferrerPolicy::EmptyString
1105 }
1106
1107 fn set_origin_clean(&self, origin_clean: bool) {
1108 if let Some(stylesheet) = self.get_cssom_stylesheet(CanGc::deprecated_note()) {
1109 stylesheet.set_origin_clean(origin_clean);
1110 }
1111 }
1112}
1113
1114impl HTMLLinkElementMethods<crate::DomTypeHolder> for HTMLLinkElement {
1115 make_url_getter!(Href, "href");
1117
1118 make_url_setter!(SetHref, "href");
1120
1121 make_getter!(Rel, "rel");
1123
1124 fn SetRel(&self, cx: &mut JSContext, rel: DOMString) {
1126 self.upcast::<Element>()
1127 .set_tokenlist_attribute(cx, &local_name!("rel"), rel);
1128 }
1129
1130 make_enumerated_getter!(
1132 As,
1133 "as",
1134 "fetch" | "audio" | "audioworklet" | "document" | "embed" | "font" | "frame"
1135 | "iframe" | "image" | "json" | "manifest" | "object" | "paintworklet"
1136 | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "track"
1137 | "video" | "webidentity" | "worker" | "xslt",
1138 missing => "",
1139 invalid => ""
1140 );
1141
1142 make_setter!(SetAs, "as");
1144
1145 make_getter!(Media, "media");
1147
1148 make_setter!(SetMedia, "media");
1150
1151 make_getter!(Integrity, "integrity");
1153
1154 make_setter!(SetIntegrity, "integrity");
1156
1157 make_getter!(Hreflang, "hreflang");
1159
1160 make_setter!(SetHreflang, "hreflang");
1162
1163 make_getter!(Type, "type");
1165
1166 make_setter!(SetType, "type");
1168
1169 make_bool_getter!(Disabled, "disabled");
1171
1172 make_bool_setter!(SetDisabled, "disabled");
1174
1175 fn RelList(&self, cx: &mut js::context::JSContext) -> DomRoot<DOMTokenList> {
1177 self.rel_list.or_init(|| {
1178 DOMTokenList::new(
1179 cx,
1180 self.upcast(),
1181 &local_name!("rel"),
1182 Some(vec![
1183 Atom::from("alternate"),
1184 Atom::from("apple-touch-icon"),
1185 Atom::from("apple-touch-icon-precomposed"),
1186 Atom::from("canonical"),
1187 Atom::from("dns-prefetch"),
1188 Atom::from("icon"),
1189 Atom::from("import"),
1190 Atom::from("manifest"),
1191 Atom::from("modulepreload"),
1192 Atom::from("next"),
1193 Atom::from("preconnect"),
1194 Atom::from("prefetch"),
1195 Atom::from("preload"),
1196 Atom::from("prerender"),
1197 Atom::from("stylesheet"),
1198 ]),
1199 )
1200 })
1201 }
1202
1203 make_getter!(Charset, "charset");
1205
1206 make_setter!(SetCharset, "charset");
1208
1209 make_getter!(Rev, "rev");
1211
1212 make_setter!(SetRev, "rev");
1214
1215 make_getter!(Target, "target");
1217
1218 make_setter!(SetTarget, "target");
1220
1221 fn Blocking(&self, cx: &mut js::context::JSContext) -> DomRoot<DOMTokenList> {
1223 self.blocking.or_init(|| {
1224 DOMTokenList::new(
1225 cx,
1226 self.upcast(),
1227 &local_name!("blocking"),
1228 Some(vec![Atom::from("render")]),
1229 )
1230 })
1231 }
1232
1233 fn GetCrossOrigin(&self) -> Option<DOMString> {
1235 reflect_cross_origin_attribute(self.upcast::<Element>())
1236 }
1237
1238 fn SetCrossOrigin(&self, cx: &mut JSContext, value: Option<DOMString>) {
1240 set_cross_origin_attribute(cx, self.upcast::<Element>(), value);
1241 }
1242
1243 fn ReferrerPolicy(&self) -> DOMString {
1245 reflect_referrer_policy_attribute(self.upcast::<Element>())
1246 }
1247
1248 make_setter!(SetReferrerPolicy, "referrerpolicy");
1250
1251 fn GetSheet(&self, can_gc: CanGc) -> Option<DomRoot<DOMStyleSheet>> {
1253 self.get_cssom_stylesheet(can_gc).map(DomRoot::upcast)
1254 }
1255}
1256
1257struct FaviconFetchContext {
1258 link: Trusted<HTMLLinkElement>,
1260 image_cache: std::sync::Arc<dyn ImageCache>,
1261 id: PendingImageId,
1262
1263 url: ServoUrl,
1265}
1266
1267impl FetchResponseListener for FaviconFetchContext {
1268 fn process_request_body(&mut self, _: RequestId) {}
1269
1270 fn process_response(
1271 &mut self,
1272 _: &mut js::context::JSContext,
1273 request_id: RequestId,
1274 metadata: Result<FetchMetadata, NetworkError>,
1275 ) {
1276 self.image_cache.notify_pending_response(
1277 self.id,
1278 FetchResponseMsg::ProcessResponse(request_id, metadata),
1279 );
1280 }
1281
1282 fn process_response_chunk(
1283 &mut self,
1284 _: &mut js::context::JSContext,
1285 request_id: RequestId,
1286 chunk: Vec<u8>,
1287 ) {
1288 self.image_cache.notify_pending_response(
1289 self.id,
1290 FetchResponseMsg::ProcessResponseChunk(request_id, chunk.into()),
1291 );
1292 }
1293
1294 fn process_response_eof(
1295 self,
1296 cx: &mut js::context::JSContext,
1297 request_id: RequestId,
1298 response: Result<(), NetworkError>,
1299 timing: ResourceFetchTiming,
1300 ) {
1301 self.image_cache.notify_pending_response(
1302 self.id,
1303 FetchResponseMsg::ProcessResponseEOF(request_id, response.clone(), timing.clone()),
1304 );
1305 submit_timing(cx, &self, &response, &timing);
1306 }
1307
1308 fn process_csp_violations(&mut self, _request_id: RequestId, violations: Vec<Violation>) {
1309 let global = &self.resource_timing_global();
1310 global.report_csp_violations(violations, None, None);
1311 }
1312}
1313
1314impl ResourceTimingListener for FaviconFetchContext {
1315 fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
1316 (
1317 InitiatorType::LocalName("link".to_string()),
1318 self.url.clone(),
1319 )
1320 }
1321
1322 fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
1323 self.link.root().upcast::<Node>().owner_doc().global()
1324 }
1325}