/* 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::{HashMap, 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; 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; use constellation_traits::{ JsEvalResult, LoadData, LoadOrigin, NavigationHistoryBehavior, ScriptToConstellationChan, ScriptToConstellationMessage, ScrollState, StructuredSerializedData, WindowSizeType, }; use content_security_policy::{self as csp}; 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::{ CompositorHitTestResult, EmbedderMsg, InputEvent, 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 html5ever::{local_name, ns}; 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 media::WindowGLContext; use metrics::MAX_TASK_NS; use net_traits::image_cache::{ImageCache, PendingImageResponse}; 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 script_layout_interface::{ LayoutConfig, LayoutFactory, ReflowGoal, ScriptThreadFactory, node_id_from_scroll_id, }; use script_traits::{ ConstellationInputEvent, DiscardBrowsingContext, DocumentActivity, InitialScriptState, NewLayoutInfo, Painter, ProgressiveWebMetricType, ScriptThreadMessage, UpdatePipelineIdReason, }; use servo_config::opts; use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl}; use style::dom::OpaqueNode; use style::thread_state::{self, ThreadState}; use stylo_atoms::Atom; use timers::{TimerEventRequest, TimerScheduler}; use url::Position; #[cfg(feature = "webgpu")] use webgpu_traits::{WebGPUDevice, WebGPUMsg}; use webrender_api::units::DevicePixel; 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, FromJSValConvertible, 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, MutNullableDom, RootCollection, ThreadLocalStackRoots, }; use crate::dom::bindings::settings_stack::AutoEntryScript; use crate::dom::bindings::str::DOMString; use crate::dom::bindings::trace::{HashMapTracedValues, JSTraceable}; use crate::dom::customelementregistry::{ CallbackReaction, CustomElementDefinition, CustomElementReactionStack, }; use crate::dom::document::{ Document, DocumentSource, FocusType, HasBrowsingContext, IsHTMLDocument, TouchEventResult, }; use crate::dom::element::Element; use crate::dom::globalscope::GlobalScope; use crate::dom::htmlanchorelement::HTMLAnchorElement; use crate::dom::htmliframeelement::HTMLIFrameElement; use crate::dom::htmlslotelement::HTMLSlotElement; use crate::dom::mutationobserver::MutationObserver; use crate::dom::node::{Node, NodeTraits, ShadowIncluding}; use crate::dom::servoparser::{ParserContext, ServoParser}; #[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_runtime::{ CanGc, JSContext, JSContextHelper, Runtime, ScriptThreadEventCategory, ThreadSafeJSContext, }; use crate::task_queue::TaskQueue; use crate::task_source::{SendableTaskSource, TaskSourceName}; 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"); 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); #[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: DomRefCell>, /// 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>>, /// 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, /// The topmost element over the mouse. topmost_mouse_over_target: MutNullableDom, /// List of pipelines that have been owned and closed by this script thread. #[no_trace] closed_pipelines: DomRefCell>, /// microtask_queue: Rc, /// Microtask Queue for adding support for mutation observer microtasks mutation_observer_microtask_queued: Cell, /// The unit of related similar-origin browsing contexts' list of MutationObserver objects mutation_observers: DomRefCell>>, /// signal_slots: DomRefCell>>, /// 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: CustomElementReactionStack, /// 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, /// Emits notifications when there is a relayout. relayout_event: 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 set of all nodes ever created in this script thread node_ids: DomRefCell>, /// Code is running as a consequence of a user interaction is_user_interacting: Cell, /// 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, // Mouse down point. // In future, this shall be mouse_down_point for primary button #[no_trace] relative_mouse_down_point: Cell>, } 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, ) { 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 roots = RootCollection::new(); let _stack_roots = ThreadLocalStackRoots::new(&roots); let id = state.id; let browsing_context_id = state.browsing_context_id; let webview_id = state.webview_id; let parent_info = state.parent_info; let opener = state.opener; let memory_profiler_sender = state.memory_profiler_sender.clone(); let viewport_details = state.viewport_details; 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); let origin = MutableOrigin::new(load_data.url.origin()); script_thread.pre_page_load(InProgressLoad::new( id, browsing_context_id, webview_id, parent_info, opener, viewport_details, origin, load_data, )); let reporter_name = format!("script-reporter-{:?}", id); 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 set_mutation_observer_microtask_queued(value: bool) { with_script_thread(|script_thread| { script_thread.mutation_observer_microtask_queued.set(value); }) } pub(crate) fn is_mutation_observer_microtask_queued() -> bool { with_script_thread(|script_thread| script_thread.mutation_observer_microtask_queued.get()) } pub(crate) fn add_mutation_observer(observer: &MutationObserver) { with_script_thread(|script_thread| { script_thread .mutation_observers .borrow_mut() .push(Dom::from_ref(observer)); }) } pub(crate) fn get_mutation_observers() -> Vec> { with_script_thread(|script_thread| { script_thread .mutation_observers .borrow() .iter() .map(|o| DomRoot::from_ref(&**o)) .collect() }) } pub(crate) fn add_signal_slot(observer: &HTMLSlotElement) { with_script_thread(|script_thread| { script_thread .signal_slots .borrow_mut() .push(Dom::from_ref(observer)); }) } pub(crate) fn take_signal_slots() -> Vec> { with_script_thread(|script_thread| { script_thread .signal_slots .take() .into_iter() .inspect(|slot| { slot.remove_from_signal_slots(); }) .map(|slot| slot.as_rooted()) .collect() }) } 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) { self.timer_scheduler.borrow_mut().schedule_timer(request); } // 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, } } /// Step 13 of pub(crate) fn navigate( browsing_context: BrowsingContextId, 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/#javascript-protocol 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 // TODO: check according to https://w3c.github.io/webappsec-csp/#should-block-navigation-request if let Some(window) = trusted_global.root().downcast::() { if ScriptThread::check_load_origin(&load_data.load_origin, &window.get_url().origin()) { ScriptThread::eval_js_url(&trusted_global.root(), &mut load_data, CanGc::note()); sender .send((pipeline_id, ScriptToConstellationMessage::LoadUrl(load_data, history_handling))) .unwrap(); } } }); global .task_manager() .dom_manipulation_task_source() .queue(task); } else { if let Some(ref sender) = script_thread.senders.devtools_server_sender { let _ = sender.send(ScriptToDevtoolsControlMsg::Navigate( browsing_context, NavigationState::Start(load_data.url.clone()), )); } 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 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)) } pub(crate) fn set_user_interacting(interacting: bool) { with_script_thread(|script_thread| { script_thread.is_user_interacting.set(interacting); }); } 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() -> HashSet { with_script_thread(|script_thread| { script_thread .documents .borrow() .iter() .filter_map(|(id, document)| { if document.is_fully_active() { Some(id) } else { None } }) .fold(HashSet::new(), |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 }) } pub(crate) fn worklet_thread_pool() -> 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(), image_cache: script_thread.image_cache.clone(), #[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 push_new_element_queue() { with_script_thread(|script_thread| { script_thread .custom_element_reaction_stack .push_new_element_queue(); }) } pub(crate) fn pop_current_element_queue(can_gc: CanGc) { with_script_thread(|script_thread| { script_thread .custom_element_reaction_stack .pop_current_element_queue(can_gc); }) } 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(node_id: String) { with_script_thread(|script_thread| { script_thread.node_ids.borrow_mut().insert(node_id); }) } pub(crate) fn has_node_id(node_id: &str) -> bool { with_script_thread(|script_thread| script_thread.node_ids.borrow().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)); } // Ask the router to proxy IPC messages from the control port to us. let constellation_receiver = ROUTER.route_ipc_receiver_to_new_crossbeam_receiver(state.constellation_receiver); // 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), Some(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(), 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, }; ScriptThread { documents: DomRefCell::new(DocumentCollection::default()), last_render_opportunity_time: Default::default(), window_proxies: DomRefCell::new(HashMapTracedValues::new()), 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: runtime.microtask_queue.clone(), js_runtime: Rc::new(runtime), topmost_mouse_over_target: MutNullableDom::new(Default::default()), closed_pipelines: DomRefCell::new(HashSet::new()), mutation_observer_microtask_queued: Default::default(), mutation_observers: Default::default(), signal_slots: 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: CustomElementReactionStack::new(), compositor_api: state.compositor_api, profile_script_events: opts.debug.profile_script_events, print_pwm: opts.print_pwm, relayout_event: opts.debug.relayout_event, 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, node_ids: Default::default(), is_user_interacting: Cell::new(false), #[cfg(feature = "webgpu")] gpu_id_hub: Arc::new(IdentityHub::default()), inherited_secure_context: state.inherited_secure_context, layout_factory, relative_mouse_down_point: Cell::new(Point2D::zero()), } } #[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 a compositor mouse move event. fn process_mouse_move_event( &self, document: &Document, hit_test_result: Option, pressed_mouse_buttons: u16, can_gc: CanGc, ) { // Get the previous target temporarily let prev_mouse_over_target = self.topmost_mouse_over_target.get(); unsafe { document.handle_mouse_move_event( hit_test_result, pressed_mouse_buttons, &self.topmost_mouse_over_target, can_gc, ) } // Short-circuit if nothing changed if self.topmost_mouse_over_target.get() == prev_mouse_over_target { return; } let mut state_already_changed = false; // Notify Constellation about the topmost anchor mouse over target. let window = document.window(); if let Some(target) = self.topmost_mouse_over_target.get() { if let Some(anchor) = target .upcast::() .inclusive_ancestors(ShadowIncluding::No) .filter_map(DomRoot::downcast::) .next() { let status = anchor .upcast::() .get_attribute(&ns!(), &local_name!("href")) .and_then(|href| { let value = href.value(); let url = document.url(); url.join(&value).map(|url| url.to_string()).ok() }); let event = EmbedderMsg::Status(document.webview_id(), status); window.send_to_embedder(event); state_already_changed = true; } } // We might have to reset the anchor state if !state_already_changed { if let Some(target) = prev_mouse_over_target { if target .upcast::() .inclusive_ancestors(ShadowIncluding::No) .filter_map(DomRoot::downcast::) .next() .is_some() { let event = EmbedderMsg::Status(window.webview_id(), None); window.send_to_embedder(event); } } } } /// 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; } ScriptThread::set_user_interacting(true); let window = document.window(); let _realm = enter_realm(document.window()); for event in document.take_pending_input_events().into_iter() { document.update_active_keyboard_modifiers(event.active_keyboard_modifiers); match event.event { InputEvent::MouseButton(mouse_button_event) => { document.handle_mouse_button_event( mouse_button_event, event.hit_test_result, event.pressed_mouse_buttons, can_gc, ); }, InputEvent::MouseMove(_) => { // The event itself is unecessary here, because the point in the viewport is in the hit test. self.process_mouse_move_event( &document, event.hit_test_result, event.pressed_mouse_buttons, can_gc, ); }, InputEvent::Touch(touch_event) => { let touch_result = document.handle_touch_event(touch_event, event.hit_test_result, can_gc); if let (TouchEventResult::Processed(handled), true) = (touch_result, touch_event.is_cancelable()) { let sequence_id = touch_event.expect_sequence_id(); let result = if handled { embedder_traits::TouchEventResult::DefaultAllowed( sequence_id, touch_event.event_type, ) } else { embedder_traits::TouchEventResult::DefaultPrevented( sequence_id, touch_event.event_type, ) }; let message = ScriptToConstellationMessage::TouchEventProcessed(result); self.senders .pipeline_to_constellation_sender .send((pipeline_id, message)) .unwrap(); } }, InputEvent::Wheel(wheel_event) => { document.handle_wheel_event(wheel_event, event.hit_test_result, can_gc); }, InputEvent::Keyboard(keyboard_event) => { document.dispatch_key_event(keyboard_event, can_gc); }, InputEvent::Ime(ime_event) => { document.dispatch_ime_event(ime_event, can_gc); }, InputEvent::Gamepad(gamepad_event) => { window.as_global_scope().handle_gamepad_event(gamepad_event); }, InputEvent::EditingAction(editing_action_event) => { document.handle_editing_action(editing_action_event, can_gc); }, } } ScriptThread::set_user_interacting(false); } /// /// /// Attempt to update the rendering and then do a microtask checkpoint if rendering was actually /// updated. pub(crate) fn update_the_rendering(&self, requested_by_compositor: bool, can_gc: CanGc) { *self.last_render_opportunity_time.borrow_mut() = Some(Instant::now()); if !self.can_continue_running_inner() { return; } // Run rafs for all pipeline, if a raf tick was received for any. // This ensures relative ordering of rafs between parent doc and iframes. let should_run_rafs = self .documents .borrow() .iter() .any(|(_, doc)| doc.is_fully_active() && doc.has_received_raf_tick()); let any_animations_running = self.documents.borrow().iter().any(|(_, document)| { document.is_fully_active() && document.animations().running_animation_count() != 0 }); // 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 // If we aren't explicitly running rAFs, this update wasn't requested by the compositor, // and we are running animations, then wait until the compositor tells us it is time to // update the rendering via a TickAllAnimations message. if !requested_by_compositor && any_animations_running { return; } // > 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 `