/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use std::io::{Read, Seek, Write}; use base::id::PipelineId; use crossbeam_channel::Sender; use cssparser::SourceLocation; use encoding_rs::UTF_8; use net_traits::mime_classifier::MimeClassifier; use net_traits::request::{CorsSettings, Destination, RequestId}; use net_traits::{ FetchMetadata, FilteredMetadata, Metadata, NetworkError, ReferrerPolicy, ResourceFetchTiming, }; use servo_arc::Arc; use servo_config::pref; use servo_url::ServoUrl; use style::context::QuirksMode; use style::global_style_data::STYLE_THREAD_POOL; use style::media_queries::MediaList; use style::shared_lock::{Locked, SharedRwLock}; use style::stylesheets::import_rule::{ImportLayer, ImportSheet, ImportSupportsCondition}; use style::stylesheets::{ ImportRule, Origin, Stylesheet, StylesheetLoader as StyleStylesheetLoader, UrlExtraData, }; use style::values::CssUrl; use crate::document_loader::LoadType; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::refcounted::Trusted; use crate::dom::bindings::reflector::DomGlobal; use crate::dom::bindings::root::DomRoot; use crate::dom::csp::{GlobalCspReporting, Violation}; use crate::dom::document::Document; use crate::dom::element::Element; use crate::dom::eventtarget::EventTarget; use crate::dom::globalscope::GlobalScope; use crate::dom::html::htmlelement::HTMLElement; use crate::dom::html::htmllinkelement::{HTMLLinkElement, RequestGenerationId}; use crate::dom::node::NodeTraits; use crate::dom::performance::performanceresourcetiming::InitiatorType; use crate::dom::shadowroot::ShadowRoot; use crate::dom::window::CSSErrorReporter; use crate::fetch::create_a_potential_cors_request; use crate::messaging::{CommonScriptMsg, MainThreadScriptMsg}; use crate::network_listener::{self, FetchResponseListener, ResourceTimingListener}; use crate::script_runtime::{CanGc, ScriptThreadEventCategory}; use crate::task_source::TaskSourceName; use crate::unminify::{ BeautifyFileType, create_output_file, create_temp_files, execute_js_beautify, }; pub(crate) trait StylesheetOwner { /// Returns whether this element was inserted by the parser (i.e., it should /// trigger a document-load-blocking load). fn parser_inserted(&self) -> bool; /// Which referrer policy should loads triggered by this owner follow fn referrer_policy(&self) -> ReferrerPolicy; /// Notes that a new load is pending to finish. fn increment_pending_loads_count(&self); /// Returns None if there are still pending loads, or whether any load has /// failed since the loads started. fn load_finished(&self, successful: bool) -> Option; /// Sets origin_clean flag. fn set_origin_clean(&self, origin_clean: bool); } pub(crate) enum StylesheetContextSource { LinkElement, Import { import_rule: Arc>, }, } /// The context required for asynchronously loading an external stylesheet. struct StylesheetContext { /// The element that initiated the request. element: Trusted, source: StylesheetContextSource, media: Arc>, url: ServoUrl, metadata: Option, /// The response body received to date. data: Vec, /// The node document for elem when the load was initiated. document: Trusted, shadow_root: Option>, origin_clean: bool, /// A token which must match the generation id of the `HTMLLinkElement` for it to load the stylesheet. /// This is ignored for `HTMLStyleElement` and imports. request_generation_id: Option, } impl StylesheetContext { fn unminify_css(&mut self, file_url: ServoUrl) { let Some(unminified_dir) = self.document.root().window().unminified_css_dir() else { return; }; let mut style_content = std::mem::take(&mut self.data); if let Some((input, mut output)) = create_temp_files() { if execute_js_beautify( input.path(), output.try_clone().unwrap(), BeautifyFileType::Css, ) { output.seek(std::io::SeekFrom::Start(0)).unwrap(); output.read_to_end(&mut style_content).unwrap(); } } match create_output_file(unminified_dir, &file_url, None) { Ok(mut file) => { file.write_all(&style_content).unwrap(); }, Err(why) => { log::warn!("Could not store script {:?}", why); }, } self.data = style_content; } fn parse( &self, quirks_mode: QuirksMode, shared_lock: SharedRwLock, css_error_reporter: &CSSErrorReporter, loader: ElementStylesheetLoader<'_>, ) -> Arc { let metadata = self .metadata .as_ref() .expect("Should never call parse without metadata."); #[cfg(feature = "tracing")] let _span = tracing::trace_span!("ParseStylesheet", servo_profiling = true).entered(); Arc::new(Stylesheet::from_bytes( &self.data, UrlExtraData(metadata.final_url.get_arc()), metadata.charset.as_deref(), // TODO: Get the actual value. http://dev.w3.org/csswg/css-syntax/#environment-encoding Some(UTF_8), Origin::Author, self.media.clone(), shared_lock, Some(&loader), Some(css_error_reporter), quirks_mode, )) } fn contributes_to_the_styling_processing_model(&self, element: &HTMLElement) -> bool { if !element.upcast::().is_connected() { return false; } // Whether or not this `StylesheetContext` is for a `` element that comes // from a previous generation. This prevents processing of earlier stylsheet URLs // when the URL has changed. // // TODO(mrobinson): Shouldn't we also exit early if this is an import that was originally // imported from a `` element that has advanced a generation as well? if !matches!(&self.source, StylesheetContextSource::LinkElement) { return true; } let link = element.downcast::().unwrap(); self.request_generation_id .is_none_or(|generation| generation == link.get_request_generation_id()) } fn decrement_load_and_render_blockers(&self, owner: &dyn StylesheetOwner, document: &Document) { if !owner.parser_inserted() { return; } document.decrement_script_blocking_stylesheet_count(); // From : // > A link element of this type is implicitly potentially render-blocking if the element // > was created by its node document's parser. if matches!(self.source, StylesheetContextSource::LinkElement) { document.decrement_render_blocking_element_count(); } } fn finish_load( self, successful: bool, owner: &dyn StylesheetOwner, element: &HTMLElement, document: &Document, ) { self.decrement_load_and_render_blockers(owner, document); document.finish_load(LoadType::Stylesheet(self.url), CanGc::note()); let Some(any_failed) = owner.load_finished(successful) else { return; }; // Do not fire any events on disconnected nodes. if !element.upcast::().is_connected() { return; } // We need to fire an event even if this load is for an ignored stylsheet (such as // one from a previous generation). Events are delayed until all loads are complete, // so we may need to fire the load event for the real load that happened earlier. // // TODO(mrobinson): This is a pretty confusing way of doing things and could potentially // delay the "load" event. Loads from previous generations should likely not count for // delaying the event. let event = match any_failed { true => atom!("error"), false => atom!("load"), }; element .upcast::() .fire_event(event, CanGc::note()); } fn do_post_parse_tasks(self, successful: bool, stylesheet: Option>) { let element = self.element.root(); let document = self.document.root(); let owner = element .upcast::() .as_stylesheet_owner() .expect("Stylesheet not loaded by