/* 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. use std::cell::{Cell, RefCell}; use std::collections::HashSet; use std::default::Default; use std::option::Option; use std::rc::Rc; 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, HangAnnotation, MonitoredComponentId, MonitoredComponentType, }; use base::cross_process_instant::CrossProcessInstant; use base::id::{BrowsingContextId, HistoryStateId, PipelineId, PipelineNamespace, WebViewId}; use canvas_traits::webgl::WebGLPipeline; use chrono::{DateTime, Local}; use compositing_traits::{CrossProcessCompositorApi, PipelineExitSource}; use constellation_traits::{ JsEvalResult, LoadData, LoadOrigin, NavigationHistoryBehavior, ScreenshotReadinessResponse, ScriptToConstellationChan, ScriptToConstellationMessage, StructuredSerializedData, WindowSizeType, }; use crossbeam_channel::unbounded; use data_url::mime::Mime; use devtools_traits::{ CSSError, DevtoolScriptControlMsg, DevtoolsPageInfo, NavigationState, ScriptToDevtoolsControlMsg, WorkerId, }; use embedder_traits::user_content_manager::UserContentManager; use embedder_traits::{ FocusSequenceNumber, InputEvent, JavaScriptEvaluationError, JavaScriptEvaluationId, MediaSessionActionType, MouseButton, MouseButtonAction, MouseButtonEvent, Theme, ViewportDetails, WebDriverScriptCommand, }; use euclid::Point2D; use euclid::default::Rect; use fonts::{FontContext, SystemFontServiceProxy}; use headers::{HeaderMapExt, LastModified, ReferrerPolicy as ReferrerPolicyHeader}; use http::header::REFRESH; use hyper_serde::Serde; use ipc_channel::ipc; use ipc_channel::router::ROUTER; use js::glue::GetWindowProxyClass; use js::jsapi::{ JS_AddInterruptCallback, JSContext as UnsafeJSContext, JSTracer, SetWindowProxyClass, }; use js::jsval::UndefinedValue; use js::rust::ParentRuntime; use layout_api::{LayoutConfig, LayoutFactory, RestyleReason, ScriptThreadFactory}; use media::WindowGLContext; use metrics::MAX_TASK_NS; use net_traits::image_cache::{ImageCache, ImageCacheResponseMessage}; use net_traits::request::{Referrer, RequestId}; use net_traits::response::ResponseInit; use net_traits::storage_thread::StorageType; use net_traits::{ FetchMetadata, FetchResponseListener, FetchResponseMsg, Metadata, NetworkError, ResourceFetchTiming, ResourceThreads, ResourceTimingType, }; 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::{FxBuildHasher, FxHashMap, FxHashSet}; use script_traits::{ ConstellationInputEvent, DiscardBrowsingContext, DocumentActivity, InitialScriptState, NewLayoutInfo, Painter, ProgressiveWebMetricType, ScriptThreadMessage, UpdatePipelineIdReason, }; use servo_config::{opts, prefs}; use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl}; 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 webrender_api::ExternalScrollId; use webrender_api::units::{DevicePixel, LayoutVector2D}; use crate::document_collection::DocumentCollection; use crate::document_loader::DocumentLoader; use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::DocumentBinding::{ DocumentMethods, DocumentReadyState, }; use crate::dom::bindings::codegen::Bindings::NavigatorBinding::NavigatorMethods; use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; use crate::dom::bindings::conversions::{ ConversionResult, SafeFromJSValConvertible, StringificationBehavior, }; use crate::dom::bindings::inheritance::Castable; use crate::dom::bindings::refcounted::Trusted; use crate::dom::bindings::reflector::DomGlobal; use crate::dom::bindings::root::{Dom, DomRoot}; use crate::dom::bindings::settings_stack::AutoEntryScript; use crate::dom::bindings::str::DOMString; use crate::dom::bindings::trace::{HashMapTracedValues, JSTraceable}; use crate::dom::csp::{CspReporting, GlobalCspReporting, Violation}; use crate::dom::customelementregistry::{ CallbackReaction, CustomElementDefinition, CustomElementReactionStack, }; use crate::dom::document::{ Document, DocumentSource, FocusInitiator, HasBrowsingContext, IsHTMLDocument, }; use crate::dom::element::Element; use crate::dom::globalscope::GlobalScope; use crate::dom::html::htmliframeelement::HTMLIFrameElement; use crate::dom::node::NodeTraits; 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::dom::worklet::WorkletThreadPool; use crate::dom::workletglobalscope::WorkletGlobalScopeInit; use crate::fetch::FetchCanceller; use crate::messaging::{ CommonScriptMsg, MainThreadScriptMsg, MixedMessage, ScriptEventLoopSender, ScriptThreadReceivers, ScriptThreadSenders, }; use crate::microtask::{Microtask, MicrotaskQueue}; use crate::mime::{APPLICATION, MimeExt, TEXT, XML}; use crate::navigation::{InProgressLoad, NavigationListener}; use crate::realms::enter_realm; use crate::script_module::ScriptFetchOptions; use crate::script_mutation_observers::ScriptMutationObservers; use crate::script_runtime::{ CanGc, IntroductionType, JSContext, JSContextHelper, Runtime, ScriptThreadEventCategory, ThreadSafeJSContext, }; use crate::task_queue::TaskQueue; use crate::task_source::{SendableTaskSource, TaskSourceName}; use crate::webdriver_handlers::jsval_to_webdriver; use crate::{devtools, webdriver_handlers}; 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()) } /// # Safety /// /// The `JSTracer` argument must point to a valid `JSTracer` in memory. In addition, /// implementors of this method must ensure that all active objects are properly traced /// or else the garbage collector may end up collecting objects that are still reachable. pub(crate) unsafe fn trace_thread(tr: *mut JSTracer) { with_script_thread(|script_thread| { trace!("tracing fields of ScriptThread"); unsafe { script_thread.trace(tr) }; }) } // 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) } } #[derive(JSTraceable)] // ScriptThread instances are rooted on creation, so this is okay #[cfg_attr(crown, allow(crown::unrooted_must_root))] pub struct ScriptThread { /// last_render_opportunity_time: Cell>, /// The documents for pipelines managed by this thread documents: DomRefCell, /// The window proxies known by this thread /// TODO: this map grows, but never shrinks. Issue #15258. window_proxies: DomRefCell, FxBuildHasher>>, /// 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, /// Image cache for this script thread. #[no_trace] image_cache: 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, /// 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>, /// microtask_queue: Rc, mutation_observers: Rc, /// A handle to the WebGL thread #[no_trace] webgl_chan: Option, /// The WebXR device registry #[no_trace] #[cfg(feature = "webxr")] webxr_registry: Option, /// The worklet thread pool worklet_thread_pool: DomRefCell>>, /// A list of pipelines containing documents that finished loading all their blocking /// resources during a turn of the event loop. docs_with_no_blocking_loads: DomRefCell>>, /// custom_element_reaction_stack: Rc, /// Cross-process access to the compositor's API. #[no_trace] compositor_api: CrossProcessCompositorApi, /// Periodically print out on which events script threads spend their processing time. profile_script_events: bool, /// Print Progressive Web Metrics to console. print_pwm: bool, /// Unminify Javascript. unminify_js: bool, /// Directory with stored unminified scripts local_script_source: Option, /// Unminify Css. unminify_css: bool, /// User content manager #[no_trace] user_content_manager: UserContentManager, /// 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, // Secure context inherited_secure_context: Option, /// A factory for making new layouts. This allows layout to depend on script. #[no_trace] layout_factory: Arc, /// The screen coordinates where the primary mouse button was pressed. #[no_trace] relative_mouse_down_point: Cell>, /// 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 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, /// A list of URLs that can access privileged internal APIs. #[no_trace] privileged_urls: Vec, } 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(); } } #[allow(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<'_> { #[cfg_attr(crown, allow(crown::unrooted_must_root))] 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, system_font_service: Arc, load_data: LoadData, ) -> JoinHandle<()> { thread::Builder::new() .name(format!("Script{:?}", state.id)) .spawn(move || { thread_state::initialize(ThreadState::SCRIPT | ThreadState::LAYOUT); PipelineNamespace::install(state.pipeline_namespace_id); WebViewId::install(state.webview_id); let memory_profiler_sender = state.memory_profiler_sender.clone(); let in_progress_load = InProgressLoad::new( state.id, state.browsing_context_id, state.webview_id, state.parent_info, state.opener, state.viewport_details, state.theme, MutableOrigin::new(load_data.url.origin()), load_data, ); let reporter_name = format!("script-reporter-{:?}", state.id); let script_thread = ScriptThread::new(state, layout_factory, system_font_service); SCRIPT_THREAD_ROOT.with(|root| { root.set(Some(&script_thread as *const _)); }); let mut failsafe = ScriptMemoryFailsafe::new(&script_thread); script_thread.pre_page_load(in_progress_load); memory_profiler_sender.run_with_memory_reporting( || { script_thread.start(CanGc::note()); let _ = script_thread .senders .content_process_shutdown_sender .send(()); }, 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") } } impl ScriptThread { 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 microtask_queue() -> Rc { with_script_thread(|script_thread| script_thread.microtask_queue.clone()) } pub(crate) fn mark_document_with_no_blocked_loads(doc: &Document) { with_script_thread(|script_thread| { script_thread .docs_with_no_blocking_loads .borrow_mut() .insert(Dom::from_ref(doc)); }) } pub(crate) fn page_headers_available( id: &PipelineId, metadata: Option, can_gc: CanGc, ) -> Option> { with_script_thread(|script_thread| { script_thread.handle_page_headers_available(id, metadata, can_gc) }) } /// 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) -> bool { with_script_thread(|script_thread| { if !script_thread.can_continue_running_inner() { return false; } script_thread.handle_msg_from_script(MainThreadScriptMsg::Common(msg)); 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) } // https://html.spec.whatwg.org/multipage/#await-a-stable-state pub(crate) fn await_stable_state(task: Microtask) { with_script_thread(|script_thread| { script_thread .microtask_queue .enqueue(task, script_thread.get_cx()); }); } /// Check that two origins are "similar enough", /// for now only used to prevent cross-origin JS url evaluation. /// /// pub(crate) fn check_load_origin(source: &LoadOrigin, target: &ImmutableOrigin) -> bool { match (source, target) { (LoadOrigin::Constellation, _) | (LoadOrigin::WebDriver, _) => { // Always allow loads initiated by the constellation or webdriver. true }, (_, ImmutableOrigin::Opaque(_)) => { // If the target is opaque, allow. // This covers newly created about:blank auxiliaries, and iframe with no src. // TODO: https://github.com/servo/servo/issues/22879 true }, (LoadOrigin::Script(source_origin), _) => source_origin == 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); } /// Step 13 of pub(crate) fn navigate( pipeline_id: PipelineId, mut load_data: LoadData, history_handling: NavigationHistoryBehavior, ) { with_script_thread(|script_thread| { let is_javascript = load_data.url.scheme() == "javascript"; // If resource is a request whose url's scheme is "javascript" // https://html.spec.whatwg.org/multipage/#navigate-to-a-javascript:-url if is_javascript { let window = match script_thread.documents.borrow().find_window(pipeline_id) { None => return, Some(window) => window, }; let global = window.as_global_scope(); let trusted_global = Trusted::new(global); let sender = script_thread .senders .pipeline_to_constellation_sender .clone(); let task = task!(navigate_javascript: move || { // Important re security. See https://github.com/servo/servo/issues/23373 if trusted_global.root().is::() { let global = &trusted_global.root(); if Self::navigate_to_javascript_url(global, global, &mut load_data, None, CanGc::note()) { sender .send((pipeline_id, ScriptToConstellationMessage::LoadUrl(load_data, history_handling))) .unwrap(); } } }); // Step 19 of global .task_manager() .dom_manipulation_task_source() .queue(task); } else { script_thread .senders .pipeline_to_constellation_sender .send(( pipeline_id, ScriptToConstellationMessage::LoadUrl(load_data, history_handling), )) .expect("Sending a LoadUrl message to the constellation failed"); } }); } /// pub(crate) fn navigate_to_javascript_url( global: &GlobalScope, containing_global: &GlobalScope, load_data: &mut LoadData, container: Option<&Element>, can_gc: CanGc, ) -> 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, &global.get_url().origin()) { 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 global .get_csp_list() .should_navigation_request_be_blocked(global, load_data, container, can_gc) { return false; } // Step 6. Let newDocument be the result of evaluating a javascript: URL given targetNavigable, // url, initiatorOrigin, and userInvolvement. Self::eval_js_url(containing_global, load_data, can_gc); true } pub(crate) fn process_attach_layout(new_layout_info: NewLayoutInfo, origin: MutableOrigin) { with_script_thread(|script_thread| { let pipeline_id = Some(new_layout_info.new_pipeline_id); script_thread.profile_event( ScriptThreadEventCategory::AttachLayout, pipeline_id, || { script_thread.handle_new_layout(new_layout_info, origin); }, ) }); } pub(crate) fn get_top_level_for_browsing_context( sender_pipeline: PipelineId, browsing_context_id: BrowsingContextId, ) -> Option { with_script_thread(|script_thread| { script_thread.ask_constellation_for_top_level_info(sender_pipeline, browsing_context_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 find_window_proxy(id: BrowsingContextId) -> Option> { with_script_thread(|script_thread| { script_thread .window_proxies .borrow() .get(&id) .map(|context| DomRoot::from_ref(&**context)) }) } pub(crate) fn find_window_proxy_by_name(name: &DOMString) -> Option> { with_script_thread(|script_thread| { for (_, proxy) in script_thread.window_proxies.borrow().iter() { if proxy.get_name() == *name { return Some(DomRoot::from_ref(&**proxy)); } } None }) } /// The worklet will use the given `ImageCache`. pub(crate) fn worklet_thread_pool(image_cache: Arc) -> Rc { with_optional_script_thread(|script_thread| { let script_thread = script_thread.unwrap(); script_thread .worklet_thread_pool .borrow_mut() .get_or_insert_with(|| { let init = WorkletGlobalScopeInit { to_script_thread_sender: script_thread.senders.self_sender.clone(), resource_threads: script_thread.resource_threads.clone(), mem_profiler_chan: script_thread.senders.memory_profiler_sender.clone(), time_profiler_chan: script_thread.senders.time_profiler_sender.clone(), devtools_chan: script_thread.senders.devtools_server_sender.clone(), to_constellation_sender: script_thread .senders .pipeline_to_constellation_sender .clone(), to_embedder_sender: script_thread .senders .pipeline_to_embedder_sender .clone(), image_cache, #[cfg(feature = "webgpu")] gpu_id_hub: script_thread.gpu_id_hub.clone(), inherited_secure_context: script_thread.inherited_secure_context, }; Rc::new(WorkletThreadPool::spawn(init)) }) .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( element: &Element, reaction: CallbackReaction, definition: Option>, ) { with_script_thread(|script_thread| { script_thread .custom_element_reaction_stack .enqueue_callback_reaction(element, reaction, definition); }) } pub(crate) fn enqueue_upgrade_reaction( element: &Element, definition: Rc, ) { with_script_thread(|script_thread| { script_thread .custom_element_reaction_stack .enqueue_upgrade_reaction(element, definition); }) } pub(crate) fn invoke_backup_element_queue(can_gc: CanGc) { with_script_thread(|script_thread| { script_thread .custom_element_reaction_stack .invoke_backup_element_queue(can_gc); }) } 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. pub(crate) fn new( state: InitialScriptState, layout_factory: Arc, system_font_service: Arc, ) -> ScriptThread { let (self_sender, self_receiver) = unbounded(); let runtime = Runtime::new(Some(SendableTaskSource { sender: ScriptEventLoopSender::MainThread(self_sender.clone()), pipeline_id: state.id, name: TaskSourceName::Networking, canceller: Default::default(), })); let cx = runtime.cx(); unsafe { SetWindowProxyClass(cx, GetWindowProxyClass()); JS_AddInterruptCallback(cx, Some(interrupt_callback)); } let constellation_receiver = state.constellation_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) = ipc::channel().unwrap(); let devtools_server_receiver = devtools_server_sender .as_ref() .map(|_| ROUTER.route_ipc_receiver_to_new_crossbeam_receiver(ipc_devtools_receiver)) .unwrap_or_else(crossbeam_channel::never); 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 = state.background_hang_monitor_register.register_component( 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 (ipc_image_cache_sender, ipc_image_cache_receiver) = ipc::channel().unwrap(); ROUTER.add_typed_route( ipc_image_cache_receiver, Box::new(move |message| { let _ = image_cache_sender.send(message.unwrap()); }), ); 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_sender, pipeline_to_constellation_sender: state.pipeline_to_constellation_sender.sender.clone(), pipeline_to_embedder_sender: state.pipeline_to_embedder_sender.clone(), image_cache_sender: ipc_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, content_process_shutdown_sender: state.content_process_shutdown_sender, }; let microtask_queue = runtime.microtask_queue.clone(); let js_runtime = Rc::new(runtime); #[cfg(feature = "webgpu")] let gpu_id_hub = Arc::new(IdentityHub::default()); let pipeline_id = PipelineId::new(); let script_to_constellation_chan = ScriptToConstellationChan { sender: senders.pipeline_to_constellation_sender.clone(), pipeline_id, }; 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(), script_to_constellation_chan, senders.pipeline_to_embedder_sender.clone(), state.resource_threads.clone(), #[cfg(feature = "webgpu")] gpu_id_hub.clone(), CanGc::note(), ); debugger_global.execute(CanGc::note()); ScriptThread { documents: DomRefCell::new(DocumentCollection::default()), last_render_opportunity_time: Default::default(), window_proxies: DomRefCell::new(HashMapTracedValues::new_fx()), incomplete_loads: DomRefCell::new(vec![]), incomplete_parser_contexts: IncompleteParserContexts(RefCell::new(vec![])), senders, receivers, image_cache: state.image_cache.clone(), resource_threads: state.resource_threads, task_queue, background_hang_monitor, closing, timer_scheduler: Default::default(), microtask_queue, js_runtime, closed_pipelines: DomRefCell::new(FxHashSet::default()), mutation_observers: Default::default(), system_font_service, webgl_chan: state.webgl_chan, #[cfg(feature = "webxr")] webxr_registry: state.webxr_registry, worklet_thread_pool: Default::default(), docs_with_no_blocking_loads: Default::default(), custom_element_reaction_stack: Rc::new(CustomElementReactionStack::new()), compositor_api: state.compositor_api, profile_script_events: opts.debug.profile_script_events, print_pwm: opts.print_pwm, unminify_js: opts.unminify_js, local_script_source: opts.local_script_source.clone(), unminify_css: opts.unminify_css, user_content_manager: state.user_content_manager, 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, inherited_secure_context: state.inherited_secure_context, layout_factory, relative_mouse_down_point: Cell::new(Point2D::zero()), scheduled_update_the_rendering: Default::default(), needs_rendering_update: Arc::new(AtomicBool::new(false)), debugger_global: debugger_global.as_traced(), privileged_urls: state.privileged_urls, } } #[allow(unsafe_code)] pub(crate) fn get_cx(&self) -> JSContext { unsafe { JSContext::from_ptr(self.js_runtime.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, can_gc: CanGc) { debug!("Starting script thread."); while self.handle_msgs(can_gc) { // Go on... debug!("Running script thread."); } debug!("Stopped script thread."); } /// Process compositor events as part of a "update the rendering task". fn process_pending_input_events(&self, pipeline_id: PipelineId, can_gc: CanGc) { let Some(document) = self.documents.borrow().find_document(pipeline_id) else { warn!("Processing pending compositor 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!("Compositor event sent to a pipeline with a closed window {pipeline_id}."); return; } let _guard = ScriptUserInteractingGuard::new(self.is_user_interacting.clone()); document.event_handler().handle_pending_input_events(can_gc); } 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, can_gc: CanGc) -> 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: The specification says to filter out non-renderable documents, // as well as those for which a rendering update would be unnecessary, // but this isn't happening here. // 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 `