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::root::Dom;
24use servo_arc::Arc;
25use servo_base::generic_channel::GenericSharedMemory;
26use servo_url::ServoUrl;
27use style::attr::AttrValue;
28use style::media_queries::MediaList as StyleMediaList;
29use style::stylesheets::Stylesheet;
30use stylo_atoms::Atom;
31use webrender_api::units::DeviceIntSize;
32
33use crate::dom::attr::Attr;
34use crate::dom::bindings::cell::DomRefCell;
35use crate::dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenList_Binding::DOMTokenListMethods;
36use crate::dom::bindings::codegen::Bindings::HTMLLinkElementBinding::HTMLLinkElementMethods;
37use crate::dom::bindings::inheritance::Castable;
38use crate::dom::bindings::refcounted::Trusted;
39use crate::dom::bindings::reflector::DomGlobal;
40use crate::dom::bindings::root::{DomRoot, MutNullableDom};
41use crate::dom::bindings::str::{DOMString, USVString};
42use crate::dom::csp::{GlobalCspReporting, Violation};
43use crate::dom::css::cssstylesheet::CSSStyleSheet;
44use crate::dom::css::stylesheet::StyleSheet as DOMStyleSheet;
45use crate::dom::document::Document;
46use crate::dom::documentorshadowroot::StylesheetSource;
47use crate::dom::domtokenlist::DOMTokenList;
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: &Attr,
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 if let AttributeMutation::Set(Some(previous_value), _) = mutation {
286 if **previous_value == **attr.value() {
287 return;
288 }
289 }
290 }
291
292 match *local_name {
293 local_name!("rel") | local_name!("rev") => {
294 if self.relations.get().contains(LinkRelations::STYLESHEET) {
297 self.handle_stylesheet_url();
298 } else {
299 self.remove_stylesheet();
300 }
301
302 if self.relations.get().contains(LinkRelations::MODULE_PRELOAD) {
303 self.fetch_and_process_modulepreload(cx);
304 }
305 },
306 local_name!("href") => {
307 if is_removal {
310 if self.relations.get().contains(LinkRelations::STYLESHEET) {
311 self.remove_stylesheet();
312 }
313 return;
314 }
315 if self.relations.get().contains(LinkRelations::STYLESHEET) {
319 self.handle_stylesheet_url();
320 }
321
322 if self.relations.get().contains(LinkRelations::ICON) {
323 self.handle_favicon_url(&attr.value());
324 }
325
326 if self.relations.get().contains(LinkRelations::PREFETCH) {
330 self.fetch_and_process_prefetch_link(&attr.value());
331 }
332
333 if self.relations.get().contains(LinkRelations::PRELOAD) {
337 self.handle_preload_url();
338 }
339
340 if self.relations.get().contains(LinkRelations::MODULE_PRELOAD) {
342 self.fetch_and_process_modulepreload(cx);
343 }
344 },
345 local_name!("sizes") if self.relations.get().contains(LinkRelations::ICON) => {
346 self.handle_favicon_url(&attr.value());
347 },
348 local_name!("crossorigin") => {
349 if self.relations.get().contains(LinkRelations::PREFETCH) {
353 self.fetch_and_process_prefetch_link(&attr.value());
354 }
355
356 if self.relations.get().contains(LinkRelations::STYLESHEET) {
360 self.handle_stylesheet_url();
361 }
362 },
363 local_name!("as") => {
364 if self.relations.get().contains(LinkRelations::PRELOAD) {
368 if let AttributeMutation::Set(Some(_), _) = mutation {
369 self.handle_preload_url();
370 }
371 }
372 },
373 local_name!("type") => {
374 if self.relations.get().contains(LinkRelations::STYLESHEET) {
382 self.handle_stylesheet_url();
383 }
384
385 if self.relations.get().contains(LinkRelations::PRELOAD) &&
391 !self.previous_type_matched.get()
392 {
393 self.handle_preload_url();
394 }
395 },
396 local_name!("media") => {
397 if self.relations.get().contains(LinkRelations::PRELOAD) &&
402 !self.previous_media_environment_matched.get()
403 {
404 match mutation {
405 AttributeMutation::Removed | AttributeMutation::Set(Some(_), _) => {
406 self.handle_preload_url()
407 },
408 _ => {},
409 };
410 } else if self.relations.get().contains(LinkRelations::STYLESHEET) {
411 if let Some(ref stylesheet) = *self.stylesheet.borrow_mut() {
412 let document = self.owner_document();
413 let shared_lock = document.style_shared_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 =
419 MediaList::parse_media_list(&attr.value(), document.window())
420 },
421 AttributeMutation::Removed => *media = StyleMediaList::empty(),
422 };
423 self.owner_document().invalidate_stylesheets();
424 }
425 }
426
427 let matches_media_environment =
428 MediaList::matches_environment(&self.owner_document(), &attr.value());
429 self.previous_media_environment_matched
430 .set(matches_media_environment);
431 },
432 _ => {},
433 }
434 }
435
436 fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
437 match name {
438 &local_name!("rel") => AttrValue::from_serialized_tokenlist(value.into()),
439 _ => self
440 .super_type()
441 .unwrap()
442 .parse_plain_attribute(name, value),
443 }
444 }
445
446 fn bind_to_tree(&self, cx: &mut JSContext, context: &BindContext) {
447 if let Some(s) = self.super_type() {
448 s.bind_to_tree(cx, context);
449 }
450
451 if context.tree_connected {
452 let element = self.upcast();
453
454 if let Some(href) = get_attr(element, &local_name!("href")) {
455 let relations = self.relations.get();
456 if relations.contains(LinkRelations::STYLESHEET) {
459 self.handle_stylesheet_url();
460 }
461
462 if relations.contains(LinkRelations::ICON) {
463 self.handle_favicon_url(&href);
464 }
465
466 if relations.contains(LinkRelations::PREFETCH) {
467 self.fetch_and_process_prefetch_link(&href);
468 }
469
470 if relations.contains(LinkRelations::PRELOAD) {
471 self.handle_preload_url();
472 }
473
474 if relations.contains(LinkRelations::MODULE_PRELOAD) {
476 let link = DomRoot::from_ref(self);
477 self.owner_document().add_delayed_task(
478 task!(FetchModulePreload: |cx, link: DomRoot<HTMLLinkElement>| {
479 link.fetch_and_process_modulepreload(cx);
480 }),
481 );
482 }
483 }
484 }
485 }
486
487 fn unbind_from_tree(&self, cx: &mut js::context::JSContext, context: &UnbindContext) {
488 if let Some(s) = self.super_type() {
489 s.unbind_from_tree(cx, context);
490 }
491
492 self.remove_stylesheet();
493 }
494}
495
496impl HTMLLinkElement {
497 fn compute_destination_for_attribute(&self) -> Option<Destination> {
498 let element = self.upcast::<Element>();
501 element
502 .get_attribute(&local_name!("as"))
503 .and_then(|attr| LinkProcessingOptions::translate_a_preload_destination(&attr.value()))
504 }
505
506 fn processing_options(&self) -> LinkProcessingOptions {
508 let element = self.upcast::<Element>();
509
510 let document = self.upcast::<Node>().owner_doc();
512 let global = document.owner_global();
513
514 let mut options = LinkProcessingOptions {
516 href: String::new(),
517 destination: Destination::None,
518 integrity: String::new(),
519 link_type: String::new(),
520 cryptographic_nonce_metadata: self.upcast::<Element>().nonce_value(),
521 cross_origin: cors_setting_for_element(element),
522 referrer_policy: referrer_policy_for_element(element),
523 policy_container: document.policy_container().to_owned(),
524 source_set: None, origin: document.borrow().origin().immutable().to_owned(),
526 base_url: document.borrow().base_url(),
527 insecure_requests_policy: document.insecure_requests_policy(),
528 has_trustworthy_ancestor_origin: document.has_trustworthy_ancestor_or_current_origin(),
529 request_client: global.request_client(),
530 referrer: global.get_referrer(),
531 };
532
533 if let Some(href_attribute) = element.get_attribute(&local_name!("href")) {
535 options.href = (**href_attribute.value()).to_owned();
536 }
537
538 if let Some(integrity_attribute) = element.get_attribute(&local_name!("integrity")) {
541 options.integrity = (**integrity_attribute.value()).to_owned();
542 }
543
544 if let Some(type_attribute) = element.get_attribute(&local_name!("type")) {
546 options.link_type = (**type_attribute.value()).to_owned();
547 }
548
549 assert!(!options.href.is_empty() || options.source_set.is_some());
551
552 options
554 }
555
556 fn default_fetch_and_process_the_linked_resource(&self) -> Option<RequestBuilder> {
561 let options = self.processing_options();
563
564 let Some(request) = options.create_link_request(self.owner_window().webview_id()) else {
566 return None;
568 };
569 let mut request = request.synchronous(true);
571
572 if !self.linked_resource_fetch_setup(&mut request) {
574 return None;
575 }
576
577 Some(request)
583 }
584
585 fn linked_resource_fetch_setup(&self, request: &mut RequestBuilder) -> bool {
587 if self.relations.get().contains(LinkRelations::ICON) {
589 request.destination = Destination::Image;
591
592 }
596
597 if self.relations.get().contains(LinkRelations::STYLESHEET) {
599 if self
601 .upcast::<Element>()
602 .has_attribute(&local_name!("disabled"))
603 {
604 return false;
605 }
606 }
621
622 true
623 }
624
625 fn fetch_and_process_prefetch_link(&self, href: &str) {
627 if href.is_empty() {
629 return;
630 }
631
632 let mut options = self.processing_options();
634
635 options.destination = Destination::None;
637
638 let Some(request) = options.create_link_request(self.owner_window().webview_id()) else {
640 return;
642 };
643 let url = request.url.url();
644
645 let request = request.initiator(Initiator::Prefetch);
647
648 let document = self.upcast::<Node>().owner_doc();
652 let fetch_context = LinkFetchContext {
653 url,
654 link: Some(Trusted::new(self)),
655 document: Trusted::new(&document),
656 global: Trusted::new(&document.global()),
657 type_: LinkFetchContextType::Prefetch,
658 response_body: vec![],
659 };
660
661 document.fetch_background(request, fetch_context);
662 }
663
664 fn handle_stylesheet_url(&self) {
666 let document = self.owner_document();
667 if document.browsing_context().is_none() {
668 return;
669 }
670
671 let element = self.upcast::<Element>();
672
673 let type_ = element.get_string_attribute(&local_name!("type"));
680 if !type_.is_empty() && type_ != "text/css" {
681 return;
682 }
683
684 let href = element.get_string_attribute(&local_name!("href"));
686 if href.is_empty() {
687 return;
688 }
689
690 let link_url = match document.base_url().join(&href.str()) {
692 Ok(url) => url,
693 Err(e) => {
694 debug!("Parsing url {} failed: {}", href, e);
695 return;
696 },
697 };
698
699 let cors_setting = cors_setting_for_element(element);
701
702 let mq_attribute = element.get_attribute(&local_name!("media"));
703 let value = mq_attribute.as_ref().map(|a| a.value());
704 let mq_str = match value {
705 Some(ref value) => &***value,
706 None => "",
707 };
708
709 let media = MediaList::parse_media_list(mq_str, document.window());
710 let media = Arc::new(document.style_shared_lock().wrap(media));
711
712 let im_attribute = element.get_attribute(&local_name!("integrity"));
713 let integrity_val = im_attribute.as_ref().map(|a| a.value());
714 let integrity_metadata = match integrity_val {
715 Some(ref value) => &***value,
716 None => "",
717 };
718
719 self.request_generation_id
720 .set(self.request_generation_id.get().increment());
721 self.pending_loads.set(0);
722
723 ElementStylesheetLoader::load_with_element(
724 self.upcast(),
725 StylesheetContextSource::LinkElement,
726 media,
727 link_url,
728 cors_setting,
729 integrity_metadata.to_owned(),
730 );
731 }
732
733 fn handle_disabled_attribute_change(&self, is_removal: bool) {
735 if is_removal {
737 self.is_explicitly_enabled.set(true);
738 }
739 if let Some(stylesheet) = self.get_stylesheet() {
740 if stylesheet.set_disabled(!is_removal) {
741 self.stylesheet_list_owner().invalidate_stylesheets();
742 }
743 }
744 }
745
746 fn handle_favicon_url(&self, href: &str) {
747 if href.is_empty() {
749 return;
750 }
751
752 let window = self.owner_window();
755 if !window.is_top_level() {
756 return;
757 }
758 let Ok(href) = self.Href().parse() else {
759 return;
760 };
761
762 self.request_generation_id
764 .set(self.request_generation_id.get().increment());
765
766 let cache_result = window.image_cache().get_cached_image_status(
767 href,
768 window.origin().immutable().clone(),
769 cors_setting_for_element(self.upcast()),
770 );
771
772 match cache_result {
773 ImageCacheResult::Available(ImageOrMetadataAvailable::ImageAvailable {
774 image, ..
775 }) => {
776 self.process_favicon_response(image);
777 },
778 ImageCacheResult::Available(ImageOrMetadataAvailable::MetadataAvailable(_, id)) |
779 ImageCacheResult::Pending(id) => {
780 let sender = self.register_image_cache_callback(id);
781 window.image_cache().add_listener(ImageLoadListener::new(
782 sender,
783 window.pipeline_id(),
784 id,
785 ));
786 },
787 ImageCacheResult::ReadyForRequest(id) => {
788 let Some(request) = self.default_fetch_and_process_the_linked_resource() else {
789 return;
790 };
791
792 let sender = self.register_image_cache_callback(id);
793 window.image_cache().add_listener(ImageLoadListener::new(
794 sender,
795 window.pipeline_id(),
796 id,
797 ));
798
799 let document = self.upcast::<Node>().owner_doc();
800 let fetch_context = FaviconFetchContext {
801 url: self.owner_document().base_url(),
802 image_cache: window.image_cache(),
803 id,
804 link: Trusted::new(self),
805 };
806 document.fetch_background(request, fetch_context);
807 },
808 ImageCacheResult::FailedToLoadOrDecode => {},
809 };
810 }
811
812 fn register_image_cache_callback(&self, id: PendingImageId) -> ImageCacheResponseCallback {
813 let trusted_node = Trusted::new(self);
814 let window = self.owner_window();
815 let request_generation_id = self.get_request_generation_id();
816 window.register_image_cache_listener(id, move |response, _| {
817 let trusted_node = trusted_node.clone();
818 let link_element = trusted_node.root();
819 let window = link_element.owner_window();
820
821 let ImageResponse::Loaded(image, _) = response.response else {
822 return;
824 };
825
826 if request_generation_id != link_element.get_request_generation_id() {
827 return;
829 };
830
831 window
832 .as_global_scope()
833 .task_manager()
834 .networking_task_source()
835 .queue(task!(process_favicon_response: move || {
836 let element = trusted_node.root();
837
838 if request_generation_id != element.get_request_generation_id() {
839 return;
841 };
842
843 element.process_favicon_response(image);
844 }));
845 })
846 }
847
848 fn process_favicon_response(&self, image: Image) {
850 let window = self.owner_window();
852 let document = self.owner_document();
853
854 let send_rasterized_favicon_to_embedder = |raster_image: &pixels::RasterImage| {
855 let frame = raster_image.first_frame();
857
858 let format = match raster_image.format {
859 PixelFormat::K8 => embedder_traits::PixelFormat::K8,
860 PixelFormat::KA8 => embedder_traits::PixelFormat::KA8,
861 PixelFormat::RGB8 => embedder_traits::PixelFormat::RGB8,
862 PixelFormat::RGBA8 => embedder_traits::PixelFormat::RGBA8,
863 PixelFormat::BGRA8 => embedder_traits::PixelFormat::BGRA8,
864 };
865
866 let embedder_image = embedder_traits::Image::new(
867 frame.width,
868 frame.height,
869 std::sync::Arc::new(GenericSharedMemory::from_bytes(&raster_image.bytes)),
870 raster_image.frames[0].byte_range.clone(),
871 format,
872 );
873 document.set_favicon(embedder_image);
874 };
875
876 match image {
877 Image::Raster(raster_image) => send_rasterized_favicon_to_embedder(&raster_image),
878 Image::Vector(vector_image) => {
879 let size = DeviceIntSize::new(250, 250);
881
882 let image_cache = window.image_cache();
883 if let Some(raster_image) =
884 image_cache.rasterize_vector_image(vector_image.id, size, None)
885 {
886 send_rasterized_favicon_to_embedder(&raster_image);
887 } else {
888 let image_cache_sender = self.register_image_cache_callback(vector_image.id);
891 image_cache.add_rasterization_complete_listener(
892 window.pipeline_id(),
893 vector_image.id,
894 size,
895 image_cache_sender,
896 );
897 }
898 },
899 }
900 }
901
902 fn handle_preload_url(&self) {
905 let mut options = self.processing_options();
909 let Some(destination) = self.compute_destination_for_attribute() else {
912 return;
914 };
915 options.destination = destination;
917 {
919 let type_matches_destination = options.type_matches_destination();
921 self.previous_type_matched.set(type_matches_destination);
922 if !type_matches_destination {
923 return;
924 }
925 }
926 let document = self.upcast::<Node>().owner_doc();
928 options.preload(
929 self.owner_window().webview_id(),
930 Some(Trusted::new(self)),
931 &document,
932 );
933 }
934
935 pub(crate) fn fire_event_after_response(
937 &self,
938 cx: &mut JSContext,
939 response: Result<(), NetworkError>,
940 ) {
941 if response.is_err() {
944 self.upcast::<EventTarget>().fire_event(cx, atom!("error"));
945 } else {
946 self.upcast::<EventTarget>().fire_event(cx, atom!("load"));
947 }
948 }
949
950 fn fetch_and_process_modulepreload(&self, cx: &mut JSContext) {
952 let el = self.upcast::<Element>();
953 let href_attribute_value = el.get_string_attribute(&local_name!("href"));
954
955 if href_attribute_value.is_empty() {
957 return;
958 }
959
960 let destination = el
962 .get_attribute(&local_name!("as"))
963 .map(|attr| attr.value().to_ascii_lowercase())
964 .and_then(|value| match value.as_str() {
965 "" => None,
967 "fetch" => Some(Destination::None),
969 _ => Destination::from_str(&value).ok(),
970 })
971 .unwrap_or(Destination::Script);
972
973 let document = self.owner_document();
974 let global = document.global();
975
976 let is_a_modulepreload_destination = match destination {
978 Destination::Json | Destination::Style => true,
979 Destination::Xslt => false,
982 d => d.is_script_like(),
983 };
984
985 if !is_a_modulepreload_destination {
988 return global
989 .task_manager()
990 .networking_task_source()
991 .queue_simple_event(self.upcast(), atom!("error"));
992 }
993
994 let Ok(url) = document.encoding_parse_a_url(&href_attribute_value.str()) else {
997 return;
998 };
999
1000 let credentials_mode = cors_settings_attribute_credential_mode(el);
1004
1005 let cryptographic_nonce = el.nonce_value();
1007
1008 let integrity_attribute = el.get_attribute(&local_name!("integrity"));
1010 let integrity_value = integrity_attribute.as_ref().map(|attr| attr.value());
1011 let integrity_metadata = match integrity_value {
1012 Some(ref value) => (***value).to_owned(),
1013 None => global
1016 .import_map()
1017 .resolve_a_module_integrity_metadata(&url),
1018 };
1019
1020 let referrer_policy = referrer_policy_for_element(el);
1022
1023 let options = ScriptFetchOptions {
1029 cryptographic_nonce,
1030 integrity_metadata,
1031 parser_metadata: ParserMetadata::NotParserInserted,
1032 credentials_mode,
1033 referrer_policy,
1034 render_blocking: false,
1035 };
1036
1037 let link = DomRoot::from_ref(self);
1038
1039 fetch_a_modulepreload_module(
1042 cx,
1043 url,
1044 destination,
1045 &global,
1046 options,
1047 move |cx, fetch_failed| {
1048 let event = match fetch_failed {
1051 true => atom!("error"),
1052 false => atom!("load"),
1053 };
1054
1055 link.upcast::<EventTarget>().fire_event(cx, event);
1056 },
1057 );
1058 }
1059}
1060
1061impl StylesheetOwner for HTMLLinkElement {
1062 fn increment_pending_loads_count(&self) {
1063 self.pending_loads.set(self.pending_loads.get() + 1)
1064 }
1065
1066 fn load_finished(&self, succeeded: bool) -> Option<bool> {
1067 assert!(self.pending_loads.get() > 0, "What finished?");
1068 if !succeeded {
1069 self.any_failed_load.set(true);
1070 }
1071
1072 self.pending_loads.set(self.pending_loads.get() - 1);
1073 if self.pending_loads.get() != 0 {
1074 return None;
1075 }
1076
1077 let any_failed = self.any_failed_load.get();
1078 self.any_failed_load.set(false);
1079 Some(any_failed)
1080 }
1081
1082 fn parser_inserted(&self) -> bool {
1083 self.parser_inserted.get()
1084 }
1085
1086 fn potentially_render_blocking(&self) -> bool {
1088 self.parser_inserted() ||
1095 self.blocking
1096 .get()
1097 .is_some_and(|list| list.Contains("render".into()))
1098 }
1099
1100 fn referrer_policy(&self) -> ReferrerPolicy {
1101 if self
1102 .RelList(CanGc::deprecated_note())
1103 .Contains("noreferrer".into())
1104 {
1105 return ReferrerPolicy::NoReferrer;
1106 }
1107
1108 ReferrerPolicy::EmptyString
1109 }
1110
1111 fn set_origin_clean(&self, origin_clean: bool) {
1112 if let Some(stylesheet) = self.get_cssom_stylesheet(CanGc::deprecated_note()) {
1113 stylesheet.set_origin_clean(origin_clean);
1114 }
1115 }
1116}
1117
1118impl HTMLLinkElementMethods<crate::DomTypeHolder> for HTMLLinkElement {
1119 make_url_getter!(Href, "href");
1121
1122 make_url_setter!(SetHref, "href");
1124
1125 make_getter!(Rel, "rel");
1127
1128 fn SetRel(&self, cx: &mut JSContext, rel: DOMString) {
1130 self.upcast::<Element>().set_tokenlist_attribute(
1131 &local_name!("rel"),
1132 rel,
1133 CanGc::from_cx(cx),
1134 );
1135 }
1136
1137 make_enumerated_getter!(
1139 As,
1140 "as",
1141 "fetch" | "audio" | "audioworklet" | "document" | "embed" | "font" | "frame"
1142 | "iframe" | "image" | "json" | "manifest" | "object" | "paintworklet"
1143 | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "track"
1144 | "video" | "webidentity" | "worker" | "xslt",
1145 missing => "",
1146 invalid => ""
1147 );
1148
1149 make_setter!(SetAs, "as");
1151
1152 make_getter!(Media, "media");
1154
1155 make_setter!(SetMedia, "media");
1157
1158 make_getter!(Integrity, "integrity");
1160
1161 make_setter!(SetIntegrity, "integrity");
1163
1164 make_getter!(Hreflang, "hreflang");
1166
1167 make_setter!(SetHreflang, "hreflang");
1169
1170 make_getter!(Type, "type");
1172
1173 make_setter!(SetType, "type");
1175
1176 make_bool_getter!(Disabled, "disabled");
1178
1179 make_bool_setter!(SetDisabled, "disabled");
1181
1182 fn RelList(&self, can_gc: CanGc) -> DomRoot<DOMTokenList> {
1184 self.rel_list.or_init(|| {
1185 DOMTokenList::new(
1186 self.upcast(),
1187 &local_name!("rel"),
1188 Some(vec![
1189 Atom::from("alternate"),
1190 Atom::from("apple-touch-icon"),
1191 Atom::from("apple-touch-icon-precomposed"),
1192 Atom::from("canonical"),
1193 Atom::from("dns-prefetch"),
1194 Atom::from("icon"),
1195 Atom::from("import"),
1196 Atom::from("manifest"),
1197 Atom::from("modulepreload"),
1198 Atom::from("next"),
1199 Atom::from("preconnect"),
1200 Atom::from("prefetch"),
1201 Atom::from("preload"),
1202 Atom::from("prerender"),
1203 Atom::from("stylesheet"),
1204 ]),
1205 can_gc,
1206 )
1207 })
1208 }
1209
1210 make_getter!(Charset, "charset");
1212
1213 make_setter!(SetCharset, "charset");
1215
1216 make_getter!(Rev, "rev");
1218
1219 make_setter!(SetRev, "rev");
1221
1222 make_getter!(Target, "target");
1224
1225 make_setter!(SetTarget, "target");
1227
1228 fn Blocking(&self, can_gc: CanGc) -> DomRoot<DOMTokenList> {
1230 self.blocking.or_init(|| {
1231 DOMTokenList::new(
1232 self.upcast(),
1233 &local_name!("blocking"),
1234 Some(vec![Atom::from("render")]),
1235 can_gc,
1236 )
1237 })
1238 }
1239
1240 fn GetCrossOrigin(&self) -> Option<DOMString> {
1242 reflect_cross_origin_attribute(self.upcast::<Element>())
1243 }
1244
1245 fn SetCrossOrigin(&self, cx: &mut JSContext, value: Option<DOMString>) {
1247 set_cross_origin_attribute(cx, self.upcast::<Element>(), value);
1248 }
1249
1250 fn ReferrerPolicy(&self) -> DOMString {
1252 reflect_referrer_policy_attribute(self.upcast::<Element>())
1253 }
1254
1255 make_setter!(SetReferrerPolicy, "referrerpolicy");
1257
1258 fn GetSheet(&self, can_gc: CanGc) -> Option<DomRoot<DOMStyleSheet>> {
1260 self.get_cssom_stylesheet(can_gc).map(DomRoot::upcast)
1261 }
1262}
1263
1264struct FaviconFetchContext {
1265 link: Trusted<HTMLLinkElement>,
1267 image_cache: std::sync::Arc<dyn ImageCache>,
1268 id: PendingImageId,
1269
1270 url: ServoUrl,
1272}
1273
1274impl FetchResponseListener for FaviconFetchContext {
1275 fn process_request_body(&mut self, _: RequestId) {}
1276
1277 fn process_response(
1278 &mut self,
1279 _: &mut js::context::JSContext,
1280 request_id: RequestId,
1281 metadata: Result<FetchMetadata, NetworkError>,
1282 ) {
1283 self.image_cache.notify_pending_response(
1284 self.id,
1285 FetchResponseMsg::ProcessResponse(request_id, metadata),
1286 );
1287 }
1288
1289 fn process_response_chunk(
1290 &mut self,
1291 _: &mut js::context::JSContext,
1292 request_id: RequestId,
1293 chunk: Vec<u8>,
1294 ) {
1295 self.image_cache.notify_pending_response(
1296 self.id,
1297 FetchResponseMsg::ProcessResponseChunk(request_id, chunk.into()),
1298 );
1299 }
1300
1301 fn process_response_eof(
1302 self,
1303 cx: &mut js::context::JSContext,
1304 request_id: RequestId,
1305 response: Result<(), NetworkError>,
1306 timing: ResourceFetchTiming,
1307 ) {
1308 self.image_cache.notify_pending_response(
1309 self.id,
1310 FetchResponseMsg::ProcessResponseEOF(request_id, response.clone(), timing.clone()),
1311 );
1312 submit_timing(cx, &self, &response, &timing);
1313 }
1314
1315 fn process_csp_violations(&mut self, _request_id: RequestId, violations: Vec<Violation>) {
1316 let global = &self.resource_timing_global();
1317 global.report_csp_violations(violations, None, None);
1318 }
1319}
1320
1321impl ResourceTimingListener for FaviconFetchContext {
1322 fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
1323 (
1324 InitiatorType::LocalName("link".to_string()),
1325 self.url.clone(),
1326 )
1327 }
1328
1329 fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
1330 self.link.root().upcast::<Node>().owner_doc().global()
1331 }
1332}