/* 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 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, LoadContext, Metadata, NetworkError, ReferrerPolicy, ResourceFetchTiming, }; use servo_arc::Arc; use servo_base::id::PipelineId; 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::{RequestWithGlobalScope, 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; /// fn potentially_render_blocking(&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(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, /// is_script_blocking: bool, /// is_render_blocking: bool, } 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 empty_stylesheet(&self, document: &Document) -> Arc { let shared_lock = document.style_shared_lock().clone(); let quirks_mode = document.quirks_mode(); Arc::new(Stylesheet::from_bytes( &[], UrlExtraData(self.url.get_arc()), None, None, Origin::Author, self.media.clone(), shared_lock, None, None, quirks_mode, )) } 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."); let _span = profile_traits::trace_span!("ParseStylesheet").entered(); Arc::new(Stylesheet::from_bytes( &self.data, UrlExtraData(metadata.final_url.get_arc()), metadata.charset.as_deref(), // The CSS environment encoding is the result of running the following steps: [CSSSYNTAX] // If el has a charset attribute, get an encoding from that attribute's value. If that succeeds, return the resulting encoding. [ENCODING] // Otherwise, return the document's character encoding. [DOM] // // TODO: Need to implement encoding 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 contributes_a_script_blocking_style_sheet( &self, element: &HTMLElement, owner: &dyn StylesheetOwner, document: &Document, ) -> bool { // el was created by that Document's parser. owner.parser_inserted() // el is either a style element or a link element that was an external resource link that // contributes to the styling processing model when the el was created by the parser. && element.downcast::().is_none_or(|link| self.contributes_to_the_styling_processing_model(element) // el's style sheet was enabled when the element was created by the parser. && !link.is_effectively_disabled() ) // el's media attribute's value matches the environment. && element.media_attribute_matches_media_environment() // The last time the event loop reached step 1, el's root was that Document. && *element.owner_document() == *document // The user agent hasn't given up on loading that particular style sheet yet. // A user agent may give up on loading a style sheet at any time. // // This might happen when we time out a resource, but that happens in `fetch` instead } fn decrement_blockers_and_finish_load( self, document: &Document, cx: &mut js::context::JSContext, ) { if self.is_script_blocking { document.decrement_script_blocking_stylesheet_count(); } if self.is_render_blocking { document.decrement_render_blocking_element_count(); } document.finish_load(LoadType::Stylesheet(self.url), cx); } fn do_post_parse_tasks( self, success: bool, stylesheet: Arc, cx: &mut js::context::JSContext, ) { let element = self.element.root(); let document = self.document.root(); let owner = element .upcast::() .as_stylesheet_owner() .expect("Stylesheet not loaded by