/* 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/. */ //! The script thread is the thread that owns the DOM in memory, runs JavaScript, and triggers //! layout. It's in charge of processing events for all same-origin pages in a frame //! tree, and manages the entire lifetime of pages in the frame tree from initial request to //! teardown. //! //! Page loads follow a two-step process. When a request for a new page load is received, the //! network request is initiated and the relevant data pertaining to the new page is stashed. //! While the non-blocking request is ongoing, the script thread is free to process further events, //! noting when they pertain to ongoing loads (such as resizes/viewport adjustments). When the //! initial response is received for an ongoing load, the second phase starts - the frame tree //! entry is created, along with the Window and Document objects, and the appropriate parser //! takes over the response body. Once parsing is complete, the document lifecycle for loading //! a page runs its course and the script thread returns to processing events in the main event //! loop. #![cfg_attr(crown, allow(crown::jscontext_first_arg))] use std::cell::{Cell, RefCell}; use std::collections::HashSet; use std::default::Default; use std::option::Option; use std::rc::{Rc, Weak}; use std::result::Result; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::thread::{self, JoinHandle}; use std::time::{Duration, Instant, SystemTime}; use background_hang_monitor_api::{ BackgroundHangMonitor, BackgroundHangMonitorExitSignal, BackgroundHangMonitorRegister, HangAnnotation, MonitoredComponentId, MonitoredComponentType, }; use bytes::Bytes; use chrono::{DateTime, Local}; use crossbeam_channel::unbounded; use data_url::mime::Mime; use devtools_traits::{ CSSError, DevtoolScriptControlMsg, DevtoolsPageInfo, NavigationState, ScriptToDevtoolsControlMsg, WorkerId, }; use embedder_traits::user_contents::{UserContentManagerId, UserContents, UserScript}; use embedder_traits::{ EmbedderControlId, EmbedderControlResponse, EmbedderMsg, FocusSequenceNumber, InputEventOutcome, JavaScriptEvaluationError, JavaScriptEvaluationId, MediaSessionActionType, ViewportDetails, WebDriverScriptCommand, }; use encoding_rs::Encoding; use fonts::{FontContext, SystemFontServiceProxy, WebFontLoadEvent}; use headers::{HeaderMapExt, LastModified, ReferrerPolicy as ReferrerPolicyHeader}; use http::header::REFRESH; use hyper_serde::Serde; use js::context::{JSContext, NoGC}; use js::glue::GetWindowProxyClass; use js::jsapi::{GCReason, JSContext as UnsafeJSContext}; use js::jsval::UndefinedValue; use js::rust::ParentRuntime; use js::rust::wrappers2::{JS_AddInterruptCallback, JS_GC, SetWindowProxyClass}; use layout_api::{LayoutConfig, LayoutFactory, RestyleReason, ScriptThreadFactory}; use media::WindowGLContext; use metrics::MAX_TASK_NS; use net_traits::image_cache::{ImageCacheFactory, ImageCacheResponseMessage}; use net_traits::pub_domains::is_same_site; use net_traits::request::{Referrer, RequestId}; use net_traits::response::ResponseInit; use net_traits::{ FetchMetadata, FetchResponseMsg, Metadata, NetworkError, ResourceFetchTiming, ResourceThreads, ResourceTimingType, }; use paint_api::{CrossProcessPaintApi, PinchZoomInfos, PipelineExitSource}; use percent_encoding::percent_decode; use profile_traits::mem::{ProcessReports, ReportsChan, perform_memory_report}; use profile_traits::time::ProfilerCategory; use profile_traits::time_profile; use rustc_hash::{FxHashMap, FxHashSet}; use script_bindings::cell::DomRefCell; use script_traits::{ ConstellationInputEvent, DiscardBrowsingContext, DocumentActivity, InitialScriptState, NewPipelineInfo, Painter, ScriptThreadMessage, UpdatePipelineIdReason, WebViewState, }; use servo_arc::Arc as ServoArc; use servo_base::cross_process_instant::CrossProcessInstant; use servo_base::generic_channel::GenericSender; use servo_base::id::{ BrowsingContextId, HistoryStateId, PipelineId, PipelineNamespace, ScriptEventLoopId, WebViewId, }; use servo_base::threadboost::{BoostAffinity, ThreadPriority}; use servo_base::{Epoch, generic_channel}; #[cfg(feature = "webgl")] use servo_canvas_traits::webgl::WebGLPipeline; use servo_config::opts::{self, DiagnosticsLoggingOption}; use servo_config::{pref, prefs}; use servo_constellation_traits::{ HistoryTraversalSource, LoadData, LoadOrigin, NavigationHistoryBehavior, PaintMetricEvent, RemoteFocusOperation, ScreenshotReadinessResponse, ScriptToConstellationChan, ScriptToConstellationMessage, ScrollStateUpdate, SessionHistoryTraversalRequest, StructuredSerializedData, TargetSnapshotParams, TraversalDirection, WindowSizeType, }; use servo_url::{ImmutableOrigin, MutableOrigin, OriginSnapshot, ServoUrl}; use smallvec::SmallVec; use storage_traits::StorageThreads; use storage_traits::webstorage_thread::WebStorageType; use style::context::QuirksMode; use style::error_reporting::RustLogReporter; use style::media_queries::MediaList; use style::shared_lock::SharedRwLock; use style::stylesheets::{AllowImportRules, DocumentStyleSheet, Origin, Stylesheet}; use style::thread_state::{self, ThreadState}; use stylo_atoms::Atom; use timers::{TimerEventRequest, TimerId, TimerScheduler}; use url::Position; #[cfg(feature = "webgpu")] use webgpu_traits::{WebGPUDevice, WebGPUMsg}; use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods; use crate::dom::bindings::codegen::Bindings::NavigatorBinding::NavigatorMethods; use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use crate::dom::bindings::conversions::{ ConversionResult, FromJSValConvertible, StringificationBehavior, }; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::str::DOMString; use crate::dom::csp::{CspReporting, GlobalCspReporting, Violation}; use crate::dom::customelementregistry::{ CallbackReaction, CustomElementDefinition, CustomElementReactionStack, }; use crate::dom::document::focus::FocusableArea; use crate::dom::document::{Document, HasBrowsingContext, IsHTMLDocument, RenderingUpdateReason}; use crate::dom::element::Element; use crate::dom::globalscope::GlobalScope; use crate::dom::html::htmliframeelement::{HTMLIFrameElement, IframeContext, ProcessingMode}; use crate::dom::node::{Node, NodeTraits}; use crate::dom::script_execution::{RethrowErrors, ScriptOptions}; use crate::dom::servoparser::{ParserContext, ServoParser}; use crate::dom::types::DebuggerGlobalScope; #[cfg(feature = "webgpu")] use crate::dom::webgpu::identityhub::IdentityHub; use crate::dom::window::Window; use crate::dom::windowproxy::{CreatorBrowsingContextInfo, WindowProxy}; use crate::event_loop::devtools::{self, DevtoolsState}; use crate::event_loop::document_collection::DocumentCollection; use crate::event_loop::document_loader::DocumentLoader; use crate::event_loop::script_mutation_observers::ScriptMutationObservers; use crate::event_loop::script_window_proxies::ScriptWindowProxies; use crate::event_loop::svg_font::SvgFontResolver; use crate::event_loop::webdriver_handlers::{self, jsval_to_webdriver}; use crate::fetch::fetch::FetchCanceller; use crate::fetch::network_listener::submit_timing; use crate::messaging::{ CommonScriptMsg, MainThreadScriptMsg, MixedMessage, ScriptEventLoopSender, ScriptThreadReceivers, ScriptThreadSenders, }; use crate::mime::{APPLICATION, CHARSET, MimeExt, TEXT, XML}; use crate::modules::script_module::ScriptFetchOptions; use crate::navigation::{InProgressLoad, NavigationListener}; use crate::realms::enter_auto_realm; use crate::runtime::job_queue::{MicrotaskRunnable, job_queue_microtask_checkpoint}; use crate::runtime::script_runtime::{ IntroductionType, Runtime, ScriptThreadEventCategory, ThreadSafeJSContext, get_reports, }; use crate::tasks::task_queue::TaskQueue; thread_local!(static SCRIPT_THREAD_ROOT: Cell> = const { Cell::new(None) }); fn with_optional_script_thread(f: impl FnOnce(Option<&ScriptThread>) -> R) -> R { SCRIPT_THREAD_ROOT.with(|root| { f(root .get() .and_then(|script_thread| unsafe { script_thread.as_ref() })) }) } pub(crate) fn with_script_thread(f: impl FnOnce(&ScriptThread) -> R) -> R { with_optional_script_thread(|script_thread| script_thread.map(f).unwrap_or_default()) } // We borrow the incomplete parser contexts mutably during parsing, // which is fine except that parsing can trigger evaluation, // which can trigger GC, and so we can end up tracing the script // thread during parsing. For this reason, we don't trace the // incomplete parser contexts during GC. pub(crate) struct IncompleteParserContexts(RefCell>); unsafe_no_jsmanaged_fields!(TaskQueue); type NodeIdSet = HashSet; /// A simple guard structure that restore the user interacting state when dropped #[derive(Default)] pub(crate) struct ScriptUserInteractingGuard { was_interacting: bool, user_interaction_cell: Rc>, } impl ScriptUserInteractingGuard { fn new(user_interaction_cell: Rc>) -> Self { let was_interacting = user_interaction_cell.get(); user_interaction_cell.set(true); Self { was_interacting, user_interaction_cell, } } } impl Drop for ScriptUserInteractingGuard { fn drop(&mut self) { self.user_interaction_cell.set(self.was_interacting) } } /// This is the `ScriptThread`'s version of [`UserContents`] with the difference that user /// stylesheets are represented as parsed `DocumentStyleSheet`s instead of simple source strings. struct ScriptThreadUserContents { user_scripts: Rc>, user_stylesheets: Rc>, } impl ScriptThreadUserContents { fn new(user_contents: UserContents, shared_locks: &SharedRwLocks) -> Self { let user_stylesheets = user_contents .stylesheets .iter() .map(|user_stylesheet| { DocumentStyleSheet(ServoArc::new(Stylesheet::from_str( user_stylesheet.source(), user_stylesheet.url().into(), Origin::User, ServoArc::new(shared_locks.ua_or_user.wrap(MediaList::empty())), shared_locks.ua_or_user.clone(), None, Some(&RustLogReporter), QuirksMode::NoQuirks, AllowImportRules::Yes, ))) }) .collect(); Self { user_scripts: Rc::new(user_contents.scripts), user_stylesheets: Rc::new(user_stylesheets), } } } #[derive(Clone, MallocSizeOf)] pub struct SharedRwLocks { pub author: SharedRwLock, pub ua_or_user: SharedRwLock, } impl Default for SharedRwLocks { fn default() -> Self { Self { author: SharedRwLock::new(), ua_or_user: SharedRwLock::new(), } } } #[derive(JSTraceable)] // ScriptThread instances are rooted on creation, so this is okay #[cfg_attr(crown, expect(crown::unrooted_must_root))] pub struct ScriptThread { /// A reference to the currently operating `ScriptThread`. This should always be /// upgradable to an `Rc` as long as the `ScriptThread` is running. #[no_trace] this: Weak, /// last_render_opportunity_time: Cell>, /// State that is common to `WebView`s to be shared with all of their `Pipeline`s. Each /// is stored as a `Weak` and pruned lazily so that there does not need to be any /// management when `WebView`s are closed. #[no_trace] webview_states: RefCell>>, /// The documents for pipelines managed by this thread documents: DomRefCell, /// The window proxies known by this thread window_proxies: Rc, /// A list of data pertaining to loads that have not yet received a network response incomplete_loads: DomRefCell>, /// A vector containing parser contexts which have not yet been fully processed incomplete_parser_contexts: IncompleteParserContexts, /// An [`ImageCacheFactory`] to use for creating [`ImageCache`]s for all of the /// child `Pipeline`s. #[no_trace] image_cache_factory: Arc, /// A [`ScriptThreadReceivers`] holding all of the incoming `Receiver`s for messages /// to this [`ScriptThread`]. receivers: ScriptThreadReceivers, /// A [`ScriptThreadSenders`] that holds all outgoing sending channels necessary to communicate /// to other parts of Servo. senders: ScriptThreadSenders, /// A handle to the resource thread. This is an `Arc` to avoid running out of file descriptors if /// there are many iframes. #[no_trace] resource_threads: ResourceThreads, #[no_trace] storage_threads: StorageThreads, /// A queue of tasks to be executed in this script-thread. task_queue: TaskQueue, /// The dedicated means of communication with the background-hang-monitor for this script-thread. #[no_trace] background_hang_monitor: Box, /// A flag set to `true` by the BHM on exit, and checked from within the interrupt handler. closing: Arc, /// A [`TimerScheduler`] used to schedule timers for this [`ScriptThread`]. Timers are handled /// in the [`ScriptThread`] event loop. #[no_trace] timer_scheduler: RefCell, /// A proxy to the `SystemFontService` to use for accessing system font lists. #[no_trace] system_font_service: Arc, /// The JavaScript runtime. js_runtime: Rc, /// List of pipelines that have been owned and closed by this script thread. #[no_trace] closed_pipelines: DomRefCell>, mutation_observers: Rc, /// A handle to the WebGL thread #[no_trace] #[cfg(feature = "webgl")] webgl_chan: Option, /// The WebXR device registry #[no_trace] #[cfg(feature = "webxr")] webxr_registry: Option, /// custom_element_reaction_stack: Rc, /// Cross-process access to `Paint`'s API. #[no_trace] paint_api: CrossProcessPaintApi, /// Periodically print out on which events script threads spend their processing time. profile_script_events: bool, /// Unminify Javascript. unminify_js: bool, /// Directory with stored unminified scripts local_script_source: Option, /// Unminify Css. unminify_css: bool, /// The [`SharedRwLocks`] that are used by all Stylo operations in this ScriptThread. #[no_trace] shared_style_locks: SharedRwLocks, /// A map from [`UserContentManagerId`] to its [`UserContents`]. This is initialized /// with a copy of the map in constellation (via the `InitialScriptState`). After that, /// the constellation forwards any mutations to this `ScriptThread` using messages. #[no_trace] user_contents_for_manager_id: RefCell>, /// Application window's GL Context for Media player #[no_trace] player_context: WindowGLContext, /// A map from pipelines to all owned nodes ever created in this script thread #[no_trace] pipeline_to_node_ids: DomRefCell>, /// Code is running as a consequence of a user interaction is_user_interacting: Rc>, /// Identity manager for WebGPU resources #[no_trace] #[cfg(feature = "webgpu")] gpu_id_hub: Arc, /// A factory for making new layouts. This allows layout to depend on script. #[no_trace] layout_factory: Arc, /// The [`TimerId`] of a ScriptThread-scheduled "update the rendering" call, if any. /// The ScriptThread schedules calls to "update the rendering," but the renderer can /// also do this when animating. Renderer-based calls always take precedence. #[no_trace] scheduled_update_the_rendering: RefCell>, /// Whether an animation tick or ScriptThread-triggered rendering update is pending. This might /// either be because the Servo renderer is managing animations and the [`ScriptThread`] has /// received a [`ScriptThreadMessage::TickAllAnimations`] message, because the [`ScriptThread`] /// itself is managing animations the timer fired triggering a [`ScriptThread`]-based /// animation tick, or if there are no animations running and the [`ScriptThread`] has noticed a /// change that requires a rendering update. needs_rendering_update: Arc, debugger_global: Dom, debugger_paused: Cell, /// A list of URLs that can access privileged internal APIs. #[no_trace] privileged_urls: Vec, devtools_state: DevtoolsState, } struct BHMExitSignal { closing: Arc, js_context: ThreadSafeJSContext, } impl BackgroundHangMonitorExitSignal for BHMExitSignal { fn signal_to_exit(&self) { self.closing.store(true, Ordering::SeqCst); self.js_context.request_interrupt_callback(); } } #[expect(unsafe_code)] unsafe extern "C" fn interrupt_callback(_cx: *mut UnsafeJSContext) -> bool { let res = ScriptThread::can_continue_running(); if !res { ScriptThread::prepare_for_shutdown(); } res } /// In the event of thread panic, all data on the stack runs its destructor. However, there /// are no reachable, owning pointers to the DOM memory, so it never gets freed by default /// when the script thread fails. The ScriptMemoryFailsafe uses the destructor bomb pattern /// to forcibly tear down the JS realms for pages associated with the failing ScriptThread. struct ScriptMemoryFailsafe<'a> { owner: Option<&'a ScriptThread>, } impl<'a> ScriptMemoryFailsafe<'a> { fn neuter(&mut self) { self.owner = None; } fn new(owner: &'a ScriptThread) -> ScriptMemoryFailsafe<'a> { ScriptMemoryFailsafe { owner: Some(owner) } } } impl Drop for ScriptMemoryFailsafe<'_> { fn drop(&mut self) { if let Some(owner) = self.owner { for (_, document) in owner.documents.borrow().iter() { document.window().clear_js_runtime_for_script_deallocation(); } } } } impl ScriptThreadFactory for ScriptThread { fn create( state: InitialScriptState, layout_factory: Arc, image_cache_factory: Arc, background_hang_monitor_register: Box, ) -> JoinHandle<()> { // Setup pipeline-namespace-installing for all threads in this process. // Idempotent in single-process mode. PipelineNamespace::set_installer_sender(state.namespace_request_sender.clone()); let script_thread_id = state.id; thread::Builder::new() .name(format!("Script#{script_thread_id}")) .stack_size(8 * 1024 * 1024) // 8 MiB stack to be consistent with other browsers. .spawn(move || { profile_traits::debug_event!( "ScriptThread::spawned", script_thread_id = script_thread_id.to_string() ); thread_state::initialize(ThreadState::SCRIPT); PipelineNamespace::install(state.pipeline_namespace_id); ScriptEventLoopId::install(state.id); let memory_profiler_sender = state.memory_profiler_sender.clone(); let reporter_name = format!("script-reporter-{script_thread_id:?}"); let (script_thread, mut cx) = ScriptThread::new( state, layout_factory, image_cache_factory, background_hang_monitor_register, ); SCRIPT_THREAD_ROOT.with(|root| { root.set(Some(Rc::as_ptr(&script_thread))); }); servo_base::threadboost::boost_thread( ThreadPriority::Critical, BoostAffinity::Boost, ); let mut failsafe = ScriptMemoryFailsafe::new(&script_thread); memory_profiler_sender.run_with_memory_reporting( || script_thread.start(&mut cx), reporter_name, ScriptEventLoopSender::MainThread(script_thread.senders.self_sender.clone()), CommonScriptMsg::CollectReports, ); // This must always be the very last operation performed before the thread completes failsafe.neuter(); }) .expect("Thread spawning failed") } } #[servo_tracing::instrument_all(skip_all)] impl ScriptThread { /// Convert the provided [`WebViewState`] into a version shared with all /// [`Window`]s that have the same `WebView` in this [`ScriptThread`], creating /// it if this is the first time the `WebView` has been encountered. fn shared_webview_state(&self, shared_state: &WebViewState) -> Rc { let mut webview_states = self.webview_states.borrow_mut(); // Prune any states that are no longer used by active pipelines. webview_states.retain(|_, state| state.upgrade().is_some()); if let Some(existing_shared_state) = webview_states.get(&shared_state.id).and_then(Weak::upgrade) { return existing_shared_state; } let shared_state = Rc::new(shared_state.clone()); webview_states.insert(shared_state.id, Rc::downgrade(&shared_state)); shared_state } pub(crate) fn runtime_handle() -> ParentRuntime { with_optional_script_thread(|script_thread| { script_thread.unwrap().js_runtime.prepare_for_new_child() }) } pub(crate) fn can_continue_running() -> bool { with_script_thread(|script_thread| script_thread.can_continue_running_inner()) } pub(crate) fn prepare_for_shutdown() { with_script_thread(|script_thread| { script_thread.prepare_for_shutdown_inner(); }) } pub(crate) fn mutation_observers() -> Rc { with_script_thread(|script_thread| script_thread.mutation_observers.clone()) } pub(crate) fn shared_style_locks(&self) -> &SharedRwLocks { &self.shared_style_locks } /// Process a single event as if it were the next event /// in the queue for this window event-loop. /// Returns a boolean indicating whether further events should be processed. pub(crate) fn process_event(msg: CommonScriptMsg, cx: &mut js::context::JSContext) -> bool { with_script_thread(|script_thread| { if !script_thread.can_continue_running_inner() { return false; } script_thread.handle_msg_from_script(MainThreadScriptMsg::Common(msg), cx); true }) } /// Schedule a [`TimerEventRequest`] on this [`ScriptThread`]'s [`TimerScheduler`]. pub(crate) fn schedule_timer(&self, request: TimerEventRequest) -> TimerId { self.timer_scheduler.borrow_mut().schedule_timer(request) } /// Cancel a the [`TimerEventRequest`] for the given [`TimerId`] on this /// [`ScriptThread`]'s [`TimerScheduler`]. pub(crate) fn cancel_timer(&self, timer_id: TimerId) { self.timer_scheduler.borrow_mut().cancel_timer(timer_id) } /// pub(crate) fn await_stable_state(cx: &JSContext, task: Box) { crate::runtime::job_queue::enqueue(cx, task); } /// Check that two origins are "similar enough", /// for now only used to prevent cross-origin JS url evaluation. /// /// fn check_load_origin(source: &LoadOrigin, target: &OriginSnapshot) -> bool { match source { LoadOrigin::Constellation | LoadOrigin::WebDriver => { // Always allow loads initiated by the constellation or webdriver. true }, LoadOrigin::Script(source_origin) => source_origin.same_origin_domain(target), } } /// Inform the `ScriptThread` that it should make a call to /// [`ScriptThread::update_the_rendering`] as soon as possible, as the rendering /// update timer has fired or the renderer has asked us for a new rendering update. pub(crate) fn set_needs_rendering_update(&self) { self.needs_rendering_update.store(true, Ordering::Relaxed); } /// pub(crate) fn can_navigate_to_javascript_url( cx: &mut js::context::JSContext, initiator_global: &GlobalScope, target_global: &GlobalScope, load_data: &mut LoadData, container: Option<&Element>, ) -> bool { // Step 3. If initiatorOrigin is not same origin-domain with targetNavigable's active document's origin, then return. // // Important re security. See https://github.com/servo/servo/issues/23373 if !Self::check_load_origin(&load_data.load_origin, &target_global.origin().snapshot()) { return false; } // Step 5: If the result of should navigation request of type be blocked by // Content Security Policy? given request and cspNavigationType is "Blocked", then return. [CSP] if initiator_global .get_csp_list() .should_navigation_request_be_blocked(cx, initiator_global, load_data, container) { return false; } true } /// Attempt to navigate a global to a javascript: URL. Returns true if a new document is created. /// pub(crate) fn navigate_to_javascript_url( cx: &mut js::context::JSContext, initiator_global: &GlobalScope, target_global: &GlobalScope, load_data: &mut LoadData, container: Option<&Element>, initial_insertion: Option, ) -> bool { // Step 6. If the result of should navigation request of type be blocked by Content // Security Policy? given request and cspNavigationType is "Blocked", then return. if !Self::can_navigate_to_javascript_url( cx, initiator_global, target_global, load_data, container, ) { return false; } // Step 7. Let newDocument be the result of evaluating a javascript: URL given targetNavigable, // url, initiatorOrigin, and userInvolvement. if !Self::evaluate_a_javascript_url(cx, target_global, load_data) { // Step 8. If newDocument is null: let window_proxy = target_global.as_window().window_proxy(); if let Some(frame_element) = window_proxy .frame_element() .and_then(Castable::downcast::) { // Step 8.1 If initialInsertion is true and targetNavigable's active document's // is initial about:blank is true, then run the iframe load event steps given // targetNavigable's container. if initial_insertion == Some(true) && frame_element.is_initial_blank_document() { frame_element.run_iframe_load_event_steps(cx); } } // Step 8.2. Return. return false; } true } pub(crate) fn get_top_level_for_browsing_context( sender_webview_id: WebViewId, sender_pipeline_id: PipelineId, browsing_context_id: BrowsingContextId, ) -> Option { with_script_thread(|script_thread| { script_thread.ask_constellation_for_top_level_info( sender_webview_id, sender_pipeline_id, browsing_context_id, ) }) } pub(crate) fn find_window(id: PipelineId) -> Option> { with_script_thread(|script_thread| script_thread.documents.borrow().find_window(id)) } pub(crate) fn find_document(id: PipelineId) -> Option> { with_script_thread(|script_thread| script_thread.documents.borrow().find_document(id)) } /// Creates a guard that sets user_is_interacting to true and returns the /// state of user_is_interacting on drop of the guard. /// Notice that you need to use `let _guard = ...` as `let _ = ...` is not enough #[must_use] pub(crate) fn user_interacting_guard() -> ScriptUserInteractingGuard { with_script_thread(|script_thread| { ScriptUserInteractingGuard::new(script_thread.is_user_interacting.clone()) }) } pub(crate) fn is_user_interacting() -> bool { with_script_thread(|script_thread| script_thread.is_user_interacting.get()) } pub(crate) fn get_fully_active_document_ids(&self) -> FxHashSet { self.documents .borrow() .iter() .filter_map(|(id, document)| { if document.is_fully_active() { Some(id) } else { None } }) .fold(FxHashSet::default(), |mut set, id| { let _ = set.insert(id); set }) } pub(crate) fn window_proxies() -> Rc { with_script_thread(|script_thread| script_thread.window_proxies.clone()) } fn handle_register_paint_worklet( &self, pipeline_id: PipelineId, name: Atom, properties: Vec, painter: Box, ) { let Some(window) = self.documents.borrow().find_window(pipeline_id) else { warn!("Paint worklet registered after pipeline {pipeline_id} closed."); return; }; window .layout_mut() .register_paint_worklet_modules(name, properties, painter); } pub(crate) fn custom_element_reaction_stack() -> Rc { with_optional_script_thread(|script_thread| { script_thread .as_ref() .unwrap() .custom_element_reaction_stack .clone() }) } pub(crate) fn enqueue_callback_reaction( cx: &mut js::context::JSContext, element: &Element, reaction: CallbackReaction, definition: Option>, ) { with_script_thread(|script_thread| { script_thread .custom_element_reaction_stack .enqueue_callback_reaction(cx, element, reaction, definition); }) } pub(crate) fn enqueue_upgrade_reaction( cx: &js::context::JSContext, element: &Element, definition: Rc, ) { with_script_thread(|script_thread| { script_thread .custom_element_reaction_stack .enqueue_upgrade_reaction(cx, element, definition); }) } pub(crate) fn invoke_backup_element_queue(cx: &mut js::context::JSContext) { with_script_thread(|script_thread| { script_thread .custom_element_reaction_stack .invoke_backup_element_queue(cx); }) } pub(crate) fn save_node_id(pipeline: PipelineId, node_id: String) { with_script_thread(|script_thread| { script_thread .pipeline_to_node_ids .borrow_mut() .entry(pipeline) .or_default() .insert(node_id); }) } pub(crate) fn has_node_id(pipeline: PipelineId, node_id: &str) -> bool { with_script_thread(|script_thread| { script_thread .pipeline_to_node_ids .borrow() .get(&pipeline) .is_some_and(|node_ids| node_ids.contains(node_id)) }) } /// Creates a new script thread. #[servo_tracing::instrument(name = "ScripThread::new", level = "debug", skip_all)] pub(crate) fn new( state: InitialScriptState, layout_factory: Arc, image_cache_factory: Arc, background_hang_monitor_register: Box, ) -> (Rc, js::context::JSContext) { let (self_sender, self_receiver) = unbounded(); let mut runtime = Runtime::new(Some(ScriptEventLoopSender::MainThread(self_sender.clone()))); // SAFETY: We ensure that only one JSContext exists in this thread. // This is the first one and the only one let mut cx = unsafe { runtime.cx() }; unsafe { SetWindowProxyClass(&cx, GetWindowProxyClass()); JS_AddInterruptCallback(&cx, Some(interrupt_callback)); } let constellation_receiver = state .constellation_to_script_receiver .route_preserving_errors(); // Ask the router to proxy IPC messages from the devtools to us. let devtools_server_sender = state.devtools_server_sender; let (ipc_devtools_sender, ipc_devtools_receiver) = generic_channel::channel().unwrap(); let devtools_server_receiver = ipc_devtools_receiver.route_preserving_errors(); let task_queue = TaskQueue::new(self_receiver, self_sender.clone()); let closing = Arc::new(AtomicBool::new(false)); let background_hang_monitor_exit_signal = BHMExitSignal { closing: closing.clone(), js_context: runtime.thread_safe_js_context(), }; let background_hang_monitor = background_hang_monitor_register.register_component( // TODO: We shouldn't rely on this PipelineId as a ScriptThread can have multiple // Pipelines and any of them might disappear at any time. MonitoredComponentId(state.id, MonitoredComponentType::Script), Duration::from_millis(1000), Duration::from_millis(5000), Box::new(background_hang_monitor_exit_signal), ); let (image_cache_sender, image_cache_receiver) = unbounded(); let receivers = ScriptThreadReceivers { constellation_receiver, image_cache_receiver, devtools_server_receiver, // Initialized to `never` until WebGPU is initialized. #[cfg(feature = "webgpu")] webgpu_receiver: RefCell::new(crossbeam_channel::never()), }; let opts = opts::get(); let senders = ScriptThreadSenders { self_sender, #[cfg(feature = "bluetooth")] bluetooth_sender: state.bluetooth_sender, constellation_sender: state.constellation_to_script_sender, pipeline_to_constellation_sender: state.script_to_constellation_sender, pipeline_to_embedder_sender: state.script_to_embedder_sender.clone(), image_cache_sender, time_profiler_sender: state.time_profiler_sender, memory_profiler_sender: state.memory_profiler_sender, devtools_server_sender, devtools_client_to_script_thread_sender: ipc_devtools_sender, }; #[cfg(feature = "webgpu")] let gpu_id_hub = Arc::new(IdentityHub::default()); let debugger_global = DebuggerGlobalScope::new( PipelineId::new(), senders.devtools_server_sender.clone(), senders.devtools_client_to_script_thread_sender.clone(), senders.memory_profiler_sender.clone(), senders.time_profiler_sender.clone(), senders.pipeline_to_constellation_sender.clone(), senders.pipeline_to_embedder_sender.clone(), state.resource_threads.clone(), state.storage_threads.clone(), #[cfg(feature = "webgpu")] gpu_id_hub.clone(), &mut cx, ); debugger_global.execute(&mut cx); let shared_style_locks = Default::default(); let user_contents_for_manager_id = FxHashMap::from_iter(state.user_contents_for_manager_id.into_iter().map( |(user_content_manager_id, user_contents)| { ( user_content_manager_id, ScriptThreadUserContents::new(user_contents, &shared_style_locks), ) }, )); ( Rc::new_cyclic(|weak_script_thread| { runtime.set_script_thread(weak_script_thread.clone()); Self { webview_states: Default::default(), documents: DomRefCell::new(DocumentCollection::default()), last_render_opportunity_time: Default::default(), window_proxies: Default::default(), incomplete_loads: DomRefCell::new(vec![]), incomplete_parser_contexts: IncompleteParserContexts(RefCell::new(vec![])), senders, receivers, image_cache_factory, resource_threads: state.resource_threads, storage_threads: state.storage_threads, task_queue, background_hang_monitor, closing, timer_scheduler: Default::default(), js_runtime: Rc::new(runtime), closed_pipelines: DomRefCell::new(FxHashSet::default()), mutation_observers: Default::default(), system_font_service: Arc::new(state.system_font_service.to_proxy()), #[cfg(feature = "webgl")] webgl_chan: state.webgl_chan, #[cfg(feature = "webxr")] webxr_registry: state.webxr_registry, custom_element_reaction_stack: Rc::new(CustomElementReactionStack::new()), paint_api: state.cross_process_paint_api, profile_script_events: opts .debug .is_enabled(DiagnosticsLoggingOption::ProfileScriptEvents), unminify_js: opts.unminify_js, local_script_source: opts.local_script_source.clone(), unminify_css: opts.unminify_css, shared_style_locks, user_contents_for_manager_id: RefCell::new(user_contents_for_manager_id), player_context: state.player_context, pipeline_to_node_ids: Default::default(), is_user_interacting: Rc::new(Cell::new(false)), #[cfg(feature = "webgpu")] gpu_id_hub, layout_factory, scheduled_update_the_rendering: Default::default(), needs_rendering_update: Arc::new(AtomicBool::new(false)), debugger_global: debugger_global.as_traced(), debugger_paused: Cell::new(false), privileged_urls: state.privileged_urls, this: weak_script_thread.clone(), devtools_state: Default::default(), } }), cx, ) } /// Check if we are closing. fn can_continue_running_inner(&self) -> bool { if self.closing.load(Ordering::SeqCst) { return false; } true } /// We are closing, ensure no script can run and potentially hang. fn prepare_for_shutdown_inner(&self) { let docs = self.documents.borrow(); for (_, document) in docs.iter() { document .owner_global() .task_manager() .cancel_all_tasks_and_ignore_future_tasks(); } } /// Starts the script thread. After calling this method, the script thread will loop receiving /// messages on its port. pub(crate) fn start(&self, cx: &mut js::context::JSContext) { debug!("Starting script thread."); while self.handle_msgs(cx) { // Go on... debug!("Running script thread."); } debug!("Stopped script thread."); } /// Process input events as part of a "update the rendering task". fn process_pending_input_events( &self, cx: &mut js::context::JSContext, pipeline_id: PipelineId, ) { let Some(document) = self.documents.borrow().find_document(pipeline_id) else { warn!("Processing pending input events for closed pipeline {pipeline_id}."); return; }; // Do not handle events if the BC has been, or is being, discarded if document.window().Closed() { warn!("Input event sent to a pipeline with a closed window {pipeline_id}."); return; } if !document.event_handler().has_pending_input_events() { return; } let _guard = ScriptUserInteractingGuard::new(self.is_user_interacting.clone()); document.event_handler().handle_pending_input_events(cx); } fn cancel_scheduled_update_the_rendering(&self) { if let Some(timer_id) = self.scheduled_update_the_rendering.borrow_mut().take() { self.timer_scheduler.borrow_mut().cancel_timer(timer_id); } } fn schedule_update_the_rendering_timer_if_necessary(&self, delay: Duration) { if self.scheduled_update_the_rendering.borrow().is_some() { return; } debug!("Scheduling ScriptThread animation frame."); let trigger_script_thread_animation = self.needs_rendering_update.clone(); let timer_id = self.schedule_timer(TimerEventRequest { callback: Box::new(move || { trigger_script_thread_animation.store(true, Ordering::Relaxed); }), duration: delay, }); *self.scheduled_update_the_rendering.borrow_mut() = Some(timer_id); } /// /// /// Attempt to update the rendering and then do a microtask checkpoint if rendering was /// actually updated. /// /// Returns true if any reflows produced a new display list. pub(crate) fn update_the_rendering(&self, cx: &mut js::context::JSContext) -> bool { self.last_render_opportunity_time.set(Some(Instant::now())); self.cancel_scheduled_update_the_rendering(); self.needs_rendering_update.store(false, Ordering::Relaxed); if !self.can_continue_running_inner() { return false; } // TODO(#31242): the filtering of docs is extended to not exclude the ones that // has pending initial observation targets // https://w3c.github.io/IntersectionObserver/#pending-initial-observation // > 2. Let docs be all fully active Document objects whose relevant agent's event loop // > is eventLoop, sorted arbitrarily except that the following conditions must be // > met: // // > Any Document B whose container document is A must be listed after A in the // > list. // // > If there are two documents A and B that both have the same non-null container // > document C, then the order of A and B in the list must match the // > shadow-including tree order of their respective navigable containers in C's // > node tree. // // > In the steps below that iterate over docs, each Document must be processed in // > the order it is found in the list. let documents_in_order = self.documents.borrow().documents_in_order(); // TODO: The specification reads: "for doc in docs" at each step whereas this runs all // steps per doc in docs. Currently `